oficina / meet Public

Calls: how the machine itself fared in each quality report, and a struggling device lowers its own camera (spec 15.30)

Paul's Mac was overloaded in call txt4wuhyg6qqellf and nothing said by
what. The apps report Calls' own CPU over the window, its resident memory,
the load average (Mac), the worst thermal state and Low Power Mode; the
browser the Compute Pressure state where it has one. The head quality line
carries them, quality-summary prints a machine line per person with the
worst window. A thermal state of serious or worse, or Calls over 150% of a
core on the Mac, for eight of ten seconds steps this device's own camera
down the same levels; the screen and audio are left alone. The watch takes
no news for 5 s after a renegotiation, and says why it stepped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev de2f5cda876097bd7b73199c4ee06aae74e1e24c parent 6182376
16 files changed, +626 −22
  • cmd/quality-summary/main.go +82 −0
  • cmd/quality-summary/relayed_test.go +17 −0
  • docs/superpowers/specs/2026-09-07-meet-design.md +38 −0
  • internal/calls/quality.go +27 −0
  • internal/calls/static/room.js +95 −9
  • internal/callstest/native_browser_test.go +18 −0
  • internal/callstest/quality_test.go +47 −3
  • native/apple/Sources/CallsKit/Call.swift +36 −4
  • native/apple/Sources/CallsKit/HostLoad.swift +112 −0
  • native/apple/Sources/CallsKit/Media.swift +13 −1
  • native/apple/Sources/CallsKit/QualityReport.swift +6 −1
  • native/apple/Sources/CallsKit/VideoAdapt.swift +26 −2
  • native/apple/Tests/CallsKitTests/VideoAdaptTests.swift +59 −0
  • protocol/quality.go +22 −0
  • test/browser/call.mjs +8 −0
  • test/browser/room-adapt.test.mjs +20 −2
