Merge branch 'feat/ambient-quality-detail' into main
25 files changed,
+3,915
−155
PRODUCT.md+18 −1callscore/report.go+35 −5callscore/report_test.go+59 −1cmd/quality-summary/detail.go+397 −0cmd/quality-summary/main.go+73 −11cmd/quality-summary/relayed_test.go+133 −0docs/operations/quality.md+54 −7docs/superpowers/specs/2026-09-07-meet-design.md+186 −0internal/calls/app.go+5 −0internal/calls/quality.go+354 −28internal/calls/static/room.js+450 −23internal/callstest/browser_test.go+62 −7internal/callstest/native_browser_test.go+43 −12internal/callstest/quality_detail_test.go+404 −0internal/callstest/quality_test.go+28 −12native/apple/Sources/CallsInterop/Interop.swift+9 −0native/apple/Sources/CallsKit/Call.swift+77 −15native/apple/Sources/CallsKit/QualityReport.swift+415 −12native/apple/Sources/CallsKit/ReportProblem.swift+54 −8native/apple/Tests/CallsKitTests/QualityReportTests.swift+449 −1native/bridge/bridge.go+24 −0native/bridge/bridge_test.go+33 −3protocol/quality.go+106 −7test/browser/call.mjs+38 −0test/browser/room-quality.test.mjs+409 −2
CI failed — run details
diff --git a/PRODUCT.md b/PRODUCT.md| index 0abffa2..eae95ce 100644 |
| --- a/PRODUCT.md |
| +++ b/PRODUCT.md |
| @@ -51,7 +51,8 @@ learns is the shape of the team's meetings and who minted what, never a |
| title, chat text, or signalling payload, enforced by a WAL-grep test and |
| a captured-logger test, not merely asserted (§0.1). Since 2026-10-03 the log also |
| holds quality and problem reports under random tags (§15.26): the shape of |
| -a call's connections, never which meeting or who. |
| +a call's connections, never which meeting or who; since 2026-10-28 a |
| +struggling client may send its diagnostics on its own (§15.29). |
| ## Positioning |
| @@ -121,6 +122,22 @@ a call's connections, never which meeting or who. |
| retention — seven days, or 50 MiB of compressed log per app per box, |
| whichever is first. `CALLS_QUALITY_REPORTS=off` stops quality reports; a |
| person can stop their own in Settings (apps) or the Devices panel (web). |
| + **Since 2026-10-28 (spec §15.29) the diagnostics may also be sent |
| + automatically when a call is struggling** — freezes in two windows in a |
| + row, a round trip over 800 ms in two in a row, "Reconnecting…" for more |
| + than 5 s, or a shared screen the recovery had to rebuild: the same |
| + anonymous diagnostics as Report a problem, scrubbed the same way, with no |
| + note (nobody typed one) and the rule that fired, at most once every ten |
| + minutes and three times per participation. It follows the same switches |
| + as the quality reports: a person who turned theirs off sends none, and |
| + `CALLS_QUALITY_REPORTS=off` stops them. The quality reports also now |
| + carry, per remote peer, the window's average and highest round trip and |
| + jitter, the counts of candidates gathered and offered by type and which |
| + kinds of pair worked (types and counts, never an address), the relay's |
| + region, whether each video encoder and decoder is hardware or software, |
| + the codec family, the screen's share mode, and how long bandwidth or the |
| + CPU held the encoder back — written as one flat `calls: quality peer` |
| + line per remote peer so `carlos logs` shows all of it. |
| ## Capabilities and Constraints |
diff --git a/callscore/report.go b/callscore/report.go| index bbdb464..3166821 100644 |
| --- a/callscore/report.go |
| +++ b/callscore/report.go |
| @@ -13,12 +13,13 @@ import ( |
| "amadan.net/oficina/calls/protocol" |
| ) |
| -// Quality and problem reports (spec §15.26). The host builds the report — |
| -// it holds the media statistics — and the core carries it, because the |
| -// core holds the two things the request needs: the session the hello was |
| -// given to, and the hello's report token. |
| +// Quality and problem reports (spec §15.26), and the automatic report |
| +// (§15.29). The host builds the report — it holds the media statistics — |
| +// and the core carries it, because the core holds the two things the |
| +// request needs: the session the hello was given to, and the hello's |
| +// report token. |
| // |
| -// Both requests run on a context of their own rather than the room's, so |
| +// Every request runs on a context of its own rather than the room's, so |
| // they still work once the room is closed: the final quality report goes |
| // at leave, and "Report a problem" is offered for ten minutes after the |
| // call (the server keeps the token that long past the participation). |
| @@ -107,6 +108,35 @@ func (r *Room) SendProblem(report []byte) (ref string, err error) { |
| return receipt.Ref, nil |
| } |
| +// SendAutoReport posts the automatic report (spec §15.29, 2026-10-28), a |
| +// protocol.AutoReport as JSON, sent with nobody pressing anything when the |
| +// host judges its call to be struggling. It answers the reference the |
| +// server gave it, which the host puts on the window's quality report; stop |
| +// is the server's kill switch (204), as for SendQuality: send no more |
| +// quality or automatic reports this call. Every other refusal is an |
| +// automatic report not sent, and the call goes on as before. |
| +func (r *Room) SendAutoReport(report []byte) (ref string, stop bool, err error) { |
| + if len(report) > protocol.MaxProblemBody || !json.Valid(report) { |
| + return "", false, &ReportError{ReportFailed} |
| + } |
| + status, body, err := r.postReport("auto-report", report) |
| + if err != nil { |
| + return "", false, err |
| + } |
| + switch status { |
| + case http.StatusNoContent: |
| + return "", true, nil |
| + case http.StatusOK: |
| + default: |
| + return "", false, &ReportError{outcomeOf(status)} |
| + } |
| + var receipt protocol.ProblemReceipt |
| + if json.Unmarshal(body, &receipt) != nil || !validRef(receipt.Ref) { |
| + return "", false, &ReportError{ReportFailed} |
| + } |
| + return receipt.Ref, false, nil |
| +} |
| + |
| func outcomeOf(status int) ReportOutcome { |
| switch status { |
| case http.StatusTooManyRequests: |
diff --git a/callscore/report_test.go b/callscore/report_test.go| index c736b74..8159664 100644 |
| --- a/callscore/report_test.go |
| +++ b/callscore/report_test.go |
| @@ -15,7 +15,7 @@ import ( |
| const testToken = "0123456789abcdef0123456789abcdef" |
| -// reportServer answers /m/room/{quality,problem} with status (and body), |
| +// reportServer answers /m/room/{quality,problem,auto-report} with status (and body), |
| // recording what it was sent. |
| type reportServer struct { |
| *httptest.Server |
| @@ -156,6 +156,55 @@ func TestSendProblemRefusals(t *testing.T) { |
| } |
| } |
| +func TestSendAutoReportAnswersTheReference(t *testing.T) { |
| + report := []byte(`{"trigger":"freezes","diagnostics":"peer abc123","client":{"app":"mac"}}`) |
| + srv := newReportServer(t, http.StatusOK, `{"ref":"AB12CD34"}`) |
| + r := helloed(t, srv.Server, testToken) |
| + r.Leave() |
| + ref, stop, err := r.SendAutoReport(report) |
| + if err != nil || stop || ref != "AB12CD34" { |
| + t.Fatalf("ref=%q stop=%v err=%v", ref, stop, err) |
| + } |
| + srv.mu.Lock() |
| + defer srv.mu.Unlock() |
| + last := len(srv.paths) - 1 |
| + if srv.paths[last] != "POST /m/room/auto-report" || srv.tokens[last] != testToken || |
| + srv.origins[last] != srv.URL || srv.bodies[last] != string(report) { |
| + t.Fatalf("request: %v %v %v", srv.paths, srv.tokens, srv.origins) |
| + } |
| +} |
| + |
| +func TestSendAutoReportOutcomes(t *testing.T) { |
| + report := []byte(`{"trigger":"rtt","diagnostics":"","client":{"app":"mac"}}`) |
| + for _, tc := range []struct { |
| + status int |
| + body string |
| + stop bool |
| + outcome ReportOutcome |
| + }{ |
| + // The kill switch: no reference, and no more reports this call. |
| + {http.StatusNoContent, "", true, ReportSent}, |
| + {http.StatusTooManyRequests, `{"error":"rate"}`, false, ReportTooMany}, |
| + {http.StatusNotFound, `{"error":"not-found"}`, false, ReportGone}, |
| + {http.StatusBadRequest, `{"error":"bad-request"}`, false, ReportFailed}, |
| + {http.StatusRequestEntityTooLarge, "", false, ReportFailed}, |
| + // A 200 that is not a reference is not put on a report as one. |
| + {http.StatusOK, `{"ref":"<script>"}`, false, ReportFailed}, |
| + {http.StatusOK, `not json`, false, ReportFailed}, |
| + {http.StatusAccepted, "", false, ReportFailed}, |
| + } { |
| + t.Run(fmt.Sprint(tc.status, tc.body), func(t *testing.T) { |
| + srv := newReportServer(t, tc.status, tc.body) |
| + r := helloed(t, srv.Server, testToken) |
| + r.Close() |
| + ref, stop, err := r.SendAutoReport(report) |
| + if ref != "" || stop != tc.stop || OutcomeOf(err) != tc.outcome { |
| + t.Fatalf("ref=%q stop=%v err=%v, want stop=%v %s", ref, stop, err, tc.stop, tc.outcome) |
| + } |
| + }) |
| + } |
| +} |
| + |
| func TestReportsNeedATokenAndABoundedBody(t *testing.T) { |
| srv := newReportServer(t, http.StatusAccepted, "") |
| // No token: a server from before §15.26 never gave one. Nothing is sent. |
| @@ -167,6 +216,9 @@ func TestReportsNeedATokenAndABoundedBody(t *testing.T) { |
| if _, err := r.SendProblem([]byte(`{}`)); OutcomeOf(err) != ReportGone { |
| t.Fatalf("no token: %v", err) |
| } |
| + if _, _, err := r.SendAutoReport([]byte(`{}`)); OutcomeOf(err) != ReportGone { |
| + t.Fatalf("no token: %v", err) |
| + } |
| r.mu.Lock() |
| r.report = testToken |
| r.mu.Unlock() |
| @@ -181,6 +233,12 @@ func TestReportsNeedATokenAndABoundedBody(t *testing.T) { |
| if _, err := r.SendProblem(huge); OutcomeOf(err) != ReportFailed { |
| t.Fatalf("oversized problem: %v", err) |
| } |
| + if _, _, err := r.SendAutoReport(huge); OutcomeOf(err) != ReportFailed { |
| + t.Fatalf("oversized auto report: %v", err) |
| + } |
| + if _, _, err := r.SendAutoReport([]byte(`{not json`)); OutcomeOf(err) != ReportFailed { |
| + t.Fatalf("invalid auto report: %v", err) |
| + } |
| srv.mu.Lock() |
| defer srv.mu.Unlock() |
| if len(srv.paths) != 0 { |
diff --git a/cmd/quality-summary/detail.go b/cmd/quality-summary/detail.go| new file mode 100644 |
| index 0000000..de1be4c |
| --- /dev/null |
| +++ b/cmd/quality-summary/detail.go |
| @@ -0,0 +1,397 @@ |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "io" |
| + "sort" |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +// The per-peer lines (spec §15.29, 2026-10-28): one `calls: quality peer` |
| +// line per report per remote peer, flat, so that `carlos logs` prints all |
| +// of it. This file reads them into what each side said about each other |
| +// side, and prints three things the head lines could never say: the path |
| +// each side took and the candidates behind it, and so whose network made a |
| +// relayed call relayed; each direction's camera and screen, as the sender |
| +// sent them and as the receiver got them; and the encoders and decoders. |
| + |
| +// side is what one person's client said about one remote peer, over every |
| +// window it reported. |
| +type side struct { |
| + windows, relayWindows int |
| + paths map[string]int |
| + regions map[string]bool |
| + // local is how often the selected pair's local end was the relay: |
| + // this side's own leg went through it. |
| + localRelay int |
| + // The candidates, at their most, and whether a kind of pair ever |
| + // worked. measured is false for a client before §15.29. |
| + measured bool |
| + host, srflx, prflx, relay float64 |
| + rHost, rSrflx, rPrflx, rRelay float64 |
| + directOK, localDirectOK, udpOK bool |
| + rttMax, jitterMax float64 |
| + rttAvgSum float64 |
| + rttAvgN int |
| + concealedMax, bufferMax float64 |
| + out, in map[string]*stream // "Camera", "Screen" |
| +} |
| + |
| +// stream is one video stream in one direction, from one side's account. |
| +type stream struct { |
| + windows int |
| + sizes map[string]int |
| + fpsSum, kbpsSum float64 |
| + fpsN, kbpsN int |
| + freezes, freezeSeconds float64 |
| + dropped float64 |
| + limits map[string]int |
| + limitedBW, limitedCPU float64 |
| + coders, codecs, modes map[string]bool |
| + stalls, rebuilds, other float64 |
| +} |
| + |
| +func newStream() *stream { |
| + return &stream{sizes: map[string]int{}, limits: map[string]int{}, coders: map[string]bool{}, codecs: map[string]bool{}, modes: map[string]bool{}} |
| +} |
| + |
| +func (c *call) addPeerLine(l line) { |
| + if l.Remote == "" { |
| + return |
| + } |
| + f := l.Fields |
| + key := [2]string{l.Peer, l.Remote} |
| + s := c.sides[key] |
| + if s == nil { |
| + s = &side{paths: map[string]int{}, regions: map[string]bool{}, out: map[string]*stream{}, in: map[string]*stream{}} |
| + c.sides[key] = s |
| + } |
| + s.windows++ |
| + num := func(k string) (float64, bool) { |
| + v, err := strconv.ParseFloat(f[k], 64) |
| + return v, err == nil |
| + } |
| + n := func(k string) float64 { v, _ := num(k); return v } |
| + if loc, rem := f["pathLocal"], f["pathRemote"]; loc != "" || rem != "" { |
| + s.paths[fmt.Sprintf("%s→%s %s", orDash(loc), orDash(rem), orDash(f["pathProtocol"]))]++ |
| + if loc == "relay" || rem == "relay" { |
| + s.relayWindows++ |
| + } |
| + if loc == "relay" { |
| + s.localRelay++ |
| + } |
| + } |
| + if r := f["relayRegion"]; r != "" { |
| + s.regions[r] = true |
| + } |
| + if _, ok := f["udpOk"]; ok { |
| + s.measured = true |
| + s.host, s.srflx, s.prflx, s.relay = max(s.host, n("candHost")), max(s.srflx, n("candSrflx")), max(s.prflx, n("candPrflx")), max(s.relay, n("candRelay")) |
| + s.rHost, s.rSrflx = max(s.rHost, n("candRemoteHost")), max(s.rSrflx, n("candRemoteSrflx")) |
| + s.rPrflx, s.rRelay = max(s.rPrflx, n("candRemotePrflx")), max(s.rRelay, n("candRemoteRelay")) |
| + s.directOK = s.directOK || f["directOk"] == "true" |
| + s.localDirectOK = s.localDirectOK || f["localDirectOk"] == "true" |
| + s.udpOK = s.udpOK || f["udpOk"] == "true" |
| + } |
| + s.rttMax = max(s.rttMax, n("rttMax"), n("rtt")) |
| + s.jitterMax = max(s.jitterMax, n("jitterMax")) |
| + if v, ok := num("rttAvg"); ok { |
| + s.rttAvgSum += v |
| + s.rttAvgN++ |
| + } |
| + s.concealedMax = max(s.concealedMax, n("inAudioConcealedPct")) |
| + s.bufferMax = max(s.bufferMax, n("inAudioJitterBufferMs")) |
| + for _, kind := range []string{"Camera", "Screen"} { |
| + for dir, m := range map[string]map[string]*stream{"out": s.out, "in": s.in} { |
| + pre := dir + kind |
| + present := false |
| + for k := range f { |
| + if strings.HasPrefix(k, pre) { |
| + present = true |
| + break |
| + } |
| + } |
| + if !present { |
| + continue |
| + } |
| + st := m[kind] |
| + if st == nil { |
| + st = newStream() |
| + m[kind] = st |
| + } |
| + st.windows++ |
| + if w, h := n(pre+"Width"), n(pre+"Height"); w > 0 && h > 0 { |
| + st.sizes[fmt.Sprintf("%g×%g", w, h)]++ |
| + } |
| + if v, ok := num(pre + "Fps"); ok { |
| + st.fpsSum += v |
| + st.fpsN++ |
| + } |
| + if v, ok := num(pre + "Kbps"); ok { |
| + st.kbpsSum += v |
| + st.kbpsN++ |
| + } |
| + st.freezes += n(pre + "Freezes") |
| + st.freezeSeconds += n(pre + "FreezeSeconds") |
| + st.dropped += n(pre + "Dropped") |
| + if lim := f[pre+"Limit"]; lim != "" { |
| + st.limits[lim]++ |
| + } |
| + st.limitedBW += n(pre + "LimitedBandwidthSeconds") |
| + st.limitedCPU += n(pre + "LimitedCpuSeconds") |
| + for _, k := range []string{pre + "Encoder", pre + "Decoder"} { |
| + if v := f[k]; v != "" { |
| + st.coders[v] = true |
| + } |
| + } |
| + if v := f[pre+"Codec"]; v != "" { |
| + st.codecs[v] = true |
| + } |
| + if v := f[pre+"Mode"]; v != "" { |
| + st.modes[v] = true |
| + } |
| + st.stalls += n(pre + "Stalls") |
| + st.rebuilds += n(pre+"Rebuilds") + n(pre+"Reshares") |
| + st.other += n(pre + "Failures") |
| + } |
| + } |
| +} |
| + |
| +func set(m map[string]bool) string { |
| + var out []string |
| + for k := range m { |
| + out = append(out, k) |
| + } |
| + sort.Strings(out) |
| + return strings.Join(out, "/") |
| +} |
| + |
| +func most(m map[string]int) string { |
| + best, n := "", 0 |
| + for k, v := range m { |
| + if v > n || (v == n && k < best) { |
| + best, n = k, v |
| + } |
| + } |
| + return best |
| +} |
| + |
| +// dominantLimit is what held the encoder back over the call: by the |
| +// seconds the clients counted, where they did (§15.29), and otherwise the |
| +// reason most windows named. |
| +func (st *stream) dominantLimit() string { |
| + switch { |
| + case st.limitedBW > 0 || st.limitedCPU > 0: |
| + if st.limitedBW >= st.limitedCPU { |
| + return fmt.Sprintf("bandwidth (%.0f s; cpu %.0f s)", st.limitedBW, st.limitedCPU) |
| + } |
| + return fmt.Sprintf("cpu (%.0f s; bandwidth %.0f s)", st.limitedCPU, st.limitedBW) |
| + case len(st.limits) > 0: |
| + return most(st.limits) + " (most windows)" |
| + } |
| + return "" |
| +} |
| + |
| +func (st *stream) words(sent bool) string { |
| + var parts []string |
| + if sz := most(st.sizes); sz != "" { |
| + parts = append(parts, sz) |
| + } |
| + if st.fpsN > 0 { |
| + parts = append(parts, fmt.Sprintf("%.1f fps", st.fpsSum/float64(st.fpsN))) |
| + } |
| + if st.kbpsN > 0 { |
| + parts = append(parts, fmt.Sprintf("%.0f kbps", st.kbpsSum/float64(st.kbpsN))) |
| + } |
| + if sent { |
| + if lim := st.dominantLimit(); lim != "" { |
| + parts = append(parts, "limited by "+lim) |
| + } |
| + if m := set(st.modes); m != "" { |
| + parts = append(parts, "mode "+m) |
| + } |
| + if c := set(st.coders); c != "" { |
| + parts = append(parts, "encoder "+c) |
| + } |
| + if st.rebuilds+st.other > 0 { |
| + parts = append(parts, fmt.Sprintf("%g rebuilds/shares again, %g gave up", st.rebuilds, st.other)) |
| + } |
| + } else { |
| + parts = append(parts, fmt.Sprintf("freezes %g (%.1f s)", st.freezes, st.freezeSeconds)) |
| + if st.dropped > 0 { |
| + parts = append(parts, fmt.Sprintf("dropped %g", st.dropped)) |
| + } |
| + if st.stalls > 0 { |
| + parts = append(parts, fmt.Sprintf("stalls %g", st.stalls)) |
| + } |
| + if c := set(st.coders); c != "" { |
| + parts = append(parts, "decoder "+c) |
| + } |
| + } |
| + if c := set(st.codecs); c != "" { |
| + parts = append(parts, c) |
| + } |
| + return strings.Join(parts, ", ") |
| +} |
| + |
| +// candidates is a side's own summary in words. |
| +func (s *side) candidates() string { |
| + if !s.measured { |
| + return "not reported (a client from before 2026-10-28)" |
| + } |
| + yes := func(b bool) string { |
| + if b { |
| + return "yes" |
| + } |
| + return "no" |
| + } |
| + return fmt.Sprintf("gathered host %g, srflx %g, relay %g; offered host %g, srflx %g, relay %g; direct pair worked %s, own network reached out %s, UDP %s", |
| + s.host, s.srflx, s.relay, s.rHost, s.rSrflx, s.rRelay, yes(s.directOK), yes(s.localDirectOK), yes(s.udpOK)) |
| +} |
| + |
| +// whyRelayed is the verdict for a pair, a and b being the two sides' |
| +// accounts (either may be nil, for a client that sent no peer lines). The |
| +// strongest evidence first: a side that found no public address of its own |
| +// cannot have been reached directly; a side whose own leg was the relay is |
| +// the one that needed it; a pair where both found their addresses and |
| +// nothing direct worked is a NAT or a firewall that maps each destination |
| +// apart. |
| +func whyRelayed(an, bn string, a, b *side) string { |
| + noSrflx := func(s *side) bool { return s != nil && s.measured && s.srflx == 0 && s.prflx == 0 } |
| + onlyRelay := func(s *side) bool { return s != nil && s.measured && s.host == 0 && s.srflx == 0 && s.relay > 0 } |
| + ownLeg := func(s *side) bool { return s != nil && s.localRelay > 0 } |
| + var said []string |
| + for _, x := range []struct { |
| + name string |
| + s *side |
| + }{{an, a}, {bn, b}} { |
| + switch { |
| + case onlyRelay(x.s): |
| + said = append(said, x.name+" gathered only relay candidates (a relay-only policy, or a network that exposes nothing)") |
| + case noSrflx(x.s): |
| + said = append(said, x.name+" found no public address (no srflx candidate: UDP to the outside blocked)") |
| + case x.s != nil && x.s.measured && !x.s.udpOK: |
| + said = append(said, x.name+" had no pair work over UDP") |
| + } |
| + } |
| + switch { |
| + case (noSrflx(a) || onlyRelay(a)) && !(noSrflx(b) || onlyRelay(b)): |
| + said = append(said, "→ "+an+"'s network forced the relay") |
| + case (noSrflx(b) || onlyRelay(b)) && !(noSrflx(a) || onlyRelay(a)): |
| + said = append(said, "→ "+bn+"'s network forced the relay") |
| + case noSrflx(a) && noSrflx(b): |
| + said = append(said, "→ both networks forced it") |
| + case ownLeg(a) && !ownLeg(b): |
| + said = append(said, "→ "+an+"'s own leg went through the relay: "+an+"'s network is the likelier cause") |
| + case ownLeg(b) && !ownLeg(a): |
| + said = append(said, "→ "+bn+"'s own leg went through the relay: "+bn+"'s network is the likelier cause") |
| + case a != nil && a.measured && b != nil && b.measured && !a.directOK && !b.directOK: |
| + said = append(said, "→ both found public addresses and no direct pair worked: a NAT or firewall on one side maps each destination apart") |
| + case (a == nil || !a.measured) && (b == nil || !b.measured): |
| + said = append(said, "→ unknown: neither side reported its candidates") |
| + default: |
| + said = append(said, "→ not clear from the candidates") |
| + } |
| + return strings.Join(said, "; ") |
| +} |
| + |
| +// printSides prints the paths, the relay verdicts and the media, when |
| +// there are peer lines to print them from. |
| +func (c *call) printSides(out io.Writer) { |
| + if len(c.sides) == 0 { |
| + return |
| + } |
| + keys := make([][2]string, 0, len(c.sides)) |
| + for k := range c.sides { |
| + keys = append(keys, k) |
| + } |
| + sort.Slice(keys, func(i, j int) bool { return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1] }) |
| + |
| + fmt.Fprintln(out, " Paths (each side's own account)") |
| + for _, k := range keys { |
| + s := c.sides[k] |
| + relay := fmt.Sprintf("relay %.0f%%", 100*float64(s.relayWindows)/float64(s.windows)) |
| + if r := set(s.regions); r != "" { |
| + relay += " via " + r |
| + } |
| + fmt.Fprintf(out, " %s → %s path %s, %s", short(k[0]), short(k[1]), orDash(most(s.paths)), relay) |
| + if s.rttAvgN > 0 { |
| + fmt.Fprintf(out, ", RTT avg %.0f ms", s.rttAvgSum/float64(s.rttAvgN)) |
| + } |
| + fmt.Fprintf(out, ", RTT max %.0f ms", s.rttMax) |
| + if s.jitterMax > 0 { |
| + fmt.Fprintf(out, ", jitter max %.0f ms", s.jitterMax) |
| + } |
| + if s.concealedMax > 0 || s.bufferMax > 0 { |
| + fmt.Fprintf(out, ", audio concealed up to %.1f%%, jitter buffer up to %.0f ms", s.concealedMax, s.bufferMax) |
| + } |
| + fmt.Fprintf(out, "\n %s's candidates: %s\n", short(k[0]), s.candidates()) |
| + } |
| + |
| + // Each unordered pair once, when either side saw the relay. |
| + var verdicts []string |
| + done := map[[2]string]bool{} |
| + for _, k := range keys { |
| + pair := [2]string{min(k[0], k[1]), max(k[0], k[1])} |
| + if done[pair] { |
| + continue |
| + } |
| + done[pair] = true |
| + a, b := c.sides[[2]string{pair[0], pair[1]}], c.sides[[2]string{pair[1], pair[0]}] |
| + if (a == nil || a.relayWindows == 0) && (b == nil || b.relayWindows == 0) { |
| + continue |
| + } |
| + verdicts = append(verdicts, fmt.Sprintf(" %s – %s %s", short(pair[0]), short(pair[1]), whyRelayed(short(pair[0]), short(pair[1]), a, b))) |
| + } |
| + if len(verdicts) > 0 { |
| + fmt.Fprintln(out, " Why relayed") |
| + for _, v := range verdicts { |
| + fmt.Fprintln(out, v) |
| + } |
| + } |
| + |
| + // Media, per direction: the sender's account of what it sent and the |
| + // receiver's of what arrived. |
| + dirs := map[[2]string]bool{} |
| + for _, k := range keys { |
| + dirs[k], dirs[[2]string{k[1], k[0]}] = true, true |
| + } |
| + ordered := make([][2]string, 0, len(dirs)) |
| + for k := range dirs { |
| + ordered = append(ordered, k) |
| + } |
| + sort.Slice(ordered, func(i, j int) bool { return ordered[i][0]+ordered[i][1] < ordered[j][0]+ordered[j][1] }) |
| + var media []string |
| + for _, k := range ordered { |
| + from, to := k[0], k[1] |
| + sent := c.sides[[2]string{from, to}] |
| + got := c.sides[[2]string{to, from}] |
| + for _, kind := range []string{"Camera", "Screen"} { |
| + var o, i *stream |
| + if sent != nil { |
| + o = sent.out[kind] |
| + } |
| + if got != nil { |
| + i = got.in[kind] |
| + } |
| + if o == nil && i == nil { |
| + continue |
| + } |
| + line := fmt.Sprintf(" %s → %s %s", short(from), short(to), strings.ToLower(kind)) |
| + if o != nil { |
| + line += " sent " + o.words(true) |
| + } |
| + if i != nil { |
| + line += " received " + i.words(false) |
| + } |
| + media = append(media, line) |
| + } |
| + } |
| + if len(media) > 0 { |
| + fmt.Fprintln(out, " Media (sender → receiver)") |
| + for _, m := range media { |
| + fmt.Fprintln(out, m) |
| + } |
| + } |
| +} |
diff --git a/cmd/quality-summary/main.go b/cmd/quality-summary/main.go| index 619775e..a1e0706 100644 |
| --- a/cmd/quality-summary/main.go |
| +++ b/cmd/quality-summary/main.go |
| @@ -3,6 +3,11 @@ |
| // peer tag and platform; for every direction between two people, the |
| // worst loss, the worst round trip, the freezes and how much of the time |
| // the media went through the relay; and the notices people saw, in order. |
| +// From the per-peer lines (§15.29): each side's path and the candidates |
| +// behind it, and so which side's network made a relayed call relayed; |
| +// each direction's camera and screen as sent and as received — size, |
| +// frame rate, freezes, what held the encoder back, the encoders and |
| +// decoders — and the automatic reports a struggling client sent. |
| // |
| // It reads `carlos logs` output on standard input, or, with nothing piped |
| // in, runs `carlos logs` itself: |
| @@ -10,7 +15,7 @@ |
| // quality-summary --since 3h # every call in the last three hours |
| // quality-summary --since 24h --at 15:40 # the call running at 15:40 (Europe/Dublin) |
| // quality-summary --call 3k2jq7m4xw5zt6ab # one call, by its tag |
| -// quality-summary --problem K7Q2M9PD --since 24h # one problem report, diagnostics and all |
| +// quality-summary --problem K7Q2M9PD --since 24h # one problem or automatic report, diagnostics and all |
| // carlos logs --app calls --account oficina --since 2h -n 5000 | quality-summary |
| // |
| // Nothing here knows a meeting, a person or a name: the lines carry none. |
| @@ -53,7 +58,7 @@ func run(args []string, stdin *os.File, out io.Writer) error { |
| fs.StringVar(&o.account, "account", "oficina", "the carlos account") |
| fs.StringVar(&o.at, "at", "", "only the call(s) running at this time, HH:MM in --zone, today (or YYYY-MM-DD HH:MM)") |
| fs.StringVar(&o.call, "call", "", "only the call with this tag") |
| - fs.StringVar(&o.problem, "problem", "", "print one problem report, by its reference, with its diagnostics") |
| + fs.StringVar(&o.problem, "problem", "", "print one problem report or automatic report, by its reference, with its diagnostics") |
| fs.StringVar(&o.zone, "zone", "Europe/Dublin", "the zone times are shown and --at is read in") |
| if err := fs.Parse(args); err != nil { |
| return err |
| @@ -116,7 +121,7 @@ func carlosArgs(o options) []string { |
| if o.call != "" { |
| return append(args, "-field", "call="+o.call) |
| } |
| - return append(args, "-grep", "^calls: (quality|problem report)") |
| + return append(args, "-grep", "^calls: (quality|problem report|auto report)") |
| } |
| // parseAt reads "15:40" as today in loc, or "2026-10-03 15:40". |
| @@ -151,6 +156,11 @@ type line struct { |
| Part int `json:"part"` |
| Of int `json:"of"` |
| Text string `json:"text"` |
| + Trigger string `json:"trigger"` |
| + Remote string `json:"remote"` |
| + // Fields is every top-level scalar field as text, from either shape: |
| + // what a `calls: quality peer` line is read from (§15.29). |
| + Fields map[string]string `json:"-"` |
| // 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`. |
| @@ -196,6 +206,7 @@ func parse(r io.Reader) ([]line, error) { |
| flush() |
| var l line |
| if json.Unmarshal([]byte(s[i:]), &l) == nil && strings.HasPrefix(l.Msg, "calls: ") { |
| + l.Fields, l.Head = jsonFields([]byte(s[i:])) |
| out = append(out, l) |
| } |
| continue |
| @@ -225,6 +236,30 @@ func parse(r io.Reader) ([]line, error) { |
| return out, sc.Err() |
| } |
| +// jsonFields are a JSON line's top-level scalars as carlos would print |
| +// them, and the numeric ones as Head. |
| +func jsonFields(raw []byte) (map[string]string, map[string]float64) { |
| + var m map[string]any |
| + fields, head := map[string]string{}, map[string]float64{} |
| + if json.Unmarshal(raw, &m) != nil { |
| + return fields, head |
| + } |
| + for k, v := range m { |
| + switch v := v.(type) { |
| + case string: |
| + fields[k] = v |
| + case bool: |
| + fields[k] = strconv.FormatBool(v) |
| + case float64: |
| + fields[k] = strconv.FormatFloat(v, 'f', -1, 64) |
| + if !freeText[k] { |
| + head[k] = v |
| + } |
| + } |
| + } |
| + return fields, head |
| +} |
| + |
| // 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+`) |
| @@ -291,6 +326,7 @@ func parseRecord(s string) (line, bool) { |
| 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.Trigger, l.Remote, l.Fields = fields["trigger"], fields["remote"], fields |
| l.Final, l.Live = fields["final"] == "true", fields["live"] == "true" |
| l.Part, _ = strconv.Atoi(fields["part"]) |
| l.Of, _ = strconv.Atoi(fields["of"]) |
| @@ -355,18 +391,22 @@ type call struct { |
| dirs map[[2]string]*direction |
| events []event |
| problems []line |
| + autos []line |
| + // From the peer lines (§15.29): what each side said about one remote |
| + // peer, keyed [reporter, remote]. |
| + sides map[[2]string]*side |
| } |
| func gather(lines []line) []*call { |
| byTag := map[string]*call{} |
| var calls []*call |
| for _, l := range lines { |
| - if l.Call == "" || l.Msg == "calls: problem report diagnostics" { |
| + if l.Call == "" || strings.HasSuffix(l.Msg, " diagnostics") { |
| continue |
| } |
| c := byTag[l.Call] |
| if c == nil { |
| - c = &call{tag: l.Call, first: l.Time, last: l.Time, people: map[string]*person{}, dirs: map[[2]string]*direction{}} |
| + c = &call{tag: l.Call, first: l.Time, last: l.Time, people: map[string]*person{}, dirs: map[[2]string]*direction{}, sides: map[[2]string]*side{}} |
| byTag[l.Call] = c |
| calls = append(calls, c) |
| } |
| @@ -382,6 +422,11 @@ func gather(lines []line) []*call { |
| c.problems = append(c.problems, l) |
| case "calls: quality": |
| c.addQuality(p, l) |
| + case "calls: quality peer": |
| + c.addPeerLine(l) |
| + case "calls: auto report": |
| + c.autos = append(c.autos, l) |
| + c.events = append(c.events, event{l.Time, fmt.Sprintf("%s sent automatic report %s (%s)", short(l.Peer), l.Ref, orDash(l.Trigger))}) |
| } |
| } |
| sort.Slice(calls, func(i, j int) bool { return calls[i].first.Before(calls[j].first) }) |
| @@ -553,8 +598,12 @@ func short(tag string) string { |
| func (c *call) print(out io.Writer, loc *time.Location) { |
| f, l := c.first.In(loc), c.last.In(loc) |
| - fmt.Fprintf(out, "Call %s %s – %s %s (%s), %d people, %d problem report(s)\n", |
| + fmt.Fprintf(out, "Call %s %s – %s %s (%s), %d people, %d problem report(s)", |
| c.tag, f.Format("2006-01-02 15:04:05"), l.Format("15:04:05"), loc, l.Sub(f).Round(time.Second), len(c.people), len(c.problems)) |
| + if len(c.autos) > 0 { |
| + fmt.Fprintf(out, ", %d automatic report(s)", len(c.autos)) |
| + } |
| + fmt.Fprintln(out) |
| fmt.Fprintln(out, " People") |
| for _, tag := range c.order { |
| p := c.people[tag] |
| @@ -602,6 +651,7 @@ func (c *call) print(out io.Writer, loc *time.Location) { |
| fmt.Fprintln(out) |
| } |
| } |
| + c.printSides(out) |
| if len(c.events) > 0 { |
| fmt.Fprintln(out, " Events") |
| sort.SliceStable(c.events, func(i, j int) bool { return c.events[i].at.Before(c.events[j].at) }) |
| @@ -617,6 +667,10 @@ func (c *call) print(out io.Writer, loc *time.Location) { |
| fmt.Fprintf(out, " Problem %s at %s from %s (%s): %q\n quality-summary --problem %s --since <far enough back>\n", |
| p.Ref, p.Time.In(loc).Format("15:04:05"), short(p.Peer), p.App, note, p.Ref) |
| } |
| + for _, a := range c.autos { |
| + fmt.Fprintf(out, " Automatic report %s at %s from %s (%s), trigger %s\n quality-summary --problem %s --since <far enough back>\n", |
| + a.Ref, a.Time.In(loc).Format("15:04:05"), short(a.Peer), orDash(a.App), orDash(a.Trigger), a.Ref) |
| + } |
| fmt.Fprintln(out) |
| } |
| @@ -660,20 +714,28 @@ func printProblem(out io.Writer, lines []line, ref string, loc *time.Location) e |
| continue |
| } |
| switch l.Msg { |
| - case "calls: problem report": |
| + case "calls: problem report", "calls: auto report": |
| head = l |
| - case "calls: problem report diagnostics": |
| + case "calls: problem report diagnostics", "calls: auto report diagnostics": |
| parts[l.Part] = l.Text |
| of = l.Of |
| } |
| } |
| if head == nil { |
| - return fmt.Errorf("no problem report %s in these lines (try a longer --since)", ref) |
| + return fmt.Errorf("no problem or automatic report %s in these lines (try a longer --since)", ref) |
| } |
| - fmt.Fprintf(out, "Problem report %s, %s\n", ref, head.Time.In(loc).Format("2006-01-02 15:04:05 MST")) |
| + kind := "Problem report" |
| + if head.Msg == "calls: auto report" { |
| + kind = "Automatic report" |
| + } |
| + fmt.Fprintf(out, "%s %s, %s\n", kind, ref, head.Time.In(loc).Format("2006-01-02 15:04:05 MST")) |
| fmt.Fprintf(out, "call %s, peer %s, %s %s %s %s %s %s, live %v\n", head.Call, head.Peer, head.App, head.Version, |
| head.Browser, head.BrowVer, head.OS, head.OSVer, head.Live) |
| - fmt.Fprintf(out, "note: %s\n\n", orDash(head.Note)) |
| + if head.Msg == "calls: auto report" { |
| + fmt.Fprintf(out, "trigger: %s (sent by the client itself; nobody typed a note)\n\n", orDash(head.Trigger)) |
| + } else { |
| + fmt.Fprintf(out, "note: %s\n\n", orDash(head.Note)) |
| + } |
| for i := 1; i <= of; i++ { |
| t, ok := parts[i] |
| if !ok { |
diff --git a/cmd/quality-summary/relayed_test.go b/cmd/quality-summary/relayed_test.go| new file mode 100644 |
| index 0000000..61e87d1 |
| --- /dev/null |
| +++ b/cmd/quality-summary/relayed_test.go |
| @@ -0,0 +1,133 @@ |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// relayedFixture is a relayed call as the app writes it (§15.29), |
| +// generated by the server's own logQuality and logAuto and given readable |
| +// tags: a Mac app (mmmmmm) sharing its screen to a Safari guest (ssssaf) |
| +// whose network found no public address, so Safari's own leg went through |
| +// the relay in Dublin over TLS; Safari froze and sent an automatic report. |
| +const relayedFixture = `{"time":"2026-10-28T14:02:30.100Z","level":"INFO","msg":"calls: quality","call":"relayedcall2f7ab","peer":"mmmmmmac0x4n13qq","app":"mac","version":"0.4.13","os":"macos","osVersion":"26.1","final":false,"seconds":30,"remotes":1,"relay":true,"maxLossPct":0.7,"maxRtt":1288,"freezes":0,"reconnecting":1,"screenKeyframes":3,"screenRebuilds":1,"report":{"seconds":30,"devices":{"input":"bluetooth","output":"built-in"},"events":{"reconnecting":1,"reconnectingSeconds":4.2}}} |
| +{"time":"2026-10-28T14:02:30.101Z","level":"INFO","msg":"calls: quality peer","call":"relayedcall2f7ab","peer":"mmmmmmac0x4n13qq","remote":"ssssafari26x5qqq","pathLocal":"srflx","pathRemote":"relay","pathProtocol":"udp","relayRegion":"eu-west-1","rtt":300,"rttAvg":398,"rttMax":1288,"jitterAvg":12,"jitterMax":40,"candHost":3,"candSrflx":1,"candRelay":2,"candRemoteHost":2,"candRemoteRelay":1,"directOk":false,"localDirectOk":true,"udpOk":true,"outAudioKbps":32,"outAudioLossPct":1.3,"outCameraKbps":380,"outCameraWidth":1280,"outCameraHeight":720,"outCameraFps":12.5,"outCameraLimit":"bandwidth","outCameraLimitedBandwidthSeconds":29,"outCameraEncoder":"hardware","outCameraCodec":"vp8","outScreenKbps":900,"outScreenWidth":1920,"outScreenHeight":1246,"outScreenFps":4,"outScreenLimit":"bandwidth","outScreenLimitedBandwidthSeconds":30,"outScreenEncoder":"hardware","outScreenCodec":"h264","outScreenMode":"balanced","outScreenKeyframes":3,"outScreenRebuilds":1,"inAudioKbps":31,"inAudioLossPct":0.7,"inAudioConcealedPct":0.2,"inAudioJitterBufferMs":90,"inCameraKbps":410,"inCameraWidth":640,"inCameraHeight":360,"inCameraFps":24,"inCameraFreezes":0,"inCameraDecoder":"hardware","inCameraCodec":"h264"} |
| +{"time":"2026-10-28T14:02:41.200Z","level":"WARN","msg":"calls: auto report","ref":"9P3J52YS","call":"relayedcall2f7ab","peer":"ssssafari26x5qqq","app":"web","version":"47afcb9","browser":"safari","browserVersion":"26.5","os":"macos","osVersion":"10.15.7","live":true,"trigger":"freezes","parts":1} |
| +{"time":"2026-10-28T14:02:41.201Z","level":"WARN","msg":"calls: auto report diagnostics","ref":"9P3J52YS","call":"relayedcall2f7ab","peer":"ssssafari26x5qqq","part":1,"of":1,"text":"Calls web diagnostics\nfirst part"} |
| +{"time":"2026-10-28T14:02:41.300Z","level":"INFO","msg":"calls: quality","call":"relayedcall2f7ab","peer":"ssssafari26x5qqq","app":"web","version":"47afcb9","browser":"safari","browserVersion":"26.5","os":"macos","osVersion":"10.15.7","final":false,"seconds":30,"remotes":1,"relay":true,"maxLossPct":1.3,"maxRtt":1312,"freezes":7,"reconnecting":2,"screenStalls":1,"screenStallsNoPackets":1,"autoReport":"9P3J52YS","report":{"seconds":30,"devices":{"input":"bluetooth","output":"built-in"},"events":{"reconnecting":1,"reconnectingSeconds":4.2}}} |
| +{"time":"2026-10-28T14:02:41.301Z","level":"INFO","msg":"calls: quality peer","call":"relayedcall2f7ab","peer":"ssssafari26x5qqq","remote":"mmmmmmac0x4n13qq","pathLocal":"relay","pathRemote":"srflx","pathProtocol":"tls","relayRegion":"eu-west-1","rtt":310,"rttAvg":402.5,"rttMax":1312,"jitterAvg":18,"jitterMax":96,"candHost":2,"candRelay":1,"candRemoteHost":1,"candRemoteSrflx":1,"candRemoteRelay":1,"directOk":false,"localDirectOk":false,"udpOk":false,"outAudioKbps":31.5,"outAudioLossPct":1,"outAudioRtt":420,"outCameraKbps":412,"outCameraWidth":640,"outCameraHeight":360,"outCameraFps":24,"outCameraLimit":"bandwidth","outCameraLimitedBandwidthSeconds":27.5,"outCameraLimitedCpuSeconds":0,"outCameraEncoder":"hardware","outCameraCodec":"h264","inAudioKbps":30,"inAudioLossPct":1.3,"inAudioJitter":22,"inAudioConcealedPct":1,"inAudioJitterBufferMs":140,"inCameraKbps":380,"inCameraWidth":1280,"inCameraHeight":720,"inCameraFps":12.5,"inCameraLossPct":1,"inCameraFreezes":4,"inCameraFreezeSeconds":6.1,"inCameraDecoded":375,"inCameraDropped":3,"inCameraDecoder":"hardware","inCameraCodec":"vp8","inScreenKbps":900,"inScreenWidth":1920,"inScreenHeight":1246,"inScreenFps":4,"inScreenFreezes":3,"inScreenFreezeSeconds":9,"inScreenDropped":0,"inScreenDecoder":"software","inScreenCodec":"h264","inScreenStalls":1,"inScreenStallsNoPackets":1,"reconnecting":1,"reconnectingSeconds":6.4,"autoRestarts":2} |
| +` |
| + |
| +// carlosPrint is a JSON line as `carlos logs` prints it: its prefix, the |
| +// message, then every top-level scalar field but level as key=value in |
| +// key order, and nothing nested. |
| +func carlosPrint(t *testing.T, jsonl string) string { |
| + t.Helper() |
| + var b strings.Builder |
| + for _, l := range strings.Split(strings.TrimSpace(jsonl), "\n") { |
| + var m map[string]any |
| + if err := json.Unmarshal([]byte(l), &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys := make([]string, 0, len(m)) |
| + for k := range m { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + ts := m["time"].(string) |
| + fmt.Fprintf(&b, "%s %s [app] calls.bds.oncarlos.com %s", ts[:10], ts[11:19], m["msg"]) |
| + for _, k := range keys { |
| + switch v := m[k].(type) { |
| + case string: |
| + if k != "msg" && k != "level" { |
| + fmt.Fprintf(&b, " %s=%s", k, v) |
| + } |
| + case float64: |
| + fmt.Fprintf(&b, " %s=%s", k, strconv.FormatFloat(v, 'f', -1, 64)) |
| + case bool: |
| + fmt.Fprintf(&b, " %s=%v", k, v) |
| + } |
| + } |
| + b.WriteString("\n") |
| + } |
| + return b.String() |
| +} |
| + |
| +// The relayed call reads the same from the app's JSON and from carlos's |
| +// print of it, which leaves out `report` and everything nested. |
| +func TestSummaryOfARelayedCall(t *testing.T) { |
| + for name, text := range map[string]string{"json": relayedFixture, "carlos": carlosPrint(t, relayedFixture)} { |
| + out := runOnText(t, text, "--call", "relayedcall2f7ab") |
| + t.Logf("%s:\n%s", name, out) |
| + for _, want := range []string{ |
| + "2 people, 0 problem report(s), 1 automatic report(s)", |
| + " Paths (each side's own account)", |
| + "mmmmmm → ssssaf path srflx→relay udp, relay 100% via eu-west-1, RTT avg 398 ms, RTT max 1288 ms, jitter max 40 ms, audio concealed up to 0.2%, jitter buffer up to 90 ms", |
| + "mmmmmm's candidates: gathered host 3, srflx 1, relay 2; offered host 2, srflx 0, relay 1; direct pair worked no, own network reached out yes, UDP yes", |
| + "ssssaf → mmmmmm path relay→srflx tls, relay 100% via eu-west-1, RTT avg 402 ms, RTT max 1312 ms, jitter max 96 ms, audio concealed up to 1.0%, jitter buffer up to 140 ms", |
| + "ssssaf's candidates: gathered host 2, srflx 0, relay 1; offered host 1, srflx 1, relay 1; direct pair worked no, own network reached out no, UDP no", |
| + " Why relayed", |
| + "mmmmmm – ssssaf ssssaf found no public address (no srflx candidate: UDP to the outside blocked); → ssssaf's network forced the relay", |
| + " Media (sender → receiver)", |
| + "mmmmmm → ssssaf camera sent 1280×720, 12.5 fps, 380 kbps, limited by bandwidth (29 s; cpu 0 s), encoder hardware, vp8 received 1280×720, 12.5 fps, 380 kbps, freezes 4 (6.1 s), dropped 3, decoder hardware, vp8", |
| + "mmmmmm → ssssaf screen sent 1920×1246, 4.0 fps, 900 kbps, limited by bandwidth (30 s; cpu 0 s), mode balanced, encoder hardware, 1 rebuilds/shares again, 0 gave up, h264 received 1920×1246, 4.0 fps, 900 kbps, freezes 3 (9.0 s), stalls 1, decoder software, h264", |
| + "ssssaf → mmmmmm camera sent 640×360, 24.0 fps, 412 kbps, limited by bandwidth (28 s; cpu 0 s), encoder hardware, h264 received 640×360, 24.0 fps, 410 kbps, freezes 0 (0.0 s), decoder hardware, h264", |
| + "ssssaf sent automatic report 9P3J52YS (freezes)", |
| + "Automatic report 9P3J52YS at 14:02:41 from ssssaf (web), trigger freezes", |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("%s: missing %q", name, want) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestAnAutomaticReportByItsReference(t *testing.T) { |
| + for name, text := range map[string]string{"json": relayedFixture, "carlos": carlosPrint(t, relayedFixture)} { |
| + out := runOnText(t, text, "--problem", "9p3j52ys") |
| + for _, want := range []string{"Automatic report 9P3J52YS", "trigger: freezes (sent by the client itself; nobody typed a note)", "Calls web diagnostics\nfirst part"} { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("%s: --problem missing %q:\n%s", name, want, out) |
| + } |
| + } |
| + } |
| + if got := strings.Join(carlosArgs(options{app: "calls", account: "oficina", since: "2h"}), " "); !strings.Contains(got, "auto report") { |
| + t.Errorf("the summary's carlos logs leaves out the automatic reports: %q", got) |
| + } |
| +} |
| + |
| +// A pair where neither side sent peer lines (clients from before §15.29) |
| +// prints no Paths section, and the old summary is unchanged. |
| +func TestNoPeerLinesNoPaths(t *testing.T) { |
| + out := runOnText(t, carlosFixture, "--call", "ayhk4nffb2gz7eur") |
| + if strings.Contains(out, "Paths") || strings.Contains(out, "Why relayed") { |
| + t.Errorf("paths from no peer lines:\n%s", out) |
| + } |
| +} |
| + |
| +func TestWhyRelayed(t *testing.T) { |
| + measured := func(host, srflx, relay float64, local int, direct bool) *side { |
| + return &side{measured: true, host: host, srflx: srflx, relay: relay, localRelay: local, directOK: direct, localDirectOK: srflx > 0, udpOK: true, relayWindows: 1} |
| + } |
| + for _, c := range []struct { |
| + name string |
| + a, b *side |
| + want string |
| + }{ |
| + {"b has no srflx", measured(2, 1, 1, 0, false), measured(2, 0, 1, 1, false), "→ b's network forced the relay"}, |
| + {"a relay-only", measured(0, 0, 1, 1, false), measured(2, 1, 1, 0, false), "a gathered only relay candidates"}, |
| + {"both without", measured(1, 0, 1, 1, false), measured(1, 0, 1, 1, false), "→ both networks forced it"}, |
| + {"both found, a's own leg", measured(2, 1, 1, 3, false), measured(2, 1, 1, 0, false), "→ a's own leg went through the relay"}, |
| + {"both found, both legs", measured(2, 1, 1, 3, false), measured(2, 1, 1, 3, false), "no direct pair worked: a NAT or firewall"}, |
| + {"b an old client", measured(2, 0, 1, 1, false), nil, "→ a's network forced the relay"}, |
| + {"neither reported", &side{relayWindows: 1}, nil, "→ unknown"}, |
| + } { |
| + if got := whyRelayed("a", "b", c.a, c.b); !strings.Contains(got, c.want) { |
| + t.Errorf("%s: %q, want %q in it", c.name, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/docs/operations/quality.md b/docs/operations/quality.md| index d002152..c79c628 100644 |
| --- a/docs/operations/quality.md |
| +++ b/docs/operations/quality.md |
| @@ -17,15 +17,34 @@ top-level members (it reads fields only from JSON lines; `--grep` matches the |
| in one call), `peer` (this participation's tag), `app` (web, mac, iphone, |
| ipad), `version`, `browser`, `browserVersion`, `os`, `osVersion`, |
| `final`, `seconds`, `remotes`, and the headlines `relay`, `maxLossPct`, |
| - `maxRtt`, `freezes`, `reconnecting`. `report` holds the rest: `devices` |
| - (kinds, never names), `events`, and `peers`, one per remote peer named by |
| - its tag, with `path`, `rtt`, `out`, `in` and `events`. |
| + `maxRtt`, `freezes`, `reconnecting`, the screen's counts when not zero, |
| + and `autoReport` (a reference) when the client sent an automatic report |
| + with that window. `report` holds `devices` (kinds, never names) and the |
| + call-wide `events`; it is nested, so `carlos logs` does not print it. |
| +- `calls: quality peer` (INFO, since 2026-10-28, spec §15.29), one per |
| + remote peer after each `calls: quality` line, flat so `carlos logs` prints |
| + all of it: `call`, `peer`, `remote` (the other person's tag), the path |
| + (`pathLocal`, `pathRemote`, `pathProtocol`, `relayRegion`), round trip and |
| + jitter (`rtt`, `rttAvg`, `rttMax`, `jitterAvg`, `jitterMax`), this side's |
| + candidates (`candHost`, `candSrflx`, `candRelay`, `candRemote…`, |
| + `directOk`, `localDirectOk`, `udpOk`), and `outAudio…`, `outCamera…`, |
| + `outScreen…`, `inAudio…`, `inCamera…`, `inScreen…` (`Kbps`, `Width`, |
| + `Height`, `Fps`, `LossPct`, `Limit`, `LimitedBandwidthSeconds`, |
| + `Encoder`, `Decoder`, `Codec`, `Mode`, `Freezes`, `FreezeSeconds`, |
| + `Dropped`, …), and the events. Only what the client measured is there. |
| - `calls: problem report` (WARN), when someone presses Send in Report a |
| problem: `ref` (what they were shown), `call`, `peer`, the client fields, |
| `live` (still in the call, or within ten minutes after), `note` and |
| `parts`. |
| - `calls: problem report diagnostics` (WARN): the diagnostics text in |
| `parts` lines, each with `ref`, `part`, `of` and `text`. |
| +- `calls: auto report` and `calls: auto report diagnostics` (WARN, since |
| + 2026-10-28): the same, sent by a client on its own when its call was |
| + struggling, with `trigger` (`freezes`: 3 or more in two windows running; |
| + `rtt`: over 800 ms in two windows running; `reconnecting`: shown more than |
| + 5 s; `screen`: the screen recovery went past keyframes) in place of a |
| + note. At most one every ten minutes and three per participation; off when |
| + the person's quality reports are off, or `CALLS_QUALITY_REPORTS=off`. |
| Tags are random. They cannot be turned back into a meeting or a person, and |
| nothing else in the log can be matched to them. The way from "the call at |
| @@ -40,14 +59,23 @@ filter the message for `calls: quality` or `calls: problem report`, then by |
| ## With carlos |
| # Every report in the last two hours |
| - carlos logs --app calls --account oficina --since 2h -n 5000 --grep '^calls: (quality|problem report)' |
| + carlos logs --app calls --account oficina --since 2h -n 5000 --grep '^calls: (quality|problem report|auto report)' |
| # One call, every line from every person in it |
| carlos logs --app calls --account oficina --since 24h -n 5000 --field call=3k2jq7m4xw5zt6ab |
| - # A problem report someone quoted, with its diagnostics |
| + # A problem report someone quoted, or an automatic report's reference, with its diagnostics |
| carlos logs --app calls --account oficina --since 7d -n 5000 --field ref=K7Q2M9PD |
| + # Every automatic report this week |
| + carlos logs --app calls --account oficina --since 7d --grep '^calls: auto report$' |
| + |
| + # One call's per-peer detail: paths, candidates, sizes, freezes, encoders |
| + carlos logs --app calls --account oficina --since 24h -n 5000 --field call=3k2jq7m4xw5zt6ab --grep '^calls: quality peer$' |
| + |
| + # Connections whose own leg went through the relay |
| + carlos logs --app calls --account oficina --since 24h --grep '^calls: quality peer$' --field pathLocal=relay |
| + |
| # Every problem report this week |
| carlos logs --app calls --account oficina --since 7d --grep '^calls: problem report$' |
| @@ -89,6 +117,24 @@ With nothing piped in it runs `carlos logs` itself. It prints, per call: |
| 15:41:30 aaaaaa left (final report) |
| Problem K7Q2M9PD at 15:41:20 from aaaaaa (mac): "video froze" |
| +From the peer lines (since 2026-10-28) it adds, per call: |
| + |
| + Paths (each side's own account) |
| + mmmmmm → ssssaf path srflx→relay udp, relay 100% via eu-west-1, RTT avg 398 ms, RTT max 1288 ms, jitter max 40 ms, … |
| + mmmmmm's candidates: gathered host 3, srflx 1, relay 2; offered host 2, srflx 0, relay 1; direct pair worked no, own network reached out yes, UDP yes |
| + ssssaf → mmmmmm path relay→srflx tls, relay 100% via eu-west-1, RTT avg 402 ms, RTT max 1312 ms, jitter max 96 ms, … |
| + ssssaf's candidates: gathered host 2, srflx 0, relay 1; offered host 1, srflx 1, relay 1; direct pair worked no, own network reached out no, UDP no |
| + Why relayed |
| + mmmmmm – ssssaf ssssaf found no public address (no srflx candidate: UDP to the outside blocked); → ssssaf's network forced the relay |
| + Media (sender → receiver) |
| + mmmmmm → ssssaf screen sent 1920×1246, 4.0 fps, 900 kbps, limited by bandwidth (30 s; cpu 0 s), mode balanced, encoder hardware, … received 1920×1246, 4.0 fps, 900 kbps, freezes 3 (9.0 s), stalls 1, decoder software, h264 |
| + Automatic report 9P3J52YS at 14:02:41 from ssssaf (web), trigger freezes |
| + |
| +"Own network reached out" is whether a pair whose local end was not the |
| +relay ever worked; "UDP" whether any pair went over UDP all the way. A side |
| +with no srflx candidate never found its public address; a side whose path |
| +starts `relay→` is the one whose own leg needed the relay. |
| + |
| "Worst loss" is the worst 30-second window's inbound packet loss, of audio, |
| camera or screen; "relay" is the share of windows whose path went through the |
| relay; "audio concealed" is the share of received audio the receiver had to |
| @@ -97,7 +143,8 @@ make up. |
| ## Turning it off |
| `carlos env set --app calls --account oficina CALLS_QUALITY_REPORTS=off`, |
| -then `carlos restart` (which drops live calls), stops the automatic reports: |
| -the endpoint answers 204 and clients stop sending for that call. Report a |
| +then `carlos restart` (which drops live calls), stops the automatic reports — |
| +quality reports and the automatic Report a problem both: the endpoints answer |
| +204 and clients stop sending for that call. Report a |
| problem keeps working. `carlos env unset --app calls --account oficina |
| CALLS_QUALITY_REPORTS` and a restart turn them back on. |
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md| index 7b184b3..5dd166f 100644 |
| --- a/docs/superpowers/specs/2026-09-07-meet-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-meet-design.md |
| @@ -3101,3 +3101,189 @@ get there first), and `TestNativeMacIceBrowser` (both, the app as an old |
| one, the browser's recovery off). An 80 s block checks the minute-later |
| sentence and "may be on an old version". |
| + |
| +### 15.29 §15.26, §15.27, §15.28 — the detail where it can be read, why a call was relayed, and a report nobody has to press (2026-10-28) |
| + |
| +**Why.** 28 October: Paul, on the Mac app (0.4.13), and a guest in Safari |
| +on macOS, call tag `akevtdmsd5fh6abg`. The whole call went through the one |
| +relay (eu-west-1, Dublin), with round trips up to 1.3 s and up to seven |
| +freezes in a window on the Safari side. Nobody pressed Report a problem, and |
| +the log could not say which side forced the relay, which stream froze (the |
| +camera or the screen), at what size and bitrate, or whether the encoder was |
| +held back by bandwidth: the clients had sent all of it except the first, but |
| +`carlos logs` prints a line's top-level fields and drops everything nested, |
| +and every per-peer number was under `report`. Paul wants that visible |
| +without anyone pressing a button. |
| + |
| +**Decision: one flat line per remote peer.** Each accepted quality report is |
| +written as its `calls: quality` head line and, after it, one `calls: |
| +quality peer` line (INFO) per remote peer: `call`, `peer` and `remote` (that |
| +peer's tag), then the peer's part of the report as scalar fields under fixed |
| +camelCase names, only what the client measured, never a zero for "not |
| +measured": |
| + |
| +- *path*: `pathLocal`, `pathRemote` (host, srflx, prflx, relay, unknown), |
| + `pathProtocol` (udp, tcp, tls, unknown) and, when either end is the relay, |
| + `relayRegion` — the configured region while there is exactly one, which is |
| + all a relayed path can have used; with several, left off. |
| +- *round trip and jitter*: `rtt` (the last reading), `rttAvg` (the selected |
| + pair's total round trip over its responses in the window, or the mean of |
| + once-a-second readings), `rttMax` (the highest once-a-second reading), |
| + `jitterAvg`, `jitterMax` (the peer's inbound audio, or camera with no |
| + audio, read once a second). The head's `maxRtt` now counts `rttMax`. |
| +- *candidates* (below): `candHost`, `candSrflx`, `candPrflx`, `candRelay`, |
| + `candRemoteHost` … `candRemoteRelay`, and `directOk`, `localDirectOk`, |
| + `udpOk`, written true or false whenever the client sent candidates. |
| +- *out*: `outAudioKbps`, `outAudioLossPct`, `outAudioRtt`; for |
| + `outCamera…` and `outScreen…`: `Kbps`, `Width`, `Height`, `Fps`, |
| + `LossPct`, `Limit`, `LimitedBandwidthSeconds`, `LimitedCpuSeconds`, |
| + `Encoder`, `Codec`, and the screen's `Mode` and §15.22's ladder |
| + (`Keyframes`, `Rebuilds`, `Reshares`, `Failures`, `Damped`, |
| + `EncoderStalls`). |
| +- *in*: `inAudioKbps`, `inAudioLossPct`, `inAudioJitter`, |
| + `inAudioConcealedPct`, `inAudioJitterBufferMs`; for `inCamera…` and |
| + `inScreen…`: `Kbps`, `Width`, `Height`, `Fps`, `LossPct`, `Freezes`, |
| + `FreezeSeconds`, `Decoded`, `Dropped`, `Decoder`, `Codec`, and the |
| + screen's `Reattaches` and `Stalls…`. |
| +- *events*: `reconnecting`, `reconnectingSeconds`, `cantHearSeconds`, |
| + `noSound`, `noSoundFromUs`, `audioBlocked`, `screenStalled`, |
| + `autoRestarts`, `autoRebuilds`. |
| + |
| +The head line's `report` keeps what is about the whole call from there |
| +(`seconds`, `final`, `devices`, `events`) and no longer carries `peers`: the |
| +peer lines are where each peer's part is, and four peers' detail would |
| +outgrow the platform's 8 KB line. The widest peer line the schema allows, |
| +every field at its widest, is 2.8 KB (a test holds it under 8 KB). The head |
| +line also says `autoReport=<ref>` when the client sent an automatic report |
| +with that window. |
| + |
| +**The new members** (`protocol/quality.go`, still version 1: an older |
| +server drops them as unknown, and a client before this sends none of them, |
| +which the server takes as it always did): |
| + |
| +- `rttAvg`, `rttMax`, `jitterAvg`, `jitterMax` per peer, in ms, bounded as |
| + every delay is. |
| +- `out.video`/`out.screen`: `limit` is now the reason that held the encoder |
| + back for most of the window, from the stack's `qualityLimitationDurations` |
| + (a tie goes to bandwidth, then cpu, other, none), and the latest reason |
| + where the stack keeps no durations; `limitedBandwidthSeconds` and |
| + `limitedCpuSeconds`, seconds in the window; `encoder` (hardware, software, |
| + unknown — from the stack's power-efficient flag, else the implementation's |
| + name, which never leaves the client); `codec` (vp8, vp9, h264, h265, av1, |
| + opus, other); the screen's `mode` (balanced, detail, motion). |
| +- `in.video`/`in.screen`: `decoder` and `codec`, the same enums. |
| +- `candidates` per peer, below; and the report's `autoReport`, a reference. |
| + |
| +**Decision: why relayed.** Each client counts, per connection, the local |
| +candidates it gathered and the remote candidates it was offered, by type, |
| +and over every candidate pair that succeeded, whether any had neither end a |
| +relay (`directOk`), any had its own end not a relay (`localDirectOk`, its |
| +own network reached the far side or the far side's relay), and any went over |
| +UDP the whole way to the peer or to the relay (`udpOk`). Types and counts |
| +only, never an address, a port or a relay URL. Read across both sides, that |
| +says whose network forced a relayed call: a side with no srflx candidate |
| +never found its own public address (UDP to the outside blocked), a side |
| +whose selected pair's local end is the relay is the one that needed it, and |
| +two sides that both found their addresses with no direct pair working is a |
| +NAT or firewall that maps each destination apart. A client from before this |
| +sends no candidates, and the other side's account (what it was offered) |
| +still says something. |
| + |
| +**Decision: the automatic report.** A client whose call is struggling |
| +sends its own Report a problem — the same anonymous diagnostics, scrubbed |
| +the same way (people as `peer:<tag>`, the meeting as `[meeting]`, device |
| +names kept), with no note, because nobody typed one — and names the |
| +reference in that window's quality report. Struggling is one of, checked in |
| +this order at the end of each (non-final) window: |
| + |
| +| Trigger | When | |
| +|---|---| |
| +| `freezes` | inbound freezes (camera and screen, all peers) at least 3 in this window **and** the one before | |
| +| `rtt` | the window's highest round trip above 800 ms in this window **and** the one before | |
| +| `reconnecting` | "Reconnecting…" (the call's, or any person's) shown for more than 5 s in the window | |
| +| `screen` | §15.22's ladder went past keyframes for anyone (a rebuild, a share again, or it gave up) | |
| + |
| +At most one every ten minutes and three in all per participation, the |
| +client counting and the server holding both on its own. `POST |
| +/m/{sqid}/auto-report` takes `protocol.AutoReport` (`trigger`, |
| +`diagnostics`, `client`) with the report token, as `/problem` does: |
| +authorized the same way, refused past 64 KB unread, and answered `200 |
| +{"ref": …}` (eight Crockford characters), 400, 404, 413, or 429 with |
| +`Retry-After`. The limit is a per-tag gate, not the token bucket, because a |
| +bucket forgets a key idle for a minute: checked before the body is read and |
| +spent only once the report is taken, so a refused body costs none of the |
| +three; bounded at 4,096 tags, the one sent longest ago going first. The |
| +server logs one `calls: auto report` line (WARN: the reference, the tags, |
| +the client, `live`, `trigger`, `parts`) and the diagnostics as `calls: auto |
| +report diagnostics` lines of at most 6,000 escaped bytes each, exactly as a |
| +problem report; a `note` member a client sends anyway is not in the schema |
| +and is dropped unread. `quality-summary --problem <ref>` prints either kind. |
| + |
| +**It follows the quality reports' switches**, not Report a problem's, |
| +because nobody asked for it: the person's own "Send anonymous quality |
| +reports" (the Devices panel on the web, Settings in the apps) off means no |
| +automatic reports either, and `CALLS_QUALITY_REPORTS=off` answers |
| +`/auto-report` 204 before it looks at anything, which a client takes as it |
| +takes the quality endpoint's 204: nothing more this call. The existing |
| +disclosure ("anonymous connection quality reports to help fix call |
| +problems") covers it; PRODUCT.md says so in as many words. |
| + |
| +**What this does to §15.26's table.** One column more: |
| + |
| +| | Automatic report | |
| +|---|---| |
| +| When | a call struggling, by the rules above; at most once every ten minutes, three times a participation | |
| +| Who | every client, guests included, unless its toggle is off or the server's kill switch is | |
| +| Numbers about the connections | yes, in the diagnostics' own words | |
| +| Call tag, peer tag | yes | |
| +| App, version, browser, OS | yes, and the browser's user agent string in the web's diagnostics | |
| +| Device names | yes, in the diagnostics, as Report a problem | |
| +| What the person typed | — (no note) | |
| +| People's names, emails, the meeting's title or sqid, peer ids | no (scrubbed) | |
| +| IP addresses, ports, candidates' addresses | no | |
| +| Chat, audio, video, SDP | no | |
| +| The database | nothing | |
| + |
| +§0.1's falsifiable claim is unchanged by it except that a struggling call's |
| +diagnostics may be in the log without anyone having pressed Send: device |
| +names, as for a problem report, and no words of anyone's. |
| + |
| +**Reading them.** `quality-summary` reads the peer lines from either shape |
| +(JSON, or `carlos logs`'s key=value), and prints for each call, after the |
| +connections: *Paths*, each side's own account of each connection (the most |
| +common path, the share of windows through the relay and its region, RTT |
| +average and highest, jitter's highest, concealment and jitter buffer at |
| +their worst, and the side's candidates); *Why relayed*, a verdict per |
| +relayed pair from both sides' candidates; *Media*, each direction's camera |
| +and screen as the sender sent them (size, fps, kbps, the dominant |
| +limitation by seconds, the mode, the encoder, the screen's rebuilds) and as |
| +the receiver got them (size, fps, kbps, freezes and their seconds, dropped |
| +frames, stalls, the decoder, the codec); and the automatic reports among |
| +the events and at the end, with their references. |
| + |
| +**Compatibility.** Nothing on the signalling wire changes. An old client's |
| +report still makes a head line and a peer line, with what it measured. A |
| +new client against an old server: the old server drops the new members, and |
| +`/auto-report` is answered 404 by its router, which the client takes as any |
| +404 — the quality report goes without a reference. `carlos logs` readers of |
| +`report.peers` (only `quality-summary`, which reads the old shape still) |
| +read the peer lines instead. |
| + |
| +**Tests.** `internal/callstest/quality_detail_test.go`: the peer line's |
| +fields, tags and flatness, the region with one relay configured, the head's |
| +`maxRtt` from `rttMax`, nothing unmeasured written; an old client's report; |
| +every new enum and bound refused; the widest peer line under 8 KB; an |
| +automatic report's reference, parts, scrubbing and dropped note, its |
| +schema and cap; one every ten minutes, three a participation, per |
| +participation, not spent by a refused body, not spending a problem report's; |
| +the token and the kill switch. `cmd/quality-summary/relayed_test.go`: a |
| +relayed call written by the server's own code, read as JSON and as carlos |
| +prints it, and the relay verdict's cases. `test/browser/room-quality.test.mjs` |
| +and `QualityReportTests.swift`: the candidates, round trip, jitter, dominant |
| +limit, coder and codec tables, mode, the four rules with their |
| +two-windows-in-a-row negatives, the gate and the switches. The browser |
| +gate's `quality` scenario forces one automatic report |
| +(`window.meet.autoReportForTest`) and checks it, its reference on a quality |
| +line and the peer lines in the log (`auto-check`); the native gate does the |
| +same with `CALLS_AUTO_REPORT_TEST`. No harness has a local TURN, so a relayed |
| +path is the unit tests' fixtures, not a real call. |
diff --git a/internal/calls/app.go b/internal/calls/app.go| index e96335f..65693ca 100644 |
| --- a/internal/calls/app.go |
| +++ b/internal/calls/app.go |
| @@ -67,6 +67,9 @@ type app struct { |
| // burst three. |
| qualityLimiter *rateLimiter |
| problemLimiter *rateLimiter |
| + // autoGate is the automatic report's (spec §15.29): one every ten |
| + // minutes and three in all per participation, keyed on its tag. |
| + autoGate *autoReportGate |
| // reportLog is where the reports go: Config.ReportLogger. |
| reportLog *slog.Logger |
| @@ -430,6 +433,7 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| a.apiLimiter = newRateLimiter(apiRatePerSecond, apiBurst, maxAgentBuckets) |
| a.qualityLimiter = newRateLimiterEvery(10*time.Second, 6, maxReportBuckets) |
| a.problemLimiter = newRateLimiterEvery(time.Minute, 3, maxReportBuckets) |
| + a.autoGate = newAutoReportGate(maxReportBuckets) |
| a.reportLog = rc.ReportLogger |
| if !rc.qualityReports { |
| rc.Logger.Info("calls: quality reports off (CALLS_QUALITY_REPORTS=off)") |
| @@ -587,6 +591,7 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err |
| r.Get("/m/{sqid}/ice", a.ice) |
| r.Post("/m/{sqid}/quality", a.quality) |
| r.Post("/m/{sqid}/problem", a.problem) |
| + r.Post("/m/{sqid}/auto-report", a.autoReport) |
| }) |
| }) |
diff --git a/internal/calls/quality.go b/internal/calls/quality.go| index 74f2fa4..611ae39 100644 |
| --- a/internal/calls/quality.go |
| +++ b/internal/calls/quality.go |
| @@ -14,6 +14,7 @@ import ( |
| "slices" |
| "strconv" |
| "strings" |
| + "sync" |
| "time" |
| "unicode/utf8" |
| @@ -40,6 +41,15 @@ import ( |
| // their client's call diagnostics, written as one `calls: problem |
| // report` line and as many `calls: problem report diagnostics` lines as |
| // the diagnostics need, under a reference the client shows. |
| +// - POST /m/{sqid}/auto-report: the same diagnostics, sent by the client |
| +// itself when its call is struggling (spec §15.29, 2026-10-28), with |
| +// no note, under a reference of its own; one every ten minutes and |
| +// three in all per participation, and off with the kill switch. |
| +// |
| +// Each quality report is also written as one `calls: quality peer` line |
| +// per remote peer, flat: `carlos logs` prints a line's top-level fields |
| +// and drops anything nested, so the per-peer detail in `report` is |
| +// readable afterwards only from these (§15.29). |
| // |
| // Neither touches the database: the log is the only store. Neither log |
| // line carries the meeting's sqid, a peer id, a person, an email, a name |
| @@ -62,6 +72,8 @@ const ( |
| var ( |
| reportTokenPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| + reportRefPattern = regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{8}$`) |
| + regionPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`) |
| versionPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z.+-]{0,23}$`) |
| numericVersion = regexp.MustCompile(`^[0-9]{1,4}([._][0-9]{1,6}){0,3}$`) |
| @@ -165,6 +177,123 @@ func (a *app) problem(w http.ResponseWriter, r *http.Request) { |
| streamJSON(w, http.StatusOK, map[string]any{"ref": ref}) |
| } |
| +// autoReport is POST /m/{sqid}/auto-report (spec §15.29): the client's |
| +// own "Report a problem" when its call is struggling. Authorized, sized |
| +// and scrubbed as a problem report is; switched off with the quality |
| +// reports, because nobody asked for it; and limited to one every ten |
| +// minutes and three in all per participation. |
| +func (a *app) autoReport(w http.ResponseWriter, r *http.Request) { |
| + if !a.cfg.qualityReports { |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + rep, sqid, ok := a.reporter(w, r) |
| + if !ok { |
| + return |
| + } |
| + // Refused before the body is read when the participation has none to |
| + // spend; spent only once the report is taken, so a refused body does |
| + // not use up one of the call's three. |
| + if allowed, retry := a.autoGate.check(rep.PeerTag, a.store.now()); !allowed { |
| + rateRefused(w, retry) |
| + return |
| + } |
| + raw, ok := readReport(w, r, protocol.MaxProblemBody) |
| + if !ok { |
| + return |
| + } |
| + p, ok := validateAuto(raw) |
| + if !ok { |
| + streamJSON(w, http.StatusBadRequest, map[string]any{"error": "bad-request"}) |
| + return |
| + } |
| + if allowed, retry := a.autoGate.allow(rep.PeerTag, a.store.now()); !allowed { |
| + rateRefused(w, retry) // another got there while this one was read |
| + return |
| + } |
| + ref := newReportRef() |
| + a.logAuto(rep, sqid, ref, p) |
| + streamJSON(w, http.StatusOK, map[string]any{"ref": ref}) |
| +} |
| + |
| +// validateAuto takes a trigger the schema names and the client as every |
| +// report does. A note, if a client sent one, is not a member of the |
| +// schema and is dropped unread. |
| +func validateAuto(raw []byte) (protocol.AutoReport, bool) { |
| + var p protocol.AutoReport |
| + if !utf8.Valid(raw) || json.Unmarshal(raw, &p) != nil { |
| + return p, false |
| + } |
| + if !slices.Contains(protocol.AutoTriggers, p.Trigger) || !validClient(&p.Client) { |
| + return p, false |
| + } |
| + return p, true |
| +} |
| + |
| +// autoReportGate is the automatic report's limit, per participation tag: |
| +// one every AutoReportEveryMinutes, and AutoReportsPerCall in all. Not a |
| +// token bucket, because the bucket forgets a key idle for a minute and |
| +// this has to remember one for the length of a call. Bounded: past |
| +// maxKeys the entry sent longest ago goes. |
| +type autoReportGate struct { |
| + mu sync.Mutex |
| + maxKeys int |
| + sent map[string]autoSent |
| +} |
| + |
| +type autoSent struct { |
| + n int |
| + last time.Time |
| +} |
| + |
| +func newAutoReportGate(maxKeys int) *autoReportGate { |
| + return &autoReportGate{maxKeys: maxKeys, sent: map[string]autoSent{}} |
| +} |
| + |
| +// check says whether key may send one now, spending nothing, or how |
| +// long until it may. |
| +func (g *autoReportGate) check(key string, now time.Time) (bool, time.Duration) { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + return g.mayLocked(key, now) |
| +} |
| + |
| +func (g *autoReportGate) mayLocked(key string, now time.Time) (bool, time.Duration) { |
| + every := protocol.AutoReportEveryMinutes * time.Minute |
| + e, found := g.sent[key] |
| + if found && e.n >= protocol.AutoReportsPerCall { |
| + // A tag lives one participation, so "never again" is honest; the |
| + // header says the longest a client would wait anyway. |
| + return false, every |
| + } |
| + if found && now.Sub(e.last) < every { |
| + return false, every - now.Sub(e.last) |
| + } |
| + return true, 0 |
| +} |
| + |
| +// allow spends one of key's reports, or says how long until the next. |
| +func (g *autoReportGate) allow(key string, now time.Time) (bool, time.Duration) { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + if ok, retry := g.mayLocked(key, now); !ok { |
| + return false, retry |
| + } |
| + e, found := g.sent[key] |
| + if !found && len(g.sent) >= g.maxKeys { |
| + var oldest string |
| + var at time.Time |
| + for k, v := range g.sent { |
| + if oldest == "" || v.last.Before(at) { |
| + oldest, at = k, v.last |
| + } |
| + } |
| + delete(g.sent, oldest) |
| + } |
| + g.sent[key] = autoSent{n: e.n + 1, last: now} |
| + return true, 0 |
| +} |
| + |
| // validateQuality is the strict half: the schema's types (a mistyped |
| // member fails the decode), its enums, its bounds and its version. A |
| // member the schema does not name is ignored, never logged: the log line |
| @@ -199,12 +328,23 @@ func validateQuality(raw []byte) (protocol.QualityReport, bool) { |
| } |
| if p.Out != nil { |
| for _, s := range []*protocol.OutStream{p.Out.Audio, p.Out.Video, p.Out.Screen} { |
| - if s != nil && !enumOrEmpty(s.Limit, protocol.QualityLimits) { |
| + if s != nil && (!enumOrEmpty(s.Limit, protocol.QualityLimits) || !enumOrEmpty(s.Encoder, protocol.CoderKinds) || |
| + !enumOrEmpty(s.Codec, protocol.Codecs) || !enumOrEmpty(s.Mode, protocol.ShareModes)) { |
| + return q, false |
| + } |
| + } |
| + } |
| + if p.In != nil { |
| + for _, v := range []*protocol.InVideo{p.In.Video, p.In.Screen} { |
| + if v != nil && (!enumOrEmpty(v.Decoder, protocol.CoderKinds) || !enumOrEmpty(v.Codec, protocol.Codecs)) { |
| return q, false |
| } |
| } |
| } |
| } |
| + if q.AutoReport != "" && !reportRefPattern.MatchString(q.AutoReport) { |
| + return q, false |
| + } |
| // Every number, wherever it is: finite, non-negative, under its |
| // ceiling, and rounded to a tenth for the line. |
| if !boundNumbers(reflect.ValueOf(&q).Elem(), "") { |
| @@ -237,9 +377,10 @@ func enumOrEmpty(v string, allowed []string) bool { return v == "" || slices.Con |
| // numberCeiling is a number's bound, by its JSON name. |
| func numberCeiling(name string) float64 { |
| switch name { |
| - case "seconds", "reconnectingSeconds", "cantHearSeconds", "freezeSeconds": |
| + case "seconds", "reconnectingSeconds", "cantHearSeconds", "freezeSeconds", |
| + "limitedBandwidthSeconds", "limitedCpuSeconds": |
| return protocol.MaxQualitySeconds |
| - case "rtt", "jitter", "jitterBufferMs": |
| + case "rtt", "jitter", "jitterBufferMs", "rttAvg", "rttMax", "jitterAvg", "jitterMax": |
| return protocol.MaxQualityMillis |
| case "kbps": |
| return protocol.MaxQualityKbps |
| @@ -308,13 +449,17 @@ func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) { |
| for i := range q.Peers { |
| q.Peers[i].Peer = protocol.PeerID(tagOrUnknown(rep, q.Peers[i].Peer)) |
| } |
| + // `report` is what the head's own fields do not say about the whole |
| + // call from here. Each remote peer's part is its own `calls: quality |
| + // peer` line (§15.29), not a member of this one: carlos prints neither |
| + // a nested member nor more than 8 KB of a line, and four peers' |
| + // detail would be both. |
| body := struct { |
| - Seconds *float64 `json:"seconds"` |
| - Final bool `json:"final,omitempty"` |
| - Devices *protocol.Devices `json:"devices,omitempty"` |
| - Events *protocol.CallEvents `json:"events,omitempty"` |
| - Peers []protocol.PeerQuality `json:"peers,omitempty"` |
| - }{q.Seconds, q.Final, q.Devices, q.Events, q.Peers} |
| + Seconds *float64 `json:"seconds"` |
| + Final bool `json:"final,omitempty"` |
| + Devices *protocol.Devices `json:"devices,omitempty"` |
| + Events *protocol.CallEvents `json:"events,omitempty"` |
| + }{q.Seconds, q.Final, q.Devices, q.Events} |
| attrs := append(clientAttrs(rep, q.Client), |
| slog.Bool("final", q.Final), |
| slog.Float64("seconds", *q.Seconds), |
| @@ -334,8 +479,169 @@ func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) { |
| attrs = append(attrs, slog.Float64(f.name, f.v)) |
| } |
| } |
| + if q.AutoReport != "" { |
| + attrs = append(attrs, slog.String("autoReport", q.AutoReport)) |
| + } |
| attrs = append(attrs, slog.Any("report", body)) |
| a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality", attrs...) |
| + region := a.relayRegionName() |
| + for _, p := range q.Peers { |
| + a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality peer", peerAttrs(rep, p, region)...) |
| + } |
| +} |
| + |
| +// relayRegionName is the relay's region for a line whose path went |
| +// through it: known while one region is configured, which is all a |
| +// relayed path can have used. With several, the client's candidate says |
| +// nothing the schema carries about which, and the field is left off. |
| +func (a *app) relayRegionName() string { |
| + regions := a.relayRegions() |
| + if len(regions) != 1 || !regionPattern.MatchString(regions[0].Region) { |
| + return "" |
| + } |
| + return regions[0].Region |
| +} |
| + |
| +// peerAttrs is one `calls: quality peer` line (spec §15.29): one remote |
| +// peer's part of a report, flattened into scalar fields so that `carlos |
| +// logs`, which prints a line's top level and nothing nested, shows all of |
| +// it. Every field is one the report validated — an enum, a bounded |
| +// number, a boolean — under a fixed name; a part the client did not |
| +// measure is left off, never written as zero. `p.Peer` is already the |
| +// remote peer's tag. The names are camelCase letters and digits only, |
| +// because quality-summary reads carlos's key=value records by them. |
| +func peerAttrs(rep hub.Reporter, p protocol.PeerQuality, region string) []slog.Attr { |
| + attrs := []slog.Attr{slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), slog.String("remote", string(p.Peer))} |
| + num := func(name string, v *float64) { |
| + if v != nil { |
| + attrs = append(attrs, slog.Float64(name, *v)) |
| + } |
| + } |
| + str := func(name, v string) { |
| + if v != "" { |
| + attrs = append(attrs, slog.String(name, v)) |
| + } |
| + } |
| + flag := func(name string, v bool) { |
| + if v { |
| + attrs = append(attrs, slog.Bool(name, true)) |
| + } |
| + } |
| + pct := func(name string, part, whole *float64, withPart bool) { |
| + if part == nil || whole == nil { |
| + return |
| + } |
| + n := *whole |
| + if withPart { |
| + n += *part |
| + } |
| + if n > 0 { |
| + attrs = append(attrs, slog.Float64(name, math.Round(1000**part/n)/10)) |
| + } |
| + } |
| + if path := p.Path; path != nil { |
| + str("pathLocal", path.Local) |
| + str("pathRemote", path.Remote) |
| + str("pathProtocol", path.Protocol) |
| + if path.Local == "relay" || path.Remote == "relay" { |
| + str("relayRegion", region) |
| + } |
| + } |
| + num("rtt", p.RTT) |
| + num("rttAvg", p.RTTAvg) |
| + num("rttMax", p.RTTMax) |
| + num("jitterAvg", p.JitterAvg) |
| + num("jitterMax", p.JitterMax) |
| + if c := p.Candidates; c != nil { |
| + num("candHost", c.Host) |
| + num("candSrflx", c.Srflx) |
| + num("candPrflx", c.Prflx) |
| + num("candRelay", c.Relay) |
| + num("candRemoteHost", c.RemoteHost) |
| + num("candRemoteSrflx", c.RemoteSrflx) |
| + num("candRemotePrflx", c.RemotePrflx) |
| + num("candRemoteRelay", c.RemoteRelay) |
| + // Present means measured, so false is said, not left off. |
| + attrs = append(attrs, slog.Bool("directOk", c.DirectOK), slog.Bool("localDirectOk", c.LocalDirectOK), slog.Bool("udpOk", c.UDPOK)) |
| + } |
| + if o := p.Out; o != nil { |
| + if s := o.Audio; s != nil { |
| + num("outAudioKbps", s.Kbps) |
| + pct("outAudioLossPct", s.Lost, s.Packets, false) |
| + num("outAudioRtt", s.RTT) |
| + } |
| + for _, v := range []struct { |
| + pre string |
| + s *protocol.OutStream |
| + }{{"outCamera", o.Video}, {"outScreen", o.Screen}} { |
| + s := v.s |
| + if s == nil { |
| + continue |
| + } |
| + num(v.pre+"Kbps", s.Kbps) |
| + num(v.pre+"Width", s.Width) |
| + num(v.pre+"Height", s.Height) |
| + num(v.pre+"Fps", s.FPS) |
| + pct(v.pre+"LossPct", s.Lost, s.Packets, false) |
| + str(v.pre+"Limit", s.Limit) |
| + num(v.pre+"LimitedBandwidthSeconds", s.LimitedBandwidthSeconds) |
| + num(v.pre+"LimitedCpuSeconds", s.LimitedCPUSeconds) |
| + str(v.pre+"Encoder", s.Encoder) |
| + str(v.pre+"Codec", s.Codec) |
| + str(v.pre+"Mode", s.Mode) |
| + num(v.pre+"Keyframes", s.Keyframes) |
| + num(v.pre+"Rebuilds", s.Rebuilds) |
| + num(v.pre+"Reshares", s.Reshares) |
| + num(v.pre+"Failures", s.Failures) |
| + num(v.pre+"Damped", s.Damped) |
| + num(v.pre+"EncoderStalls", s.EncoderStalls) |
| + } |
| + } |
| + if in := p.In; in != nil { |
| + if a := in.Audio; a != nil { |
| + num("inAudioKbps", a.Kbps) |
| + pct("inAudioLossPct", a.Lost, a.Packets, true) |
| + num("inAudioJitter", a.Jitter) |
| + pct("inAudioConcealedPct", a.Concealed, a.Samples, false) |
| + num("inAudioJitterBufferMs", a.JitterBufferMs) |
| + } |
| + for _, v := range []struct { |
| + pre string |
| + s *protocol.InVideo |
| + }{{"inCamera", in.Video}, {"inScreen", in.Screen}} { |
| + s := v.s |
| + if s == nil { |
| + continue |
| + } |
| + num(v.pre+"Kbps", s.Kbps) |
| + num(v.pre+"Width", s.Width) |
| + num(v.pre+"Height", s.Height) |
| + num(v.pre+"Fps", s.FPS) |
| + pct(v.pre+"LossPct", s.Lost, s.Packets, true) |
| + num(v.pre+"Freezes", s.Freezes) |
| + num(v.pre+"FreezeSeconds", s.FreezeSeconds) |
| + num(v.pre+"Decoded", s.Decoded) |
| + num(v.pre+"Dropped", s.Dropped) |
| + str(v.pre+"Decoder", s.Decoder) |
| + str(v.pre+"Codec", s.Codec) |
| + num(v.pre+"Reattaches", s.Reattaches) |
| + num(v.pre+"Stalls", s.Stalls) |
| + num(v.pre+"StallsNoPackets", s.StallsNoPackets) |
| + num(v.pre+"StallsUndecoded", s.StallsUndecoded) |
| + } |
| + } |
| + if e := p.Events; e != nil { |
| + num("reconnecting", e.Reconnecting) |
| + num("reconnectingSeconds", e.ReconnectingSeconds) |
| + num("cantHearSeconds", e.CantHearSeconds) |
| + flag("noSound", e.NoSound) |
| + flag("noSoundFromUs", e.NoSoundFromUs) |
| + flag("audioBlocked", e.AudioBlocked) |
| + flag("screenStalled", e.ScreenStalled) |
| + num("autoRestarts", e.AutoRestarts) |
| + num("autoRebuilds", e.AutoRebuilds) |
| + } |
| + return attrs |
| } |
| func clientAttrs(rep hub.Reporter, c protocol.ReportClient) []slog.Attr { |
| @@ -421,7 +727,7 @@ func summarize(q protocol.QualityReport) qualitySummary { |
| if p.Path != nil && (p.Path.Local == "relay" || p.Path.Remote == "relay") { |
| s.relay = true |
| } |
| - s.rtt = max(s.rtt, val(p.RTT)) |
| + s.rtt = max(s.rtt, val(p.RTT), val(p.RTTMax)) |
| if p.In != nil { |
| if p.In.Audio != nil { |
| loss(p.In.Audio.Packets, p.In.Audio.Lost) |
| @@ -449,15 +755,45 @@ func summarize(q protocol.QualityReport) qualitySummary { |
| // logProblem writes the report: one head line with the note, and the |
| // diagnostics in as many lines as they take, each under the reference. |
| -// |
| -// The diagnostics are the client's own text, and are scrubbed here of |
| -// what the client could not know to leave out: every peer id this call |
| -// has held, in full or as the six-character prefix the diagnostics use, |
| -// becomes "peer:<tag>", and the meeting's sqid becomes "[meeting]". A |
| -// client already writes "peer abc123" for a person instead of their |
| -// name; device names stay, which the spec says. |
| func (a *app) logProblem(rep hub.Reporter, sqid, ref string, p protocol.ProblemReport) { |
| - scrub := func(s string) string { |
| + scrub := scrubber(rep, sqid) |
| + attrs := append([]slog.Attr{slog.String("ref", ref)}, clientAttrs(rep, p.Client)...) |
| + attrs = append(attrs, slog.Bool("live", rep.Live), slog.String("note", scrub(p.Note))) |
| + a.logDiagnostics(rep, ref, "calls: problem report", attrs, scrub(p.Diagnostics)) |
| +} |
| + |
| +// logAuto writes an automatic report (spec §15.29) as logProblem writes a |
| +// problem report, under its own messages, with the rule that fired in |
| +// place of a note: nobody typed anything. |
| +func (a *app) logAuto(rep hub.Reporter, sqid, ref string, p protocol.AutoReport) { |
| + scrub := scrubber(rep, sqid) |
| + attrs := append([]slog.Attr{slog.String("ref", ref)}, clientAttrs(rep, p.Client)...) |
| + attrs = append(attrs, slog.Bool("live", rep.Live), slog.String("trigger", p.Trigger)) |
| + a.logDiagnostics(rep, ref, "calls: auto report", attrs, scrub(p.Diagnostics)) |
| +} |
| + |
| +// logDiagnostics writes a head line, msg, with attrs and how many parts |
| +// follow, and the diagnostics as `<msg> diagnostics` lines of at most |
| +// diagnosticsChunk escaped bytes each. |
| +func (a *app) logDiagnostics(rep hub.Reporter, ref, msg string, attrs []slog.Attr, diagnostics string) { |
| + chunks := chunkEscaped(diagnostics, diagnosticsChunk) |
| + attrs = append(attrs, slog.Int("parts", len(chunks))) |
| + a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, msg, attrs...) |
| + for i, c := range chunks { |
| + a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, msg+" diagnostics", |
| + slog.String("ref", ref), slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), |
| + slog.Int("part", i+1), slog.Int("of", len(chunks)), slog.String("text", c)) |
| + } |
| +} |
| + |
| +// scrubber cleans a report's text of what the client could not know to |
| +// leave out: every peer id this call has held, in full or as the |
| +// six-character prefix the diagnostics use, becomes "peer:<tag>", and the |
| +// meeting's sqid becomes "[meeting]". A client already writes "peer |
| +// abc123" for a person instead of their name; device names stay, which |
| +// the spec says. |
| +func scrubber(rep hub.Reporter, sqid string) func(string) string { |
| + return func(s string) string { |
| s = strings.ReplaceAll(s, sqid, "[meeting]") |
| for id, tag := range rep.Peers { |
| s = strings.ReplaceAll(s, string(id), "peer:"+tag) |
| @@ -467,16 +803,6 @@ func (a *app) logProblem(rep hub.Reporter, sqid, ref string, p protocol.ProblemR |
| } |
| return s |
| } |
| - note := scrub(p.Note) |
| - chunks := chunkEscaped(scrub(p.Diagnostics), diagnosticsChunk) |
| - attrs := append([]slog.Attr{slog.String("ref", ref)}, clientAttrs(rep, p.Client)...) |
| - attrs = append(attrs, slog.Bool("live", rep.Live), slog.String("note", note), slog.Int("parts", len(chunks))) |
| - a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, "calls: problem report", attrs...) |
| - for i, c := range chunks { |
| - a.reportLog.LogAttrs(context.Background(), slog.LevelWarn, "calls: problem report diagnostics", |
| - slog.String("ref", ref), slog.String("call", rep.CallTag), slog.String("peer", rep.PeerTag), |
| - slog.Int("part", i+1), slog.Int("of", len(chunks)), slog.String("text", c)) |
| - } |
| } |
| // chunkEscaped splits s into pieces whose JSON-escaped length is at most |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 82a46ac..4dd4a69 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -395,6 +395,22 @@ |
| // counted as time a notice was showing: a suspended tab's timers stop, |
| // and the gap when they start again is not a notice someone saw. |
| const QUALITY_LOOK_MAX = 1000; |
| + // §15.29 (2026-10-28), the automatic "Report a problem": what counts as |
| + // a call struggling, and how often this tab may say so. The rules are |
| + // protocol/quality.go's, which the server enforces on its own: inbound |
| + // freezes at least AUTO_FREEZES in this window and the one before it; |
| + // the window's highest round trip above AUTO_RTT_MS in both; a |
| + // "Reconnecting…" showing longer than AUTO_RECONNECTING_SECONDS in one |
| + // window; or the screen's ladder past its keyframes. At most |
| + // AUTO_REPORTS_PER_CALL in one participation, at least AUTO_REPORT_EVERY |
| + // apart. AUTO_BODY_MAX is report.js's BODY_MAX: the server's 64 KB, less |
| + // a margin. |
| + const AUTO_FREEZES = 3; |
| + const AUTO_RTT_MS = 800; |
| + const AUTO_RECONNECTING_SECONDS = 5; |
| + const AUTO_REPORTS_PER_CALL = 3; |
| + const AUTO_REPORT_EVERY = 600000; |
| + const AUTO_BODY_MAX = 65024; |
| // §5.4, sending: "Optimise shared screen for". What a screen gives up |
| // first when the uplink or the encoder cannot carry all of it. The |
| // first is the default; sharePlan says what each one means. |
| @@ -601,7 +617,18 @@ |
| let qualityServerOff = false; |
| let qualityLocalOff = false; // the switch, where there is no storage to keep it in |
| let qualityFinalSent = false; |
| - const quality = { sent: 0, accepted: 0, status: 0 }; |
| + const quality = { sent: 0, accepted: 0, status: 0, auto: { sent: 0, status: 0, refs: [], reported: 0 } }; |
| + // §15.29: the window's once-a-second readings of each connection's |
| + // round trip and inbound jitter (peer id -> qualitySample's record), |
| + // emptied by every report; the facts the last window's report held, |
| + // for the rules that need two windows in a row; the automatic report's |
| + // gate for this participation ({token, count, last}); and the gate's |
| + // forced trigger (window.meet.autoReportForTest), spent by the next |
| + // window. |
| + const qualitySamples = new Map(); |
| + let autoPrevFacts = null; |
| + let autoGate = autoReportGate(null, ''); |
| + let autoForce = ''; |
| // How many rosters this tab has applied. Nothing in the page reads |
| // it: it is the one fact a gate cannot infer from the DOM or from |
| // `peers`, because a connection can be closed locally without any |
| @@ -4871,8 +4898,10 @@ |
| function qualityCeiling(name) { |
| switch (name) { |
| case 'seconds': case 'reconnectingSeconds': case 'cantHearSeconds': case 'freezeSeconds': |
| + case 'limitedBandwidthSeconds': case 'limitedCpuSeconds': |
| return QUALITY_MAX_SECONDS; |
| case 'rtt': case 'jitter': case 'jitterBufferMs': |
| + case 'rttAvg': case 'rttMax': case 'jitterAvg': case 'jitterMax': |
| return QUALITY_MAX_MILLIS; |
| case 'kbps': |
| return QUALITY_MAX_KBPS; |
| @@ -4904,6 +4933,25 @@ |
| // copied by name from the lists below and nothing else is: a |
| // candidate's address and port never leave this function. Pure, and |
| // lifted by name in test/browser/room-quality.test.mjs. |
| + // |
| + // §15.29 (2026-10-28) reads more of the same walk, by name as before. |
| + // An outbound stream's encoder and an inbound one's decoder, as the |
| + // implementation's name and the browser's own hardware-or-not, kept |
| + // here only for coderKind to turn into an enum: "VideoToolbox" or |
| + // "libvpx" is read and never reported. The codec by its MIME type, |
| + // through the stream's codecId. The encoder's qualityLimitationDurations |
| + // — seconds held back by each reason since the stream began — as four |
| + // counters (limitNone, limitCpu, limitBandwidth, limitOther), so a |
| + // window can say which reason held it back longest rather than which |
| + // one happened to hold at the moment it ended. The selected pair's |
| + // totalRoundTripTime and responsesReceived, for the window's mean round |
| + // trip, and the pair's id, so the next window knows the counters are the |
| + // same pair's (an id of the stats walk's own: never an address, and it |
| + // never leaves qualityPeer). And `candidates`: what this side gathered |
| + // and what it was offered, by type, and which kinds of pair succeeded — |
| + // whether any had neither end a relay (directOk), any had this side's |
| + // end not a relay (localDirectOk), and any went over UDP the whole way |
| + // to the peer or the relay (udpOk). Types and counts only. |
| function qualityReading(reports, classify) { |
| const COUNTERS = { |
| out: ['bytesSent', 'packetsSent'], |
| @@ -4913,10 +4961,12 @@ |
| 'jitterBufferEmittedCount', 'freezeCount', 'totalFreezesDuration', 'framesDecoded', 'framesDropped'], |
| }; |
| const GAUGES = { |
| - out: ['frameWidth', 'frameHeight', 'framesPerSecond', 'qualityLimitationReason'], |
| + out: ['frameWidth', 'frameHeight', 'framesPerSecond', 'qualityLimitationReason', 'encoderImplementation', |
| + 'powerEfficientEncoder'], |
| remote: ['roundTripTime', 'jitter'], |
| - in: ['jitter', 'frameWidth', 'frameHeight', 'framesPerSecond'], |
| + in: ['jitter', 'frameWidth', 'frameHeight', 'framesPerSecond', 'decoderImplementation', 'powerEfficientDecoder'], |
| }; |
| + const LIMITS = [['none', 'limitNone'], ['cpu', 'limitCpu'], ['bandwidth', 'limitBandwidth'], ['other', 'limitOther']]; |
| const all = []; |
| const byId = new Map(); |
| if (reports && typeof reports.forEach === 'function') { |
| @@ -4931,7 +4981,17 @@ |
| const counters = {}; |
| const gauges = {}; |
| for (const n of COUNTERS[dir]) if (typeof r[n] === 'number') counters[n] = r[n]; |
| - for (const n of GAUGES[dir]) if (typeof r[n] === 'number' || typeof r[n] === 'string') gauges[n] = r[n]; |
| + for (const n of GAUGES[dir]) { |
| + if (typeof r[n] === 'number' || typeof r[n] === 'string' || typeof r[n] === 'boolean') gauges[n] = r[n]; |
| + } |
| + if (dir === 'out' && r.qualityLimitationDurations && typeof r.qualityLimitationDurations === 'object') { |
| + for (const [reason, name] of LIMITS) { |
| + const v = r.qualityLimitationDurations[reason]; |
| + if (typeof v === 'number') counters[name] = v; |
| + } |
| + } |
| + const codec = dir !== 'remote' && r.codecId ? byId.get(r.codecId) : null; |
| + if (codec && codec.type === 'codec' && typeof codec.mimeType === 'string') gauges.mimeType = codec.mimeType; |
| streams.set(key, { dir, kind, counters, gauges }); |
| }; |
| for (const r of all) { |
| @@ -4971,9 +5031,107 @@ |
| remote: kinds.includes(remote.candidateType) ? remote.candidateType : 'unknown', |
| protocol: transport, |
| rtt: typeof pair.currentRoundTripTime === 'number' ? pair.currentRoundTripTime * 1000 : undefined, |
| + pair: typeof pair.id === 'string' ? pair.id : '', |
| + totalRoundTripTime: typeof pair.totalRoundTripTime === 'number' ? pair.totalRoundTripTime : undefined, |
| + responsesReceived: typeof pair.responsesReceived === 'number' ? pair.responsesReceived : undefined, |
| }; |
| } |
| - return { streams, path }; |
| + // §15.29: the candidates, by type, and the pairs that worked. |
| + let candidates = null; |
| + const types = ['host', 'srflx', 'prflx', 'relay']; |
| + for (const r of all) { |
| + if (r.type !== 'local-candidate' && r.type !== 'remote-candidate') continue; |
| + if (!candidates) { |
| + candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0 }, |
| + directOk: false, localDirectOk: false, udpOk: false }; |
| + } |
| + const side = r.type === 'local-candidate' ? candidates.local : candidates.remote; |
| + if (types.includes(r.candidateType)) side[r.candidateType] += 1; |
| + } |
| + if (candidates) { |
| + for (const r of all) { |
| + if (r.type !== 'candidate-pair' || r.state !== 'succeeded') continue; |
| + const local = byId.get(r.localCandidateId); |
| + const remote = byId.get(r.remoteCandidateId); |
| + if (!local || !types.includes(local.candidateType)) continue; |
| + const localRelay = local.candidateType === 'relay'; |
| + if (!localRelay) candidates.localDirectOk = true; |
| + if (!localRelay && remote && types.includes(remote.candidateType) && remote.candidateType !== 'relay') { |
| + candidates.directOk = true; |
| + } |
| + if (local.protocol === 'udp' && (!localRelay || local.relayProtocol === 'udp')) candidates.udpOk = true; |
| + } |
| + } |
| + return { streams, path, candidates }; |
| + } |
| + |
| + // coderKind is a video encoder's or decoder's kind (§15.29): 'hardware' |
| + // or 'software', or 'unknown' for an implementation it cannot place, and |
| + // '' — left out of the report — when the browser said nothing at all. |
| + // The browser's own powerEfficientEncoder/Decoder is the better word |
| + // where it gives one; otherwise the implementation's name, which never |
| + // leaves this function ("ExternalEncoder", "VideoToolbox", "libvpx", |
| + // "OpenH264", "FallbackEncoder (…)"). Pure, and lifted by name in the |
| + // node test. |
| + function coderKind(impl, powerEfficient) { |
| + if (typeof powerEfficient === 'boolean') return powerEfficient ? 'hardware' : 'software'; |
| + const name = typeof impl === 'string' ? impl : ''; |
| + if (!name) return ''; |
| + if (/videotoolbox|external|mediacodec|vaapi|v4l2|d3d11|dxva|nvenc|nvdec|mediafoundation|qsv|amf/i.test(name)) { |
| + return 'hardware'; |
| + } |
| + if (/libvpx|openh264|libaom|dav1d|ffmpeg|libav|fallback|software/i.test(name)) return 'software'; |
| + return 'unknown'; |
| + } |
| + |
| + // codecKind is a stream's codec family (protocol.Codecs) from its MIME |
| + // type: '' when there is none, 'other' for one not on the list. Pure, |
| + // and lifted by name in the node test. |
| + function codecKind(mimeType) { |
| + const m = typeof mimeType === 'string' ? mimeType.toLowerCase() : ''; |
| + if (!m) return ''; |
| + if (m === 'video/vp8') return 'vp8'; |
| + if (m === 'video/vp9') return 'vp9'; |
| + if (m === 'video/h264') return 'h264'; |
| + if (m === 'video/h265' || m === 'video/hevc') return 'h265'; |
| + if (m === 'video/av1') return 'av1'; |
| + if (m === 'audio/opus') return 'opus'; |
| + return 'other'; |
| + } |
| + |
| + // qualitySample is one look of the window's sampler (§15.29): the |
| + // selected pair's round trip and the peer's inbound jitter as one stats |
| + // walk has them, taken once a second by qualityTick, so a window can |
| + // say how high the round trip went and what the jitter was on average |
| + // rather than only what the last walk said. The jitter is the peer's |
| + // audio, or their camera when no audio arrives. `acc` is the record |
| + // so far, or null for a new one; returns it. Pure, and lifted by name |
| + // in the node test. |
| + function qualitySample(acc, reading) { |
| + const a = acc || { rttSum: 0, rttN: 0, rttMax: 0, jitterSum: 0, jitterN: 0, jitterMax: 0 }; |
| + const rtt = reading && reading.path ? reading.path.rtt : undefined; |
| + if (typeof rtt === 'number' && Number.isFinite(rtt) && rtt >= 0) { |
| + a.rttSum += rtt; |
| + a.rttN += 1; |
| + a.rttMax = Math.max(a.rttMax, rtt); |
| + } |
| + let jitter; |
| + for (const kind of ['audio', 'video']) { |
| + if (reading && reading.streams) { |
| + for (const s of reading.streams.values()) { |
| + const j = s.gauges.jitter; |
| + if (s.dir !== 'in' || s.kind !== kind || typeof j !== 'number' || !Number.isFinite(j) || j < 0) continue; |
| + jitter = Math.max(jitter === undefined ? 0 : jitter, j * 1000); |
| + } |
| + } |
| + if (jitter !== undefined) break; |
| + } |
| + if (jitter !== undefined) { |
| + a.jitterSum += jitter; |
| + a.jitterN += 1; |
| + a.jitterMax = Math.max(a.jitterMax, jitter); |
| + } |
| + return a; |
| } |
| // qualityPeer is one remote peer's statistics for a window: what moved |
| @@ -4985,7 +5143,20 @@ |
| // a new transceiver during the window) add up. Returns {path, rtt, out, |
| // in} with whatever parts there is something for. Pure, and lifted by |
| // name in the node test. |
| - function qualityPeer(prev, now, seconds) { |
| + // |
| + // §15.29 (2026-10-28): `sample` is qualitySample's record for the |
| + // window, or null. The peer gains the window's round trip — its mean, |
| + // the pair's own total over its responses where the pair is the one |
| + // the last window had (a new pair counts from nothing, as a new stream |
| + // does), else the once-a-second readings' mean; its highest, of those |
| + // readings and the last walk's — and the inbound jitter's mean and |
| + // highest, and the candidates. A camera's or screen's limit is the |
| + // reason that held its encoder back longest in the window, where the |
| + // stack keeps the durations (a tie goes to bandwidth, then cpu, then |
| + // other, then none, the reasons that say most first), and how long |
| + // bandwidth and the cpu each held it back; the encoder and decoder are |
| + // coderKind's enum and the codec codecKind's. |
| + function qualityPeer(prev, now, seconds, sample) { |
| const sums = new Map(); |
| for (const [key, s] of now.streams) { |
| const p = prev && prev.streams ? prev.streams.get(key) : null; |
| @@ -5003,6 +5174,8 @@ |
| const v = s.gauges[n]; |
| if (typeof v === 'string') { |
| if (!b.g[n] || b.g[n] === 'none') b.g[n] = v; |
| + } else if (typeof v === 'boolean') { |
| + if (typeof b.g[n] !== 'boolean') b.g[n] = v; |
| } else { |
| b.g[n] = typeof b.g[n] === 'number' ? Math.max(b.g[n], v) : v; |
| } |
| @@ -5025,7 +5198,26 @@ |
| qualitySet(s, 'width', o.g.frameWidth); |
| qualitySet(s, 'height', o.g.frameHeight); |
| qualitySet(s, 'fps', o.g.framesPerSecond); |
| - if (limits.includes(o.g.qualityLimitationReason)) s.limit = o.g.qualityLimitationReason; |
| + // Bandwidth first, so a tie is named for the reason that says |
| + // most; and only a reason that held for some of the window. |
| + let dominant = ''; |
| + let longest = 0; |
| + for (const [reason, name] of [['bandwidth', 'limitBandwidth'], ['cpu', 'limitCpu'], ['other', 'limitOther'], |
| + ['none', 'limitNone']]) { |
| + const d = o.d[name]; |
| + if (typeof d === 'number' && d > longest) { |
| + dominant = reason; |
| + longest = d; |
| + } |
| + } |
| + if (dominant) s.limit = dominant; |
| + else if (limits.includes(o.g.qualityLimitationReason)) s.limit = o.g.qualityLimitationReason; |
| + qualitySet(s, 'limitedBandwidthSeconds', o.d.limitBandwidth); |
| + qualitySet(s, 'limitedCpuSeconds', o.d.limitCpu); |
| + const encoder = coderKind(o.g.encoderImplementation, o.g.powerEfficientEncoder); |
| + if (encoder) s.encoder = encoder; |
| + const codec = codecKind(o.g.mimeType); |
| + if (codec) s.codec = codec; |
| } |
| } |
| if (ri) { |
| @@ -5058,6 +5250,10 @@ |
| qualitySet(s, 'width', i.g.frameWidth); |
| qualitySet(s, 'height', i.g.frameHeight); |
| qualitySet(s, 'fps', i.g.framesPerSecond); |
| + const decoder = coderKind(i.g.decoderImplementation, i.g.powerEfficientDecoder); |
| + if (decoder) s.decoder = decoder; |
| + const codec = codecKind(i.g.mimeType); |
| + if (codec) s.codec = codec; |
| } |
| if (Object.keys(s).length) inbound[kind] = s; |
| } |
| @@ -5069,6 +5265,38 @@ |
| qualitySet(r, 'rtt', now.path.rtt); |
| if ('rtt' in r) peer.rtt = r.rtt; |
| } |
| + const smp = sample || null; |
| + const was = prev && prev.path && now.path && prev.path.pair && prev.path.pair === now.path.pair ? prev.path : null; |
| + const responses = now.path && typeof now.path.responsesReceived === 'number' |
| + ? now.path.responsesReceived - (was && typeof was.responsesReceived === 'number' ? was.responsesReceived : 0) |
| + : 0; |
| + const total = now.path && typeof now.path.totalRoundTripTime === 'number' |
| + ? now.path.totalRoundTripTime - (was && typeof was.totalRoundTripTime === 'number' ? was.totalRoundTripTime : 0) |
| + : -1; |
| + const rtts = {}; |
| + if (responses > 0 && total >= 0) qualitySet(rtts, 'rttAvg', (total / responses) * 1000); |
| + else if (smp && smp.rttN > 0) qualitySet(rtts, 'rttAvg', smp.rttSum / smp.rttN); |
| + const highest = Math.max(smp && smp.rttN > 0 ? smp.rttMax : -1, |
| + now.path && typeof now.path.rtt === 'number' && Number.isFinite(now.path.rtt) ? now.path.rtt : -1); |
| + qualitySet(rtts, 'rttMax', highest); |
| + if (smp && smp.jitterN > 0) { |
| + qualitySet(rtts, 'jitterAvg', smp.jitterSum / smp.jitterN); |
| + qualitySet(rtts, 'jitterMax', smp.jitterMax); |
| + } |
| + Object.assign(peer, rtts); |
| + if (now.candidates) { |
| + const c = {}; |
| + for (const t of ['host', 'srflx', 'prflx', 'relay']) { |
| + if (now.candidates.local[t] > 0) qualitySet(c, t, now.candidates.local[t]); |
| + if (now.candidates.remote[t] > 0) { |
| + qualitySet(c, 'remote' + t.charAt(0).toUpperCase() + t.slice(1), now.candidates.remote[t]); |
| + } |
| + } |
| + c.directOk = !!now.candidates.directOk; |
| + c.localDirectOk = !!now.candidates.localDirectOk; |
| + c.udpOk = !!now.candidates.udpOk; |
| + peer.candidates = c; |
| + } |
| if (Object.keys(out).length) peer.out = out; |
| if (Object.keys(inbound).length) peer.in = inbound; |
| return peer; |
| @@ -5185,6 +5413,12 @@ |
| // that did not happen are left out rather than sent as zeros: the line |
| // the server writes has a size limit, and absent means none. Pure, and |
| // lifted by name in the node test. |
| + // |
| + // §15.29: each peer's `sample` is qualitySample's record for the window; |
| + // `o.shareMode` is the screen's share mode while this tab shares |
| + // (shareMode(), passed in so this stays pure), written on every screen |
| + // leaving for someone; and `o.autoReport` the reference of the |
| + // automatic report sent with this window, if one was. |
| function qualityReport(o) { |
| const report = { v: 1 }; |
| if (o.final) report.final = true; |
| @@ -5196,7 +5430,7 @@ |
| for (const p of o.peers || []) { |
| if (peers.length >= QUALITY_MAX_PEERS) break; |
| if (typeof p.id !== 'string' || !/^[0-9a-f]{32}$/.test(p.id)) continue; |
| - const q = qualityPeer(p.prev, p.now, o.seconds); |
| + const q = qualityPeer(p.prev, p.now, o.seconds, p.sample || null); |
| const ladder = {}; |
| for (const k of ['keyframes', 'rebuilds', 'reshares', 'failures', 'damped']) { |
| if (p.ladder && p.ladder[k] > 0) qualitySet(ladder, k, p.ladder[k]); |
| @@ -5215,14 +5449,113 @@ |
| if (p.stalls.undecoded > 0) qualitySet(q.in.screen, 'stallsUndecoded', p.stalls.undecoded); |
| } |
| } |
| + if (q.out && q.out.screen && ['balanced', 'detail', 'motion'].includes(o.shareMode)) q.out.screen.mode = o.shareMode; |
| if (p.events && Object.keys(p.events).length) q.events = p.events; |
| if (!Object.keys(q).length) continue; |
| peers.push(Object.assign({ peer: p.id }, q)); |
| } |
| if (peers.length) report.peers = peers; |
| + if (typeof o.autoReport === 'string' && /^[0-9A-Z]{8}$/.test(o.autoReport)) report.autoReport = o.autoReport; |
| return report; |
| } |
| + // --------------------------------------------------------------- |
| + // The automatic report (§15.29, 2026-10-28) |
| + // --------------------------------------------------------------- |
| + // |
| + // Paul, 2026-10-28: the calls that go wrong without anyone pressing |
| + // Report a problem are the ones §15.26's numbers can only half explain, |
| + // so a tab whose call is struggling sends Report a problem on its own — |
| + // the same anonymous diagnostics, no note, and which rule fired — and |
| + // names the reference it was given in that window's quality report, so |
| + // the numbers and the words can be read together. Nothing is shown to |
| + // the person. It rides on their "Send anonymous quality reports": off, |
| + // and nothing automatic is sent either; the server's kill switch stops |
| + // it too. Never with the final report, at most three times in one |
| + // participation and ten minutes apart, which the server holds as well. |
| + |
| + // qualityFacts is what the rules read from one window's report: inbound |
| + // freezes, camera and screen, summed over everyone; the highest round |
| + // trip anywhere in it (the window's highest reading, the last, and the |
| + // far side's own account of what we send); the longest "Reconnecting…", |
| + // the call's or anyone's; and whether the screen's ladder went past its |
| + // keyframes for anybody. Pure, and lifted by name in the node test. |
| + function qualityFacts(report) { |
| + const facts = { freezes: 0, maxRtt: 0, reconnectingSeconds: 0, screenEscalated: false }; |
| + const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0); |
| + if (report && report.events) facts.reconnectingSeconds = num(report.events.reconnectingSeconds); |
| + for (const p of (report && report.peers) || []) { |
| + if (p.in) facts.freezes += num(p.in.video && p.in.video.freezes) + num(p.in.screen && p.in.screen.freezes); |
| + facts.maxRtt = Math.max(facts.maxRtt, num(p.rttMax), num(p.rtt)); |
| + if (p.out) { |
| + for (const s of Object.values(p.out)) facts.maxRtt = Math.max(facts.maxRtt, num(s && s.rtt)); |
| + const sc = p.out.screen; |
| + if (sc && num(sc.rebuilds) + num(sc.reshares) + num(sc.failures) > 0) facts.screenEscalated = true; |
| + } |
| + if (p.events) facts.reconnectingSeconds = Math.max(facts.reconnectingSeconds, num(p.events.reconnectingSeconds)); |
| + } |
| + return facts; |
| + } |
| + |
| + // qualityTrouble is the first rule that holds, in protocol.AutoTriggers' |
| + // order, or '': freezes and a high round trip need this window and the |
| + // one before it (`prev`, null for the first), so one bad moment is not a |
| + // struggling call; a long "Reconnecting…" and a screen that needed more |
| + // than keyframes are enough in one. Pure, and lifted by name in the |
| + // node test. |
| + function qualityTrouble(prev, facts) { |
| + if (prev && prev.freezes >= AUTO_FREEZES && facts.freezes >= AUTO_FREEZES) return 'freezes'; |
| + if (prev && prev.maxRtt > AUTO_RTT_MS && facts.maxRtt > AUTO_RTT_MS) return 'rtt'; |
| + if (facts.reconnectingSeconds > AUTO_RECONNECTING_SECONDS) return 'reconnecting'; |
| + if (facts.screenEscalated) return 'screen'; |
| + return ''; |
| + } |
| + |
| + // autoReportGate is the gate for the participation `token` names: the |
| + // one it was, while the token is the same (a resumed stream's hello |
| + // carries the same token), and a fresh one for a new participation. |
| + // Pure, and lifted by name in the node test. |
| + function autoReportGate(gate, token) { |
| + if (gate && gate.token === token) return gate; |
| + return { token, count: 0, last: null }; |
| + } |
| + |
| + // autoReportAllowed: fewer than AUTO_REPORTS_PER_CALL sent in this |
| + // participation, and none in the last AUTO_REPORT_EVERY. Pure, and |
| + // lifted by name in the node test. |
| + function autoReportAllowed(gate, now) { |
| + return gate.count < AUTO_REPORTS_PER_CALL && (gate.last === null || now - gate.last >= AUTO_REPORT_EVERY); |
| + } |
| + |
| + // autoReportDecision is the whole of whether this window sends an |
| + // automatic report, and on which rule: never with the final report, |
| + // never with the person's switch off, the server's kill switch thrown |
| + // or no token; then the rule that holds — or `force`, the gate's test |
| + // hook, standing in for one — if the gate allows. Returns the trigger |
| + // or ''. Pure, and lifted by name in the node test. |
| + function autoReportDecision(o) { |
| + if (o.final || !o.on || o.serverOff || !o.token) return ''; |
| + const forced = ['freezes', 'rtt', 'reconnecting', 'screen'].includes(o.force) ? o.force : ''; |
| + const trigger = forced || qualityTrouble(o.prevFacts || null, o.facts); |
| + if (!trigger || !autoReportAllowed(o.gate, o.now)) return ''; |
| + return trigger; |
| + } |
| + |
| + // autoReportBody is protocol.AutoReport as JSON, at most `max` bytes: |
| + // report.js's problemBody's rule, the diagnostics cut short from the end |
| + // with a line saying so — the state of the call comes first. Pure, and |
| + // lifted by name in the node test. |
| + function autoReportBody(trigger, diagnostics, client, max) { |
| + const size = (x) => (typeof TextEncoder === 'function' ? new TextEncoder().encode(x).length : x.length * 3); |
| + let d = String(diagnostics || ''); |
| + let body = JSON.stringify({ trigger, diagnostics: d, client }); |
| + while (size(body) > max && d.length > 0) { |
| + d = d.slice(0, Math.floor(d.length * 0.9)); |
| + body = JSON.stringify({ trigger, diagnostics: d + '\n[cut short to fit]', client }); |
| + } |
| + return body; |
| + } |
| + |
| // deviceKind is a microphone's or speaker's kind, by its label, which |
| // never leaves this function: only the enum is reported. A heuristic, |
| // and an honest one — what it cannot place is 'unknown'. Pure, and |
| @@ -5299,6 +5632,14 @@ |
| // leave or at the end, sent once with keepalive so it survives the page |
| // going. Never retried, and never said to the person: a report that |
| // did not arrive is one fewer line in a log. |
| + // |
| + // §15.29: the report is built whatever the switches say, because the |
| + // rules that need two windows in a row read the last window's facts, |
| + // sent or not. When a rule holds and autoReportDecision lets it, the |
| + // automatic report goes first, and the quality report follows it naming |
| + // the reference it was given: a 204 is the kill switch, and nothing more |
| + // is sent; any other refusal, or no answer, and the quality report goes |
| + // without one. |
| function sendQuality(final) { |
| if (!qualityFrom || (final && qualityFinalSent)) return; |
| if (final) qualityFinalSent = true; |
| @@ -5316,6 +5657,7 @@ |
| id, |
| prev: was && was.pc === entry.pc ? was.reading : null, |
| now: reading, |
| + sample: qualitySamples.get(id) || null, |
| ladder: shareCountsBy.get(id) || null, |
| reattaches: reattachesBy.get(id) || 0, |
| stalls: stallsBy.get(id) || null, |
| @@ -5326,8 +5668,8 @@ |
| shareCountsBy.clear(); |
| reattachesBy.clear(); |
| stallsBy.clear(); |
| + qualitySamples.clear(); |
| refreshOutputKind(); |
| - if (!reportToken || qualityServerOff || !qualityOn()) return; |
| const track = local && local.getAudioTracks()[0]; |
| const report = qualityReport({ |
| final, |
| @@ -5339,30 +5681,91 @@ |
| }, |
| events: events.call, |
| peers, |
| + shareMode: share ? shareMode() : '', |
| }); |
| - let body = JSON.stringify(report); |
| - while (body.length > QUALITY_MAX_BODY && report.peers && report.peers.length) { |
| - report.peers.pop(); |
| - body = JSON.stringify(report); |
| + // A new participation is a new gate, and its first window has no |
| + // window before it. |
| + const gate = autoReportGate(autoGate, reportToken); |
| + if (gate !== autoGate) { |
| + autoGate = gate; |
| + autoPrevFacts = null; |
| + } |
| + const facts = qualityFacts(report); |
| + const prevFacts = autoPrevFacts; |
| + if (!final) autoPrevFacts = facts; |
| + const on = qualityOn(); |
| + const trigger = autoReportDecision({ facts, prevFacts, gate: autoGate, now, on, serverOff: qualityServerOff, |
| + token: reportToken, final, force: final ? '' : autoForce }); |
| + if (!final) autoForce = ''; |
| + if (!reportToken || qualityServerOff || !on) return; |
| + const token = reportToken; |
| + const post = () => { |
| + if (qualityServerOff) return; |
| + let body = JSON.stringify(report); |
| + while (body.length > QUALITY_MAX_BODY && report.peers && report.peers.length) { |
| + report.peers.pop(); |
| + body = JSON.stringify(report); |
| + } |
| + const named = !!report.autoReport; |
| + quality.sent += 1; |
| + fetch('/m/' + encodeURIComponent(sqid) + '/quality', { |
| + method: 'POST', |
| + credentials: 'same-origin', |
| + headers: { 'Content-Type': 'application/json', 'X-Calls-Report': token }, |
| + body, |
| + keepalive: !!final, |
| + }).then((res) => { |
| + quality.status = res.status; |
| + if (res.status === 202) { |
| + quality.accepted += 1; |
| + if (named) quality.auto.reported += 1; |
| + } |
| + if (res.status === 204) qualityServerOff = true; |
| + }, () => { |
| + quality.status = 0; |
| + }); |
| + }; |
| + if (!trigger) { |
| + post(); |
| + return; |
| } |
| - quality.sent += 1; |
| - fetch('/m/' + encodeURIComponent(sqid) + '/quality', { |
| + autoGate.count += 1; |
| + autoGate.last = now; |
| + quality.auto.sent += 1; |
| + fetch('/m/' + encodeURIComponent(sqid) + '/auto-report', { |
| method: 'POST', |
| credentials: 'same-origin', |
| - headers: { 'Content-Type': 'application/json', 'X-Calls-Report': reportToken }, |
| - body, |
| - keepalive: !!final, |
| - }).then((res) => { |
| - quality.status = res.status; |
| - if (res.status === 202) quality.accepted += 1; |
| - if (res.status === 204) qualityServerOff = true; |
| + headers: { 'Content-Type': 'application/json', 'X-Calls-Report': token }, |
| + body: autoReportBody(trigger, callDiagnostics({ anonymous: true }), reportClient(), AUTO_BODY_MAX), |
| + }).then(async (res) => { |
| + quality.auto.status = res.status; |
| + if (res.status === 204) { |
| + qualityServerOff = true; |
| + return; |
| + } |
| + if (res.status === 200) { |
| + let data = null; |
| + try { |
| + data = await res.json(); |
| + } catch { |
| + data = null; |
| + } |
| + if (data && typeof data.ref === 'string' && /^[0-9A-Z]{8}$/.test(data.ref)) { |
| + report.autoReport = data.ref; |
| + quality.auto.refs.push(data.ref); |
| + } |
| + } |
| + post(); |
| }, () => { |
| - quality.status = 0; |
| + quality.auto.status = 0; |
| + post(); |
| }); |
| } |
| // qualityTick runs after each stats walk: the window opens when this |
| // tab is first admitted, and a report closes it every qualityEvery. |
| + // §15.29: every walk in between is one look of the window's sampler, |
| + // per connection. |
| function qualityTick() { |
| if (state.stopped || !state.admitted) return; |
| const now = Date.now(); |
| @@ -5371,6 +5774,11 @@ |
| refreshOutputKind(); |
| return; |
| } |
| + for (const [id, entry] of pcs) { |
| + if (!entry.statsReport) continue; |
| + const reading = qualityReading(entry.statsReport, (r) => qualityKind(id, entry, r)); |
| + qualitySamples.set(id, qualitySample(qualitySamples.get(id) || null, reading)); |
| + } |
| if (now - qualityFrom >= qualityEvery) sendQuality(false); |
| } |
| @@ -8627,6 +9035,16 @@ |
| qualityEveryForTest(ms) { |
| qualityEvery = Math.max(QUALITY_EVERY_MIN, Math.min(Number(ms) || QUALITY_EVERY, QUALITY_EVERY)); |
| }, |
| + // §15.29, for the gate: the next window's report fires the automatic |
| + // report on `trigger` (one of protocol.AutoTriggers) as though its rule |
| + // had held, since a call on one machine never struggles on cue. |
| + // Everything else still decides — the gate, the person's switch, the |
| + // server's kill switch, the token — and the next window spends it, |
| + // sent or not. Returns whether the trigger was one it knows. |
| + autoReportForTest(trigger) { |
| + autoForce = ['freezes', 'rtt', 'reconnecting', 'screen'].includes(trigger) ? trigger : ''; |
| + return !!autoForce; |
| + }, |
| // §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. |
| @@ -8776,6 +9194,15 @@ |
| serverOff: qualityServerOff, |
| on: qualityOn(), |
| every: qualityEvery, |
| + // §15.29: automatic reports sent, the last answer, the |
| + // references they were given, and the quality reports naming |
| + // one that were accepted. |
| + auto: { |
| + sent: quality.auto.sent, |
| + status: quality.auto.status, |
| + refs: quality.auto.refs.slice(), |
| + reported: quality.auto.reported, |
| + }, |
| }, |
| }; |
| }, |
diff --git a/internal/callstest/browser_test.go b/internal/callstest/browser_test.go| index 65293df..ea66243 100644 |
| --- a/internal/callstest/browser_test.go |
| +++ b/internal/callstest/browser_test.go |
| @@ -807,6 +807,8 @@ func (rig *browserRig) control(t *testing.T, verb string) string { |
| return "FAIL problem-check needs a reference" |
| } |
| return rig.problemCheck(fields[0], fields[1:]) |
| + case strings.HasPrefix(verb, "auto-check "): |
| + return rig.autoCheck(strings.Fields(strings.TrimPrefix(verb, "auto-check "))) |
| case verb == "quality-final": |
| for _, l := range rig.reports.linesFrom(rig.reportsFrom, "calls: quality") { |
| if l["final"] == true { |
| @@ -845,15 +847,32 @@ func (rig *browserRig) qualityCheck(peers []string) string { |
| } |
| calls[call] = true |
| tags[peer] = true |
| - report, _ := l["report"].(map[string]any) |
| - ps, _ := report["peers"].([]any) |
| - for _, p := range ps { |
| - if m, ok := p.(map[string]any); ok { |
| - if tag, ok := m["peer"].(string); ok { |
| - named[tag] = true |
| - } |
| + } |
| + // Each remote peer is on a `calls: quality peer` line of its own |
| + // (§15.29), flat, under the same tags, naming the remote by its tag. |
| + peerLines := rig.reports.linesFrom(rig.reportsFrom, "calls: quality peer") |
| + measured := 0 |
| + for _, l := range peerLines { |
| + if !calls[fmt.Sprint(l["call"])] || !tags[fmt.Sprint(l["peer"])] { |
| + return fmt.Sprintf("FAIL a peer line under tags no quality line has: %v", l) |
| + } |
| + if tag, ok := l["remote"].(string); ok { |
| + named[tag] = true |
| + } |
| + for k, v := range l { |
| + switch v.(type) { |
| + case map[string]any, []any: |
| + return fmt.Sprintf("FAIL peer line member %s is nested", k) |
| } |
| } |
| + // A real call between two Chromiums on one machine: a path, the |
| + // candidates behind it, and audio arriving. |
| + if l["pathLocal"] != nil && l["pathProtocol"] != nil && l["candHost"] != nil && l["udpOk"] != nil && l["inAudioKbps"] != nil { |
| + measured++ |
| + } |
| + } |
| + if measured == 0 { |
| + return fmt.Sprintf("FAIL no peer line carries the path, the candidates and the audio (%d peer lines): %v", len(peerLines), peerLines) |
| } |
| if len(calls) != 1 { |
| return fmt.Sprintf("FAIL quality lines under %d call tags, want one: %v", len(calls), calls) |
| @@ -872,6 +891,42 @@ func (rig *browserRig) qualityCheck(peers []string) string { |
| return "ok" |
| } |
| +// autoCheck answers the automatic report (§15.29): a browser sent one |
| +// with nobody pressing anything, it reached the log as a `calls: auto |
| +// report` line with its diagnostics under one reference, a `calls: |
| +// quality` line from the same participation says autoReport=<that |
| +// reference>, and still nobody is named anywhere in the log. |
| +func (rig *browserRig) autoCheck(peers []string) string { |
| + heads := rig.reports.linesFrom(rig.reportsFrom, "calls: auto report") |
| + if len(heads) == 0 { |
| + return "FAIL no calls: auto report line" |
| + } |
| + for _, head := range heads { |
| + ref, _ := head["ref"].(string) |
| + if _, ok := head["note"]; ok { |
| + return "FAIL an auto report carries a note" |
| + } |
| + parts := 0 |
| + for _, l := range rig.reports.linesFrom(rig.reportsFrom, "calls: auto report diagnostics") { |
| + if l["ref"] == ref { |
| + parts++ |
| + } |
| + } |
| + if parts == 0 { |
| + return "FAIL no diagnostics under auto report " + ref |
| + } |
| + for _, l := range rig.reports.linesFrom(rig.reportsFrom, "calls: quality") { |
| + if l["autoReport"] == ref && l["peer"] == head["peer"] && l["call"] == head["call"] { |
| + if why := rig.leaks(peers); why != "" { |
| + return "FAIL " + why |
| + } |
| + return fmt.Sprintf("ok (ref %s, trigger %v, %d diagnostics part(s))", ref, head["trigger"], parts) |
| + } |
| + } |
| + } |
| + return fmt.Sprintf("FAIL no calls: quality line notes any of the %d auto report(s)", len(heads)) |
| +} |
| + |
| // problemCheck answers "Report a problem": a `calls: problem report` |
| // line under the reference the sheet showed, at least one diagnostics |
| // line under it, and still nobody named anywhere in the log. |
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go| index 967c520..a9687fa 100644 |
| --- a/internal/callstest/native_browser_test.go |
| +++ b/internal/callstest/native_browser_test.go |
| @@ -85,7 +85,10 @@ func nativeMacCallsBrowser(t *testing.T, guest, chat bool) { |
| input, _ := json.Marshal(fixture) |
| // CALLS_QUALITY_INTERVAL: the app's quality reports every two seconds |
| // rather than thirty (spec §15.26), so the call holds several. |
| - cmd.Env = append(os.Environ(), "CALLS_COOKIE_NAME="+rig.cookieName, "CALLS_COOKIE_A="+rig.cookieA, "CALLS_NATIVE_INPUT="+string(input), "CALLS_QUALITY_INTERVAL=2") |
| + cmd.Env = append(os.Environ(), "CALLS_COOKIE_NAME="+rig.cookieName, "CALLS_COOKIE_A="+rig.cookieA, "CALLS_NATIVE_INPUT="+string(input), "CALLS_QUALITY_INTERVAL=2", |
| + // §15.29: the app's first eligible window counts as struggling, so |
| + // the gate sees an automatic report reach the log. |
| + "CALLS_AUTO_REPORT_TEST=freezes") |
| out, err := cmd.StdoutPipe() |
| if err != nil { |
| t.Fatal(err) |
| @@ -124,21 +127,49 @@ func assertNativeQualityReports(t *testing.T, rig *browserRig) { |
| if line["os"] != "macos" || line["osVersion"] == nil { |
| t.Fatalf("the app's report does not say what it runs on: %v", line) |
| } |
| - report, _ := line["report"].(map[string]any) |
| - peers, _ := report["peers"].([]any) |
| - for _, p := range peers { |
| - peer, _ := p.(map[string]any) |
| - in, _ := peer["in"].(map[string]any) |
| - audio, _ := in["audio"].(map[string]any) |
| - path, _ := peer["path"].(map[string]any) |
| - if packets, _ := audio["packets"].(float64); packets > 0 && path["protocol"] != nil { |
| - measured = true |
| - } |
| + } |
| + // The per-peer detail is the peer lines' (§15.29): flat, under the |
| + // app's own tags, with the path, the candidates behind it, and the |
| + // browser's audio arriving. |
| + macTags := map[any]bool{} |
| + for _, line := range mac { |
| + macTags[line["peer"]] = true |
| + } |
| + var peerLines []map[string]any |
| + for _, l := range rig.reports.lines("calls: quality peer") { |
| + if !macTags[l["peer"]] { |
| + continue |
| + } |
| + peerLines = append(peerLines, l) |
| + if kbps, _ := l["inAudioKbps"].(float64); kbps > 0 && l["pathProtocol"] != nil && l["candHost"] != nil && l["udpOk"] != nil { |
| + measured = true |
| } |
| } |
| if !measured { |
| - t.Fatalf("no report from the app measured the browser's audio and path: %v", mac) |
| + t.Fatalf("no peer line from the app measured the browser's audio, path and candidates: %v", peerLines) |
| + } |
| + // CALLS_AUTO_REPORT_TEST made the app's first eligible window |
| + // struggle: its automatic report is logged, and the quality line it |
| + // went with names it. |
| + var auto map[string]any |
| + for _, l := range rig.reports.lines("calls: auto report") { |
| + if l["app"] == "mac" { |
| + auto = l |
| + } |
| + } |
| + if auto == nil { |
| + t.Fatalf("no automatic report from the app; the report log holds:\n%s", rig.reports.raw()) |
| + } |
| + noted := false |
| + for _, line := range mac { |
| + if line["autoReport"] == auto["ref"] { |
| + noted = true |
| + } |
| + } |
| + if !noted { |
| + t.Fatalf("no quality line from the app names its automatic report %v", auto["ref"]) |
| } |
| + t.Logf("PASS the app's automatic report %v (trigger %v)", auto["ref"], auto["trigger"]) |
| b, _ := json.Marshal(mac[len(mac)-1]) |
| t.Logf("PASS %d quality reports from the app; the last: %s", len(mac), b) |
| } |
diff --git a/internal/callstest/quality_detail_test.go b/internal/callstest/quality_detail_test.go| new file mode 100644 |
| index 0000000..2f42125 |
| --- /dev/null |
| +++ b/internal/callstest/quality_detail_test.go |
| @@ -0,0 +1,404 @@ |
| +package callstest |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| +) |
| + |
| +// Spec §15.29 (2026-10-28): the per-peer detail written flat, so `carlos |
| +// logs` shows it; why a call was relayed; and the automatic report a |
| +// struggling client sends without anyone pressing anything. |
| + |
| +// relayedQuality is a report from the side of a relayed call whose own |
| +// network found no public address: a Safari guest, sharing nothing, |
| +// receiving a camera and a screen. |
| +func relayedQuality(remote string) protocol.QualityReport { |
| + q := sampleQuality(remote) |
| + q.Client = protocol.ReportClient{App: "web", Version: "47afcb9", Browser: "safari", BrowserVersion: "26.5", OS: "macos", OSVersion: "10.15.7"} |
| + p := &q.Peers[0] |
| + p.Path = &protocol.Path{Local: "relay", Remote: "srflx", Protocol: "tls"} |
| + p.RTT, p.RTTAvg, p.RTTMax = num(310), num(402.5), num(1312) |
| + p.JitterAvg, p.JitterMax = num(18), num(96) |
| + p.Candidates = &protocol.Candidates{Host: num(2), Relay: num(1), RemoteHost: num(1), RemoteSrflx: num(1), RemoteRelay: num(1), UDPOK: false} |
| + p.Out = &protocol.Outbound{ |
| + Audio: &protocol.OutStream{Kbps: num(31.5), Packets: num(1500), Lost: num(15), RTT: num(420)}, |
| + Video: &protocol.OutStream{Kbps: num(412), Width: num(640), Height: num(360), FPS: num(24), Limit: "bandwidth", |
| + LimitedBandwidthSeconds: num(27.5), LimitedCPUSeconds: num(0), Encoder: "hardware", Codec: "h264"}, |
| + } |
| + p.In = &protocol.Inbound{ |
| + Audio: &protocol.InAudio{Kbps: num(30), Packets: num(1480), Lost: num(20), Jitter: num(22), Samples: num(1440000), Concealed: num(14400), JitterBufferMs: num(140)}, |
| + Video: &protocol.InVideo{Kbps: num(380), Packets: num(1200), Lost: num(12), Width: num(1280), Height: num(720), FPS: num(12.5), |
| + Freezes: num(4), FreezeSeconds: num(6.1), Decoded: num(375), Dropped: num(3), Decoder: "hardware", Codec: "vp8"}, |
| + Screen: &protocol.InVideo{Kbps: num(900), Width: num(1920), Height: num(1246), FPS: num(4), Freezes: num(3), FreezeSeconds: num(9), |
| + Dropped: num(0), Decoder: "software", Codec: "h264", Stalls: num(1), StallsNoPackets: num(1)}, |
| + } |
| + p.Events = &protocol.PeerEvents{Reconnecting: num(1), ReconnectingSeconds: num(6.4), AutoRestarts: num(2)} |
| + return q |
| +} |
| + |
| +// peerLines are the `calls: quality peer` lines. |
| +func (r *reportRig) peerLines(t *testing.T) []map[string]any { |
| + t.Helper() |
| + return r.reports.lines(t, "calls: quality peer") |
| +} |
| + |
| +func TestTheQualityPeerLineIsFlatAndCarriesTheDetail(t *testing.T) { |
| + r := newReportRig(t, "") |
| + if err := r.x.ctl.SetRelay(relayContract(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp, body := r.b.report(r.sqid, "quality", r.tokB, mustJSON(t, relayedQuality(r.peerA))); resp.StatusCode != http.StatusAccepted { |
| + t.Fatalf("quality: %d %s", resp.StatusCode, body) |
| + } |
| + heads := r.reports.lines(t, "calls: quality") |
| + lines := r.peerLines(t) |
| + if len(heads) != 1 || len(lines) != 1 { |
| + t.Fatalf("%d quality lines and %d peer lines, want one of each", len(heads), len(lines)) |
| + } |
| + head, line := heads[0], lines[0] |
| + // The same tags as the head, and the remote peer by its tag: A's, |
| + // which is what A's own lines are under. |
| + if line["call"] != head["call"] || line["peer"] != head["peer"] || line["level"] != "INFO" { |
| + t.Fatalf("peer line tags %v, head %v", line, head) |
| + } |
| + if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sampleQuality(r.peerB))); resp.StatusCode != http.StatusAccepted { |
| + t.Fatal("A's report") |
| + } |
| + if tagA := r.reports.lines(t, "calls: quality")[1]["peer"]; line["remote"] != tagA { |
| + t.Fatalf("remote = %v, want A's tag %v", line["remote"], tagA) |
| + } |
| + want := map[string]any{ |
| + "pathLocal": "relay", "pathRemote": "srflx", "pathProtocol": "tls", "relayRegion": "eu-west-1", |
| + "rtt": 310.0, "rttAvg": 402.5, "rttMax": 1312.0, "jitterAvg": 18.0, "jitterMax": 96.0, |
| + "candHost": 2.0, "candRelay": 1.0, "candRemoteHost": 1.0, "candRemoteSrflx": 1.0, "candRemoteRelay": 1.0, |
| + "directOk": false, "localDirectOk": false, "udpOk": false, |
| + "outAudioKbps": 31.5, "outAudioLossPct": 1.0, "outAudioRtt": 420.0, |
| + "outCameraKbps": 412.0, "outCameraWidth": 640.0, "outCameraHeight": 360.0, "outCameraFps": 24.0, |
| + "outCameraLimit": "bandwidth", "outCameraLimitedBandwidthSeconds": 27.5, "outCameraLimitedCpuSeconds": 0.0, |
| + "outCameraEncoder": "hardware", "outCameraCodec": "h264", |
| + "inAudioKbps": 30.0, "inAudioLossPct": 1.3, "inAudioJitter": 22.0, "inAudioConcealedPct": 1.0, "inAudioJitterBufferMs": 140.0, |
| + "inCameraKbps": 380.0, "inCameraWidth": 1280.0, "inCameraHeight": 720.0, "inCameraFps": 12.5, "inCameraLossPct": 1.0, |
| + "inCameraFreezes": 4.0, "inCameraFreezeSeconds": 6.1, "inCameraDropped": 3.0, "inCameraDecoder": "hardware", "inCameraCodec": "vp8", |
| + "inScreenWidth": 1920.0, "inScreenHeight": 1246.0, "inScreenFps": 4.0, "inScreenFreezes": 3.0, "inScreenDecoder": "software", |
| + "inScreenStalls": 1.0, "inScreenStallsNoPackets": 1.0, |
| + "reconnecting": 1.0, "reconnectingSeconds": 6.4, "autoRestarts": 2.0, |
| + } |
| + for k, v := range want { |
| + if line[k] != v { |
| + t.Errorf("peer line %s = %#v, want %#v", k, line[k], v) |
| + } |
| + } |
| + // Flat: nothing nested for carlos to drop, and every key a name |
| + // quality-summary's reader takes. |
| + key := regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`) |
| + for k, v := range line { |
| + switch v.(type) { |
| + case map[string]any, []any: |
| + t.Errorf("peer line member %s is nested: %v", k, v) |
| + } |
| + if !key.MatchString(k) { |
| + t.Errorf("peer line key %q is not letters and digits", k) |
| + } |
| + } |
| + // Not measured is left off, not written as zero. |
| + for _, k := range []string{"outScreenKbps", "inScreenKbps0", "candSrflx", "noSound", "outScreenMode"} { |
| + if _, ok := line[k]; ok { |
| + t.Errorf("peer line has %s, which the report did not measure", k) |
| + } |
| + } |
| + // The head's maxRtt reads the window's highest, not only the latest. |
| + if head["maxRtt"] != 1312.0 { |
| + t.Errorf("head maxRtt = %v, want the window's 1312", head["maxRtt"]) |
| + } |
| + r.assertClean(t) |
| +} |
| + |
| +// A report from a client before §15.29 — none of the new members — is |
| +// taken as it always was, and its peer line says what it can. |
| +func TestAnOldClientsReportStillMakesAPeerLine(t *testing.T) { |
| + r := newReportRig(t, "") |
| + if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sampleQuality(r.peerB))); resp.StatusCode != http.StatusAccepted { |
| + t.Fatalf("an old client's report: %d", resp.StatusCode) |
| + } |
| + lines := r.peerLines(t) |
| + if len(lines) != 1 { |
| + t.Fatalf("%d peer lines", len(lines)) |
| + } |
| + l := lines[0] |
| + if l["pathLocal"] != "srflx" || l["pathRemote"] != "relay" || l["outCameraLimit"] != "bandwidth" || l["inCameraFreezes"] != 2.0 { |
| + t.Fatalf("old client's peer line %v", l) |
| + } |
| + // No relay configured here: the region is not guessed. |
| + for _, k := range []string{"relayRegion", "directOk", "candHost", "rttMax", "outCameraEncoder", "autoReport"} { |
| + if _, ok := l[k]; ok { |
| + t.Errorf("old client's peer line has %s", k) |
| + } |
| + } |
| + if _, ok := r.reports.lines(t, "calls: quality")[0]["autoReport"]; ok { |
| + t.Error("a quality line with no auto report says autoReport") |
| + } |
| +} |
| + |
| +func TestTheNewMembersAreStrict(t *testing.T) { |
| + r := newReportRig(t, "") |
| + cases := map[string]func(*protocol.QualityReport){ |
| + "an encoder by name": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.Encoder = "VideoToolbox" }, |
| + "a codec off the list": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.Codec = "theora" }, |
| + "a share mode off the list": func(q *protocol.QualityReport) { q.Peers[0].Out.Screen = &protocol.OutStream{Mode: "fast"} }, |
| + "a decoder by name": func(q *protocol.QualityReport) { q.Peers[0].In.Video.Decoder = "libvpx" }, |
| + "an inbound codec": func(q *protocol.QualityReport) { q.Peers[0].In.Screen = &protocol.InVideo{Codec: "H264"} }, |
| + "an auto report ref": func(q *protocol.QualityReport) { q.AutoReport = "not-a-ref" }, |
| + "a lowercase ref": func(q *protocol.QualityReport) { q.AutoReport = "k7q2m9pd" }, |
| + "rttMax over its ceiling": func(q *protocol.QualityReport) { q.Peers[0].RTTMax = num(600_001) }, |
| + "a negative jitter": func(q *protocol.QualityReport) { q.Peers[0].JitterAvg = num(-1) }, |
| + "limited seconds too long": func(q *protocol.QualityReport) { q.Peers[0].Out.Video.LimitedBandwidthSeconds = num(601) }, |
| + "a candidate count too big": func(q *protocol.QualityReport) { q.Peers[0].Candidates = &protocol.Candidates{Host: num(2e9)} }, |
| + } |
| + for name, edit := range cases { |
| + q := relayedQuality(r.peerB) |
| + edit(&q) |
| + r.x.advance(10 * time.Second) |
| + if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusBadRequest { |
| + t.Errorf("%s: %d, want 400", name, resp.StatusCode) |
| + } |
| + } |
| + // And the good values are taken. |
| + q := relayedQuality(r.peerB) |
| + q.AutoReport = "K7Q2M9PD" |
| + q.Peers[0].Out.Screen = &protocol.OutStream{Kbps: num(2400), Mode: "detail", Encoder: "software", Codec: "h264", Limit: "cpu", LimitedCPUSeconds: num(12)} |
| + r.x.advance(10 * time.Second) |
| + if resp, body := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { |
| + t.Fatalf("a good report: %d %s", resp.StatusCode, body) |
| + } |
| + head := r.reports.lines(t, "calls: quality")[0] |
| + if head["autoReport"] != "K7Q2M9PD" { |
| + t.Errorf("head autoReport = %v", head["autoReport"]) |
| + } |
| + l := r.peerLines(t)[0] |
| + if l["outScreenMode"] != "detail" || l["outScreenEncoder"] != "software" || l["outScreenLimit"] != "cpu" || l["outScreenLimitedCpuSeconds"] != 12.0 { |
| + t.Errorf("screen fields %v", l) |
| + } |
| +} |
| + |
| +// The largest per-peer line the schema allows, every field present and at |
| +// its widest, fits the platform's line. |
| +func TestTheLargestPeerLineFitsThePlatformsLine(t *testing.T) { |
| + r := newReportRig(t, "") |
| + if err := r.x.ctl.SetRelay(relayContract(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + q := largestQuality(r.peerB) |
| + if resp, body := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { |
| + t.Fatalf("the largest report: %d %s", resp.StatusCode, body) |
| + } |
| + lines := strings.Split(strings.TrimSpace(r.reports.String()), "\n") |
| + if len(lines) != 1+protocol.MaxQualityPeers { |
| + t.Fatalf("%d lines, want the head and %d peer lines", len(lines), protocol.MaxQualityPeers) |
| + } |
| + widest := 0 |
| + for _, l := range lines { |
| + widest = max(widest, len(l)) |
| + if len(l) > 8192 { |
| + t.Fatalf("a line of %d bytes; the platform keeps 8192:\n%.300s", len(l), l) |
| + } |
| + } |
| + peer := r.peerLines(t)[0] |
| + if len(peer) < 90 { |
| + t.Errorf("the largest peer line has only %d fields", len(peer)) |
| + } |
| + t.Logf("widest line %d bytes; a peer line %d bytes with %d fields", widest, len(lines[1]), len(peer)) |
| +} |
| + |
| +// largestQuality is the widest report the schema allows: every peer, |
| +// every number at its widest, every enum at its longest. |
| +func largestQuality(remote string) protocol.QualityReport { |
| + big := func() *float64 { return num(123456789.1) } |
| + ms := func() *float64 { return num(599999.9) } |
| + secs := func() *float64 { return num(599.9) } |
| + out := func(mode string) *protocol.OutStream { |
| + return &protocol.OutStream{Kbps: num(999999.9), Packets: big(), Lost: big(), RTT: ms(), Jitter: ms(), Limit: "bandwidth", |
| + Width: num(16384), Height: num(16384), FPS: num(240), Keyframes: big(), Rebuilds: big(), Reshares: big(), Failures: big(), |
| + Damped: big(), EncoderStalls: big(), LimitedBandwidthSeconds: secs(), LimitedCPUSeconds: secs(), |
| + Encoder: "software", Codec: "other", Mode: mode} |
| + } |
| + in := func() *protocol.InVideo { |
| + return &protocol.InVideo{Kbps: num(999999.9), Packets: big(), Lost: big(), Jitter: ms(), Freezes: big(), FreezeSeconds: secs(), |
| + Decoded: big(), Dropped: big(), Width: num(16384), Height: num(16384), FPS: num(240), Reattaches: big(), |
| + Stalls: big(), StallsNoPackets: big(), StallsUndecoded: big(), Decoder: "software", Codec: "other"} |
| + } |
| + q := sampleQuality(remote) |
| + q.AutoReport = "K7Q2M9PD" |
| + q.Peers = nil |
| + for i := 0; i < protocol.MaxQualityPeers; i++ { |
| + q.Peers = append(q.Peers, protocol.PeerQuality{ |
| + Peer: protocol.PeerID(fmt.Sprintf("%032x", i)), |
| + Path: &protocol.Path{Local: "relay", Remote: "relay", Protocol: "unknown"}, RTT: ms(), |
| + RTTAvg: ms(), RTTMax: ms(), JitterAvg: ms(), JitterMax: ms(), |
| + Candidates: &protocol.Candidates{Host: big(), Srflx: big(), Prflx: big(), Relay: big(), RemoteHost: big(), RemoteSrflx: big(), |
| + RemotePrflx: big(), RemoteRelay: big(), DirectOK: true, LocalDirectOK: true, UDPOK: true}, |
| + Out: &protocol.Outbound{Audio: out(""), Video: out(""), Screen: out("balanced")}, |
| + In: &protocol.Inbound{ |
| + Audio: &protocol.InAudio{Kbps: num(999999.9), Packets: big(), Lost: big(), Jitter: ms(), Samples: big(), Concealed: big(), Inserted: big(), Removed: big(), JitterBufferMs: ms()}, |
| + Video: in(), Screen: in(), |
| + }, |
| + Events: &protocol.PeerEvents{Reconnecting: big(), ReconnectingSeconds: secs(), CantHearSeconds: secs(), |
| + NoSound: true, NoSoundFromUs: true, AudioBlocked: true, ScreenStalled: true, AutoRestarts: big(), AutoRebuilds: big()}, |
| + }) |
| + } |
| + return q |
| +} |
| + |
| +// autoBody is an automatic report as a client sends it. |
| +func autoBody(t *testing.T, trigger, diagnostics string) []byte { |
| + return mustJSON(t, protocol.AutoReport{Trigger: trigger, Diagnostics: diagnostics, |
| + Client: protocol.ReportClient{App: "web", Version: "47afcb9", Browser: "safari", BrowserVersion: "26.5", OS: "macos", OSVersion: "10.15.7"}}) |
| +} |
| + |
| +func TestAnAutoReportIsLoggedUnderItsReferenceScrubbedAndWithoutANote(t *testing.T) { |
| + r := newReportRig(t, "") |
| + diag := fmt.Sprintf("Calls web diagnostics\n## Call\npeer %s: connection connected, ICE connected\nopened %s/m/%s\nfull id %s\n", |
| + r.peerA[:6], testOrigin, r.sqid, r.peerA) |
| + for len(diag) < 14_000 { |
| + diag += "12:00:00.000 screen from " + r.peerA[:6] + " stalled here: no packets arriving\n" |
| + } |
| + // A client that sent a note anyway: the schema has none, so it is |
| + // dropped unread. |
| + var withNote map[string]any |
| + _ = json.Unmarshal(autoBody(t, "freezes", diag), &withNote) |
| + withNote["note"] = "Ana's video froze" |
| + resp, body := r.b.report(r.sqid, "auto-report", r.tokB, mustJSON(t, withNote)) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("auto report: %d %s", resp.StatusCode, body) |
| + } |
| + var receipt protocol.ProblemReceipt |
| + if err := json.Unmarshal(body, &receipt); err != nil || !regexp.MustCompile(`^[0-9A-HJKMNP-TV-Z]{8}$`).MatchString(receipt.Ref) { |
| + t.Fatalf("receipt %s", body) |
| + } |
| + heads := r.reports.lines(t, "calls: auto report") |
| + if len(heads) != 1 { |
| + t.Fatalf("%d auto report lines", len(heads)) |
| + } |
| + head := heads[0] |
| + if head["ref"] != receipt.Ref || head["trigger"] != "freezes" || head["level"] != "WARN" || head["live"] != true || head["browser"] != "safari" { |
| + t.Fatalf("auto report head %v", head) |
| + } |
| + if _, ok := head["note"]; ok { |
| + t.Errorf("an auto report head carries a note: %v", head) |
| + } |
| + if strings.Contains(r.reports.String(), "Ana's video") { |
| + t.Error("the note a client added reached the log") |
| + } |
| + parts := r.reports.lines(t, "calls: auto report diagnostics") |
| + if len(parts) < 3 || float64(len(parts)) != head["parts"] { |
| + t.Fatalf("%d diagnostics parts, head says %v", len(parts), head["parts"]) |
| + } |
| + var text strings.Builder |
| + for i, p := range parts { |
| + if p["ref"] != receipt.Ref || p["part"] != float64(i+1) || p["call"] != head["call"] || p["peer"] != head["peer"] { |
| + t.Fatalf("part %d: %v", i+1, p) |
| + } |
| + text.WriteString(p["text"].(string)) |
| + } |
| + if !strings.Contains(text.String(), "/m/[meeting]") || !strings.Contains(text.String(), "full id peer:") || strings.Contains(text.String(), r.peerA[:6]) { |
| + t.Fatalf("diagnostics not scrubbed:\n%.300s", text.String()) |
| + } |
| + for _, line := range strings.Split(r.reports.String(), "\n") { |
| + if len(line) > 8192 { |
| + t.Fatalf("a line of %d bytes", len(line)) |
| + } |
| + } |
| + // Not a problem report: quality-summary tells them apart. |
| + if n := len(r.reports.lines(t, "calls: problem report")); n != 0 { |
| + t.Errorf("%d problem report lines from an auto report", n) |
| + } |
| + r.assertClean(t) |
| + |
| + // The schema: a trigger off the list, a client off the list, the cap. |
| + r.x.advance(11 * time.Minute) |
| + for name, b := range map[string][]byte{ |
| + "no trigger": autoBody(t, "", "x"), |
| + "a trigger by name": autoBody(t, "my video froze", "x"), |
| + "a bad client": mustJSON(t, protocol.AutoReport{Trigger: "rtt", Client: protocol.ReportClient{App: "Paul's Mac"}}), |
| + "not json": []byte("trigger=rtt"), |
| + } { |
| + r.x.advance(11 * time.Minute) |
| + if resp, _ := r.a.report(r.sqid, "auto-report", r.tokA, b); resp.StatusCode != http.StatusBadRequest { |
| + t.Errorf("%s: %d, want 400", name, resp.StatusCode) |
| + } |
| + } |
| + r.x.advance(11 * time.Minute) |
| + if resp, _ := r.a.report(r.sqid, "auto-report", r.tokA, autoBody(t, "rtt", strings.Repeat("a", 65<<10))); resp.StatusCode != http.StatusRequestEntityTooLarge { |
| + t.Errorf("65 KB of diagnostics: %d, want 413", resp.StatusCode) |
| + } |
| +} |
| + |
| +func TestAutoReportsAreOneEveryTenMinutesAndThreeACall(t *testing.T) { |
| + r := newReportRig(t, "") |
| + send := func(c *client, tok string) *http.Response { |
| + resp, _ := c.report(r.sqid, "auto-report", tok, autoBody(t, "rtt", "Calls web diagnostics")) |
| + return resp |
| + } |
| + if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("the first: %d", resp.StatusCode) |
| + } |
| + resp := send(r.a, r.tokA) |
| + if resp.StatusCode != http.StatusTooManyRequests || resp.Header.Get("Retry-After") == "" { |
| + t.Fatalf("a second at once: %d (Retry-After %q), want 429", resp.StatusCode, resp.Header.Get("Retry-After")) |
| + } |
| + // Per participation: B's are its own. |
| + if resp := send(r.b, r.tokB); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("B's first, after A's: %d", resp.StatusCode) |
| + } |
| + r.x.advance(9*time.Minute + 50*time.Second) |
| + if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusTooManyRequests { |
| + t.Fatalf("nine minutes fifty later: %d, want 429", resp.StatusCode) |
| + } |
| + // Two minutes idle is longer than the problem limiter's memory; this |
| + // limit remembers. |
| + r.x.advance(10 * time.Second) |
| + if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("ten minutes later: %d, want 200", resp.StatusCode) |
| + } |
| + r.x.advance(10 * time.Minute) |
| + if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("the third, twenty minutes in: %d", resp.StatusCode) |
| + } |
| + r.x.advance(time.Hour) |
| + if resp := send(r.a, r.tokA); resp.StatusCode != http.StatusTooManyRequests { |
| + t.Fatalf("a fourth an hour later: %d, want 429 (three a call)", resp.StatusCode) |
| + } |
| + if n := len(r.reports.lines(t, "calls: auto report")); n != 4 { |
| + t.Fatalf("%d auto reports logged, want A's three and B's one", n) |
| + } |
| + // Problem reports are the person's, and spend nothing of this. |
| + if resp, _ := r.a.report(r.sqid, "problem", r.tokA, mustJSON(t, protocol.ProblemReport{Note: "x", Client: protocol.ReportClient{App: "web"}})); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("a problem report after the auto reports ran out: %d", resp.StatusCode) |
| + } |
| +} |
| + |
| +func TestAutoReportsNeedTheTokenAndFollowTheKillSwitch(t *testing.T) { |
| + r := newReportRig(t, "") |
| + if resp, _ := r.a.report(r.sqid, "auto-report", strings.Repeat("0", 32), autoBody(t, "rtt", "x")); resp.StatusCode != http.StatusNotFound { |
| + t.Fatalf("a made-up token: %d, want 404", resp.StatusCode) |
| + } |
| + if resp, _ := r.a.report(r.sqid, "auto-report", r.tokB, autoBody(t, "rtt", "x")); resp.StatusCode != http.StatusNotFound { |
| + t.Fatalf("B's token from A's session: %d, want 404", resp.StatusCode) |
| + } |
| + |
| + off := newReportRig(t, "off") |
| + for _, token := range []string{off.tokA, ""} { |
| + if resp, _ := off.a.report(off.sqid, "auto-report", token, autoBody(t, "freezes", "x")); resp.StatusCode != http.StatusNoContent { |
| + t.Fatalf("quality reports off (token %q): %d, want 204", token, resp.StatusCode) |
| + } |
| + } |
| + if n := len(off.reports.lines(t, "calls: auto report")); n != 0 { |
| + t.Fatalf("%d auto report lines with reports off", n) |
| + } |
| +} |
diff --git a/internal/callstest/quality_test.go b/internal/callstest/quality_test.go| index 268f3a0..dabeaeb 100644 |
| --- a/internal/callstest/quality_test.go |
| +++ b/internal/callstest/quality_test.go |
| @@ -223,11 +223,20 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| if a["peer"] == b["peer"] { |
| t.Errorf("two participations, one peer tag %v", a["peer"]) |
| } |
| - // A's report names B by B's tag, never B's id. |
| + // A's report names B by B's tag, never B's id: on A's peer line |
| + // (§15.29), which is where each remote peer's part now goes. |
| rep := a["report"].(map[string]any) |
| - peers := rep["peers"].([]any) |
| - if got := peers[0].(map[string]any)["peer"]; got != b["peer"] { |
| - t.Errorf("A's report names its peer %v, want B's tag %v", got, b["peer"]) |
| + if _, ok := rep["peers"]; ok { |
| + t.Error("the head line still carries the peers; they are the peer lines'") |
| + } |
| + var peerA map[string]any |
| + for _, l := range r.reports.lines(t, "calls: quality peer") { |
| + if l["peer"] == a["peer"] { |
| + peerA = l |
| + } |
| + } |
| + if peerA == nil || peerA["remote"] != b["peer"] || peerA["call"] != a["call"] { |
| + t.Fatalf("A's peer line %v, want remote B's tag %v", peerA, b["peer"]) |
| } |
| // The line's shape: what carlos logs --field can filter on, at the |
| // top, and the rest under report. |
| @@ -244,10 +253,10 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| } |
| } |
| // §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) |
| + if peerA["autoRestarts"] != 2.0 || peerA["autoRebuilds"] != 1.0 { |
| + t.Errorf("the recovery's counts are not in the line: %v", peerA) |
| } |
| - if got := peers[0].(map[string]any)["rtt"]; got != 48.3 { |
| + if got := peerA["rtt"]; got != 48.3 { |
| t.Errorf("rtt %v, want rounded to a tenth (48.3)", got) |
| } |
| if _, ok := rep["client"]; ok { |
| @@ -323,13 +332,13 @@ func TestQualityReportSchemaIsStrict(t *testing.T) { |
| m["name"] = "Paul Campbell" |
| m["client"].(map[string]any)["device"] = "Paul's MacBook Pro" |
| peer0(m)["address"] = "203.0.113.9" |
| - peer0(m)["out"].(map[string]any)["audio"].(map[string]any)["codec"] = "opus" |
| + peer0(m)["out"].(map[string]any)["audio"].(map[string]any)["mimeType"] = "audio/opus" |
| r.x.advance(10 * time.Second) |
| if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, m)); resp.StatusCode != http.StatusAccepted { |
| t.Fatalf("unknown members: %d, want 202", resp.StatusCode) |
| } |
| raw := r.reports.String() |
| - for _, f := range []string{"Paul Campbell", "MacBook", "203.0.113.9", "codec", "opus"} { |
| + for _, f := range []string{"Paul Campbell", "MacBook", "203.0.113.9", "mimeType", "audio/opus"} { |
| if strings.Contains(raw, f) { |
| t.Errorf("an unknown member reached the log: %q", f) |
| } |
| @@ -379,9 +388,16 @@ func TestTheLargestQualityLineFitsThePlatformsLine(t *testing.T) { |
| if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { |
| t.Fatalf("the largest report: %d", resp.StatusCode) |
| } |
| - line := strings.TrimSpace(r.reports.String()) |
| - if n := len(line); n > 8192 { |
| - t.Fatalf("the largest quality line is %d bytes; the platform keeps 8192", n) |
| + // The head line, and (§15.29) one flat line per remote peer: each |
| + // fits on its own. |
| + lines := strings.Split(strings.TrimSpace(r.reports.String()), "\n") |
| + if len(lines) != 1+protocol.MaxQualityPeers { |
| + t.Fatalf("%d lines, want the head and one per peer", len(lines)) |
| + } |
| + for _, line := range lines { |
| + if n := len(line); n > 8192 { |
| + t.Fatalf("the largest quality line is %d bytes; the platform keeps 8192", n) |
| + } |
| } |
| } |
diff --git a/native/apple/Sources/CallsInterop/Interop.swift b/native/apple/Sources/CallsInterop/Interop.swift| index 9dbdbc3..9b12746 100644 |
| --- a/native/apple/Sources/CallsInterop/Interop.swift |
| +++ b/native/apple/Sources/CallsInterop/Interop.swift |
| @@ -107,6 +107,15 @@ struct Input: Decodable { |
| if let seconds = ProcessInfo.processInfo.environment["CALLS_QUALITY_INTERVAL"].flatMap(Double.init), seconds >= 1 { |
| Call.qualityInterval = seconds |
| } |
| + // The automatic report (spec §15.29) on the first window that may send |
| + // one, whatever the call is like, so the gate sees one reach the log: |
| + // the trigger to name, one of "freezes", "rtt", "reconnecting", |
| + // "screen". Anything else is ignored. |
| + if let trigger = ProcessInfo.processInfo.environment["CALLS_AUTO_REPORT_TEST"], |
| + AutoReportRules.triggers.contains(trigger) |
| + { |
| + Call.autoReportForTest = trigger |
| + } |
| // WebRTC's own log, filtered to the video encoder, into a file: for |
| // diagnosing the gate's screen scenarios by hand. Never credentials: |
| // the filter keeps encoder lines only. |
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift| index beffa0a..ee59b7d 100644 |
| --- a/native/apple/Sources/CallsKit/Call.swift |
| +++ b/native/apple/Sources/CallsKit/Call.swift |
| @@ -134,6 +134,15 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| /// Thirty seconds, as the ruling has it; the gate shortens it |
| /// (CALLS_QUALITY_INTERVAL, read by the interop harness). |
| @_spi(Fixtures) public static var qualityInterval: Double = 30 |
| + /// The automatic report (spec §15.29): the last window's facts, for the |
| + /// rules that need two in a row; how many this participation has sent |
| + /// and when; and the gate's forced trigger, spent by the first window |
| + /// that may send one (CALLS_AUTO_REPORT_TEST, read by the interop |
| + /// harness, which copies it here per call). |
| + private var qualityFacts: QualityTrouble.Facts? |
| + private var autoReportGate = AutoReportGate() |
| + private var autoReportForced: String? |
| + @_spi(Fixtures) public static var autoReportForTest: String? |
| /// "Report a problem" (spec §15.26): the sheet, while it is open. |
| @Published public var problemReport: ProblemReportModel? |
| /// Until when the last call can still be reported: ten minutes after it |
| @@ -1461,13 +1470,18 @@ extension Call { |
| /// window starts at admission, and each report covers the time since |
| /// the last. Read and built on the main actor, as the statistics reads |
| /// for the meters are; sent off it, because the bridge's send is a |
| - /// request. |
| + /// request. Between reports it reads the connections once a second for |
| + /// the window's round trip and jitter (§15.29), only while there is a |
| + /// report to read for. |
| fileprivate func startQualityWatch() { |
| qualityWatch?.cancel() |
| qualityTally = QualityEventTally() |
| qualityBuilder = QualityReportBuilder() |
| qualityStopped = false |
| qualityFinalSent = false |
| + qualityFacts = nil |
| + autoReportGate = AutoReportGate() |
| + autoReportForced = Self.autoReportForTest |
| qualityWatch = Task { @MainActor [weak self] in |
| while !Task.isCancelled { |
| try? await Task.sleep(nanoseconds: 1_000_000_000) |
| @@ -1480,27 +1494,75 @@ extension Call { |
| } |
| continue |
| } |
| - guard self.qualityBuilder.elapsed(at: now) >= Self.qualityInterval else { continue } |
| + let due = self.qualityBuilder.elapsed(at: now) >= Self.qualityInterval |
| guard self.admittedForReports, !self.qualityStopped, QualityReporting.enabled() else { |
| // Off, stopped, or between participations: the window moves on |
| - // with nothing sent, so a report never covers time it did not see. |
| - self.qualityBuilder.start(at: now) |
| - self.qualityTally = QualityEventTally() |
| + // with nothing sent, so a report never covers time it did not |
| + // see, and nothing is read until there is a report to read for. |
| + if due { |
| + self.qualityBuilder.start(at: now) |
| + self.qualityTally = QualityEventTally() |
| + self.qualityFacts = nil |
| + } |
| continue |
| } |
| + // Once a second (§15.29): the round trip and jitter for the |
| + // window's mean and highest. The window's own report is built from |
| + // the same look. |
| let samples = await self.built?.qualitySamples() ?? [:] |
| guard !Task.isCancelled, self.bridge === client else { return } |
| - guard let body = self.qualityReport(at: ProcessInfo.processInfo.systemUptime, samples: samples, final: false) |
| - else { continue } |
| - Task.detached { [weak self] in |
| - let answer = client.sendQuality(body) |
| - if answer == "stop" { |
| - await MainActor.run { [weak self] in |
| - self?.qualityStopped = true |
| - CallLog.info("quality reports: the server asked for no more this call") |
| - } |
| + self.qualityBuilder.observe(samples: samples) |
| + guard due else { continue } |
| + self.sendQualityWindow(samples: samples, client: client) |
| + } |
| + } |
| + } |
| + |
| + /// A window's report, and with it the automatic report when the call is |
| + /// struggling (§15.29): that goes first, so the quality report can carry |
| + /// its reference. |
| + private func sendQualityWindow(samples: [String: QualityPeerSample], client: BridgeClient) { |
| + let now = ProcessInfo.processInfo.systemUptime |
| + let report = qualityBuilder.build( |
| + at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(), |
| + devices: qualityDevices(), final: false, screenMode: sharingScreen ? screenMode.rawValue : nil) |
| + let facts = QualityTrouble.facts(report) |
| + let trigger = AutoReportDecision.trigger( |
| + previous: qualityFacts, now: facts, gate: autoReportGate, at: now, enabled: QualityReporting.enabled(), |
| + stopped: qualityStopped, final: false, forced: autoReportForced) |
| + qualityFacts = facts |
| + var auto: String? |
| + if let trigger { |
| + autoReportGate.record(at: now) |
| + autoReportForced = nil |
| + auto = AutoReportBody(trigger: trigger, diagnostics: anonymousDiagnosticsText(), client: QualityClientInfo.current()) |
| + .encoded() |
| + } |
| + Task.detached { [weak self] in |
| + var report = report |
| + if let trigger, let auto { |
| + let outcome = AutoReportOutcome(bridgeAnswer: client.sendAutoReport(auto)) |
| + await MainActor.run { [weak self] in |
| + switch outcome { |
| + case .sent(let ref): CallLog.info("automatic report sent: \(trigger), reference \(ref)") |
| + case .stop: |
| + self?.qualityStopped = true |
| + CallLog.info("quality reports: the server asked for no more this call") |
| + case .notSent(let why): CallLog.info("automatic report not sent: \(trigger), \(why)") |
| } |
| } |
| + switch outcome { |
| + case .sent(let ref): report.autoReport = ref |
| + case .stop: return |
| + case .notSent: break |
| + } |
| + } |
| + guard let body = report.encoded() else { return } |
| + if client.sendQuality(body) == "stop" { |
| + await MainActor.run { [weak self] in |
| + self?.qualityStopped = true |
| + CallLog.info("quality reports: the server asked for no more this call") |
| + } |
| } |
| } |
| } |
| @@ -1513,7 +1575,7 @@ extension Call { |
| private func qualityReport(at now: Double, samples: [String: QualityPeerSample], final: Bool) -> String? { |
| qualityBuilder.build( |
| at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(), |
| - devices: qualityDevices(), final: final |
| + devices: qualityDevices(), final: final, screenMode: sharingScreen ? screenMode.rawValue : nil |
| ).encoded() |
| } |
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift| index 1856d39..f9a324a 100644 |
| --- a/native/apple/Sources/CallsKit/QualityReport.swift |
| +++ b/native/apple/Sources/CallsKit/QualityReport.swift |
| @@ -13,6 +13,15 @@ import Foundation |
| // (`QualityPeerSample`), the notices as a tally (`QualityEventTally`), and |
| // the report comes out, so the whole of it is tested from fixtures. Call |
| // gathers the snapshot and sends what comes out. |
| +// |
| +// Spec §15.29, "ambient quality detail and the automatic report" |
| +// (2026-10-28): each window also says how its round trip and jitter went |
| +// over the whole of it (a once-a-second sampler), why the connection took |
| +// the path it took (its candidates, by type), which reason held each |
| +// encoder back longest, and which kind of encoder, decoder and codec each |
| +// stream had. And when a call is struggling — QualityTrouble's rules — |
| +// the app sends the automatic "Report a problem" with that window, as |
| +// the web client does, under the same rules and limits. |
| // MARK: - The wire (protocol/quality.go) |
| @@ -44,9 +53,12 @@ public struct QualityReport: Encodable, Equatable, Sendable { |
| public var devices: QualityDevices? |
| public var events: QualityCallEvents? |
| public var peers: [QualityPeer]? |
| + /// The reference of the automatic report sent with this window |
| + /// (§15.29), when one was. |
| + public var autoReport: String? |
| enum CodingKeys: String, CodingKey { |
| - case v, seconds, client, devices, events, peers |
| + case v, seconds, client, devices, events, peers, autoReport |
| case isFinal = "final" |
| } |
| @@ -92,11 +104,43 @@ public struct QualityPeer: Encodable, Equatable, Sendable { |
| public var peer: String |
| public var path: QualityPath? |
| public var rtt: Double? |
| + /// The window's round trip (§15.29): its mean, the pair's own total over |
| + /// its responses where it has them and the once-a-second readings' |
| + /// otherwise, and its highest reading; and the peer's inbound jitter, |
| + /// read once a second, its mean and highest. All in ms. |
| + public var rttAvg: Double? |
| + public var rttMax: Double? |
| + public var jitterAvg: Double? |
| + public var jitterMax: Double? |
| + public var candidates: QualityCandidates? |
| public var out: QualityOutbound? |
| public var `in`: QualityInbound? |
| public var events: QualityPeerEvents? |
| } |
| +/// How the connection was found (§15.29): what this side gathered and what |
| +/// the peer offered, by type, and which kinds of pair worked. Types and |
| +/// counts only, never an address. A count is left out when it is none; |
| +/// the three booleans always go, because the server reads the struct's |
| +/// presence as "measured". |
| +public struct QualityCandidates: Encodable, Equatable, Sendable { |
| + public var host: Double? |
| + public var srflx: Double? |
| + public var prflx: Double? |
| + public var relay: Double? |
| + public var remoteHost: Double? |
| + public var remoteSrflx: Double? |
| + public var remotePrflx: Double? |
| + public var remoteRelay: Double? |
| + /// A pair with neither end a relay succeeded. |
| + public var directOk = false |
| + /// A pair whose local end is not a relay succeeded. |
| + public var localDirectOk = false |
| + /// A pair carried over UDP the whole way to the peer or the relay |
| + /// succeeded. |
| + public var udpOk = false |
| +} |
| + |
| public struct QualityPath: Encodable, Equatable, Sendable { |
| public var local: String? |
| public var remote: String? |
| @@ -127,6 +171,14 @@ public struct QualityOutStream: Encodable, Equatable, Sendable { |
| /// (2026-10-21). |
| public var damped: Double? |
| public var encoderStalls: Double? |
| + /// §15.29: how long bandwidth and the cpu each held the encoder back in |
| + /// the window, in seconds; the encoder's kind (CoderKinds), the codec's |
| + /// family (Codecs), and the screen's share mode (ShareModes). |
| + public var limitedBandwidthSeconds: Double? |
| + public var limitedCpuSeconds: Double? |
| + public var encoder: String? |
| + public var codec: String? |
| + public var mode: String? |
| } |
| public struct QualityInbound: Encodable, Equatable, Sendable { |
| @@ -165,6 +217,9 @@ public struct QualityInVideo: Encodable, Equatable, Sendable { |
| public var stalls: Double? |
| public var stallsNoPackets: Double? |
| public var stallsUndecoded: Double? |
| + /// §15.29: the decoder's kind (CoderKinds) and the codec's family. |
| + public var decoder: String? |
| + public var codec: String? |
| } |
| public struct QualityPeerEvents: Encodable, Equatable, Sendable { |
| @@ -183,7 +238,9 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable { |
| // MARK: - The snapshot |
| /// One statistics object from WebRTC's report, its values split by kind: |
| -/// numbers (NSNumber, booleans among them) and strings. Nothing else in a |
| +/// numbers (NSNumber, booleans among them) and strings. A dictionary of |
| +/// numbers (qualityLimitationDurations) is kept as numbers named |
| +/// "qualityLimitationDurations.bandwidth" and so on. Nothing else in a |
| /// report is read. |
| public struct QualityStat: Equatable, Sendable { |
| public var type: String |
| @@ -205,6 +262,10 @@ public struct QualityStat: Equatable, Sendable { |
| numbers[key] = n.doubleValue |
| } else if let s = value as? String { |
| strings[key] = s |
| + } else if let d = value as? [String: Any] { |
| + for (name, inner) in d { |
| + if let n = inner as? NSNumber { numbers[key + "." + name] = n.doubleValue } |
| + } |
| } |
| } |
| self.init(type: type, numbers: numbers, strings: strings) |
| @@ -234,6 +295,12 @@ public struct QualityPeerSample: Equatable, Sendable { |
| /// The cumulative counters and current gauges of one connection, as the |
| /// statistics have them. A report is the difference between two of these. |
| +/// |
| +/// What is read is read by name (§15.29 as §15.26): an encoder's or |
| +/// decoder's implementation name and a codec's MIME type become the |
| +/// schema's enums here, as they are read, and the selected pair's id is |
| +/// kept only to tell the next window it is the same pair. No address, |
| +/// port, url or implementation name is kept. |
| struct QualityCounters: Equatable, Sendable { |
| struct Out: Equatable, Sendable { |
| var bytes: Double? |
| @@ -245,6 +312,12 @@ struct QualityCounters: Equatable, Sendable { |
| var width: Double? |
| var height: Double? |
| var fps: Double? |
| + /// qualityLimitationDurations: seconds the encoder has been held back |
| + /// by each reason since the stream began, by reason. |
| + var limitSeconds: [String: Double]? |
| + /// CoderKinds and Codecs. |
| + var encoder: String? |
| + var codec: String? |
| } |
| struct InAudio: Equatable, Sendable { |
| var bytes: Double? |
| @@ -270,6 +343,9 @@ struct QualityCounters: Equatable, Sendable { |
| var width: Double? |
| var height: Double? |
| var fps: Double? |
| + /// CoderKinds and Codecs. |
| + var decoder: String? |
| + var codec: String? |
| } |
| var outAudio: Out? |
| var outVideo: Out? |
| @@ -279,6 +355,13 @@ struct QualityCounters: Equatable, Sendable { |
| var inScreen: InVideo? |
| var path: QualityPath? |
| var rtt: Double? |
| + /// The selected pair's id (the statistics' own, never sent) and its |
| + /// running totals: the round trips it has measured, in seconds, and the |
| + /// responses they came from. |
| + var pair: String? |
| + var totalRtt: Double? |
| + var responses: Double? |
| + var candidates: QualityCandidates? |
| init() {} |
| @@ -298,6 +381,11 @@ struct QualityCounters: Equatable, Sendable { |
| out.width = stat.numbers["frameWidth"] |
| out.height = stat.numbers["frameHeight"] |
| out.fps = stat.numbers["framesPerSecond"] |
| + out.limitSeconds = Self.limitSeconds(stat) |
| + out.encoder = QualityWords.coder( |
| + impl: stat.strings["encoderImplementation"], |
| + powerEfficient: stat.numbers["powerEfficientEncoder"].map { $0 != 0 }) |
| + out.codec = QualityWords.codec(mimeType: Self.mimeType(of: stat, in: stats)) |
| // The receiver's own account of this stream. |
| if let remote = stats.values.first(where: { $0.type == "remote-inbound-rtp" && $0.strings["localId"] == id }) { |
| out.lost = remote.numbers["packetsLost"] |
| @@ -340,6 +428,10 @@ struct QualityCounters: Equatable, Sendable { |
| v.width = stat.numbers["frameWidth"] |
| v.height = stat.numbers["frameHeight"] |
| v.fps = stat.numbers["framesPerSecond"] |
| + v.decoder = QualityWords.coder( |
| + impl: stat.strings["decoderImplementation"], |
| + powerEfficient: stat.numbers["powerEfficientDecoder"].map { $0 != 0 }) |
| + v.codec = QualityWords.codec(mimeType: Self.mimeType(of: stat, in: stats)) |
| // Told apart by mid, as the statistics elsewhere are: a peer |
| // sharing its screen sends two video streams. |
| if !sample.screenMid.isEmpty, mid == sample.screenMid { |
| @@ -352,6 +444,25 @@ struct QualityCounters: Equatable, Sendable { |
| } |
| } |
| readPath(stats) |
| + readCandidates(stats) |
| + } |
| + |
| + /// The reasons qualityLimitationDurations is kept for, as QualityStat |
| + /// flattens it. |
| + static let limitReasons = ["none", "cpu", "bandwidth", "other"] |
| + |
| + private static func limitSeconds(_ stat: QualityStat) -> [String: Double]? { |
| + var out: [String: Double] = [:] |
| + for reason in limitReasons { |
| + if let v = stat.numbers["qualityLimitationDurations." + reason] { out[reason] = v } |
| + } |
| + return out.isEmpty ? nil : out |
| + } |
| + |
| + /// The stream's codec's MIME type, through its codecId. |
| + private static func mimeType(of stat: QualityStat, in stats: [String: QualityStat]) -> String? { |
| + guard let id = stat.strings["codecId"], let codec = stats[id], codec.type == "codec" else { return nil } |
| + return codec.strings["mimeType"] |
| } |
| /// The selected candidate pair: each end's kind of candidate and the |
| @@ -378,6 +489,46 @@ struct QualityCounters: Equatable, Sendable { |
| } |
| self.path = path |
| rtt = pair.numbers["currentRoundTripTime"].map { $0 * 1000 } |
| + self.pair = pairId |
| + totalRtt = pair.numbers["totalRoundTripTime"] |
| + responses = pair.numbers["responsesReceived"] |
| + } |
| + |
| + /// §15.29: the candidates each side has, counted by type, and which |
| + /// kinds of pair succeeded. Nothing when the statistics have no |
| + /// candidates at all: a side that cannot read them says nothing, rather |
| + /// than "none". |
| + private mutating func readCandidates(_ stats: [String: QualityStat]) { |
| + let types: Set = ["host", "srflx", "prflx", "relay"] |
| + var local: [String: Double] = [:] |
| + var remote: [String: Double] = [:] |
| + var any = false |
| + for stat in stats.values where stat.type == "local-candidate" || stat.type == "remote-candidate" { |
| + any = true |
| + guard let type = stat.strings["candidateType"], types.contains(type) else { continue } |
| + if stat.type == "local-candidate" { local[type, default: 0] += 1 } else { remote[type, default: 0] += 1 } |
| + } |
| + guard any else { return } |
| + let some = { (n: Double?) in n.flatMap { $0 > 0 ? QualityReportBuilder.bound($0, QualityBounds.count) : nil } } |
| + var c = QualityCandidates( |
| + host: some(local["host"]), srflx: some(local["srflx"]), prflx: some(local["prflx"]), |
| + relay: some(local["relay"]), remoteHost: some(remote["host"]), remoteSrflx: some(remote["srflx"]), |
| + remotePrflx: some(remote["prflx"]), remoteRelay: some(remote["relay"])) |
| + for pair in stats.values where pair.type == "candidate-pair" && pair.strings["state"] == "succeeded" { |
| + guard let near = pair.strings["localCandidateId"].flatMap({ stats[$0] }), |
| + let nearType = near.strings["candidateType"], types.contains(nearType) |
| + else { continue } |
| + let farType = pair.strings["remoteCandidateId"].flatMap { stats[$0] }?.strings["candidateType"] |
| + let relayed = nearType == "relay" |
| + if !relayed { c.localDirectOk = true } |
| + if !relayed, let farType, types.contains(farType), farType != "relay" { c.directOk = true } |
| + if near.strings["protocol"]?.lowercased() == "udp", |
| + !relayed || near.strings["relayProtocol"]?.lowercased() == "udp" |
| + { |
| + c.udpOk = true |
| + } |
| + } |
| + candidates = c |
| } |
| private static func sum(_ a: Double?, _ b: Double?) -> Double? { |
| @@ -402,6 +553,11 @@ struct QualityCounters: Equatable, Sendable { |
| a.width = most(a.width, b.width) |
| a.height = most(a.height, b.height) |
| a.fps = most(a.fps, b.fps) |
| + if let more = b.limitSeconds { |
| + a.limitSeconds = (a.limitSeconds ?? [:]).merging(more, uniquingKeysWith: +) |
| + } |
| + a.encoder = a.encoder ?? b.encoder |
| + a.codec = a.codec ?? b.codec |
| return a |
| } |
| private static func add(_ a: InVideo?, _ b: InVideo) -> InVideo { |
| @@ -417,6 +573,8 @@ struct QualityCounters: Equatable, Sendable { |
| a.width = most(a.width, b.width) |
| a.height = most(a.height, b.height) |
| a.fps = most(a.fps, b.fps) |
| + a.decoder = a.decoder ?? b.decoder |
| + a.codec = a.codec ?? b.codec |
| return a |
| } |
| } |
| @@ -432,7 +590,10 @@ enum QualityWords { |
| /// udp or tcp; tls for a relay reached over TURN/TLS. |
| static func transport(_ proto: String?, relayProtocol: String?, relay: Bool) -> String { |
| - if relay, relayProtocol?.lowercased() == "tls" { return "tls" } |
| + // A relay candidate's own protocol is the relay's leg to the peer; how |
| + // this side reaches the relay is relayProtocol, as room.js reads it |
| + // (2026-10-28: TURN over TCP was "udp" here and "tcp" on the web). |
| + if relay, let via = relayProtocol?.lowercased(), ["udp", "tcp", "tls"].contains(via) { return via } |
| switch proto?.lowercased() { |
| case "udp": return "udp" |
| case "tcp": return "tcp" |
| @@ -444,6 +605,39 @@ enum QualityWords { |
| guard let reason, !reason.isEmpty else { return nil } |
| return ["none", "cpu", "bandwidth"].contains(reason) ? reason : "other" |
| } |
| + |
| + /// A video encoder's or decoder's kind (§15.29, CoderKinds), the web |
| + /// client's coderKind: the stack's own powerEfficientEncoder/Decoder |
| + /// where it says, else the implementation's name ("VideoToolbox", |
| + /// "libvpx", "FallbackEncoder (…)"), which never leaves this function; |
| + /// "unknown" for a name it cannot place, nil when there is nothing. |
| + static func coder(impl: String?, powerEfficient: Bool?) -> String? { |
| + if let powerEfficient { return powerEfficient ? "hardware" : "software" } |
| + guard let name = impl?.lowercased(), !name.isEmpty else { return nil } |
| + let hardware = [ |
| + "videotoolbox", "external", "mediacodec", "vaapi", "v4l2", "d3d11", "dxva", "nvenc", "nvdec", |
| + "mediafoundation", "qsv", "amf", |
| + ] |
| + if hardware.contains(where: name.contains) { return "hardware" } |
| + let software = ["libvpx", "openh264", "libaom", "dav1d", "ffmpeg", "libav", "fallback", "software"] |
| + if software.contains(where: name.contains) { return "software" } |
| + return "unknown" |
| + } |
| + |
| + /// A stream's codec family (§15.29, Codecs) from its MIME type, the web |
| + /// client's codecKind: "other" for one not on the list, nil for none. |
| + static func codec(mimeType: String?) -> String? { |
| + guard let m = mimeType?.lowercased(), !m.isEmpty else { return nil } |
| + switch m { |
| + case "video/vp8": return "vp8" |
| + case "video/vp9": return "vp9" |
| + case "video/h264": return "h264" |
| + case "video/h265", "video/hevc": return "h265" |
| + case "video/av1": return "av1" |
| + case "audio/opus": return "opus" |
| + default: return "other" |
| + } |
| + } |
| } |
| // MARK: - The notices, tallied |
| @@ -558,16 +752,48 @@ public struct QualityEventTally: Equatable, Sendable { |
| } |
| } |
| +// MARK: - The window's once-a-second readings |
| + |
| +/// One peer's round trip and inbound jitter, read once a second through a |
| +/// window (§15.29): a sum, a count and the highest, in ms. The report says |
| +/// the mean and the highest, so a window that spiked and settled is not |
| +/// reported as the moment it ended. |
| +struct QualityWindowSamples: Equatable, Sendable { |
| + var rttSum = 0.0 |
| + var rttCount = 0 |
| + var rttMax = 0.0 |
| + var jitterSum = 0.0 |
| + var jitterCount = 0 |
| + var jitterMax = 0.0 |
| + |
| + /// One reading; a value that is not a finite, non-negative number is |
| + /// not one. |
| + mutating func add(rtt: Double?, jitter: Double?) { |
| + if let rtt, rtt.isFinite, rtt >= 0 { |
| + rttSum += rtt |
| + rttCount += 1 |
| + rttMax = max(rttMax, rtt) |
| + } |
| + if let jitter, jitter.isFinite, jitter >= 0 { |
| + jitterSum += jitter |
| + jitterCount += 1 |
| + jitterMax = max(jitterMax, jitter) |
| + } |
| + } |
| +} |
| + |
| // MARK: - The report |
| /// Turns snapshots into reports: keeps each connection's running totals |
| /// from the last report, so a report's counts are what happened during |
| /// its window. A new connection generation, or a counter that went |
| /// backwards (a stream rebuilt on a fresh transceiver), starts from |
| -/// nothing. |
| +/// nothing. Between reports, `observe` takes the once-a-second readings |
| +/// the window's round trip and jitter are made from (§15.29). |
| public struct QualityReportBuilder: Equatable, Sendable { |
| private var since: Double? |
| private var previous: [String: (generation: Int64, counters: QualityCounters)] = [:] |
| + private var window: [String: QualityWindowSamples] = [:] |
| public init() {} |
| @@ -580,16 +806,30 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| public mutating func start(at now: Double) { |
| since = now |
| previous = [:] |
| + window = [:] |
| } |
| public static func == (a: Self, b: Self) -> Bool { |
| - a.since == b.since && a.previous.keys == b.previous.keys |
| + a.since == b.since && a.previous.keys == b.previous.keys && a.window == b.window |
| + } |
| + |
| + /// One look at every connection, once a second (§15.29): the selected |
| + /// pair's round trip and the peer's inbound jitter — their audio, or |
| + /// their camera when no audio arrives — for the window's mean and |
| + /// highest. |
| + public mutating func observe(samples: [String: QualityPeerSample]) { |
| + for (id, sample) in samples { |
| + let now = QualityCounters(sample) |
| + window[id, default: QualityWindowSamples()].add(rtt: now.rtt, jitter: now.inAudio?.jitter ?? now.inVideo?.jitter) |
| + } |
| } |
| /// One report, for the window from the last one (or `start`) to `now`. |
| + /// `screenMode` is this app's screen share mode (ScreenShareMode's raw |
| + /// value) while it shares, and nil while it does not. |
| public mutating func build( |
| at now: Double, samples: [String: QualityPeerSample], events tally: inout QualityEventTally, |
| - client: QualityClient, devices: QualityDevices?, final: Bool |
| + client: QualityClient, devices: QualityDevices?, final: Bool, screenMode: String? = nil |
| ) -> QualityReport { |
| let seconds = max(now - (since ?? now), 0.1) |
| since = now |
| @@ -612,10 +852,12 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| previous[id] = (sample.generation, now) |
| peer.path = now.path |
| peer.rtt = Self.bound(now.rtt, QualityBounds.millis) |
| + Self.applyWindow(window[id], now: now, before: before, to: &peer) |
| + peer.candidates = now.candidates |
| var out = QualityOutbound() |
| - out.audio = now.outAudio.map { Self.out($0, before?.outAudio, seconds) } |
| - out.video = now.outVideo.map { Self.out($0, before?.outVideo, seconds) } |
| - out.screen = now.outScreen.map { Self.out($0, before?.outScreen, seconds) } |
| + out.audio = now.outAudio.map { Self.out($0, before?.outAudio, seconds, video: false) } |
| + out.video = now.outVideo.map { Self.out($0, before?.outVideo, seconds, video: true) } |
| + out.screen = now.outScreen.map { Self.out($0, before?.outScreen, seconds, video: true) } |
| if out != QualityOutbound() { peer.out = out } |
| var inbound = QualityInbound() |
| inbound.audio = now.inAudio.map { Self.inAudio($0, before?.inAudio, seconds) } |
| @@ -624,14 +866,41 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| if inbound != QualityInbound() { peer.in = inbound } |
| } |
| if let e = events.peers[id] { Self.apply(e, to: &peer) } |
| + if let screenMode, peer.out?.screen != nil { peer.out?.screen?.mode = screenMode } |
| peers.append(peer) |
| } |
| // A connection gone is forgotten; if it comes back it starts again. |
| for id in Array(previous.keys) where samples[id] == nil { previous.removeValue(forKey: id) } |
| + window = [:] |
| report.peers = peers.isEmpty ? nil : peers |
| return report |
| } |
| + /// The window's round trip and jitter (§15.29). The mean round trip is |
| + /// the pair's own: what its totals moved by, over the responses they |
| + /// came from, where the pair is the one the last report read (a new |
| + /// pair, or a new connection, counts from nothing, as a new stream |
| + /// does); without responses, the once-a-second readings' mean. The |
| + /// highest is of those readings and this one. |
| + private static func applyWindow( |
| + _ w: QualityWindowSamples?, now: QualityCounters, before: QualityCounters?, to peer: inout QualityPeer |
| + ) { |
| + let same = before?.pair != nil && before?.pair == now.pair |
| + if let responses = delta(now.responses, same ? before?.responses : nil), responses > 0, |
| + let total = delta(now.totalRtt, same ? before?.totalRtt : nil) |
| + { |
| + peer.rttAvg = bound(total / responses * 1000, QualityBounds.millis) |
| + } else if let w, w.rttCount > 0 { |
| + peer.rttAvg = bound(w.rttSum / Double(w.rttCount), QualityBounds.millis) |
| + } |
| + let highest = [w.flatMap { $0.rttCount > 0 ? $0.rttMax : nil }, now.rtt].compactMap { $0 }.max() |
| + peer.rttMax = bound(highest, QualityBounds.millis) |
| + if let w, w.jitterCount > 0 { |
| + peer.jitterAvg = bound(w.jitterSum / Double(w.jitterCount), QualityBounds.millis) |
| + peer.jitterMax = bound(w.jitterMax, QualityBounds.millis) |
| + } |
| + } |
| + |
| private static func apply(_ e: QualityEventTally.Peer, to peer: inout QualityPeer) { |
| var events = QualityPeerEvents() |
| events.reconnecting = steps(e.reconnecting) |
| @@ -693,9 +962,9 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| return bound(bytes * 8 / 1000 / seconds, QualityBounds.kbps) |
| } |
| - private static func out(_ now: QualityCounters.Out, _ before: QualityCounters.Out?, _ seconds: Double) |
| - -> QualityOutStream |
| - { |
| + private static func out( |
| + _ now: QualityCounters.Out, _ before: QualityCounters.Out?, _ seconds: Double, video: Bool |
| + ) -> QualityOutStream { |
| var s = QualityOutStream() |
| s.kbps = kbps(delta(now.bytes, before?.bytes), seconds) |
| s.packets = bound(delta(now.packets, before?.packets), QualityBounds.count) |
| @@ -706,6 +975,25 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| s.width = bound(now.width, QualityBounds.pixels) |
| s.height = bound(now.height, QualityBounds.pixels) |
| s.fps = bound(now.fps, QualityBounds.fps) |
| + guard video else { return s } |
| + // §15.29: the reason that held the encoder back longest in the window, |
| + // where the stack keeps the durations — a tie to bandwidth, then cpu, |
| + // then other, then none, the reasons that say most first, and only a |
| + // reason that held for some of it — else the latest reason. |
| + if let durations = now.limitSeconds { |
| + let held = { (reason: String) in delta(durations[reason], before?.limitSeconds?[reason]) } |
| + var longest = 0.0 |
| + for reason in ["bandwidth", "cpu", "other", "none"] { |
| + if let d = held(reason), d > longest { |
| + s.limit = reason |
| + longest = d |
| + } |
| + } |
| + s.limitedBandwidthSeconds = bound(held("bandwidth"), QualityBounds.seconds) |
| + s.limitedCpuSeconds = bound(held("cpu"), QualityBounds.seconds) |
| + } |
| + s.encoder = now.encoder |
| + s.codec = now.codec |
| return s |
| } |
| @@ -746,6 +1034,8 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| v.width = bound(now.width, QualityBounds.pixels) |
| v.height = bound(now.height, QualityBounds.pixels) |
| v.fps = bound(now.fps, QualityBounds.fps) |
| + v.decoder = now.decoder |
| + v.codec = now.codec |
| return v |
| } |
| } |
| @@ -823,3 +1113,116 @@ public enum QualityReporting { |
| /// The settings line, both platforms. |
| public static let disclosure = "Calls sends anonymous connection quality reports to help fix call problems." |
| } |
| + |
| +// MARK: - The automatic report (§15.29) |
| + |
| +/// What counts as a call struggling, and how often an app may say so: |
| +/// protocol/quality.go's rules, which the server enforces on its own and |
| +/// the web client holds as well. |
| +public enum AutoReportRules { |
| + /// Inbound freezes, this window and the one before it: at least this |
| + /// many in each. |
| + public static let freezes = 3.0 |
| + /// The window's highest round trip, this window and the one before it: |
| + /// above this in each, in ms. |
| + public static let rttMillis = 800.0 |
| + /// "Reconnecting…" (the call's or a person's) shown for longer than this |
| + /// in one window, in seconds. |
| + public static let reconnectingSeconds = 5.0 |
| + public static let perCall = 3 |
| + public static let everyMinutes = 10.0 |
| + /// AutoTriggers, in the order they are checked. |
| + public static let triggers = ["freezes", "rtt", "reconnecting", "screen"] |
| +} |
| + |
| +/// The rules, read from a window's report. Pure. |
| +public enum QualityTrouble { |
| + /// What one window's report says about the call, for the rules. |
| + public struct Facts: Equatable, Sendable { |
| + /// Freezes of everything arriving: cameras and screens, every peer. |
| + public var freezes: Double |
| + /// The highest round trip anything in the report saw, in ms. |
| + public var maxRtt: Double |
| + /// The longest "Reconnecting…" showed, the call's or anyone's. |
| + public var reconnectingSeconds: Double |
| + /// The screen's ladder went past its keyframes toward anyone: a |
| + /// rebuild, a share again, or giving up. |
| + public var screenEscalated: Bool |
| + |
| + public init(freezes: Double = 0, maxRtt: Double = 0, reconnectingSeconds: Double = 0, screenEscalated: Bool = false) { |
| + self.freezes = freezes |
| + self.maxRtt = maxRtt |
| + self.reconnectingSeconds = reconnectingSeconds |
| + self.screenEscalated = screenEscalated |
| + } |
| + } |
| + |
| + public static func facts(_ report: QualityReport) -> Facts { |
| + var facts = Facts(reconnectingSeconds: report.events?.reconnectingSeconds ?? 0) |
| + for peer in report.peers ?? [] { |
| + facts.freezes += (peer.in?.video?.freezes ?? 0) + (peer.in?.screen?.freezes ?? 0) |
| + let rtts = [peer.rttMax, peer.rtt, peer.out?.audio?.rtt, peer.out?.video?.rtt, peer.out?.screen?.rtt] |
| + facts.maxRtt = max(facts.maxRtt, rtts.compactMap { $0 }.max() ?? 0) |
| + facts.reconnectingSeconds = max(facts.reconnectingSeconds, peer.events?.reconnectingSeconds ?? 0) |
| + if let screen = peer.out?.screen, (screen.rebuilds ?? 0) + (screen.reshares ?? 0) + (screen.failures ?? 0) > 0 { |
| + facts.screenEscalated = true |
| + } |
| + } |
| + return facts |
| + } |
| + |
| + /// The first rule that holds, in AutoTriggers' order, or nil. The |
| + /// freezes and the round trip need two windows in a row; a window with |
| + /// nothing before it (the first, or one after reports were off) cannot |
| + /// meet them. |
| + public static func trigger(previous: Facts?, now: Facts) -> String? { |
| + if let previous, previous.freezes >= AutoReportRules.freezes, now.freezes >= AutoReportRules.freezes { |
| + return "freezes" |
| + } |
| + if let previous, previous.maxRtt > AutoReportRules.rttMillis, now.maxRtt > AutoReportRules.rttMillis { |
| + return "rtt" |
| + } |
| + if now.reconnectingSeconds > AutoReportRules.reconnectingSeconds { return "reconnecting" } |
| + if now.screenEscalated { return "screen" } |
| + return nil |
| + } |
| +} |
| + |
| +/// How many automatic reports this participation has sent, and when the |
| +/// last went: at most AutoReportRules.perCall, at least everyMinutes apart. |
| +public struct AutoReportGate: Equatable, Sendable { |
| + public private(set) var sent = 0 |
| + public private(set) var last: Double? |
| + |
| + public init() {} |
| + |
| + public func allows(at now: Double) -> Bool { |
| + guard sent < AutoReportRules.perCall else { return false } |
| + guard let last else { return true } |
| + return now - last >= AutoReportRules.everyMinutes * 60 |
| + } |
| + |
| + /// One sent (or tried: one the server refused still counts, so a server |
| + /// saying no is not asked again every window). |
| + public mutating func record(at now: Double) { |
| + sent += 1 |
| + last = now |
| + } |
| +} |
| + |
| +/// Whether this window sends the automatic report, and why. Pure. |
| +public enum AutoReportDecision { |
| + /// The trigger to send, or nil. Never for the final report, never with |
| + /// quality reports switched off in Settings (`enabled`) or the server's |
| + /// kill switch thrown (`stopped`), and never past the gate. `forced` is |
| + /// the gate's test hook (CALLS_AUTO_REPORT_TEST): a trigger the rules |
| + /// need not have met, for a window the rest of this allows. |
| + public static func trigger( |
| + previous: QualityTrouble.Facts?, now: QualityTrouble.Facts, gate: AutoReportGate, at time: Double, |
| + enabled: Bool, stopped: Bool, final: Bool, forced: String? = nil |
| + ) -> String? { |
| + guard !final, enabled, !stopped, gate.allows(at: time) else { return nil } |
| + if let forced, AutoReportRules.triggers.contains(forced) { return forced } |
| + return QualityTrouble.trigger(previous: previous, now: now) |
| + } |
| +} |
diff --git a/native/apple/Sources/CallsKit/ReportProblem.swift b/native/apple/Sources/CallsKit/ReportProblem.swift| index 32cc1da..0ed328f 100644 |
| --- a/native/apple/Sources/CallsKit/ReportProblem.swift |
| +++ b/native/apple/Sources/CallsKit/ReportProblem.swift |
| @@ -114,14 +114,60 @@ struct ProblemReportBody: Encodable { |
| /// JSON within the server's 64 KB: diagnostics are cut from the front, |
| /// keeping the newest lines, which are the ones about the problem. |
| func encoded() -> String { |
| - var diagnostics = self.diagnostics |
| - while true { |
| - let body = ProblemReportBody(note: note, diagnostics: diagnostics, client: client) |
| - let data = (try? JSONEncoder().encode(body)) ?? Data() |
| - if data.count <= QualityBounds.problemBody - 256 || diagnostics.isEmpty { |
| - return String(data: data, encoding: .utf8) ?? "{}" |
| - } |
| - diagnostics = "(earlier lines cut)\n" + String(diagnostics.suffix(diagnostics.count * 3 / 4)) |
| + withinProblemBody(diagnostics) { ProblemReportBody(note: note, diagnostics: $0, client: client) } |
| + } |
| +} |
| + |
| +/// The automatic report's body (§15.29): protocol.AutoReport. What Report |
| +/// a problem sends, scrubbed the same way, and no note, because nobody |
| +/// typed one; `trigger` is the rule that fired. |
| +struct AutoReportBody: Encodable { |
| + let trigger: String |
| + let diagnostics: String |
| + let client: QualityClient |
| + |
| + /// Within the server's 64 KB, as a problem report is. |
| + func encoded() -> String { |
| + withinProblemBody(diagnostics) { AutoReportBody(trigger: trigger, diagnostics: $0, client: client) } |
| + } |
| +} |
| + |
| +/// A report's JSON with its diagnostics cut from the front until the whole |
| +/// is under the server's 64 KB, with a margin. |
| +private func withinProblemBody<Body: Encodable>(_ diagnostics: String, _ body: (String) -> Body) -> String { |
| + var diagnostics = diagnostics |
| + while true { |
| + let data = (try? JSONEncoder().encode(body(diagnostics))) ?? Data() |
| + if data.count <= QualityBounds.problemBody - 256 || diagnostics.isEmpty { |
| + return String(data: data, encoding: .utf8) ?? "{}" |
| + } |
| + diagnostics = "(earlier lines cut)\n" + String(diagnostics.suffix(diagnostics.count * 3 / 4)) |
| + } |
| +} |
| + |
| +/// What became of an automatic report, from the bridge's answer |
| +/// (bridge.SendAutoReport). |
| +public enum AutoReportOutcome: Equatable, Sendable { |
| + case sent(ref: String) |
| + /// The server's kill switch: no more quality or automatic reports this |
| + /// call. |
| + case stop |
| + /// Not sent ("too-many", "gone", "failed"): the call goes on as before. |
| + case notSent(String) |
| + |
| + /// `{"ref":"K7Q2M9PD"}` or `{"outcome":"stop"|"too-many"|"gone"|"failed"}`. |
| + public init(bridgeAnswer: String) { |
| + struct Answer: Decodable { |
| + let ref: String? |
| + let outcome: String? |
| + } |
| + let answer = try? JSONDecoder().decode(Answer.self, from: Data(bridgeAnswer.utf8)) |
| + if let ref = answer?.ref, !ref.isEmpty { |
| + self = .sent(ref: ref) |
| + } else if answer?.outcome == "stop" { |
| + self = .stop |
| + } else { |
| + self = .notSent(answer?.outcome ?? "failed") |
| } |
| } |
| } |
diff --git a/native/apple/Tests/CallsKitTests/QualityReportTests.swift b/native/apple/Tests/CallsKitTests/QualityReportTests.swift| index b7e8927..b0151ed 100644 |
| --- a/native/apple/Tests/CallsKitTests/QualityReportTests.swift |
| +++ b/native/apple/Tests/CallsKitTests/QualityReportTests.swift |
| @@ -6,7 +6,9 @@ import XCTest |
| /// over the window, rates, the schema's enums and bounds — and nothing in |
| /// it that names a person, a device or an address; the notices tallied; |
| /// the device kinds; "Report a problem"'s anonymous diagnostics and its |
| -/// sheet's states. |
| +/// sheet's states. Spec §15.29: the window's round trip and jitter, the |
| +/// candidates, the dominant limit, the coders and codecs; and the |
| +/// automatic report's rules, gate and body. |
| final class QualityReportTests: XCTestCase { |
| // MARK: - Fixtures |
| @@ -199,6 +201,8 @@ final class QualityReportTests: XCTestCase { |
| XCTAssertEqual(QualityWords.candidate(nil), "unknown") |
| XCTAssertEqual(QualityWords.transport("tcp", relayProtocol: nil, relay: false), "tcp") |
| XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tls", relay: true), "tls") |
| + XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tcp", relay: true), "tcp") |
| + XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "udp", relay: true), "udp") |
| XCTAssertEqual(QualityWords.transport("udp", relayProtocol: "tls", relay: false), "udp") |
| XCTAssertEqual(QualityWords.transport(nil, relayProtocol: nil, relay: false), "unknown") |
| } |
| @@ -246,6 +250,450 @@ final class QualityReportTests: XCTestCase { |
| XCTAssertNotNil(current.osVersion) |
| } |
| + // MARK: - §15.29: the window's detail |
| + |
| + /// A relayed connection, as WebRTC's report has it: this side gathered a |
| + /// host, a srflx and a relay (TURN over TLS), the peer offered a srflx, |
| + /// and the selected pair is relay to srflx. With `direct`, a srflx to |
| + /// srflx pair also succeeded. Planted: addresses, ports, the relay's |
| + /// url, the encoder's and decoder's implementation names and the codec's |
| + /// format line, none of which may be reported. |
| + static func relayed( |
| + direct: Bool = false, rtt: Double = 0.12, totalRtt: Double? = 3.0, responses: Double? = 30, |
| + pair: String = "CPrelay_srflx", audioJitter: Double = 0.018, limit: [String: Double]? = nil, |
| + reason: String = "bandwidth" |
| + ) -> QualityPeerSample { |
| + var pairNumbers: [String: Double] = ["currentRoundTripTime": rtt, "nominated": 1] |
| + pairNumbers["totalRoundTripTime"] = totalRtt |
| + pairNumbers["responsesReceived"] = responses |
| + var outVideo: [String: Double] = [ |
| + "bytesSent": 900_000, "packetsSent": 900, "frameWidth": 640, "frameHeight": 360, "framesPerSecond": 15, |
| + ] |
| + for (k, v) in limit ?? [:] { outVideo["qualityLimitationDurations." + k] = v } |
| + var stats: [String: QualityStat] = [ |
| + "T": QualityStat(type: "transport", strings: ["selectedCandidatePairId": pair]), |
| + pair: QualityStat( |
| + type: "candidate-pair", numbers: pairNumbers, |
| + strings: ["localCandidateId": "LR", "remoteCandidateId": "RS", "state": "succeeded"]), |
| + "CPhost": QualityStat( |
| + type: "candidate-pair", strings: ["localCandidateId": "LH", "remoteCandidateId": "RS", "state": "failed"]), |
| + "LH": QualityStat( |
| + type: "local-candidate", numbers: ["port": 50000], |
| + strings: ["candidateType": "host", "protocol": "udp", "address": "192.168.1.20"]), |
| + "LS": QualityStat( |
| + type: "local-candidate", numbers: ["port": 50001, "relatedPort": 50000], |
| + strings: [ |
| + "candidateType": "srflx", "protocol": "udp", "address": "198.51.100.4", "relatedAddress": "192.168.1.20", |
| + "url": "stun:stun.example.com:3478", |
| + ]), |
| + "LR": QualityStat( |
| + type: "local-candidate", numbers: ["port": 50002], |
| + strings: [ |
| + "candidateType": "relay", "protocol": "udp", "relayProtocol": "tls", "address": "203.0.113.50", |
| + "url": "turns:relay.example.com:443?transport=tcp", |
| + ]), |
| + "RS": QualityStat( |
| + type: "remote-candidate", numbers: ["port": 61000], |
| + strings: ["candidateType": "srflx", "protocol": "udp", "address": "203.0.113.7"]), |
| + "OV": QualityStat( |
| + type: "outbound-rtp", numbers: outVideo, |
| + strings: [ |
| + "kind": "video", "mid": "1", "qualityLimitationReason": reason, |
| + "encoderImplementation": "SimulcastEncoderAdapter (VideoToolbox)", "codecId": "COT", |
| + ]), |
| + "COT": QualityStat( |
| + type: "codec", numbers: ["payloadType": 102], |
| + strings: ["mimeType": "video/H264", "sdpFmtpLine": "level-asymmetry-allowed=1;profile-level-id=42e01f"]), |
| + "IA": QualityStat( |
| + type: "inbound-rtp", numbers: ["packetsReceived": 1500, "jitter": audioJitter], |
| + strings: ["kind": "audio", "mid": "0", "codecId": "CIA"]), |
| + "CIA": QualityStat(type: "codec", strings: ["mimeType": "audio/opus"]), |
| + "IV": QualityStat( |
| + type: "inbound-rtp", |
| + numbers: ["packetsReceived": 1200, "jitter": 0.03, "framesDecoded": 450, "freezeCount": 0], |
| + strings: ["kind": "video", "mid": "1", "decoderImplementation": "libvpx", "codecId": "CIV"]), |
| + "CIV": QualityStat(type: "codec", strings: ["mimeType": "video/VP8"]), |
| + ] |
| + if direct { |
| + stats["CPdirect"] = QualityStat( |
| + type: "candidate-pair", strings: ["localCandidateId": "LS", "remoteCandidateId": "RS", "state": "succeeded"]) |
| + } |
| + return QualityPeerSample(generation: 1, stats: stats) |
| + } |
| + |
| + func testARelayedConnectionSaysWhy() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + var report = build(&builder, at: 30, ["p1": Self.relayed()]) |
| + var peer = try XCTUnwrap(report.peers?.first) |
| + XCTAssertEqual(peer.path, QualityPath(local: "relay", remote: "srflx", protocol: "tls")) |
| + // This side found its public address, and nothing direct worked. |
| + XCTAssertEqual( |
| + peer.candidates, |
| + QualityCandidates( |
| + host: 1, srflx: 1, relay: 1, remoteSrflx: 1, directOk: false, localDirectOk: false, udpOk: false)) |
| + // And with a direct pair that worked beside it. |
| + report = build(&builder, at: 60, ["p1": Self.relayed(direct: true)]) |
| + peer = try XCTUnwrap(report.peers?.first) |
| + XCTAssertEqual( |
| + peer.candidates, |
| + QualityCandidates(host: 1, srflx: 1, relay: 1, remoteSrflx: 1, directOk: true, localDirectOk: true, udpOk: true)) |
| + // The booleans go even when false: the struct's presence is "measured". |
| + var relayedOnly = QualityReportBuilder() |
| + relayedOnly.start(at: 0) |
| + let json = try XCTUnwrap(build(&relayedOnly, at: 30, ["p1": Self.relayed()]).encoded()) |
| + XCTAssertTrue(json.contains(#""directOk":false"#), json) |
| + XCTAssertTrue(json.contains(#""localDirectOk":false"#), json) |
| + XCTAssertTrue(json.contains(#""udpOk":false"#), json) |
| + XCTAssertFalse(json.contains("remoteHost"), "a type with none is left out: \(json)") |
| + } |
| + |
| + func testNoCandidatesInTheStatisticsIsNoCandidates() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + var sample = Self.relayed() |
| + sample.stats = sample.stats.filter { !$0.value.type.hasSuffix("-candidate") } |
| + let report = build(&builder, at: 30, ["p1": sample]) |
| + XCTAssertNil(report.peers?.first?.candidates, "a side that cannot read them says nothing, not none") |
| + } |
| + |
| + func testARelayOverUDPAndAHostPairAreUDP() throws { |
| + var sample = Self.relayed() |
| + sample.stats["LR"]?.strings["relayProtocol"] = "udp" |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + var c = try XCTUnwrap(build(&builder, at: 30, ["p1": sample]).peers?.first?.candidates) |
| + XCTAssertTrue(c.udpOk, "UDP to the relay, and the relay's leg is UDP") |
| + XCTAssertFalse(c.localDirectOk) |
| + XCTAssertFalse(c.directOk) |
| + // A pair from this side's own address to the peer's relay: local |
| + // direct, not direct. |
| + sample = Self.relayed() |
| + sample.stats["RR"] = QualityStat(type: "remote-candidate", strings: ["candidateType": "relay", "protocol": "udp"]) |
| + sample.stats["CPtheirs"] = QualityStat( |
| + type: "candidate-pair", strings: ["localCandidateId": "LH", "remoteCandidateId": "RR", "state": "succeeded"]) |
| + c = try XCTUnwrap(build(&builder, at: 60, ["p1": sample]).peers?.first?.candidates) |
| + XCTAssertTrue(c.localDirectOk) |
| + XCTAssertFalse(c.directOk) |
| + XCTAssertTrue(c.udpOk) |
| + XCTAssertEqual(c.remoteRelay, 1) |
| + } |
| + |
| + func testTheEncodersDecodersAndCodecsAreEnums() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + let peer = try XCTUnwrap(build(&builder, at: 30, ["p1": Self.relayed()]).peers?.first) |
| + XCTAssertEqual(peer.out?.video?.encoder, "hardware") |
| + XCTAssertEqual(peer.out?.video?.codec, "h264") |
| + XCTAssertEqual(peer.in?.video?.decoder, "software") |
| + XCTAssertEqual(peer.in?.video?.codec, "vp8") |
| + XCTAssertNil(peer.out?.audio, "nothing goes out here but the camera") |
| + // The stack's own word wins over the name. |
| + var sample = Self.relayed() |
| + sample.stats["OV"]?.numbers["powerEfficientEncoder"] = 0 |
| + sample.stats["IV"]?.numbers["powerEfficientDecoder"] = 1 |
| + var again = QualityReportBuilder() |
| + again.start(at: 0) |
| + let other = try XCTUnwrap(build(&again, at: 30, ["p1": sample]).peers?.first) |
| + XCTAssertEqual(other.out?.video?.encoder, "software") |
| + XCTAssertEqual(other.in?.video?.decoder, "hardware") |
| + } |
| + |
| + func testTheCoderAndCodecTables() { |
| + XCTAssertEqual(QualityWords.coder(impl: "libvpx", powerEfficient: true), "hardware") |
| + XCTAssertEqual(QualityWords.coder(impl: "VideoToolbox", powerEfficient: false), "software") |
| + XCTAssertEqual(QualityWords.coder(impl: nil, powerEfficient: true), "hardware") |
| + for name in [ |
| + "VideoToolbox", "ExternalEncoder", "MediaCodec", "VAAPI", "V4L2", "D3D11", "DXVA2", "NVENC", "NVDEC", |
| + "MediaFoundationVideoEncodeAccelerator", "QSV", "AMF", |
| + ] { |
| + XCTAssertEqual(QualityWords.coder(impl: name, powerEfficient: nil), "hardware", name) |
| + } |
| + for name in [ |
| + "libvpx", "OpenH264", "libaom", "dav1d", "FFmpeg", "libavcodec", "FallbackEncoder (libvpx)", "SoftwareH264", |
| + ] { |
| + XCTAssertEqual(QualityWords.coder(impl: name, powerEfficient: nil), "software", name) |
| + } |
| + XCTAssertEqual(QualityWords.coder(impl: "SomethingNew", powerEfficient: nil), "unknown") |
| + XCTAssertNil(QualityWords.coder(impl: "", powerEfficient: nil)) |
| + XCTAssertNil(QualityWords.coder(impl: nil, powerEfficient: nil)) |
| + for (mime, codec) in [ |
| + ("video/VP8", "vp8"), ("video/vp9", "vp9"), ("video/H264", "h264"), ("video/H265", "h265"), |
| + ("video/HEVC", "h265"), ("video/AV1", "av1"), ("audio/opus", "opus"), ("audio/PCMU", "other"), |
| + ("video/rtx", "other"), |
| + ] { |
| + XCTAssertEqual(QualityWords.codec(mimeType: mime), codec, mime) |
| + } |
| + XCTAssertNil(QualityWords.codec(mimeType: nil)) |
| + XCTAssertNil(QualityWords.codec(mimeType: "")) |
| + } |
| + |
| + func testTheMeanRoundTripIsThePairsOwnOverTheWindow() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + // The first window: everything the pair has, 3 s over 30 responses. |
| + var peer = try XCTUnwrap(build(&builder, at: 30, ["p1": Self.relayed()]).peers?.first) |
| + XCTAssertEqual(peer.rttAvg, 100) |
| + XCTAssertEqual(peer.rttMax, 120, "no readings yet: the last walk's") |
| + // The next: 6 s more over 20 more responses. |
| + peer = try XCTUnwrap(build(&builder, at: 60, ["p1": Self.relayed(totalRtt: 9, responses: 50)]).peers?.first) |
| + XCTAssertEqual(peer.rttAvg, 300) |
| + // A new pair counts from nothing, not from the old pair's totals. |
| + peer = try XCTUnwrap( |
| + build(&builder, at: 90, ["p1": Self.relayed(totalRtt: 4, responses: 20, pair: "CPnew")]).peers?.first) |
| + XCTAssertEqual(peer.rttAvg, 200) |
| + } |
| + |
| + func testTheSamplerGivesTheWindowsMeanAndHighest() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + for (rtt, jitter) in [(0.1, 0.01), (0.5, 0.03), (0.2, 0.02)] { |
| + builder.observe(samples: ["p1": Self.relayed(rtt: rtt, totalRtt: nil, responses: nil, audioJitter: jitter)]) |
| + } |
| + // No pair totals: the mean is the readings'. |
| + var peer = try XCTUnwrap( |
| + build(&builder, at: 30, ["p1": Self.relayed(rtt: 0.15, totalRtt: nil, responses: nil)]).peers?.first) |
| + XCTAssertEqual(peer.rttAvg, 266.7) |
| + XCTAssertEqual(peer.rttMax, 500) |
| + XCTAssertEqual(peer.rtt, 150, "the latest is still the latest") |
| + XCTAssertEqual(peer.jitterAvg, 20) |
| + XCTAssertEqual(peer.jitterMax, 30) |
| + // The readings are the window's: the next one starts again, and its |
| + // highest is at least the latest reading. |
| + builder.observe(samples: ["p1": Self.relayed(rtt: 0.05, totalRtt: nil, responses: nil)]) |
| + peer = try XCTUnwrap( |
| + build(&builder, at: 60, ["p1": Self.relayed(rtt: 0.09, totalRtt: nil, responses: nil)]).peers?.first) |
| + XCTAssertEqual(peer.rttAvg, 50) |
| + XCTAssertEqual(peer.rttMax, 90) |
| + XCTAssertEqual(peer.jitterMax, 18) |
| + // The camera's jitter when no audio arrives. |
| + var noAudio = Self.relayed() |
| + noAudio.stats.removeValue(forKey: "IA") |
| + builder.observe(samples: ["p1": noAudio]) |
| + peer = try XCTUnwrap(build(&builder, at: 90, ["p1": noAudio]).peers?.first) |
| + XCTAssertEqual(peer.jitterAvg, 30) |
| + // Restarting the window forgets them. |
| + builder.observe(samples: ["p1": Self.relayed(rtt: 2)]) |
| + builder.start(at: 100) |
| + peer = try XCTUnwrap(build(&builder, at: 130, ["p1": Self.relayed()]).peers?.first) |
| + XCTAssertEqual(peer.rttMax, 120) |
| + XCTAssertNil(peer.jitterAvg) |
| + } |
| + |
| + func testTheLimitIsTheReasonThatHeldLongest() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + _ = build(&builder, at: 30, ["p1": Self.relayed(limit: ["bandwidth": 10, "cpu": 0, "none": 20, "other": 0])]) |
| + // Over the window: bandwidth 15 s, cpu 10 s, none 5 s, though the |
| + // latest reason is none. |
| + var video = try XCTUnwrap( |
| + build( |
| + &builder, at: 60, ["p1": Self.relayed(limit: ["bandwidth": 25, "cpu": 10, "none": 25, "other": 0], reason: "none")] |
| + ).peers?.first?.out?.video) |
| + XCTAssertEqual(video.limit, "bandwidth") |
| + XCTAssertEqual(video.limitedBandwidthSeconds, 15) |
| + XCTAssertEqual(video.limitedCpuSeconds, 10) |
| + // A tie goes to bandwidth, and cpu beats none. |
| + video = try XCTUnwrap( |
| + build( |
| + &builder, at: 90, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 15, "none": 30, "other": 0], reason: "none")] |
| + ).peers?.first?.out?.video) |
| + XCTAssertEqual(video.limit, "bandwidth") |
| + video = try XCTUnwrap( |
| + build( |
| + &builder, at: 120, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 40, "none": 50, "other": 0], reason: "none")] |
| + ).peers?.first?.out?.video) |
| + XCTAssertEqual(video.limit, "cpu") |
| + XCTAssertEqual(video.limitedBandwidthSeconds, 0, "measured, and none") |
| + // Nothing moved: the latest reason. |
| + video = try XCTUnwrap( |
| + build( |
| + &builder, at: 150, ["p1": Self.relayed(limit: ["bandwidth": 30, "cpu": 40, "none": 50, "other": 0], reason: "cpu")] |
| + ).peers?.first?.out?.video) |
| + XCTAssertEqual(video.limit, "cpu") |
| + // No durations at all: the latest reason, and no seconds. |
| + video = try XCTUnwrap(build(&builder, at: 180, ["p1": Self.relayed(reason: "other")]).peers?.first?.out?.video) |
| + XCTAssertEqual(video.limit, "other") |
| + XCTAssertNil(video.limitedBandwidthSeconds) |
| + XCTAssertNil(video.limitedCpuSeconds) |
| + } |
| + |
| + func testWebRTCsDictionariesAndBooleansAreRead() { |
| + let values: [String: Any] = [ |
| + "qualityLimitationDurations": ["bandwidth": NSNumber(value: 1.5), "cpu": NSNumber(value: 2), "none": NSNumber(value: 26.5)] |
| + as NSDictionary, |
| + "powerEfficientEncoder": NSNumber(value: true), |
| + "encoderImplementation": "VideoToolbox" as NSString, |
| + "ssrcs": [1, 2] as NSArray, |
| + ] |
| + let stat = QualityStat(type: "outbound-rtp", values: values) |
| + XCTAssertEqual(stat.numbers["qualityLimitationDurations.bandwidth"], 1.5) |
| + XCTAssertEqual(stat.numbers["qualityLimitationDurations.cpu"], 2) |
| + XCTAssertEqual(stat.numbers["powerEfficientEncoder"], 1) |
| + XCTAssertEqual(stat.strings["encoderImplementation"], "VideoToolbox") |
| + XCTAssertNil(stat.numbers["ssrcs"]) |
| + } |
| + |
| + func testTheScreensModeGoesOnTheScreen() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + var tally = QualityEventTally() |
| + let peer = try XCTUnwrap( |
| + builder.build( |
| + at: 30, samples: ["p1": Self.sample(screen: true)], events: &tally, client: Self.client, devices: nil, |
| + final: false, screenMode: "detail" |
| + ).peers?.first) |
| + XCTAssertEqual(peer.out?.screen?.mode, "detail") |
| + XCTAssertNil(peer.out?.video?.mode, "the camera has no share mode") |
| + // Not sharing: nowhere. |
| + let none = try XCTUnwrap( |
| + builder.build( |
| + at: 60, samples: ["p1": Self.sample()], events: &tally, client: Self.client, devices: nil, final: false, |
| + screenMode: "detail" |
| + ).peers?.first) |
| + XCTAssertNil(none.out?.screen) |
| + } |
| + |
| + func testTheDetailCarriesNoAddressesPortsUrlsOrNames() throws { |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + builder.observe(samples: ["p1": Self.relayed(direct: true)]) |
| + let report = build( |
| + &builder, at: 30, ["p1": Self.relayed(direct: true, limit: ["bandwidth": 12, "cpu": 3, "none": 15, "other": 0])]) |
| + let json = try XCTUnwrap(report.encoded()) |
| + for forbidden in [ |
| + "192.168", "198.51.100", "203.0.113", "50000", "50001", "50002", "61000", "stun.example.com", |
| + "relay.example.com", "turns:", "stun:", "VideoToolbox", "Simulcast", "libvpx", "profile-level-id", "H264", |
| + "VP8", "CPrelay", "CPdirect", "address", "url", "Implementation", "mimeType", "codecId", |
| + ] { |
| + XCTAssertFalse(json.contains(forbidden), "the report carries \(forbidden): \(json)") |
| + } |
| + XCTAssertTrue(json.contains(#""encoder":"hardware""#), json) |
| + XCTAssertTrue(json.contains(#""candidates":{"#), json) |
| + } |
| + |
| + // MARK: - §15.29: the automatic report |
| + |
| + static func window( |
| + freezes: Double? = nil, rttMax: Double? = nil, rtt: Double? = nil, outRtt: Double? = nil, |
| + reconnecting: Double? = nil, peerReconnecting: Double? = nil, rebuilds: Double? = nil |
| + ) -> QualityReport { |
| + var peer = QualityPeer(peer: "p1", rtt: rtt, rttMax: rttMax) |
| + if let freezes { |
| + peer.in = QualityInbound(video: QualityInVideo(freezes: freezes - 1), screen: QualityInVideo(freezes: 1)) |
| + } |
| + if outRtt != nil || rebuilds != nil { |
| + peer.out = QualityOutbound(audio: QualityOutStream(rtt: outRtt), screen: QualityOutStream(rebuilds: rebuilds)) |
| + } |
| + if let peerReconnecting { peer.events = QualityPeerEvents(reconnectingSeconds: peerReconnecting) } |
| + var report = QualityReport(seconds: 30, client: client, peers: [peer, QualityPeer(peer: "p2")]) |
| + if let reconnecting { report.events = QualityCallEvents(reconnectingSeconds: reconnecting) } |
| + return report |
| + } |
| + |
| + func testTheFactsOfAWindow() { |
| + XCTAssertEqual(QualityTrouble.facts(Self.window()), QualityTrouble.Facts()) |
| + XCTAssertEqual(QualityTrouble.facts(Self.window(freezes: 4)).freezes, 4, "cameras and screens") |
| + XCTAssertEqual(QualityTrouble.facts(Self.window(rttMax: 300, rtt: 900, outRtt: 200)).maxRtt, 900) |
| + XCTAssertEqual(QualityTrouble.facts(Self.window(rttMax: 300, rtt: 100, outRtt: 1200)).maxRtt, 1200) |
| + XCTAssertEqual(QualityTrouble.facts(Self.window(reconnecting: 2, peerReconnecting: 7)).reconnectingSeconds, 7) |
| + XCTAssertEqual(QualityTrouble.facts(Self.window(reconnecting: 9, peerReconnecting: 7)).reconnectingSeconds, 9) |
| + XCTAssertTrue(QualityTrouble.facts(Self.window(rebuilds: 1)).screenEscalated) |
| + XCTAssertFalse(QualityTrouble.facts(Self.window(rebuilds: 0)).screenEscalated) |
| + // Keyframes alone are the ladder's first step, not trouble. |
| + var keyframes = Self.window() |
| + keyframes.peers?[0].out = QualityOutbound(screen: QualityOutStream(keyframes: 5)) |
| + XCTAssertFalse(QualityTrouble.facts(keyframes).screenEscalated) |
| + } |
| + |
| + func testTheRulesNeedTwoWindowsForFreezesAndTheRoundTrip() { |
| + typealias F = QualityTrouble.Facts |
| + XCTAssertEqual(QualityTrouble.trigger(previous: F(freezes: 3), now: F(freezes: 3)), "freezes") |
| + XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(freezes: 10)), "one window is not enough") |
| + XCTAssertNil(QualityTrouble.trigger(previous: F(freezes: 2), now: F(freezes: 10))) |
| + XCTAssertNil(QualityTrouble.trigger(previous: F(freezes: 10), now: F(freezes: 2))) |
| + XCTAssertEqual(QualityTrouble.trigger(previous: F(maxRtt: 801), now: F(maxRtt: 900)), "rtt") |
| + XCTAssertNil(QualityTrouble.trigger(previous: F(maxRtt: 800), now: F(maxRtt: 900)), "above, not at") |
| + XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(maxRtt: 5000))) |
| + XCTAssertEqual(QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 5.1)), "reconnecting") |
| + XCTAssertNil(QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 5))) |
| + XCTAssertEqual(QualityTrouble.trigger(previous: nil, now: F(screenEscalated: true)), "screen") |
| + XCTAssertNil(QualityTrouble.trigger(previous: F(), now: F())) |
| + // In AutoTriggers' order. |
| + let everything = F(freezes: 5, maxRtt: 1000, reconnectingSeconds: 20, screenEscalated: true) |
| + XCTAssertEqual(QualityTrouble.trigger(previous: everything, now: everything), "freezes") |
| + XCTAssertEqual( |
| + QualityTrouble.trigger(previous: F(maxRtt: 1000), now: F(freezes: 5, maxRtt: 1000, screenEscalated: true)), "rtt") |
| + XCTAssertEqual( |
| + QualityTrouble.trigger(previous: nil, now: F(reconnectingSeconds: 20, screenEscalated: true)), "reconnecting") |
| + XCTAssertEqual(AutoReportRules.triggers, ["freezes", "rtt", "reconnecting", "screen"]) |
| + } |
| + |
| + func testTheGateIsThreeACallTenMinutesApart() { |
| + var gate = AutoReportGate() |
| + XCTAssertTrue(gate.allows(at: 0)) |
| + gate.record(at: 0) |
| + XCTAssertFalse(gate.allows(at: 599)) |
| + XCTAssertTrue(gate.allows(at: 600)) |
| + gate.record(at: 600) |
| + gate.record(at: 1300) |
| + XCTAssertEqual(gate.sent, 3) |
| + XCTAssertFalse(gate.allows(at: 10_000), "three in one participation, and no more") |
| + } |
| + |
| + func testTheDecision() { |
| + typealias F = QualityTrouble.Facts |
| + let bad = F(freezes: 5) |
| + let gate = AutoReportGate() |
| + func decide( |
| + enabled: Bool = true, stopped: Bool = false, final: Bool = false, gate: AutoReportGate = gate, |
| + previous: F? = bad, now: F = bad, forced: String? = nil |
| + ) -> String? { |
| + AutoReportDecision.trigger( |
| + previous: previous, now: now, gate: gate, at: 1000, enabled: enabled, stopped: stopped, final: final, |
| + forced: forced) |
| + } |
| + XCTAssertEqual(decide(), "freezes") |
| + XCTAssertNil(decide(enabled: false), "quality reports off in Settings: automatic reports off") |
| + XCTAssertNil(decide(final: true), "the final report never sends one") |
| + XCTAssertNil(decide(stopped: true), "the kill switch") |
| + var spent = AutoReportGate() |
| + spent.record(at: 900) |
| + XCTAssertNil(decide(gate: spent), "ten minutes apart") |
| + XCTAssertNil(decide(previous: F(), now: F())) |
| + // The gate's forced trigger: whatever the call is like, but only where |
| + // the rest allows. |
| + XCTAssertEqual(decide(previous: nil, now: F(), forced: "screen"), "screen") |
| + XCTAssertNil(decide(enabled: false, forced: "screen")) |
| + XCTAssertNil(decide(final: true, forced: "screen")) |
| + XCTAssertNil(decide(gate: spent, forced: "screen")) |
| + XCTAssertNil(decide(previous: nil, now: F(), forced: "anything"), "not a trigger: the rules decide") |
| + } |
| + |
| + func testTheAutomaticReportsBodyHasNoNote() throws { |
| + let body = AutoReportBody(trigger: "rtt", diagnostics: "peer abc123: unmuted", client: Self.client).encoded() |
| + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any]) |
| + XCTAssertEqual(Set(object.keys), ["trigger", "diagnostics", "client"]) |
| + XCTAssertEqual(object["trigger"] as? String, "rtt") |
| + XCTAssertEqual(object["diagnostics"] as? String, "peer abc123: unmuted") |
| + XCTAssertEqual((object["client"] as? [String: String])?["app"], "mac") |
| + let long = AutoReportBody( |
| + trigger: "freezes", diagnostics: String(repeating: "line of diagnostics\n", count: 10_000), client: Self.client |
| + ).encoded() |
| + XCTAssertLessThanOrEqual(long.utf8.count, QualityBounds.problemBody) |
| + } |
| + |
| + func testTheAutomaticReportsAnswersAndReference() throws { |
| + XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"ref":"AB12CD34"}"#), .sent(ref: "AB12CD34")) |
| + XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"outcome":"stop"}"#), .stop) |
| + XCTAssertEqual(AutoReportOutcome(bridgeAnswer: #"{"outcome":"too-many"}"#), .notSent("too-many")) |
| + XCTAssertEqual(AutoReportOutcome(bridgeAnswer: "nonsense"), .notSent("failed")) |
| + var report = QualityReport(seconds: 30, client: Self.client) |
| + XCTAssertFalse(try XCTUnwrap(report.encoded()).contains("autoReport")) |
| + report.autoReport = "AB12CD34" |
| + XCTAssertTrue(try XCTUnwrap(report.encoded()).contains(#""autoReport":"AB12CD34""#)) |
| + } |
| + |
| // MARK: - Notices |
| func testNoticesAreCountedWhenTheyBeginAndTimedWhileTheyShow() { |
diff --git a/native/bridge/bridge.go b/native/bridge/bridge.go| index eca9ad9..ad6586c 100644 |
| --- a/native/bridge/bridge.go |
| +++ b/native/bridge/bridge.go |
| @@ -205,6 +205,30 @@ func (c *Client) SendProblem(report string) string { |
| return string(b) |
| } |
| +// SendAutoReport posts the automatic report (spec §15.29, 2026-10-28), a |
| +// protocol.AutoReport as JSON, and answers JSON: {"ref":"K7Q2M9PD"} when |
| +// the server took it, or {"outcome":"stop"|"too-many"|"gone"|"failed"} — |
| +// "stop" being the kill switch, as SendQuality's is: send no more quality |
| +// or automatic reports this call. It blocks like the others; call it off |
| +// the main thread. |
| +func (c *Client) SendAutoReport(report string) string { |
| + ref, stop, err := c.room.SendAutoReport([]byte(report)) |
| + var out struct { |
| + Ref string `json:"ref,omitempty"` |
| + Outcome string `json:"outcome,omitempty"` |
| + } |
| + switch { |
| + case err != nil: |
| + out.Outcome = string(callscore.OutcomeOf(err)) |
| + case stop: |
| + out.Outcome = string(callscore.ReportStop) |
| + default: |
| + out.Ref = ref |
| + } |
| + b, _ := json.Marshal(out) |
| + return string(b) |
| +} |
| + |
| // RegisterDevice hands the server an Apple device token so a knock can |
| // reach this device when the app is closed. Best effort: the caller |
| // ignores the error beyond logging, because a device that did not |
diff --git a/native/bridge/bridge_test.go b/native/bridge/bridge_test.go| index 8d4b68c..1d37184 100644 |
| --- a/native/bridge/bridge_test.go |
| +++ b/native/bridge/bridge_test.go |
| @@ -117,13 +117,15 @@ func TestOpenLinkKeepsNoMeetingAndNoSessionApart(t *testing.T) { |
| } |
| // TestReportsCarryTheHellosTokenAfterLeave is spec §15.26 through the |
| -// bridge: the token from the stream's hello goes on both report requests |
| +// bridge: the token from the stream's hello goes on every report request |
| // with the session, the answers come back as values the host can act on, |
| -// and both still work once the call has been left. |
| +// and all of them still work once the call has been left. The automatic |
| +// report (§15.29) is answered as Report a problem is, and its 204 is the |
| +// kill switch. |
| func TestReportsCarryTheHellosTokenAfterLeave(t *testing.T) { |
| const report = "0123456789abcdef0123456789abcdef" |
| session, cookies := loopbackSession() |
| - var quality, problem atomic.Int32 |
| + var quality, problem, auto atomic.Int32 |
| hello := make(chan struct{}) |
| var once atomic.Bool |
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| @@ -157,6 +159,20 @@ func TestReportsCarryTheHellosTokenAfterLeave(t *testing.T) { |
| } else { |
| w.WriteHeader(http.StatusTooManyRequests) |
| } |
| + case "/m/room/auto-report": |
| + if r.Header.Get("X-Calls-Report") != report { |
| + t.Error("auto report without the token") |
| + } |
| + switch auto.Add(1) { |
| + case 1: |
| + w.Write([]byte(`{"ref":"AB12CD34"}`)) |
| + case 2: |
| + w.WriteHeader(http.StatusTooManyRequests) |
| + case 3: |
| + w.WriteHeader(http.StatusNotFound) |
| + default: |
| + w.WriteHeader(http.StatusNoContent) |
| + } |
| case "/m/room/info": |
| w.Write([]byte(`{"title":"x"}`)) |
| default: |
| @@ -172,6 +188,9 @@ func TestReportsCarryTheHellosTokenAfterLeave(t *testing.T) { |
| if got := c.SendQuality(`{}`); got != "gone" { |
| t.Fatalf("before the hello: %q", got) |
| } |
| + if got := c.SendAutoReport(`{}`); got != `{"outcome":"gone"}` { |
| + t.Fatalf("auto report before the hello: %s", got) |
| + } |
| if err := c.Start(); err != nil { |
| t.Fatal(err) |
| } |
| @@ -190,4 +209,15 @@ func TestReportsCarryTheHellosTokenAfterLeave(t *testing.T) { |
| if got := c.SendProblem(`{"note":"x"}`); got != `{"outcome":"too-many"}` { |
| t.Fatalf("second problem: %s", got) |
| } |
| + auto1 := `{"trigger":"freezes","diagnostics":"peer abc123","client":{"app":"mac"}}` |
| + for i, want := range []string{ |
| + `{"ref":"AB12CD34"}`, `{"outcome":"too-many"}`, `{"outcome":"gone"}`, `{"outcome":"stop"}`, |
| + } { |
| + if got := c.SendAutoReport(auto1); got != want { |
| + t.Fatalf("auto report %d: %s, want %s", i+1, got, want) |
| + } |
| + } |
| + if got := c.SendAutoReport(`{not json`); got != `{"outcome":"failed"}` { |
| + t.Fatalf("an invalid auto report: %s", got) |
| + } |
| } |
diff --git a/protocol/quality.go b/protocol/quality.go| index 4e79e49..04f6d66 100644 |
| --- a/protocol/quality.go |
| +++ b/protocol/quality.go |
| @@ -30,6 +30,19 @@ const ( |
| MaxProblemBody = 64 << 10 // the whole problem report, diagnostics included |
| ) |
| +// The automatic report (spec §15.29, 2026-10-28): what a client counts as |
| +// a call struggling, and how often it may say so. A client sends an |
| +// AutoReport when one of these holds, at most once every AutoReportEvery |
| +// and at most AutoReportsPerCall times in one participation; the server |
| +// enforces both limits on its own. |
| +const ( |
| + AutoFreezes = 3 // inbound freezes, this window and the one before it: at least this many in each |
| + AutoRTTMillis = 800 // the window's highest round trip, this window and the one before it: above this in each |
| + AutoReconnectingSeconds = 5 // "Reconnecting…" (the call's or a person's) shown for longer than this in one window |
| + AutoReportsPerCall = 3 |
| + AutoReportEveryMinutes = 10 |
| +) |
| + |
| // QualityReport is one window's summary. |
| type QualityReport struct { |
| V int `json:"v"` |
| @@ -39,6 +52,10 @@ type QualityReport struct { |
| Devices *Devices `json:"devices,omitempty"` |
| Events *CallEvents `json:"events,omitempty"` |
| Peers []PeerQuality `json:"peers,omitempty"` |
| + // AutoReport is the reference of the automatic report this client |
| + // sent with this window (§15.29), when it sent one. Eight characters |
| + // of Crockford's alphabet, as every report reference is. |
| + AutoReport string `json:"autoReport,omitempty"` |
| } |
| // ReportClient says what is reporting. Enums, and versions as digits and |
| @@ -75,12 +92,52 @@ type CallEvents struct { |
| type PeerQuality struct { |
| // Peer is the remote peer's id as this client knows it. The server |
| // logs the peer's tag in its place and never the id. |
| - Peer PeerID `json:"peer"` |
| - Path *Path `json:"path,omitempty"` |
| - RTT *float64 `json:"rtt,omitempty"` // the selected candidate pair's, ms |
| - Out *Outbound `json:"out,omitempty"` |
| - In *Inbound `json:"in,omitempty"` |
| - Events *PeerEvents `json:"events,omitempty"` |
| + Peer PeerID `json:"peer"` |
| + Path *Path `json:"path,omitempty"` |
| + RTT *float64 `json:"rtt,omitempty"` // the selected candidate pair's, ms |
| + // The window's round trip and jitter (2026-10-28): RTTAvg is the |
| + // pair's mean over the window (its total round trip over its |
| + // responses, or the mean of once-a-second readings), RTTMax the |
| + // highest once-a-second reading; JitterAvg and JitterMax are the |
| + // peer's inbound audio jitter read once a second, in ms. |
| + RTTAvg *float64 `json:"rttAvg,omitempty"` |
| + RTTMax *float64 `json:"rttMax,omitempty"` |
| + JitterAvg *float64 `json:"jitterAvg,omitempty"` |
| + JitterMax *float64 `json:"jitterMax,omitempty"` |
| + // Candidates is this side's account of how the connection was found: |
| + // what it gathered and what it was offered, by type, and which kinds |
| + // of pair worked. Types and counts only, never an address. |
| + Candidates *Candidates `json:"candidates,omitempty"` |
| + Out *Outbound `json:"out,omitempty"` |
| + In *Inbound `json:"in,omitempty"` |
| + Events *PeerEvents `json:"events,omitempty"` |
| +} |
| + |
| +// Candidates says why a connection took the path it took (2026-10-28): a |
| +// relayed call is told apart as "this side never found its own public |
| +// address" (no srflx), "this side found it and nothing direct worked" |
| +// (srflx, no direct pair), or "the far side offered only the relay". The |
| +// booleans are meaningful only when the struct is present: a client that |
| +// cannot read candidates sends no Candidates at all. |
| +type Candidates struct { |
| + // Local candidates gathered, by type. |
| + Host *float64 `json:"host,omitempty"` |
| + Srflx *float64 `json:"srflx,omitempty"` |
| + Prflx *float64 `json:"prflx,omitempty"` |
| + Relay *float64 `json:"relay,omitempty"` |
| + // Remote candidates the peer offered, by type. |
| + RemoteHost *float64 `json:"remoteHost,omitempty"` |
| + RemoteSrflx *float64 `json:"remoteSrflx,omitempty"` |
| + RemotePrflx *float64 `json:"remotePrflx,omitempty"` |
| + RemoteRelay *float64 `json:"remoteRelay,omitempty"` |
| + // DirectOK: a pair with neither end a relay succeeded. LocalDirectOK: |
| + // a pair whose local end is not a relay succeeded (this side's own |
| + // network reached the far side, or the far side's relay). UDPOK: a |
| + // pair carried over UDP the whole way to the peer or the relay |
| + // succeeded. |
| + DirectOK bool `json:"directOk,omitempty"` |
| + LocalDirectOK bool `json:"localDirectOk,omitempty"` |
| + UDPOK bool `json:"udpOk,omitempty"` |
| } |
| // Path is the selected candidate pair: what kind of candidate each end |
| @@ -129,11 +186,34 @@ type OutStream struct { |
| // frames went in (2026-10-21). |
| Damped *float64 `json:"damped,omitempty"` |
| EncoderStalls *float64 `json:"encoderStalls,omitempty"` |
| + // 2026-10-28. Limit is the reason that held the encoder back for most |
| + // of the window where the stack says (qualityLimitationDurations), and |
| + // the latest reason where it does not; LimitedBandwidthSeconds and |
| + // LimitedCPUSeconds are how long in the window each held it back. |
| + // Encoder is hardware or software, never the implementation's name; |
| + // Codec the codec's family; Mode the screen's share mode. |
| + LimitedBandwidthSeconds *float64 `json:"limitedBandwidthSeconds,omitempty"` |
| + LimitedCPUSeconds *float64 `json:"limitedCpuSeconds,omitempty"` |
| + Encoder string `json:"encoder,omitempty"` // CoderKinds |
| + Codec string `json:"codec,omitempty"` // Codecs |
| + Mode string `json:"mode,omitempty"` // ShareModes, the screen only |
| } |
| // QualityLimits are qualityLimitationReason's values. |
| var QualityLimits = []string{"none", "cpu", "bandwidth", "other"} |
| +// CoderKinds say whether a video encoder or decoder is the platform's |
| +// hardware one or a software one: the implementation's own name |
| +// ("VideoToolbox", "libvpx") is never sent. |
| +var CoderKinds = []string{"hardware", "software", "unknown"} |
| + |
| +// Codecs are a stream's codec family, from its MIME type. |
| +var Codecs = []string{"vp8", "vp9", "h264", "h265", "av1", "opus", "other"} |
| + |
| +// ShareModes are the screen share's modes (§15.22): the browser's |
| +// SHARE_MODES and the apps' ScreenShareMode. |
| +var ShareModes = []string{"balanced", "detail", "motion"} |
| + |
| // Inbound is what arrives from the peer. |
| type Inbound struct { |
| Audio *InAudio `json:"audio,omitempty"` |
| @@ -174,6 +254,9 @@ type InVideo struct { |
| Stalls *float64 `json:"stalls,omitempty"` |
| StallsNoPackets *float64 `json:"stallsNoPackets,omitempty"` |
| StallsUndecoded *float64 `json:"stallsUndecoded,omitempty"` |
| + // The decoder, hardware or software, and the codec (2026-10-28). |
| + Decoder string `json:"decoder,omitempty"` // CoderKinds |
| + Codec string `json:"codec,omitempty"` // Codecs |
| } |
| // PeerEvents are the notices about this peer during the window. |
| @@ -201,7 +284,23 @@ type ProblemReport struct { |
| Client ReportClient `json:"client"` |
| } |
| -// ProblemReceipt is the server's answer: the reference to quote. |
| +// AutoReport is the automatic "Report a problem" (§15.29, 2026-10-28): |
| +// sent by a client, with nobody pressing anything, when its call is |
| +// struggling. The diagnostics are what Report a problem sends, scrubbed |
| +// the same way; there is no note, because nobody typed one. Trigger says |
| +// which of the rules above fired. |
| +type AutoReport struct { |
| + Trigger string `json:"trigger"` // AutoTriggers |
| + Diagnostics string `json:"diagnostics"` |
| + Client ReportClient `json:"client"` |
| +} |
| + |
| +// AutoTriggers are the rules an AutoReport may name, in the order a |
| +// client checks them. |
| +var AutoTriggers = []string{"freezes", "rtt", "reconnecting", "screen"} |
| + |
| +// ProblemReceipt is the server's answer: the reference to quote. An |
| +// AutoReport is answered the same way. |
| type ProblemReceipt struct { |
| Ref string `json:"ref"` |
| } |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index f40e349..2f28740 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -6434,6 +6434,12 @@ const run = { |
| // stops the automatic reports. And last, B leaves for the holding |
| // screen, which offers the sheet for the call just left, and the report |
| // still lands: the token works for ten minutes after the participation. |
| + // §15.29 (2026-10-28): between the reports and the sheet, A's next |
| + // window is made to fire the automatic report (the test hook stands in |
| + // for a rule: a call on one machine never struggles on cue), and Go |
| + // answers whether the report and its diagnostics are in the log, the |
| + // quality line after it names its reference, and the per-peer lines |
| + // carry the path and the candidates — and nothing that leaks. |
| async quality() { |
| const ctxA = await newContext('member A', { cookie: cookieA }); |
| const ctxB = await newContext('member B', { cookie: cookieB }); |
| @@ -6443,10 +6449,14 @@ const run = { |
| // What a report looks like on the wire, for the record, and the proof |
| // that the browser itself sends no name, address, label or meeting. |
| const bodies = []; |
| + const autoBodies = []; |
| pageA.on('request', (req) => { |
| if (req.method() === 'POST' && where({ url: () => req.url() }) === '/m' && req.url().endsWith('/quality')) { |
| bodies.push(req.postData() || ''); |
| } |
| + if (req.method() === 'POST' && where({ url: () => req.url() }) === '/m' && req.url().endsWith('/auto-report')) { |
| + autoBodies.push(req.postData() || ''); |
| + } |
| }); |
| const pair = await assertPair(pageA, pageB, 'member A', 'member B'); |
| if (!pair) return; |
| @@ -6467,6 +6477,34 @@ const run = { |
| 'the report on the wire carries no name, address, label, meeting or user agent'); |
| const answer = await control('quality-check ' + peers.join(' ')); |
| check(answer === 'ok', 'the report log has both browsers’ quality lines under one call tag, and names nobody (' + answer + ')'); |
| + check(autoBodies.length === 0, 'a call going well sends no automatic report (' + autoBodies.length + ')'); |
| + |
| + // §15.29: the automatic report, forced on A's next window. |
| + check(await pageA.evaluate(() => window.meet.autoReportForTest('freezes')), 'the gate can force an automatic report'); |
| + const auto = await until(async () => { |
| + const x = (await quality(pageA)).auto; |
| + return x && x.reported >= 1 ? x : false; |
| + }, 15000); |
| + check(auto && auto.sent === 1 && auto.status === 200 && auto.refs.length === 1 && /^[0-9A-Z]{8}$/.test(auto.refs[0]), |
| + 'A sent one automatic report, was given a reference, and a quality report naming it was accepted (' + |
| + JSON.stringify(auto || (await quality(pageA)).auto) + ')'); |
| + const autoWire = autoBodies[0] || ''; |
| + let autoSent = null; |
| + try { |
| + autoSent = JSON.parse(autoWire); |
| + } catch { |
| + autoSent = null; |
| + } |
| + check(autoSent && autoSent.trigger === 'freezes' && typeof autoSent.diagnostics === 'string' && |
| + autoSent.diagnostics.includes('peer ' + pair.b.peer.slice(0, 6)) && !/\bbea\b|\bpaul\b/i.test(autoSent.diagnostics) && |
| + !('note' in autoSent) && autoSent.client && autoSent.client.app === 'web', |
| + 'the automatic report carries its trigger and the anonymous diagnostics, and no note (' + autoWire.slice(0, 200) + ')'); |
| + const namedWire = auto && bodies.find((x) => x.includes('"autoReport":"' + auto.refs[0] + '"')); |
| + check(namedWire, 'the quality report after it names the reference on the wire'); |
| + if (namedWire) line('a quality report naming its automatic report: ' + namedWire); |
| + const autoAnswer = await control('auto-check ' + peers.join(' ')); |
| + check(autoAnswer.startsWith('ok'), 'the log has the automatic report, its diagnostics, the quality line naming it, ' + |
| + 'and the per-peer path and candidates, and leaks nothing (' + autoAnswer + ')'); |
| // What "Report a problem" sends: people by short peer id, never by name. |
| const anon = await pageA.evaluate(() => window.meet.diagnostics({ anonymous: true })); |
diff --git a/test/browser/room-quality.test.mjs b/test/browser/room-quality.test.mjs| index 4b61626..2a463d5 100644 |
| --- a/test/browser/room-quality.test.mjs |
| +++ b/test/browser/room-quality.test.mjs |
| @@ -3,6 +3,12 @@ |
| // |
| // node --test test/browser/room-quality.test.mjs |
| // |
| +// §15.29 (2026-10-28) adds the window's round trip and jitter, the |
| +// candidates, the encoder and decoder, the codec, the limit that held |
| +// longest, and the automatic report's rules and gate: the same lifting, |
| +// and a relayed walk whose candidates, implementation names and |
| +// addresses the report must reduce to types, counts and enums. |
| +// |
| // The report's builders are lifted out of the shipped room.js by name, |
| // with the constants they read, as room-reconnect.test.mjs does; the |
| // client's description and the sheet's answers out of report.js. The |
| @@ -38,9 +44,12 @@ function liftConst(name) { |
| } |
| const CONSTS = ['QUALITY_MAX_PEERS', 'QUALITY_MAX_SECONDS', 'QUALITY_MAX_MILLIS', 'QUALITY_MAX_COUNT', |
| - 'QUALITY_MAX_KBPS', 'QUALITY_MAX_PIXELS', 'QUALITY_MAX_FPS', 'QUALITY_LOOK_MAX'].map(liftConst).join('\n'); |
| + 'QUALITY_MAX_KBPS', 'QUALITY_MAX_PIXELS', 'QUALITY_MAX_FPS', 'QUALITY_LOOK_MAX', |
| + 'AUTO_FREEZES', 'AUTO_RTT_MS', 'AUTO_RECONNECTING_SECONDS', 'AUTO_REPORTS_PER_CALL', 'AUTO_REPORT_EVERY', |
| + 'AUTO_BODY_MAX'].map(liftConst).join('\n'); |
| const ROOM = ['qualityCeiling', 'qualitySet', 'qualityReading', 'qualityPeer', 'qualityWatchRecord', |
| - 'qualityWatch', 'qualityTake', 'qualityReport', 'deviceKind']; |
| + 'qualityWatch', 'qualityTake', 'qualityReport', 'deviceKind', 'coderKind', 'codecKind', 'qualitySample', |
| + 'qualityFacts', 'qualityTrouble', 'autoReportGate', 'autoReportAllowed', 'autoReportDecision', 'autoReportBody']; |
| // eslint-disable-next-line no-new-func |
| const q = new Function(CONSTS + '\n' + ROOM.map((n) => lift(roomSrc, 'room.js', n)).join('\n') + |
| '; return { ' + ROOM.join(', ') + ' };')(); |
| @@ -67,6 +76,17 @@ test('the bounds are the protocol package\'s', () => { |
| assert.equal(room('QUALITY_MAX_PIXELS'), bound('MaxQualityPixels')); |
| assert.equal(room('QUALITY_MAX_FPS'), bound('MaxQualityFPS')); |
| assert.equal(room('QUALITY_MAX_BODY'), bound('MaxQualityBody')); |
| + // §15.29: the automatic report's rules and limits. |
| + assert.equal(room('AUTO_FREEZES'), bound('AutoFreezes')); |
| + assert.equal(room('AUTO_RTT_MS'), bound('AutoRTTMillis')); |
| + assert.equal(room('AUTO_RECONNECTING_SECONDS'), bound('AutoReconnectingSeconds')); |
| + assert.equal(room('AUTO_REPORTS_PER_CALL'), bound('AutoReportsPerCall')); |
| + assert.equal(room('AUTO_REPORT_EVERY'), bound('AutoReportEveryMinutes') * 60000); |
| + assert.ok(room('AUTO_BODY_MAX') <= bound('MaxProblemBody')); |
| + // And the triggers, in the order the protocol says a client checks them. |
| + const triggers = go.match(/AutoTriggers = \[\]string\{([^}]*)\}/); |
| + assert.ok(triggers, 'AutoTriggers is not in protocol/quality.go'); |
| + assert.deepEqual(JSON.parse('[' + triggers[1] + ']'), ['freezes', 'rtt', 'reconnecting', 'screen']); |
| }); |
| // ── fixtures ───────────────────────────────────────────────────────── |
| @@ -245,6 +265,393 @@ test('the screen stalls judged here, with what the statistics said, and steps he |
| assert.equal(p.in.screen.reattaches, undefined); |
| }); |
| +// ── §15.29: the window's detail ────────────────────────────────────── |
| + |
| +// A relayed connection, Chromium's shape, with what §15.29 reads: the |
| +// encoder's and decoder's implementation names (never reported), the |
| +// codecs, qualityLimitationDurations, the pair's round-trip totals, and |
| +// every candidate this side gathered and was offered, addresses, ports |
| +// and the relay's URL included. This side found its own public address |
| +// (srflx) and nothing direct worked: the pair that carries the call is |
| +// this side's relay, reached over TURN/TLS, to the far side's srflx. |
| +// `opts.hostPair` adds a host pair that succeeded; `opts.relayUdp` reaches |
| +// the relay over UDP instead. |
| +function relayWalk(t, opts = {}) { |
| + const reports = [ |
| + { id: 'COA', type: 'codec', mimeType: 'audio/opus', payloadType: 111, clockRate: 48000, sdpFmtpLine: 'minptime=10;useinbandfec=1' }, |
| + { id: 'COV', type: 'codec', mimeType: 'video/H264', payloadType: 102, sdpFmtpLine: 'profile-level-id=42e01f' }, |
| + { id: 'COS', type: 'codec', mimeType: 'video/VP9', payloadType: 98 }, |
| + { id: 'CIV', type: 'codec', mimeType: 'video/AV1', payloadType: 45 }, |
| + { id: 'OA', type: 'outbound-rtp', kind: 'audio', mid: '0', ssrc: 11, codecId: 'COA', bytesSent: 10000 + t * 4000, packetsSent: 100 + t * 50 }, |
| + { id: 'OV', type: 'outbound-rtp', kind: 'video', mid: '1', ssrc: 12, codecId: 'COV', bytesSent: 500000 + t * 100000, |
| + packetsSent: 1000 + t * 300, frameWidth: 640, frameHeight: 360, framesPerSecond: 30, |
| + // The gauge says "none" at the moment the window ends; for 21 of the |
| + // window's 30 seconds it was the bandwidth. |
| + qualityLimitationReason: 'none', qualityLimitationDurations: { none: 10 + t * 5, cpu: 1 + t * 4, bandwidth: 2 + t * 21, other: 0 }, |
| + encoderImplementation: 'ExternalEncoder (VideoToolbox)', powerEfficientEncoder: true }, |
| + { id: 'OS', type: 'outbound-rtp', kind: 'video', mid: '3', ssrc: 13, codecId: 'COS', bytesSent: 90000 + t * 60000, |
| + packetsSent: 200 + t * 100, frameWidth: 1920, frameHeight: 1080, framesPerSecond: 5, qualityLimitationReason: 'cpu', |
| + // A tie: fifteen seconds each of cpu and bandwidth. Bandwidth is named. |
| + qualityLimitationDurations: { none: 3, cpu: t * 15, bandwidth: t * 15, other: 0 }, encoderImplementation: 'libvpx' }, |
| + { id: 'IA', type: 'inbound-rtp', kind: 'audio', mid: '0', ssrc: 21, codecId: 'COA', bytesReceived: 20000 + t * 3750, |
| + packetsReceived: 200 + t * 1500, packetsLost: 1 + t * 15, jitter: 0.0031 }, |
| + { id: 'IV', type: 'inbound-rtp', kind: 'video', mid: '1', ssrc: 22, codecId: 'CIV', bytesReceived: 400000 + t * 3000000, |
| + packetsReceived: 900 + t * 3000, packetsLost: 0, jitter: 0.012, freezeCount: 1 + t * 3, totalFreezesDuration: 0.5 + t, |
| + framesDecoded: 300 + t * 900, framesDropped: 0, frameWidth: 1280, frameHeight: 720, framesPerSecond: 30, |
| + decoderImplementation: 'ExternalDecoder' }, |
| + { id: 'T', type: 'transport', selectedCandidatePairId: 'CP3' }, |
| + // The selected pair: this side's relay to the far side's srflx. |
| + { id: 'CP3', type: 'candidate-pair', localCandidateId: 'L3', remoteCandidateId: 'R1', state: 'succeeded', nominated: true, |
| + currentRoundTripTime: 0.12, totalRoundTripTime: 3 + t * 4.5, responsesReceived: 30 + t * 30 }, |
| + { id: 'CP1', type: 'candidate-pair', localCandidateId: 'L1', remoteCandidateId: 'R2', state: 'failed' }, |
| + { id: 'CP2', type: 'candidate-pair', localCandidateId: 'L2', remoteCandidateId: 'R1', state: 'in-progress' }, |
| + { id: 'L1', type: 'local-candidate', candidateType: 'host', protocol: 'udp', address: '192.168.1.20', port: 50000, ip: '192.168.1.20' }, |
| + { id: 'L2', type: 'local-candidate', candidateType: 'srflx', protocol: 'udp', address: '203.0.113.9', port: 50001, ip: '203.0.113.9', |
| + url: 'stun:stun.example.net:3478' }, |
| + { id: 'L3', type: 'local-candidate', candidateType: 'relay', protocol: 'udp', relayProtocol: opts.relayUdp ? 'udp' : 'tls', |
| + address: '192.0.2.44', port: 54321, ip: '192.0.2.44', url: 'turns:relay.example.net:443' }, |
| + { id: 'R1', type: 'remote-candidate', candidateType: 'srflx', protocol: 'udp', address: '198.51.100.7', port: 61000, ip: '198.51.100.7' }, |
| + { id: 'R2', type: 'remote-candidate', candidateType: 'host', protocol: 'udp', address: '10.1.2.3', port: 61001, ip: '10.1.2.3' }, |
| + ]; |
| + if (opts.hostPair) { |
| + reports.push({ id: 'CP4', type: 'candidate-pair', localCandidateId: 'L1', remoteCandidateId: 'R2', state: 'succeeded' }); |
| + } |
| + return new Map(reports.map((x) => [x.id, x])); |
| +} |
| +const RELAY_FORBIDDEN = [...FORBIDDEN, '192.168.1.20', '203.0.113.9', '10.1.2.3', '50000', '50001', '61001', 'stun.example.net', |
| + 'ExternalEncoder', 'VideoToolbox', 'libvpx', 'ExternalDecoder', 'video/', 'audio/', 'profile-level-id', 'useinbandfec', 'CP3', 'L3']; |
| + |
| +// A window's once-a-second looks: round trips of 100, 900 and 120 ms (one |
| +// bad second), and audio jitter of 10 and 30 ms. |
| +function sampled() { |
| + let acc = null; |
| + const look = (rtt, jitter) => ({ |
| + path: { local: 'relay', remote: 'srflx', protocol: 'tls', rtt }, |
| + streams: new Map([['inbound-rtp:IA', { dir: 'in', kind: 'audio', counters: {}, gauges: { jitter } }]]), |
| + }); |
| + acc = q.qualitySample(acc, look(100, 0.01)); |
| + acc = q.qualitySample(acc, look(900, 0.03)); |
| + acc = q.qualitySample(acc, look(120, undefined)); |
| + return acc; |
| +} |
| + |
| +test('§15.29: a relayed call says why — candidates by type, which pairs worked, the path — and never an address', () => { |
| + const one = q.qualityReading(relayWalk(0), classify); |
| + const two = q.qualityReading(relayWalk(1), classify); |
| + const report = q.qualityReport({ |
| + seconds: 30, |
| + client: { app: 'web', browser: 'chrome' }, |
| + shareMode: 'detail', |
| + peers: [{ id: PEER, prev: one, now: two, sample: sampled() }], |
| + }); |
| + const json = JSON.stringify(report); |
| + for (const bad of RELAY_FORBIDDEN) assert.ok(!json.includes(bad), 'the report carries ' + bad + ': ' + json); |
| + const p = report.peers[0]; |
| + assert.deepEqual(p.path, { local: 'relay', remote: 'srflx', protocol: 'tls' }); |
| + // Found its own public address, offered the far side's host and srflx, |
| + // and nothing but the relay worked; the relay is reached over TLS. |
| + assert.deepEqual(p.candidates, { host: 1, srflx: 1, relay: 1, remoteHost: 1, remoteSrflx: 1, |
| + directOk: false, localDirectOk: false, udpOk: false }); |
| + |
| + // The same, with the relay over UDP: UDP the whole way to the relay. |
| + const udp = q.qualityPeer(null, q.qualityReading(relayWalk(1, { relayUdp: true }), classify), 30); |
| + assert.deepEqual(udp.path, { local: 'relay', remote: 'srflx', protocol: 'udp' }); |
| + assert.equal(udp.candidates.udpOk, true); |
| + assert.equal(udp.candidates.directOk, false); |
| + // And a host pair that succeeded while the relay was chosen: direct |
| + // worked, from this side's own network. |
| + const direct = q.qualityPeer(null, q.qualityReading(relayWalk(1, { hostPair: true }), classify), 30); |
| + assert.deepEqual([direct.candidates.directOk, direct.candidates.localDirectOk, direct.candidates.udpOk], [true, true, true]); |
| +}); |
| + |
| +test('§15.29: this side\'s own end worked to the far side\'s relay — localDirectOk without directOk', () => { |
| + const walk = new Map([ |
| + ['T', { id: 'T', type: 'transport', selectedCandidatePairId: 'P' }], |
| + ['P', { id: 'P', type: 'candidate-pair', localCandidateId: 'L', remoteCandidateId: 'R', state: 'succeeded' }], |
| + ['L', { id: 'L', type: 'local-candidate', candidateType: 'host', protocol: 'udp', address: '10.0.0.2' }], |
| + ['R', { id: 'R', type: 'remote-candidate', candidateType: 'relay', protocol: 'udp', address: '192.0.2.99' }], |
| + ]); |
| + const p = q.qualityPeer(null, q.qualityReading(walk, classify), 30); |
| + assert.deepEqual(p.candidates, { host: 1, remoteRelay: 1, directOk: false, localDirectOk: true, udpOk: true }); |
| + assert.deepEqual(p.path, { local: 'host', remote: 'relay', protocol: 'udp' }); |
| + // A walk with no candidates at all says nothing about them, rather than |
| + // claiming nothing worked. |
| + const none = q.qualityPeer(null, q.qualityReading(new Map([['T', { id: 'T', type: 'transport' }]]), classify), 30); |
| + assert.equal(none.candidates, undefined); |
| +}); |
| + |
| +test('§15.29: the window\'s round trip — the pair\'s own mean, the highest second — and its jitter', () => { |
| + const one = q.qualityReading(relayWalk(0), classify); |
| + const two = q.qualityReading(relayWalk(1), classify); |
| + const p = q.qualityPeer(one, two, 30, sampled()); |
| + // 4.5 s of round trip over thirty responses: 150 ms each, whatever the |
| + // once-a-second readings averaged. |
| + assert.equal(p.rttAvg, 150); |
| + // The bad second, which the last walk's 120 ms would have hidden. |
| + assert.equal(p.rtt, 120); |
| + assert.equal(p.rttMax, 900); |
| + assert.equal(p.jitterAvg, 20); |
| + assert.equal(p.jitterMax, 30); |
| + |
| + // The first window counts the pair's totals from zero. |
| + assert.equal(q.qualityPeer(null, two, 30, null).rttAvg, (7.5 / 60) * 1000); |
| + // A new pair counts from zero too: last window's totals were another |
| + // pair's. |
| + const other = q.qualityReading(relayWalk(0), classify); |
| + other.path.pair = 'CPold'; |
| + other.path.totalRoundTripTime = 100; |
| + other.path.responsesReceived = 1000; |
| + assert.equal(q.qualityPeer(other, two, 30, null).rttAvg, 125); |
| + // No totals (Safari, Firefox): the mean of the readings. |
| + const bare = q.qualityReading(walk(1), classify); |
| + const fromSamples = q.qualityPeer(null, bare, 30, sampled()); |
| + assert.equal(fromSamples.rttAvg, 373.3); |
| + assert.equal(fromSamples.rttMax, 900); |
| + // No readings and no totals: the highest is the last walk's, and there |
| + // is no mean and no jitter to give. |
| + const alone = q.qualityPeer(null, bare, 30, null); |
| + assert.equal(alone.rttMax, 31); |
| + assert.equal(alone.rttAvg, undefined); |
| + assert.equal(alone.jitterAvg, undefined); |
| +}); |
| + |
| +test('§15.29: the sampler reads the audio\'s jitter, the camera\'s when no audio arrives, and nothing else', () => { |
| + const camera = { path: null, streams: new Map([ |
| + ['out', { dir: 'out', kind: 'audio', counters: {}, gauges: { jitter: 0.5 } }], |
| + ['cam', { dir: 'in', kind: 'video', counters: {}, gauges: { jitter: 0.012 } }], |
| + ]) }; |
| + const a = q.qualitySample(null, camera); |
| + assert.deepEqual(a, { rttSum: 0, rttN: 0, rttMax: 0, jitterSum: 12, jitterN: 1, jitterMax: 12 }); |
| + const both = { path: { rtt: NaN }, streams: new Map([ |
| + ['cam', { dir: 'in', kind: 'video', counters: {}, gauges: { jitter: 0.012 } }], |
| + ['mic', { dir: 'in', kind: 'audio', counters: {}, gauges: { jitter: 0.004 } }], |
| + ]) }; |
| + assert.deepEqual(q.qualitySample(null, both), { rttSum: 0, rttN: 0, rttMax: 0, jitterSum: 4, jitterN: 1, jitterMax: 4 }); |
| + assert.deepEqual(q.qualitySample(null, { path: null, streams: new Map() }), |
| + { rttSum: 0, rttN: 0, rttMax: 0, jitterSum: 0, jitterN: 0, jitterMax: 0 }); |
| +}); |
| + |
| +test('§15.29: the limit that held longest, how long, the encoder and decoder, the codec and the mode', () => { |
| + const one = q.qualityReading(relayWalk(0), classify); |
| + const two = q.qualityReading(relayWalk(1), classify); |
| + const report = q.qualityReport({ seconds: 30, client: { app: 'web' }, shareMode: 'detail', |
| + peers: [{ id: PEER, prev: one, now: two }] }); |
| + const p = report.peers[0]; |
| + // The gauge said none; the window was 21 s bandwidth, 4 s cpu, 5 s none. |
| + assert.equal(p.out.video.limit, 'bandwidth'); |
| + assert.equal(p.out.video.limitedBandwidthSeconds, 21); |
| + assert.equal(p.out.video.limitedCpuSeconds, 4); |
| + assert.equal(p.out.video.encoder, 'hardware'); |
| + assert.equal(p.out.video.codec, 'h264'); |
| + // A tie goes to bandwidth; the screen's encoder is software by its name. |
| + assert.deepEqual([p.out.screen.limit, p.out.screen.limitedBandwidthSeconds, p.out.screen.limitedCpuSeconds], |
| + ['bandwidth', 15, 15]); |
| + assert.equal(p.out.screen.encoder, 'software'); |
| + assert.equal(p.out.screen.codec, 'vp9'); |
| + assert.equal(p.out.screen.mode, 'detail'); |
| + assert.equal(p.out.video.mode, undefined, 'the mode is the screen\'s'); |
| + assert.equal(p.out.audio.codec, undefined, 'audio is opus, and says nothing'); |
| + assert.equal(p.in.video.decoder, 'hardware'); |
| + assert.equal(p.in.video.codec, 'av1'); |
| + // The first window: everything held so far is the window's, and a |
| + // stream that never left none is none. |
| + const first = q.qualityPeer(null, one, 10); |
| + assert.equal(first.out.video.limit, 'none'); |
| + assert.equal(first.out.video.limitedBandwidthSeconds, 2); |
| + // Not sharing, or a mode it does not know: no mode. |
| + const quiet = q.qualityReport({ seconds: 30, client: { app: 'web' }, shareMode: '', peers: [{ id: PEER, prev: one, now: two }] }); |
| + assert.equal(quiet.peers[0].out.screen.mode, undefined); |
| + const odd = q.qualityReport({ seconds: 30, client: { app: 'web' }, shareMode: 'cinema', peers: [{ id: PEER, prev: one, now: two }] }); |
| + assert.equal(odd.peers[0].out.screen.mode, undefined); |
| + // Nothing held in the window at all: the gauge, as before. |
| + const still = q.qualityPeer(two, two, 30); |
| + assert.equal(still.out.video.limit, 'none'); |
| + assert.equal(still.out.screen.limit, 'cpu'); |
| + assert.equal(still.out.video.limitedBandwidthSeconds, 0); |
| +}); |
| + |
| +test('§15.29: an encoder\'s or decoder\'s kind, never its name', () => { |
| + const cases = [ |
| + ['ExternalEncoder', undefined, 'hardware'], |
| + ['VideoToolbox', undefined, 'hardware'], |
| + ['MediaCodec', undefined, 'hardware'], |
| + ['VaapiVideoEncodeAccelerator', undefined, 'hardware'], |
| + ['V4L2', undefined, 'hardware'], |
| + ['D3D11VideoDecoder', undefined, 'hardware'], |
| + ['DXVAVideoDecodeAccelerator', undefined, 'hardware'], |
| + ['NVENC', undefined, 'hardware'], |
| + ['MediaFoundationVideoEncodeAccelerator', undefined, 'hardware'], |
| + ['QSV', undefined, 'hardware'], |
| + ['AMF', undefined, 'hardware'], |
| + ['libvpx', undefined, 'software'], |
| + ['SimulcastEncoderAdapter (libvpx, libvpx)', undefined, 'software'], |
| + ['OpenH264', undefined, 'software'], |
| + ['libaom', undefined, 'software'], |
| + ['dav1d', undefined, 'software'], |
| + ['FFmpeg', undefined, 'software'], |
| + ['libavcodec', undefined, 'software'], |
| + ['FallbackEncoder', undefined, 'software'], |
| + ['Something new', undefined, 'unknown'], |
| + ['', undefined, ''], |
| + [undefined, undefined, ''], |
| + [42, undefined, ''], |
| + // The browser's own word wins over the name. |
| + ['libvpx', true, 'hardware'], |
| + ['ExternalEncoder', false, 'software'], |
| + [undefined, true, 'hardware'], |
| + [undefined, false, 'software'], |
| + ]; |
| + for (const [impl, pe, want] of cases) assert.equal(q.coderKind(impl, pe), want, String(impl) + ' / ' + pe); |
| +}); |
| + |
| +test('§15.29: a codec\'s family by its MIME type', () => { |
| + const cases = [ |
| + ['video/VP8', 'vp8'], ['video/vp9', 'vp9'], ['video/H264', 'h264'], ['video/H265', 'h265'], ['video/HEVC', 'h265'], |
| + ['video/AV1', 'av1'], ['audio/opus', 'opus'], ['audio/PCMU', 'other'], ['video/rtx', 'other'], ['', ''], [undefined, ''], |
| + ]; |
| + for (const [mime, want] of cases) assert.equal(q.codecKind(mime), want, String(mime)); |
| +}); |
| + |
| +// ── §15.29: the automatic report ───────────────────────────────────── |
| + |
| +test('§15.29: the facts a window\'s report holds', () => { |
| + const report = { |
| + events: { reconnectingSeconds: 2 }, |
| + peers: [ |
| + { peer: PEER, rtt: 90, rttMax: 300, in: { video: { freezes: 2 }, screen: { freezes: 1 } }, |
| + out: { audio: { rtt: 950 }, screen: { keyframes: 4 } }, events: { reconnectingSeconds: 6.5 } }, |
| + { peer: OTHER, rtt: 1200, in: { video: { freezes: 1 } }, out: { screen: { rebuilds: 1 } } }, |
| + ], |
| + }; |
| + assert.deepEqual(q.qualityFacts(report), { freezes: 4, maxRtt: 1200, reconnectingSeconds: 6.5, screenEscalated: true }); |
| + // Keyframes alone are the ladder's first step, not trouble. |
| + assert.deepEqual(q.qualityFacts({ peers: [{ peer: PEER, out: { screen: { keyframes: 9, damped: 2 } } }] }), |
| + { freezes: 0, maxRtt: 0, reconnectingSeconds: 0, screenEscalated: false }); |
| + assert.deepEqual(q.qualityFacts({ v: 1 }), { freezes: 0, maxRtt: 0, reconnectingSeconds: 0, screenEscalated: false }); |
| + for (const k of ['reshares', 'failures']) { |
| + assert.equal(q.qualityFacts({ peers: [{ peer: PEER, out: { screen: { [k]: 1 } } }] }).screenEscalated, true, k); |
| + } |
| + // The call's own "Reconnecting…" counts as anyone's. |
| + assert.equal(q.qualityFacts({ events: { reconnectingSeconds: 9 }, peers: [] }).reconnectingSeconds, 9); |
| +}); |
| + |
| +test('§15.29: the rules — freezes and round trip two windows in a row, a long reconnect or a screen in one', () => { |
| + const f = (o) => Object.assign({ freezes: 0, maxRtt: 0, reconnectingSeconds: 0, screenEscalated: false }, o); |
| + // Freezes: three or more in this window and the one before it. |
| + assert.equal(q.qualityTrouble(f({ freezes: 3 }), f({ freezes: 3 })), 'freezes'); |
| + assert.equal(q.qualityTrouble(f({ freezes: 9 }), f({ freezes: 4 })), 'freezes'); |
| + assert.equal(q.qualityTrouble(null, f({ freezes: 50 })), '', 'the first window has no window before it'); |
| + assert.equal(q.qualityTrouble(f({ freezes: 2 }), f({ freezes: 50 })), ''); |
| + assert.equal(q.qualityTrouble(f({ freezes: 50 }), f({ freezes: 2 })), ''); |
| + // Round trip: above 800 ms in both. |
| + assert.equal(q.qualityTrouble(f({ maxRtt: 801 }), f({ maxRtt: 2000 })), 'rtt'); |
| + assert.equal(q.qualityTrouble(f({ maxRtt: 800 }), f({ maxRtt: 2000 })), '', 'at 800 is not above it'); |
| + assert.equal(q.qualityTrouble(f({ maxRtt: 2000 }), f({ maxRtt: 800 })), ''); |
| + assert.equal(q.qualityTrouble(null, f({ maxRtt: 5000 })), ''); |
| + // Reconnecting: longer than five seconds, in one window. |
| + assert.equal(q.qualityTrouble(null, f({ reconnectingSeconds: 5.1 })), 'reconnecting'); |
| + assert.equal(q.qualityTrouble(null, f({ reconnectingSeconds: 5 })), ''); |
| + // The screen past its keyframes, in one window. |
| + assert.equal(q.qualityTrouble(null, f({ screenEscalated: true })), 'screen'); |
| + // Quiet: nothing. |
| + assert.equal(q.qualityTrouble(f({}), f({})), ''); |
| + // In the protocol's order. |
| + const all = f({ freezes: 5, maxRtt: 900, reconnectingSeconds: 8, screenEscalated: true }); |
| + assert.equal(q.qualityTrouble(all, all), 'freezes'); |
| + assert.equal(q.qualityTrouble(f({ maxRtt: 900 }), f({ maxRtt: 900, reconnectingSeconds: 8, screenEscalated: true })), 'rtt'); |
| + assert.equal(q.qualityTrouble(null, f({ reconnectingSeconds: 8, screenEscalated: true })), 'reconnecting'); |
| + |
| + // From real windows: two of the relayed walk, three freezes each. |
| + const w0 = q.qualityReading(relayWalk(0), classify); |
| + const w1 = q.qualityReading(relayWalk(1), classify); |
| + const w2 = q.qualityReading(relayWalk(2), classify); |
| + const at = (prev, now) => q.qualityFacts(q.qualityReport({ seconds: 30, client: { app: 'web' }, peers: [{ id: PEER, prev, now }] })); |
| + const one = at(w0, w1); |
| + const two = at(w1, w2); |
| + assert.equal(one.freezes, 3); |
| + assert.equal(q.qualityTrouble(null, one), ''); |
| + assert.equal(q.qualityTrouble(one, two), 'freezes'); |
| + // A quiet window between them breaks the run. |
| + assert.equal(q.qualityTrouble(at(w2, w2), two), ''); |
| +}); |
| + |
| +test('§15.29: at most three a participation, ten minutes apart, and a new participation a new gate', () => { |
| + const MIN = 60000; |
| + let gate = q.autoReportGate(null, 'a'.repeat(32)); |
| + assert.deepEqual(gate, { token: 'a'.repeat(32), count: 0, last: null }); |
| + assert.equal(q.autoReportAllowed(gate, 0), true); |
| + gate.count = 1; |
| + gate.last = 1000; |
| + assert.equal(q.autoReportAllowed(gate, 1000 + 10 * MIN - 1), false); |
| + assert.equal(q.autoReportAllowed(gate, 1000 + 10 * MIN), true); |
| + gate.count = 3; |
| + assert.equal(q.autoReportAllowed(gate, 1000 + 60 * MIN), false); |
| + // A resumed stream's hello carries the same token: the same gate. |
| + assert.equal(q.autoReportGate(gate, 'a'.repeat(32)), gate); |
| + // A new participation's token: a fresh one. |
| + const fresh = q.autoReportGate(gate, 'b'.repeat(32)); |
| + assert.notEqual(fresh, gate); |
| + assert.deepEqual(fresh, { token: 'b'.repeat(32), count: 0, last: null }); |
| + |
| + // A call in trouble for fifty minutes, a window every thirty seconds: |
| + // sent in the first window that may, ten minutes later, ten after that, |
| + // and never again. |
| + const trouble = { freezes: 0, maxRtt: 0, reconnectingSeconds: 30, screenEscalated: false }; |
| + gate = q.autoReportGate(null, 'c'.repeat(32)); |
| + const sent = []; |
| + for (let now = 30000; now <= 50 * MIN; now += 30000) { |
| + const trigger = q.autoReportDecision({ facts: trouble, prevFacts: trouble, gate, now, on: true, serverOff: false, |
| + token: gate.token, final: false, force: '' }); |
| + if (trigger) { |
| + gate.count += 1; |
| + gate.last = now; |
| + sent.push(now); |
| + } |
| + } |
| + assert.deepEqual(sent, [30000, 30000 + 10 * MIN, 30000 + 20 * MIN]); |
| +}); |
| + |
| +test('§15.29: never with the switch off, the kill switch thrown, no token, or the final report', () => { |
| + const trouble = { freezes: 0, maxRtt: 0, reconnectingSeconds: 30, screenEscalated: false }; |
| + const quiet = { freezes: 0, maxRtt: 0, reconnectingSeconds: 0, screenEscalated: false }; |
| + const base = { facts: trouble, prevFacts: null, gate: q.autoReportGate(null, 't'), now: 1, on: true, serverOff: false, |
| + token: 'f'.repeat(32), final: false, force: '' }; |
| + const d = (o) => q.autoReportDecision(Object.assign({}, base, o)); |
| + assert.equal(d({}), 'reconnecting'); |
| + // "Send anonymous quality reports" off: nothing automatic either. |
| + assert.equal(d({ on: false }), ''); |
| + assert.equal(d({ on: false, force: 'freezes' }), '', 'not even forced'); |
| + assert.equal(d({ serverOff: true }), ''); |
| + assert.equal(d({ token: '' }), ''); |
| + assert.equal(d({ final: true }), ''); |
| + assert.equal(d({ facts: quiet }), ''); |
| + // The gate's hook stands in for a rule, and the gate still decides. |
| + assert.equal(d({ facts: quiet, force: 'screen' }), 'screen'); |
| + assert.equal(d({ facts: quiet, force: 'everything' }), '', 'a trigger the protocol does not name is no trigger'); |
| + assert.equal(d({ force: 'rtt', gate: { token: 't', count: 3, last: null } }), ''); |
| +}); |
| + |
| +test('§15.29: the automatic report\'s body fits the server\'s 64 KB, cutting the diagnostics', () => { |
| + const client = { app: 'web' }; |
| + assert.deepEqual(JSON.parse(q.autoReportBody('rtt', 'all fine', client, 65024)), { trigger: 'rtt', diagnostics: 'all fine', client }); |
| + const big = q.autoReportBody('freezes', 'line\n'.repeat(40000), client, 65024); |
| + assert.ok(new TextEncoder().encode(big).length <= 65024); |
| + const parsed = JSON.parse(big); |
| + assert.equal(parsed.trigger, 'freezes'); |
| + assert.ok(parsed.diagnostics.startsWith('line\n')); |
| + assert.ok(parsed.diagnostics.endsWith('[cut short to fit]')); |
| + assert.deepEqual(Object.keys(parsed), ['trigger', 'diagnostics', 'client']); |
| +}); |
| + |
| +test('§15.29: a window that sent one names its reference, and only a reference', () => { |
| + const now = q.qualityReading(walk(1), classify); |
| + const r = (autoReport) => q.qualityReport({ seconds: 30, client: { app: 'web' }, autoReport, peers: [{ id: PEER, prev: null, now }] }); |
| + assert.equal(r('K7Q2M9PD').autoReport, 'K7Q2M9PD'); |
| + assert.equal(r(undefined).autoReport, undefined); |
| + assert.equal(r('<b>x</b>').autoReport, undefined); |
| + assert.equal(r('k7q2m9pd').autoReport, undefined); |
| +}); |
| + |
| // ── the notices ────────────────────────────────────────────────────── |
| test('the notices: counted once each time they appear, timed while they show', () => { |