diff --git a/cmd/quality-summary/main.go b/cmd/quality-summary/main.go
index 474dbdc..a5f81da 100644
--- a/cmd/quality-summary/main.go
+++ b/cmd/quality-summary/main.go
@@ -31,6 +31,7 @@ import (
"os"
"os/exec"
"regexp"
+ "slices"
"sort"
"strconv"
"strings"
@@ -360,6 +361,83 @@ type person struct {
// head sums (or, for the max* fields, maxes) each quality line's
// headline fields: all a line read from carlos has.
head map[string]float64
+ // §15.30 (2026-10-29): the machine itself, at its worst window.
+ machine machine
+}
+
+// machine is one person's machine across the call: the worst window for
+// Calls' own CPU and for the thermal state, the most memory and load,
+// and whether Low Power Mode was ever on. seen is false for a client
+// that reported none of it.
+type machine struct {
+ seen bool
+ cpu, mem, load float64
+ cpuAt, thermalAt time.Time
+ thermal int // 1 + the index in thermalWords; 0 for none
+ lowPower, lowPowerKnown bool
+}
+
+var thermalWords = []string{"nominal", "fair", "serious", "critical"}
+
+func (m *machine) add(l line) {
+ f := l.Fields
+ num := func(k string) (float64, bool) {
+ v, err := strconv.ParseFloat(f[k], 64)
+ return v, err == nil
+ }
+ if v, ok := num("procCpuPct"); ok {
+ m.seen = true
+ if v > m.cpu || m.cpuAt.IsZero() {
+ m.cpu, m.cpuAt = v, l.Time
+ }
+ }
+ if v, ok := num("procMemMB"); ok {
+ m.seen = true
+ m.mem = max(m.mem, v)
+ }
+ if v, ok := num("sysLoad1"); ok {
+ m.seen = true
+ m.load = max(m.load, v)
+ }
+ if t := slices.Index(thermalWords, f["thermal"]) + 1; t > 0 {
+ m.seen = true
+ if t > m.thermal {
+ m.thermal, m.thermalAt = t, l.Time
+ }
+ }
+ if v := f["lowPower"]; v != "" {
+ m.seen = true
+ m.lowPowerKnown = true
+ m.lowPower = m.lowPower || v == "true"
+ }
+}
+
+// words is the machine line, or "" for a client that said nothing.
+func (m machine) words(loc *time.Location) string {
+ if !m.seen {
+ return ""
+ }
+ var parts []string
+ if !m.cpuAt.IsZero() {
+ parts = append(parts, fmt.Sprintf("Calls' CPU up to %g%% (worst window %s)", m.cpu, m.cpuAt.In(loc).Format("15:04:05")))
+ }
+ if m.mem > 0 {
+ parts = append(parts, fmt.Sprintf("memory up to %g MB", m.mem))
+ }
+ if m.load > 0 {
+ parts = append(parts, fmt.Sprintf("load up to %g", m.load))
+ }
+ if m.thermal > 0 {
+ parts = append(parts, fmt.Sprintf("thermal worst %s (%s)", thermalWords[m.thermal-1], m.thermalAt.In(loc).Format("15:04:05")))
+ }
+ if m.lowPowerKnown {
+ if m.lowPower {
+ parts = append(parts, "Low Power Mode on")
+ } else {
+ parts = append(parts, "Low Power Mode off")
+ }
+ }
+ return strings.Join(parts, ", ")
}
// direction is what one person received from another, over every window.
@@ -475,6 +553,7 @@ func lossPct(packets, lost *float64) float64 {
func (c *call) addQuality(p *person, l line) {
p.reports++
+ p.machine.add(l)
if p.head == nil {
p.head = map[string]float64{}
}
@@ -636,6 +715,9 @@ func (c *call) print(out io.Writer, loc *time.Location) {
}
fmt.Fprintln(out)
}
+ if m := p.machine.words(loc); m != "" {
+ fmt.Fprintf(out, " machine: %s\n", m)
+ }
}
if len(c.dirs) > 0 {
fmt.Fprintln(out, " Connections (what the first heard from the second)")
diff --git a/cmd/quality-summary/relayed_test.go b/cmd/quality-summary/relayed_test.go
index d1b5a61..8235230 100644
--- a/cmd/quality-summary/relayed_test.go
+++ b/cmd/quality-summary/relayed_test.go
@@ -153,3 +153,20 @@ func TestVideoLevelsFromThePeerLines(t *testing.T) {
t.Error("a call at normal throughout has a Video levels section")
}
}
+
+// Spec §15.30 (2026-10-29): the machine's own load, per person, with the
+// worst window, read as JSON and as carlos prints it.
+func TestTheMachineLine(t *testing.T) {
+ fixture := strings.Replace(relayedFixture, `"remotes":1,"relay":true,"maxLossPct":0.7`,
+ `"remotes":1,"relay":true,"maxLossPct":0.7,"procCpuPct":182.5,"procMemMB":412,"sysLoad1":6.2,"thermal":"serious","lowPower":false`, 1)
+ for name, text := range map[string]string{"json": fixture, "carlos": carlosPrint(t, fixture)} {
+ out := runOnText(t, text, "--call", "relayedcall2f7ab")
+ want := "machine: Calls' CPU up to 182.5% (worst window 14:02:30), memory up to 412 MB, load up to 6.2, thermal worst serious (14:02:30), Low Power Mode off"
+ if !strings.Contains(out, want) {
+ t.Errorf("%s: missing %q in\n%s", name, want, out)
+ }
+ if strings.Count(out, "machine:") != 1 {
+ t.Errorf("%s: a person who reported nothing of their machine has a machine line:\n%s", name, out)
+ }
+ }
+}
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md
index e1d212d..ec2e073 100644
--- a/docs/superpowers/specs/2026-09-07-meet-design.md
+++ b/docs/superpowers/specs/2026-09-07-meet-design.md
@@ -3346,6 +3346,13 @@ news either way (a connection that is down is §15.28's).
next, to at most 5 minutes; a probe that holds puts the wait back to 45 s.
- Available incoming bitrate is not used: no browser and neither app
exposes it (send-side estimation).
+- A renegotiation — a screen added or taken away, by either side — costs
+ the camera a freeze or two that are not the link's (the browser gate's
+ `mutualshare` stepped both sides down on them): for 5 s after one settles
+ the watch takes no news (`ADAPT_SETTLE`, `VideoAdapt.settle`).
+- *Why* is kept with each step — "2 freezes", "8% loss", "this device
+ struggling 8 s" — on the console, the apps' `connection` log and the
+ gate's diagnostics.
The gate measured, on a 60 kbit/s downlink cap (an encoded transform
dropping what does not fit, `lowbandwidth`): normal to minimal 3 s after
@@ -3353,6 +3360,37 @@ the cap (severe), the camera at 180 lines, audio arriving throughout;
minimal to reduced 57 s after the cap was lifted (a freeze 9 s after the
lift restarted the clean run).
+**The sender's own half, and the machine's load (2026-10-29).** Paul's Mac
+"got completely overloaded" in a call (call `txt4wuhyg6qqellf`, Mac 0.4.13),
+and its encoder never named the CPU as its limit, so nothing could say
+whether Calls or something else was eating the machine.
+
+- *The report.* §15.26's report gains `host`: `procCpuPct` (Calls' own
+ process over the window, percent of one core, from `getrusage`; at most
+ 12,800), `procMemMB` (resident memory at the window's end, from
+ `task_info`; at most 1,048,576), `sysLoad1` (the one-minute load average,
+ Mac only; at most 10,000), `thermal` (the worst `ProcessInfo.thermalState`
+ in the window: `nominal`, `fair`, `serious`, `critical`) and `lowPower`
+ (Low Power Mode at any point in the window). The apps send all of them;
+ the browser sends `thermal` alone, and only where it has the Compute
+ Pressure API (Chromium's `PressureObserver` on `cpu`, whose four states
+ have the same names), as the worst state in the window. Validated as
+ every number and enum is; a `thermal` outside the four is 400. The head
+ `calls: quality` line carries each as a scalar of the same name, only
+ when the client sent it; `quality-summary` prints a per-person "machine"
+ line: Calls' CPU at its worst window and when, memory and load at their
+ highest, the worst thermal state and when, and Low Power Mode.
+- *The sender's own watch.* The same watch, with the same levels and
+ timings, watches the sending device itself: a second is *struggling*
+ when the thermal state (the browser: compute pressure) is serious or
+ critical, or, on the Mac, when Calls' own CPU over that second is above
+ 150% of one core. Eight struggling seconds in the window are trouble
+ (never severe), one level at a time; a struggling second is never clean.
+ Its level is a floor under the camera this device sends to everyone —
+ the camera to each person goes at the larger of theirs and this — and
+ never touches the screen or the audio. It is not sent to anyone: it is
+ this device's own business.
+
**The person's own choice.** "Video quality" in the Devices panel, on the
web, the Mac and the iPhone, remembered (the browser's device preferences;
the apps' `videoQuality` default): *Auto* (the default), *Low bandwidth*
diff --git a/internal/calls/quality.go b/internal/calls/quality.go
index f1b4b17..f5fc7d6 100644
--- a/internal/calls/quality.go
+++ b/internal/calls/quality.go
@@ -315,6 +315,9 @@ func validateQuality(raw []byte) (protocol.QualityReport, bool) {
if e := q.Events; e != nil && !enumOrEmpty(e.VideoSetting, protocol.VideoSettings) {
return q, false
}
+ if h := q.Host; h != nil && !enumOrEmpty(h.Thermal, protocol.ThermalStates) {
+ return q, false
+ }
if len(q.Peers) > protocol.MaxQualityPeers {
return q, false
}
@@ -410,6 +413,12 @@ func numberCeiling(name string) float64 {
return protocol.MaxQualityKbps
case "width", "height":
return protocol.MaxQualityPixels
+ case "procCpuPct":
+ return protocol.MaxQualityCPUPct
+ case "procMemMB":
+ return protocol.MaxQualityMemMB
+ case "sysLoad1":
+ return protocol.MaxQualityLoad
case "fps":
return protocol.MaxQualityFPS
}
@@ -516,6 +525,24 @@ func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) {
if q.Events != nil && q.Events.VideoSetting != "" {
attrs = append(attrs, slog.String("videoSetting", q.Events.VideoSetting))
}
+ // The machine itself (§15.30, 2026-10-29), on the head line where
+ // carlos logs shows it: what the client measured, and nothing else.
+ if h := q.Host; h != nil {
+ for _, f := range []struct {
+ name string
+ v *float64
+ }{{"procCpuPct", h.ProcCPUPct}, {"procMemMB", h.ProcMemMB}, {"sysLoad1", h.SysLoad1}} {
+ if f.v != nil {
+ attrs = append(attrs, slog.Float64(f.name, *f.v))
+ }
+ }
+ if h.Thermal != "" {
+ attrs = append(attrs, slog.String("thermal", h.Thermal))
+ }
+ if h.LowPower != nil {
+ attrs = append(attrs, slog.Bool("lowPower", *h.LowPower))
+ }
+ }
attrs = append(attrs, slog.Any("report", body))
a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality", attrs...)
region := a.relayRegionName()
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js
index 26f7b1c..adecffb 100644
--- a/internal/calls/static/room.js
+++ b/internal/calls/static/room.js
@@ -442,6 +442,14 @@
const ADAPT_PROBE_WATCH = 20000; // trouble this soon after a probe steps back
const ADAPT_PROBE_JUDGE = 5000; // and is judged on at least this much of it
const ADAPT_UP_MAX = 300000; // the probe's wait doubles to at most this
+ const ADAPT_SETTLE = 5000; // after a renegotiation (a screen added or taken away), no news this long
+ // The sender's own half (2026-10-29): this device struggling — the
+ // Compute Pressure API at serious or critical in the browser; the apps
+ // add their own process's CPU — for this many of the window's seconds is
+ // trouble for its own camera, judged by the same watch at the same
+ // levels. The screen and audio are not touched.
+ const ADAPT_DOWN_LOAD_SECONDS = 8;
+ const PRESSURE_STATES = ['nominal', 'fair', 'serious', 'critical'];
// What each level sends (the sender's half). The camera: its bitrate,
// frame rate, and the box its picture is fitted into (long side, short
// side). The screen keeps its size and gives up frame rate first, and
@@ -544,6 +552,10 @@
let adaptNoticeShown = '';
const videoTime = new Map();
let adaptUpAfter = ADAPT_UP_AFTER;
+ // The sender's own watch of this device, and the Compute Pressure API's
+ // state now and at its worst since the last quality report.
+ let localAdapt = adaptRecord();
+ const pressure = { state: '', worst: '', observer: null };
let adaptPolledAt = 0;
let shareRecovery = '';
let screenStallTestUntil = 0;
@@ -926,7 +938,10 @@
const track = camera && camera.sender && camera.sender.track;
if (!track) return;
const settings = track.getSettings ? track.getSettings() : {};
- const encoding = cameraAtLevel(videoSetting() === 'audio' ? 3 : level, sharing, settings.width || 0, settings.height || 0);
+ // This device's own trouble lowers its camera to everyone, never its
+ // screen or its audio.
+ const cameraLevel = videoSetting() === 'audio' ? 3 : Math.max(level, localAdapt.level);
+ const encoding = cameraAtLevel(cameraLevel, sharing, settings.width || 0, settings.height || 0);
// The camera watch's to know: a camera paused on purpose encodes
// nothing, and that is not a stalled encoder.
entry.cameraPaused = encoding.active === false;
@@ -2132,6 +2147,8 @@
// renewal.
pc.addEventListener('signalingstatechange', () => {
if (pcs.get(id) !== entry) return;
+ // §15.30: the adaptive watch takes no news while this settles.
+ entry.adaptSettleUntil = Date.now() + ADAPT_SETTLE;
// §5.4: the same quiet moment is when a deferred share transceiver
// is added. addShareTo will not add one to a connection that is
// mid-negotiation, because an unassociated sendonly transceiver is
@@ -4699,13 +4716,14 @@
// round trip as their median (one spike is not a slow link), the jitter
// buffer as their mean.
function adaptWindow(samples) {
- const w = { freezes: 0, freezeSeconds: 0, keyframeAsks: 0, packets: 0, lost: 0, decoded: 0, dropped: 0, rtt: null, jitterBuffer: null };
+ const w = { freezes: 0, freezeSeconds: 0, keyframeAsks: 0, loadSeconds: 0, packets: 0, lost: 0, decoded: 0, dropped: 0, rtt: null, jitterBuffer: null };
const rtts = [];
const jbs = [];
for (const x of samples) {
w.freezes += x.freezes;
w.freezeSeconds += x.freezeSeconds;
w.keyframeAsks += x.keyframeAsks || 0;
+ if (x.load) w.loadSeconds += 1;
w.packets += x.packets;
w.lost += x.lost;
w.decoded += x.decoded;
@@ -4729,7 +4747,7 @@
return 'severe';
}
if (w.freezes >= ADAPT_DOWN_FREEZES || w.freezeSeconds >= ADAPT_DOWN_FREEZE_SECONDS || w.loss > ADAPT_DOWN_LOSS ||
- w.keyframeAsks >= ADAPT_DOWN_KEYFRAME_ASKS ||
+ w.keyframeAsks >= ADAPT_DOWN_KEYFRAME_ASKS || w.loadSeconds >= ADAPT_DOWN_LOAD_SECONDS ||
(w.rtt !== null && w.rtt >= ADAPT_DOWN_RTT && w.freezes >= 1) ||
(w.jitterBuffer !== null && w.jitterBuffer >= ADAPT_DOWN_JITTER_BUFFER) ||
(w.dropped >= ADAPT_DOWN_DROPPED_MIN && w.dropped >= ADAPT_DOWN_DROPPED * (w.decoded + w.dropped))) {
@@ -4738,10 +4756,30 @@
return '';
}
+ // adaptWhy names what made a window trouble, for the console and the
+ // diagnostics: the first rule it broke.
+ function adaptWhy(w) {
+ if (w.freezes >= ADAPT_DOWN_FREEZES) return w.freezes + ' freezes';
+ if (w.freezeSeconds >= ADAPT_DOWN_FREEZE_SECONDS) return w.freezeSeconds + ' s frozen';
+ if (w.loss > ADAPT_DOWN_LOSS) return Math.round(w.loss * 100) + '% loss';
+ if (w.keyframeAsks >= ADAPT_DOWN_KEYFRAME_ASKS) return w.keyframeAsks + ' keyframe asks';
+ if (w.loadSeconds >= ADAPT_DOWN_LOAD_SECONDS) return 'this device struggling ' + w.loadSeconds + ' s';
+ if (w.rtt !== null && w.rtt >= ADAPT_DOWN_RTT && w.freezes >= 1) return w.rtt + ' ms round trip with a freeze';
+ if (w.jitterBuffer !== null && w.jitterBuffer >= ADAPT_DOWN_JITTER_BUFFER) return Math.round(w.jitterBuffer) + ' ms jitter buffer';
+ return w.dropped + ' of ' + (w.decoded + w.dropped) + ' frames dropped';
+ }
+
+ // loadSample is one second of this device's own load, for the sender's
+ // watch of itself: nothing about a link, only whether it struggled.
+ function loadSample(struggling) {
+ return { freezes: 0, freezeSeconds: 0, keyframeAsks: 0, load: !!struggling, packets: 0, lost: 0, rtt: null,
+ jitterBufferMs: null, decoded: 0, dropped: 0 };
+ }
+
// adaptClean is whether one second was clean, for the slow way up.
function adaptClean(x) {
const n = x.packets + x.lost;
- return x.freezes === 0 && x.freezeSeconds === 0 && !x.keyframeAsks && (n === 0 || x.lost / n <= ADAPT_CLEAN_LOSS) &&
+ return x.freezes === 0 && x.freezeSeconds === 0 && !x.keyframeAsks && !x.load && (n === 0 || x.lost / n <= ADAPT_CLEAN_LOSS) &&
(x.rtt === null || x.rtt < ADAPT_CLEAN_RTT) &&
(x.jitterBufferMs === null || x.jitterBufferMs < ADAPT_CLEAN_JITTER_BUFFER);
}
@@ -4776,7 +4814,9 @@
rec.samples.push(Object.assign({ at: now }, sample));
while (rec.samples.length && rec.samples[0].at <= now - ADAPT_WINDOW) rec.samples.shift();
const observed = now - rec.since;
- const verdict = adaptTrouble(adaptWindow(rec.samples));
+ const win = adaptWindow(rec.samples);
+ const verdict = adaptTrouble(win);
+ if (verdict) rec.why = adaptWhy(win);
if (adaptClean(sample)) {
if (rec.cleanSince === null) rec.cleanSince = now;
} else {
@@ -4915,16 +4955,19 @@
const asks = keyframeAsksFor(id, entry, prev.stats, stats);
const media = remoteMedia.get(id) || null;
const watched = !(media && media.cameraOff) && !(typeof document !== 'undefined' && document.hidden);
+ // A renegotiation — a screen added or taken away, either side — costs
+ // the camera a freeze or two that are not the link's: no news then.
+ const settling = now < (entry.adaptSettleUntil || 0);
let rec = adapt.get(id);
if (!rec) {
rec = adaptRecord(adaptUpAfter);
adapt.set(id, rec);
}
const before = rec.level;
- adaptStep(rec, now, adaptSample(q, watched, asks));
+ adaptStep(rec, now, settling ? null : adaptSample(q, watched, asks));
if (rec.level !== before) {
console.info('calls: video from ' + id.slice(0, 6) + ' ' + ADAPT_LEVELS[before] + ' -> ' +
- ADAPT_LEVELS[rec.level] + (rec.level < before ? ' (probe)' : ''));
+ ADAPT_LEVELS[rec.level] + (rec.level < before ? ' (probe)' : ' (' + (rec.why || '') + ')'));
}
}
@@ -4952,6 +4995,15 @@
// when they change; the tiles' badges; and the seconds at each level,
// asked and sent, for the next quality report.
function answerAdapt(now, dt) {
+ if (dt > 0) {
+ const was = localAdapt.level;
+ adaptStep(localAdapt, now, loadSample(PRESSURE_STATES.indexOf(pressure.state) >= 2));
+ if (localAdapt.level !== was) {
+ console.info('calls: own camera ' + ADAPT_LEVELS[was] + ' -> ' + ADAPT_LEVELS[localAdapt.level] +
+ ' (compute pressure ' + (pressure.state || 'unknown') + ')');
+ for (const entry of pcs.values()) tuneShare(entry);
+ }
+ }
for (const id of Array.from(adapt.keys())) if (!pcs.has(id)) adapt.delete(id);
const levels = new Map();
for (const id of pcs.keys()) levels.set(id, adapt.has(id) ? adapt.get(id).level : 0);
@@ -5980,6 +6032,10 @@
report.client = o.client;
if (o.devices) report.devices = o.devices;
if (o.events && Object.keys(o.events).length) report.events = o.events;
+ // §15.30 (2026-10-29): the machine's own state, where the browser says
+ // it — the Compute Pressure API's worst in the window, and nothing
+ // else (a page cannot see its own CPU or memory).
+ if (o.thermal && ['nominal', 'fair', 'serious', 'critical'].includes(o.thermal)) report.host = { thermal: o.thermal };
const peers = [];
for (const p of o.peers || []) {
if (peers.length >= QUALITY_MAX_PEERS) break;
@@ -6226,6 +6282,8 @@
stallsBy.clear();
qualitySamples.clear();
refreshOutputKind();
+ const pressureWorst = pressure.worst;
+ pressure.worst = pressure.state;
const track = local && local.getAudioTracks()[0];
const report = qualityReport({
final,
@@ -6238,6 +6296,7 @@
events: events.call,
peers,
shareMode: share ? shareMode() : '',
+ thermal: pressureWorst,
});
// A new participation is a new gate, and its first window has no
// window before it.
@@ -9677,9 +9736,14 @@
// up, shortened so a scenario can see a whole climb back; at least a
// second, at most the real one, and only for watches made after it.
adaptForTest(o) {
+ // And this device's compute pressure, as if the API had said it.
+ if (o && PRESSURE_STATES.includes(o.pressure)) {
+ pressure.state = o.pressure;
+ if (PRESSURE_STATES.indexOf(o.pressure) > PRESSURE_STATES.indexOf(pressure.worst)) pressure.worst = o.pressure;
+ }
const up = Number(o && o.upAfter) || ADAPT_UP_AFTER;
adaptUpAfter = Math.max(1000, Math.min(up, ADAPT_UP_AFTER));
- for (const r of adapt.values()) {
+ for (const r of [...adapt.values(), localAdapt]) {
r.upBase = adaptUpAfter;
r.upWait = Math.min(r.upWait, adaptUpAfter);
}
@@ -9797,10 +9861,12 @@
return [id, { level: r ? ADAPT_LEVELS[r.level] : 'normal', asked: videoAsks[id] || 'normal',
sent: ADAPT_LEVELS[(e && e.sentLevel) || 0], downs: r ? r.downs : 0, ups: r ? r.ups : 0,
upWait: r ? r.upWait : adaptUpAfter, cameraPaused: !!(e && e.cameraPaused),
- wire: e ? adaptWire(id, e) : null, last: r && r.samples.length ? r.samples[r.samples.length - 1] : null }];
+ why: r ? r.why || '' : '', wire: e ? adaptWire(id, e) : null, last: r && r.samples.length ? r.samples[r.samples.length - 1] : null }];
})),
videoAsks: Object.assign({}, videoAsks),
videoSetting: videoSetting(),
+ ownCamera: ADAPT_LEVELS[localAdapt.level],
+ pressure: pressure.state,
videoNotice: adaptNoticeShown,
// §15.19: what this tab reports, and what it has been told, by
// peer id. Peers that never reported are absent.
@@ -9883,9 +9949,29 @@
console.error('meet: levels', err);
});
}, LEVEL_EVERY);
+ watchPressure();
connectStream();
}
+ // watchPressure follows the Compute Pressure API where the browser has
+ // it (Chromium's PressureObserver): this device's CPU pressure, for the
+ // sender's own watch and the quality report's `thermal`. Where it is
+ // missing, or refused, nothing is said and nothing changes.
+ function watchPressure() {
+ if (typeof PressureObserver !== 'function') return;
+ try {
+ pressure.observer = new PressureObserver((records) => {
+ const last = records[records.length - 1];
+ if (!last || !PRESSURE_STATES.includes(last.state)) return;
+ pressure.state = last.state;
+ if (PRESSURE_STATES.indexOf(last.state) > PRESSURE_STATES.indexOf(pressure.worst)) pressure.worst = last.state;
+ });
+ Promise.resolve(pressure.observer.observe('cpu', { sampleInterval: 1000 })).catch(() => {});
+ } catch {
+ pressure.observer = null;
+ }
+ }
+
// Nothing above may throw into nowhere: an unhandled rejection here
// would leave the room revealed, empty and silent.
start().catch((err) => {
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go
index a9687fa..1378647 100644
--- a/internal/callstest/native_browser_test.go
+++ b/internal/callstest/native_browser_test.go
@@ -6,17 +6,21 @@ import (
"bufio"
"context"
"encoding/json"
+ "fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
+ "slices"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
+
+ "amadan.net/oficina/calls/protocol"
)
// This gate uses the shipping Go bridge and WebRTC implementation with a
@@ -148,6 +152,20 @@ func assertNativeQualityReports(t *testing.T, rig *browserRig) {
if !measured {
t.Fatalf("no peer line from the app measured the browser's audio, path and candidates: %v", peerLines)
}
+ // §15.30 (2026-10-29): and how the Mac itself fared, on the head line.
+ host := false
+ for _, line := range mac {
+ cpu, ok := line["procCpuPct"].(float64)
+ mem, _ := line["procMemMB"].(float64)
+ _, load := line["sysLoad1"].(float64)
+ _, low := line["lowPower"].(bool)
+ if ok && cpu >= 0 && mem > 1 && load && low && slices.Contains(protocol.ThermalStates, fmt.Sprint(line["thermal"])) {
+ host = true
+ }
+ }
+ if !host {
+ t.Fatalf("no report from the app said how the Mac fared (CPU, memory, load, thermal, Low Power): %v", mac)
+ }
// 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.
diff --git a/internal/callstest/quality_test.go b/internal/callstest/quality_test.go
index 6fea402..ebefca5 100644
--- a/internal/callstest/quality_test.go
+++ b/internal/callstest/quality_test.go
@@ -322,6 +322,42 @@ func TestQualityReportsCarryAdaptiveVideo(t *testing.T) {
r.assertClean(t)
}
+// Spec §15.30 (2026-10-29): how the machine itself fared — the client's
+// own CPU and memory, the load, the thermal state and Low Power Mode — on
+// the head line, and nothing when the client measured none of it.
+func TestQualityReportsCarryTheMachinesLoad(t *testing.T) {
+ r := newReportRig(t, "")
+ q := sampleQuality(r.peerB)
+ off := false
+ q.Host = &protocol.HostLoad{ProcCPUPct: num(182.46), ProcMemMB: num(412), SysLoad1: num(6.2), Thermal: "serious", LowPower: &off}
+ if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted {
+ t.Fatalf("report: %d, want 202", resp.StatusCode)
+ }
+ l := r.reports.lines(t, "calls: quality")[0]
+ for k, want := range map[string]any{"procCpuPct": 182.5, "procMemMB": 412.0, "sysLoad1": 6.2, "thermal": "serious", "lowPower": false} {
+ if l[k] != want {
+ t.Errorf("line[%q] = %v, want %v", k, l[k], want)
+ }
+ }
+ r.x.advance(10 * time.Second)
+ web := sampleQuality(r.peerB)
+ web.Client = protocol.ReportClient{App: "web", Browser: "chrome", BrowserVersion: "141"}
+ web.Host = &protocol.HostLoad{Thermal: "fair"}
+ if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, web)); resp.StatusCode != http.StatusAccepted {
+ t.Fatalf("web report: %d", resp.StatusCode)
+ }
+ w := r.reports.lines(t, "calls: quality")[1]
+ if w["thermal"] != "fair" {
+ t.Errorf("web thermal %v", w["thermal"])
+ }
+ for _, k := range []string{"procCpuPct", "procMemMB", "sysLoad1", "lowPower"} {
+ if _, ok := w[k]; ok {
+ t.Errorf("a web report put %q on the line", k)
+ }
+ }
+ r.assertClean(t)
+}
+
func TestQualityReportSchemaIsStrict(t *testing.T) {
r := newReportRig(t, "")
base := func() map[string]any {
@@ -366,9 +402,15 @@ func TestQualityReportSchemaIsStrict(t *testing.T) {
"levels as a map": func(m map[string]any) {
peer0(m)["events"].(map[string]any)["askedSeconds"] = map[string]any{"minimal": 3}
},
- "an unknown setting": func(m map[string]any) { m["events"].(map[string]any)["videoSetting"] = "potato" },
- "the same peer twice": func(m map[string]any) { m["peers"] = append(m["peers"].([]any), peer0(m)) },
- "a peer list for a room": func(m map[string]any) { m["peers"] = "everyone" },
+ "an unknown setting": func(m map[string]any) { m["events"].(map[string]any)["videoSetting"] = "potato" },
+ // The machine's own load (§15.30, 2026-10-29).
+ "an unknown thermal state": func(m map[string]any) { m["host"] = map[string]any{"thermal": "toasty"} },
+ "a negative cpu": func(m map[string]any) { m["host"] = map[string]any{"procCpuPct": -1} },
+ "a cpu past 128 cores": func(m map[string]any) { m["host"] = map[string]any{"procCpuPct": 12801} },
+ "low power as words": func(m map[string]any) { m["host"] = map[string]any{"lowPower": "yes"} },
+ "a load as words": func(m map[string]any) { m["host"] = map[string]any{"sysLoad1": "high"} },
+ "the same peer twice": func(m map[string]any) { m["peers"] = append(m["peers"].([]any), peer0(m)) },
+ "a peer list for a room": func(m map[string]any) { m["peers"] = "everyone" },
"five peers": func(m map[string]any) {
var ps []any
for i := 0; i <= protocol.MaxQualityPeers; i++ {
@@ -435,6 +477,8 @@ func TestTheLargestQualityLineFitsThePlatformsLine(t *testing.T) {
}
q := sampleQuality(r.peerB)
q.Events.VideoSetting = "audio"
+ on := true
+ q.Host = &protocol.HostLoad{ProcCPUPct: num(12799.9), ProcMemMB: num(1048575.9), SysLoad1: num(9999.9), Thermal: "critical", LowPower: &on}
q.Peers = nil
for i := 0; i < protocol.MaxQualityPeers; i++ {
q.Peers = append(q.Peers, protocol.PeerQuality{
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift
index c66d600..39a1b61 100644
--- a/native/apple/Sources/CallsKit/Call.swift
+++ b/native/apple/Sources/CallsKit/Call.swift
@@ -146,6 +146,12 @@ private final class Events: NSObject, BridgeListenerProtocol {
applyVideoQuality()
}
}
+ /// The sender's own watch of this device (thermal state, Calls' CPU),
+ /// and the readings the quality report's host load is taken from.
+ private var localAdapt = VideoAdapt()
+ private var hostSampler = HostLoadSampler()
+ /// The level this device's own trouble holds its camera at, for the gate.
+ @Published public private(set) var ownCameraLevel = VideoLevel.normal
/// The watch's clean time before a probe up; the gate shortens it.
@_spi(Fixtures) public var adaptUpAfter = VideoAdapt.upAfter
/// Quality reports (spec §15.26): the notices tallied over the window,
@@ -728,6 +734,9 @@ private final class Events: NSObject, BridgeListenerProtocol {
adapt = [:]
adaptCounters = [:]
adaptLookedAt = nil
+ localAdapt = VideoAdapt()
+ ownCameraLevel = .normal
+ built?.localLevel = .normal
reportedVideo = [:]
videoAsks = [:]
videoNotice = ""
@@ -1534,6 +1543,7 @@ extension Call {
#else
let watching = UIApplication.shared.applicationState == .active
#endif
+ let negotiated = media.negotiatedAt
for (id, sample) in samples where id != current.peer {
let counters = QualityCounters(sample)
let before = adaptCounters[id].flatMap { $0.generation == sample.generation ? $0.counters : nil }
@@ -1542,7 +1552,10 @@ extension Call {
var watch = adapt[id] ?? VideoAdapt(upAfter: adaptUpAfter)
let was = watch.level
let cameraWatched = watching && !isCameraOff(id)
- watch.observe(at: now, VideoAdapt.sample(counters, before, cameraWatched: cameraWatched))
+ // A renegotiation costs the camera a freeze or two that are not the
+ // link's: no news while it settles.
+ let settling = now - (negotiated[id] ?? 0) < VideoAdapt.settle
+ watch.observe(at: now, settling ? nil : VideoAdapt.sample(counters, before, cameraWatched: cameraWatched))
adapt[id] = watch
if watch.level != was {
CallLog.info("video from \(id.prefix(6)): \(was.wire) -> \(watch.level.wire)\(watch.level < was ? " (probe)" : "")")
@@ -1552,6 +1565,23 @@ extension Call {
for id in Array(adaptCounters.keys) where samples[id] == nil { adaptCounters.removeValue(forKey: id) }
reportVideo()
answerVideoAsks(current)
+ // The sender's own half: this device struggling lowers its camera.
+ #if os(macOS)
+ let mac = true
+ #else
+ let mac = false
+ #endif
+ let reading = HostLoadSampler.Reading.now(at: now)
+ let cpu = hostSampler.tick(reading)
+ let wasOwn = localAdapt.level
+ localAdapt.observe(
+ at: now, VideoAdapt.loadSample(struggling: VideoAdapt.struggling(thermal: reading.thermal, cpuPct: cpu, mac: mac)))
+ if localAdapt.level != wasOwn {
+ CallLog.info(
+ "own camera: \(wasOwn.wire) -> \(localAdapt.level.wire) (thermal \(HostLoadSampler.word(reading.thermal)), CPU \(Int(cpu ?? 0))%)")
+ media.localLevel = localAdapt.level
+ ownCameraLevel = localAdapt.level
+ }
let sent = media.sentLevels
qualityTally.videoSetting = videoQuality
for id in samples.keys where id != current.peer {
@@ -1724,10 +1754,12 @@ extension Call {
}
private func qualityReport(at now: Double, samples: [String: QualityPeerSample], final: Bool) -> String? {
- qualityBuilder.build(
+ var report = qualityBuilder.build(
at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(),
- devices: qualityDevices(), final: final, screenMode: sharingScreen ? screenMode.rawValue : nil
- ).encoded()
+ devices: qualityDevices(), final: final, screenMode: sharingScreen ? screenMode.rawValue : nil)
+ // §15.30 (2026-10-29): how this machine fared over the window.
+ report.host = hostSampler.take(HostLoadSampler.Reading.now(at: now))
+ return report.encoded()
}
/// The report sent at leave, built while the connections are still up;
diff --git a/native/apple/Sources/CallsKit/HostLoad.swift b/native/apple/Sources/CallsKit/HostLoad.swift
new file mode 100644
index 0000000..e52b8bf
--- /dev/null
+++ b/native/apple/Sources/CallsKit/HostLoad.swift
@@ -0,0 +1,112 @@
+import Darwin
+import Foundation
+
+/// Spec §15.30 (2026-10-29): how the machine itself fared. Paul's Mac "got
+/// completely overloaded" in a call (call txt4wuhyg6qqellf, 0.4.13), and the
+/// encoder never named the CPU as its limit, so nothing could say whether
+/// Calls or something else was eating it. Each quality report now carries
+/// Calls' own CPU over the window, its resident memory, the load average
+/// (Mac), the worst thermal state, and Low Power Mode; and the same
+/// readings, once a second, tell the sender's own watch when this device
+/// is struggling.
+public struct QualityHost: Encodable, Equatable, Sendable {
+ /// Calls' own process, percent of one core, over the window.
+ public var procCpuPct: Double?
+ /// Its resident memory at the window's end, in MB.
+ public var procMemMB: Double?
+ /// The system's one-minute load average (Mac only).
+ public var sysLoad1: Double?
+ /// The worst thermal state in the window: nominal, fair, serious, critical.
+ public var thermal: String?
+ /// Low Power Mode, at any point in the window.
+ public var lowPower: Bool?
+}
+
+/// The readings, kept between looks: the process's CPU time at the last
+/// second and at the window's start, and the worst the window has seen.
+/// Pure over what it is given; `Reading.now()` is the one place the system
+/// is asked.
+struct HostLoadSampler: Equatable, Sendable {
+ struct Reading: Equatable, Sendable {
+ var at: Double
+ /// Seconds of CPU this process has used, user and system.
+ var cpuSeconds: Double
+ var thermal: ProcessInfo.ThermalState
+ var lowPower: Bool
+ var memMB: Double?
+ var load1: Double?
+
+ static func now(at: Double) -> Reading {
+ var usage = rusage()
+ getrusage(RUSAGE_SELF, &usage)
+ let cpu =
+ Double(usage.ru_utime.tv_sec) + Double(usage.ru_utime.tv_usec) / 1e6 + Double(usage.ru_stime.tv_sec)
+ + Double(usage.ru_stime.tv_usec) / 1e6
+ var info = mach_task_basic_info()
+ var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size / MemoryLayout<natural_t>.size)
+ let ok = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
+ task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
+ }
+ }
+ #if os(macOS)
+ var loads = [Double](repeating: 0, count: 3)
+ let load: Double? = getloadavg(&loads, 3) >= 1 ? loads[0] : nil
+ #else
+ let load: Double? = nil
+ #endif
+ return Reading(
+ at: at, cpuSeconds: cpu, thermal: ProcessInfo.processInfo.thermalState,
+ lowPower: ProcessInfo.processInfo.isLowPowerModeEnabled,
+ memMB: ok == KERN_SUCCESS ? Double(info.resident_size) / 1_048_576 : nil, load1: load)
+ }
+ }
+
+ private var last: Reading?
+ private var windowStart: Reading?
+ private var worstThermal = ProcessInfo.ThermalState.nominal
+ private var lowPowerSeen = false
+
+ /// One look, about once a second: the process's CPU over the last
+ /// second, percent of one core, or nil for the first look.
+ mutating func tick(_ r: Reading) -> Double? {
+ defer { last = r }
+ if windowStart == nil { windowStart = r }
+ worstThermal = max(worstThermal, r.thermal)
+ lowPowerSeen = lowPowerSeen || r.lowPower
+ guard let last, r.at > last.at else { return nil }
+ return max(0, r.cpuSeconds - last.cpuSeconds) / (r.at - last.at) * 100
+ }
+
+ /// The window's host load, and the next window started from `r`.
+ mutating func take(_ r: Reading) -> QualityHost {
+ _ = tick(r)
+ var host = QualityHost()
+ if let start = windowStart, r.at > start.at {
+ host.procCpuPct = QualityReportBuilder.bound(
+ max(0, r.cpuSeconds - start.cpuSeconds) / (r.at - start.at) * 100, QualityBounds.cpuPct)
+ }
+ host.procMemMB = QualityReportBuilder.bound(r.memMB, QualityBounds.memMB)
+ host.sysLoad1 = QualityReportBuilder.bound(r.load1, QualityBounds.load)
+ host.thermal = Self.word(worstThermal)
+ host.lowPower = lowPowerSeen
+ windowStart = r
+ worstThermal = r.thermal
+ lowPowerSeen = r.lowPower
+ return host
+ }
+
+ static func word(_ t: ProcessInfo.ThermalState) -> String {
+ switch t {
+ case .nominal: return "nominal"
+ case .fair: return "fair"
+ case .serious: return "serious"
+ case .critical: return "critical"
+ @unknown default: return "nominal"
+ }
+ }
+}
+
+extension ProcessInfo.ThermalState: @retroactive Comparable {
+ public static func < (a: Self, b: Self) -> Bool { a.rawValue < b.rawValue }
+}
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift
index 7526fdf..7a15efd 100644
--- a/native/apple/Sources/CallsKit/Media.swift
+++ b/native/apple/Sources/CallsKit/Media.swift
@@ -251,12 +251,19 @@ import LiveKitWebRTC
p.sentLevel = level
p.applySendPolicy()
}
+ /// When each connection last renegotiated.
+ var negotiatedAt: [String: Double] { peers.mapValues(\.negotiatedAt) }
/// What each connection is sending at, as asked.
var sentLevels: [String: VideoLevel] { peers.mapValues(\.sentLevel) }
/// The person's own Audio only: no camera to anyone.
var ownAudioOnly = false {
didSet { if ownAudioOnly != oldValue { applySendPolicy() } }
}
+ /// This device's own trouble (§15.30's sender watch): a floor under the
+ /// camera to everyone; the screen and audio are not touched.
+ var localLevel = VideoLevel.normal {
+ didSet { if localLevel != oldValue { applySendPolicy() } }
+ }
/// The screen's source size, as its statistics report it.
func screenSource(width: Int, height: Int) {
guard width > 0, height > 0, (width, height) != screenSize else { return }
@@ -600,6 +607,9 @@ struct PeerAudioReading: Equatable, Sendable {
/// Spec §15.30: what this peer asks of us, and so what this connection's
/// camera and screen are sent at.
var sentLevel = VideoLevel.normal
+ /// When a negotiation on this connection last settled (§15.30's watch
+ /// takes no news for a few seconds after).
+ var negotiatedAt = 0.0
private var screenReceiver: String?
private var screenMid = ""
// Whether this connection carries a camera of ours: the classifier's
@@ -736,7 +746,8 @@ struct PeerAudioReading: Equatable, Sendable {
// the person's own Video quality is Audio only.
let level = sentLevel
let size = engine.screenSourceSize
- let camera = VideoAdapt.camera(engine.ownAudioOnly ? .audio : level, sharing: screenTx != nil)
+ let camera = VideoAdapt.camera(
+ engine.ownAudioOnly ? .audio : max(level, engine.localLevel), sharing: screenTx != nil)
AudioWork.post {
if let screen {
// The format this connection negotiated, which may hold the
@@ -798,6 +809,7 @@ struct PeerAudioReading: Equatable, Sendable {
/// The connection is back at stable: the one moment a deferred screen
/// can be added, and an owed offer made.
private func settled() {
+ negotiatedAt = ProcessInfo.processInfo.systemUptime
guard let pc, !closed else { return }
Task { @MainActor [weak self] in
// Read on the audio queue, as every call into the connection is.
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift
index 5374134..7e1a078 100644
--- a/native/apple/Sources/CallsKit/QualityReport.swift
+++ b/native/apple/Sources/CallsKit/QualityReport.swift
@@ -39,6 +39,9 @@ public enum QualityBounds {
public static let kbps = 1e6
public static let pixels = 16384.0
public static let fps = 240.0
+ public static let cpuPct = 12800.0
+ public static let memMB = 1_048_576.0
+ public static let load = 10000.0
public static let body = 16 << 10
public static let note = 1000
public static let problemBody = 64 << 10
@@ -56,9 +59,11 @@ public struct QualityReport: Encodable, Equatable, Sendable {
/// The reference of the automatic report sent with this window
/// (§15.29), when one was.
public var autoReport: String?
+ /// How this machine fared in the window (§15.30, 2026-10-29).
+ public var host: QualityHost?
enum CodingKeys: String, CodingKey {
- case v, seconds, client, devices, events, peers, autoReport
+ case v, seconds, client, devices, events, peers, autoReport, host
case isFinal = "final"
}
diff --git a/native/apple/Sources/CallsKit/VideoAdapt.swift b/native/apple/Sources/CallsKit/VideoAdapt.swift
index 769a8a2..66aec3e 100644
--- a/native/apple/Sources/CallsKit/VideoAdapt.swift
+++ b/native/apple/Sources/CallsKit/VideoAdapt.swift
@@ -95,6 +95,14 @@ struct VideoAdapt: Equatable, Sendable {
static let probeWatch = 20.0 // trouble this soon after a probe steps back
static let probeJudge = 5.0 // judged on at least this much of it
static let upMax = 300.0 // the probe's wait doubles to at most this
+ static let settle = 5.0 // after a renegotiation (a screen added or taken away), no news this long
+ // The sender's own half (2026-10-29): this device struggling for this
+ // many of the window's seconds is trouble for its own camera, judged by
+ // the same watch at the same levels; the screen and audio are not
+ // touched. Struggling is a thermal state of serious or worse, or (Mac)
+ // Calls' own process over loadCPUPct of one core.
+ static let downLoadSeconds = 8
+ static let loadCPUPct = 150.0
/// One second of what arrived from the sender.
struct Sample: Equatable, Sendable {
@@ -107,6 +115,20 @@ struct VideoAdapt: Equatable, Sendable {
var jitterBufferMs: Double?
var decoded = 0.0
var dropped = 0.0
+ /// This device struggled in this second (the sender's own watch).
+ var load = false
+ }
+
+ /// One second of this device's own load, for the sender's watch of
+ /// itself: nothing about a link, only whether it struggled.
+ static func loadSample(struggling: Bool) -> Sample {
+ Sample(rtt: nil, jitterBufferMs: nil, load: struggling)
+ }
+
+ /// Whether this device is struggling now (see `downLoadSeconds`).
+ static func struggling(thermal: ProcessInfo.ThermalState, cpuPct: Double?, mac: Bool) -> Bool {
+ if thermal == .serious || thermal == .critical { return true }
+ return mac && (cpuPct ?? 0) > loadCPUPct
}
private(set) var level = VideoLevel.normal
@@ -133,6 +155,7 @@ struct VideoAdapt: Equatable, Sendable {
/// spike is not a slow link), the jitter buffer as their mean.
struct Window: Equatable {
var freezes = 0.0, freezeSeconds = 0.0, keyframeAsks = 0.0, packets = 0.0, lost = 0.0
+ var loadSeconds = 0
var decoded = 0.0, dropped = 0.0
var rtt: Double?
var jitterBuffer: Double?
@@ -147,6 +170,7 @@ struct VideoAdapt: Equatable, Sendable {
w.freezes += x.freezes
w.freezeSeconds += x.freezeSeconds
w.keyframeAsks += x.keyframeAsks
+ if x.load { w.loadSeconds += 1 }
w.packets += x.packets
w.lost += x.lost
w.decoded += x.decoded
@@ -166,7 +190,7 @@ struct VideoAdapt: Equatable, Sendable {
return .severe
}
if w.freezes >= downFreezes || w.freezeSeconds >= downFreezeSeconds || w.loss > downLoss
- || w.keyframeAsks >= downKeyframeAsks
+ || w.keyframeAsks >= downKeyframeAsks || w.loadSeconds >= downLoadSeconds
|| (w.rtt.map { $0 >= downRTT } ?? false && w.freezes >= 1)
|| (w.jitterBuffer.map { $0 >= downJitterBuffer } ?? false)
|| (w.dropped >= downDroppedMin && w.dropped >= downDropped * (w.decoded + w.dropped))
@@ -178,7 +202,7 @@ struct VideoAdapt: Equatable, Sendable {
static func clean(_ x: Sample) -> Bool {
let n = x.packets + x.lost
- return x.freezes == 0 && x.freezeSeconds == 0 && x.keyframeAsks == 0 && (n == 0 || x.lost / n <= cleanLoss)
+ return x.freezes == 0 && x.freezeSeconds == 0 && x.keyframeAsks == 0 && !x.load && (n == 0 || x.lost / n <= cleanLoss)
&& (x.rtt.map { $0 < cleanRTT } ?? true) && (x.jitterBufferMs.map { $0 < cleanJitterBuffer } ?? true)
}
diff --git a/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift
index 4c0f83f..d05e51a 100644
--- a/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift
+++ b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift
@@ -282,4 +282,63 @@ final class VideoAdaptTests: XCTestCase {
XCTAssertTrue(body.contains(#""videoSetting":"low""#), body)
XCTAssertFalse(body.contains(#""peer":"q""#), "a peer at normal both ways says nothing")
}
+
+ // MARK: - The sender's own watch, and the machine's load (2026-10-29)
+
+ func testThisDeviceStrugglingLowersItsOwnCameraAndCalmBringsItBack() {
+ var w = VideoAdapt()
+ XCTAssertEqual(run(&w, 0, 35) { _ in VideoAdapt.loadSample(struggling: true) }, [[10, 1], [20, 2], [30, 3]])
+ var calm = VideoAdapt()
+ run(&calm, 0, 10) { _ in VideoAdapt.loadSample(struggling: true) }
+ XCTAssertEqual(calm.level, .reduced)
+ XCTAssertEqual(run(&calm, 11, 60) { _ in VideoAdapt.loadSample(struggling: false) }, [[56, 0]])
+ var brief = VideoAdapt()
+ XCTAssertEqual(run(&brief, 0, 60) { t in VideoAdapt.loadSample(struggling: t % 10 < 7) }, [], "seven in ten is not sustained")
+ }
+
+ func testWhatCountsAsStruggling() {
+ XCTAssertTrue(VideoAdapt.struggling(thermal: .serious, cpuPct: 10, mac: false))
+ XCTAssertTrue(VideoAdapt.struggling(thermal: .critical, cpuPct: nil, mac: true))
+ XCTAssertFalse(VideoAdapt.struggling(thermal: .fair, cpuPct: 140, mac: true))
+ XCTAssertTrue(VideoAdapt.struggling(thermal: .nominal, cpuPct: 151, mac: true))
+ XCTAssertFalse(VideoAdapt.struggling(thermal: .nominal, cpuPct: 400, mac: false), "the iPhone goes by its thermal state")
+ }
+
+ func testTheOwnLevelLowersTheCameraNotTheScreen() {
+ // The camera at the larger of what they ask and this device's own.
+ XCTAssertEqual(VideoAdapt.camera(max(.normal, .minimal), sharing: false).maxBitrate, 120_000)
+ let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080)
+ XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan, "the screen goes by the ask alone")
+ }
+
+ func testTheHostLoadOverAWindow() {
+ typealias R = HostLoadSampler.Reading
+ var h = HostLoadSampler()
+ XCTAssertNil(h.tick(R(at: 0, cpuSeconds: 10, thermal: .nominal, lowPower: false)))
+ XCTAssertEqual(h.tick(R(at: 1, cpuSeconds: 11.6, thermal: .fair, lowPower: false)) ?? 0, 160, accuracy: 1e-9)
+ _ = h.tick(R(at: 2, cpuSeconds: 12, thermal: .serious, lowPower: true))
+ let host = h.take(R(at: 30, cpuSeconds: 25, thermal: .nominal, lowPower: false, memMB: 412.04, load1: 6.21))
+ XCTAssertEqual(host.procCpuPct, 50, "15 s of CPU in 30")
+ XCTAssertEqual(host.procMemMB, 412)
+ XCTAssertEqual(host.sysLoad1, 6.2)
+ XCTAssertEqual(host.thermal, "serious", "the worst in the window")
+ XCTAssertEqual(host.lowPower, true)
+ let next = h.take(R(at: 60, cpuSeconds: 25, thermal: .nominal, lowPower: false))
+ XCTAssertEqual(next.procCpuPct, 0)
+ XCTAssertEqual(next.thermal, "nominal")
+ XCTAssertEqual(next.lowPower, false)
+ XCTAssertNil(next.procMemMB)
+ }
+
+ func testTheHostLoadIsInTheReport() throws {
+ var report = QualityReport(seconds: 30, client: QualityClient(app: "mac", version: "0.4.15"))
+ report.host = QualityHost(procCpuPct: 182.5, procMemMB: 412, sysLoad1: 6.2, thermal: "serious", lowPower: false)
+ let body = try XCTUnwrap(report.encoded())
+ XCTAssertTrue(
+ body.contains(#""host":{"lowPower":false,"procCpuPct":182.5,"procMemMB":412,"sysLoad1":6.2,"thermal":"serious"}"#),
+ body)
+ let reading = HostLoadSampler.Reading.now(at: 1)
+ XCTAssertGreaterThan(reading.cpuSeconds, 0)
+ XCTAssertGreaterThan(reading.memMB ?? 0, 1)
+ }
}
diff --git a/protocol/quality.go b/protocol/quality.go
index fadb75b..6feb046 100644
--- a/protocol/quality.go
+++ b/protocol/quality.go
@@ -25,6 +25,9 @@ const (
MaxQualityKbps = 1e6 // any bitrate, in kbit/s
MaxQualityPixels = 16384 // a frame's width or height
MaxQualityFPS = 240 // frames per second
+ MaxQualityCPUPct = 12800 // a process's CPU, percent of one core: 128 cores' worth
+ MaxQualityMemMB = 1 << 20 // resident memory, in MB
+ MaxQualityLoad = 10000 // a load average
MaxQualityBody = 16 << 10
MaxProblemNote = 1000 // characters of "What went wrong?"
MaxProblemBody = 64 << 10 // the whole problem report, diagnostics included
@@ -56,8 +59,27 @@ type QualityReport struct {
// 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"`
+ // Host is how the machine itself fared in the window (spec §15.30,
+ // 2026-10-29): whether Calls, or something else, was eating it.
+ Host *HostLoad `json:"host,omitempty"`
}
+// HostLoad is the reporting machine's own load over the window. Every
+// member is optional: the apps send what they can measure, and the web
+// only Thermal, where the browser has the Compute Pressure API.
+type HostLoad struct {
+ ProcCPUPct *float64 `json:"procCpuPct,omitempty"` // the client's own process, percent of one core, over the window
+ ProcMemMB *float64 `json:"procMemMB,omitempty"` // its resident memory at the window's end
+ SysLoad1 *float64 `json:"sysLoad1,omitempty"` // the system's one-minute load average (Mac)
+ Thermal string `json:"thermal,omitempty"` // ThermalStates: the worst in the window
+ LowPower *bool `json:"lowPower,omitempty"` // Low Power Mode, at any point in the window
+}
+
+// ThermalStates are the values HostLoad.Thermal may carry: Apple's
+// ProcessInfo.ThermalState, and the Compute Pressure API's states, which
+// have the same four names.
+var ThermalStates = []string{"nominal", "fair", "serious", "critical"}
+
// ReportClient says what is reporting. Enums, and versions as digits and
// dots: never a user agent string, a device model or a machine name.
type ReportClient struct {
diff --git a/test/browser/call.mjs b/test/browser/call.mjs
index da01441..8b038b2 100644
--- a/test/browser/call.mjs
+++ b/test/browser/call.mjs
@@ -506,6 +506,10 @@ function state(page) {
chat: s.chat,
sharing: s.sharing,
shares: s.shares,
+ // §15.30: what this tab asks of each sender, and sends each.
+ videoAsks: s.videoAsks,
+ adapt: s.adapt ? Object.fromEntries(Object.entries(s.adapt).map(([id, a]) =>
+ [id, { level: a.level, sent: a.sent, last: a.last }])) : null,
// §15.20. `hearing` is keyed by tile ('self' for this tab's own):
// what each tile says about its audio, its levels between 0 and
// 1, its lit bars and any notice. All plain values.
@@ -702,6 +706,10 @@ async function diagnose(page, label) {
chat: s.chat,
sharing: s.sharing,
shares: s.shares,
+ // §15.30: what this page asks of each sender, and sends each.
+ videoAsks: s.videoAsks,
+ adapt: s.adapt ? Object.fromEntries(Object.entries(s.adapt).map(([id, a]) =>
+ [id, { level: a.level, sent: a.sent, cameraPaused: a.cameraPaused, why: a.why, last: a.last }])) : null,
}
: null,
tiles,
diff --git a/test/browser/room-adapt.test.mjs b/test/browser/room-adapt.test.mjs
index 8776f7c..dcb12c0 100644
--- a/test/browser/room-adapt.test.mjs
+++ b/test/browser/room-adapt.test.mjs
@@ -35,11 +35,11 @@ function liftConst(name) {
return 'const ' + name + ' = ' + m[1] + ';';
}
const CONSTS = ['ADAPT_LEVELS', 'ADAPT_WINDOW', 'ADAPT_SEVERE_AFTER', 'ADAPT_DOWN_FREEZES', 'ADAPT_DOWN_LOSS',
- 'ADAPT_DOWN_RTT', 'ADAPT_DOWN_JITTER_BUFFER', 'ADAPT_DOWN_DROPPED', 'ADAPT_DOWN_DROPPED_MIN', 'ADAPT_DOWN_FREEZE_SECONDS', 'ADAPT_DOWN_KEYFRAME_ASKS', 'ADAPT_SEVERE_FREEZES',
+ 'ADAPT_DOWN_RTT', 'ADAPT_DOWN_JITTER_BUFFER', 'ADAPT_DOWN_DROPPED', 'ADAPT_DOWN_DROPPED_MIN', 'ADAPT_DOWN_FREEZE_SECONDS', 'ADAPT_DOWN_KEYFRAME_ASKS', 'ADAPT_DOWN_LOAD_SECONDS', 'ADAPT_SEVERE_FREEZES',
'ADAPT_SEVERE_FREEZE_SECONDS', 'ADAPT_SEVERE_LOSS', 'ADAPT_CLEAN_LOSS', 'ADAPT_CLEAN_RTT', 'ADAPT_CLEAN_JITTER_BUFFER',
'ADAPT_UP_AFTER', 'ADAPT_PROBE_WATCH', 'ADAPT_PROBE_JUDGE', 'ADAPT_UP_MAX', 'ADAPT_CAMERA', 'ADAPT_SCREEN',
'ADAPT_MIN_NATIVE_VERSION', 'QUALITY_MAX_SECONDS'].map(liftConst).join('\n');
-const NAMES = ['adaptRecord', 'adaptSample', 'adaptWindow', 'adaptTrouble', 'adaptClean', 'adaptMove', 'adaptStep',
+const NAMES = ['adaptRecord', 'adaptSample', 'loadSample', 'adaptWhy', 'adaptWindow', 'adaptTrouble', 'adaptClean', 'adaptMove', 'adaptStep',
'videoFloor', 'adaptAsks', 'askedOf', 'cameraCap', 'cameraAtLevel', 'sharePlan', 'screenAtLevel', 'parseClient',
'compareVersions', 'honoursAsks', 'adaptNoticeWords', 'withVideoTime', 'mediaFrom', 'mediaKey', 'mediaPayload'];
// eslint-disable-next-line no-new-func
@@ -295,3 +295,21 @@ test('the media report carries the asks, and reads them back leniently', () => {
assert.notEqual(a, c);
assert.notEqual(r.mediaKey({ muted: false, cameraOff: false }), a);
});
+
+test('the sender’s own watch: this device struggling for 8 of 10 seconds lowers its camera, and calm brings it back', () => {
+ const rec = r.adaptRecord();
+ // Struggling every second: a level every ten, never severe.
+ assert.deepEqual(run(rec, 0, 35, () => r.loadSample(true)), [[10, 1], [20, 2], [30, 3]]);
+ // Calm: up after forty-five seconds, as any watch.
+ const calm = r.adaptRecord();
+ run(calm, 0, 10, () => r.loadSample(true));
+ assert.equal(calm.level, 1);
+ assert.deepEqual(run(calm, 11, 60, () => r.loadSample(false)), [[56, 0]]);
+ // Seven seconds in ten is not sustained.
+ const brief = r.adaptRecord();
+ assert.deepEqual(run(brief, 0, 60, (t) => r.loadSample(t % 10 < 7)), []);
+ // A struggling second is not a clean one.
+ assert.equal(r.adaptSample({ in: {} }, true), null);
+ const one = r.loadSample(true);
+ assert.equal(one.load, true);
+});