Merge branch 'feat/adaptive-bandwidth' into main
Merge branch 'feat/adaptive-bandwidth' into main Adaptive video (spec 15.30): each receiver asks each sender for normal, reduced, minimal or audio only, down after 10 s of trouble, up after 45 s clean with a probe that backs off; Video quality (Auto, Low bandwidth, Audio only) on web, Mac and iPhone; the machine's own load in quality reports, and a struggling device lowers its own camera.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
42 files changed,
+3,817
−73
Makefile+1 −0callscore/media_test.go+88 −0callscore/room.go+42 −4cmd/quality-summary/detail.go+28 −0cmd/quality-summary/main.go+123 −0cmd/quality-summary/main_test.go+8 −3cmd/quality-summary/relayed_test.go+39 −0docs/superpowers/specs/2026-09-07-meet-design.md+165 −0internal/calls/hub/media.go+13 −1internal/calls/hub/media_test.go+60 −0internal/calls/quality.go+86 −1internal/calls/signal.go+63 −6internal/calls/static/calls.css+30 −12internal/calls/static/room.js+738 −10internal/calls/templates/room.html+11 −0internal/callstest/browser_test.go+2 −0internal/callstest/media_test.go+104 −1internal/callstest/native_browser_test.go+18 −0internal/callstest/quality_test.go+115 −4native/apple/Sources/CallsKit/Call.swift+192 −5native/apple/Sources/CallsKit/DevicePanel.swift+20 −0native/apple/Sources/CallsKit/HostLoad.swift+112 −0native/apple/Sources/CallsKit/InviteLinkCopy.swift+2 −2native/apple/Sources/CallsKit/MacCallView.swift+3 −1native/apple/Sources/CallsKit/MacVideoTile.swift+15 −5native/apple/Sources/CallsKit/Media.swift+38 −2native/apple/Sources/CallsKit/MiniWindow.swift+2 −0native/apple/Sources/CallsKit/MutedBadge.swift+23 −0native/apple/Sources/CallsKit/QualityReport.swift+36 −3native/apple/Sources/CallsKit/ScreenSendPolicy.swift+5 −1native/apple/Sources/CallsKit/VideoAdapt.swift+408 −0native/apple/Sources/CallsKit/Wire.swift+23 −1native/apple/Tests/CallsKitTests/VideoAdaptTests.swift+344 −0native/bridge/bridge.go+14 −0native/ios/Sources/CallsPhone.swift+17 −6native/ios/project.yml+1 −1protocol/messages.go+48 −1protocol/quality.go+42 −0test/browser/call.mjs+366 −3test/browser/native.mjs+51 −0test/browser/room-adapt.test.mjs+315 −0test/browser/room-mute.test.mjs+6 −0
CI failed — run details
diff --git a/Makefile b/Makefile| index 09e2561..f9579cf 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -153,6 +153,7 @@ browser: |
| node --test test/browser/room-screen.test.mjs |
| node --test test/browser/room-reconnect.test.mjs |
| node --test test/browser/room-recovery.test.mjs |
| + node --test test/browser/room-adapt.test.mjs |
| node --test test/browser/room-connecting.test.mjs |
| node --test test/browser/room-glow.test.mjs |
| node --test test/browser/room-layout.test.mjs |
diff --git a/callscore/media_test.go b/callscore/media_test.go| index 28956d5..2634fd1 100644 |
| --- a/callscore/media_test.go |
| +++ b/callscore/media_test.go |
| @@ -409,3 +409,91 @@ func TestHearingFallsBackOnAnOldServer(t *testing.T) { |
| } |
| nothingPosted(t, posted, "a roster that agrees with the plain report needs nothing") |
| } |
| + |
| +// §15.30: the asks are kept to roster peers and the wire's levels, sent |
| +// only on a change, and an empty set is no key at all. |
| +func TestVideoAsksAreReportedFromTheRoster(t *testing.T) { |
| + r, posted := mediaRoom(t) |
| + a, b := protocol.PeerID("aaaa"), protocol.PeerID("bbbb") |
| + if err := r.receive(roster(protocol.RosterPeer{Peer: "self"}, protocol.RosterPeer{Peer: a, Gen: 1}, protocol.RosterPeer{Peer: b, Gen: 1})); err != nil { |
| + t.Fatal(err) |
| + } |
| + nextMedia(t, posted) |
| + err := r.SetVideo(map[protocol.PeerID]protocol.VideoLevel{ |
| + a: protocol.VideoMinimal, b: "normal", "self": protocol.VideoAudio, "stranger": protocol.VideoAudio, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if m := nextMedia(t, posted); len(m.Video) != 1 || m.Video[a] != protocol.VideoMinimal { |
| + t.Fatalf("video %v, want only aaaa at minimal", m.Video) |
| + } |
| + if err := r.SetVideo(map[protocol.PeerID]protocol.VideoLevel{a: protocol.VideoMinimal}); err != nil { |
| + t.Fatal(err) |
| + } |
| + nothingPosted(t, posted, "the same asks are not a change") |
| + if err := r.SetVideo(map[protocol.PeerID]protocol.VideoLevel{a: protocol.VideoAudio, b: protocol.VideoReduced}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m := nextMedia(t, posted); len(m.Video) != 2 || m.Video[a] != protocol.VideoAudio || m.Video[b] != protocol.VideoReduced { |
| + t.Fatalf("video %v", m.Video) |
| + } |
| + if err := r.SetVideo(nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case s := <-posted: |
| + if strings.Contains(string(s.Payload), "video") { |
| + t.Fatalf("cleared report %s, want no video key", s.Payload) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("clearing the asks sent nothing") |
| + } |
| +} |
| + |
| +// A server from before §15.30 refuses a report carrying asks. The core |
| +// sends it again without them, hearing kept, and leaves them out from |
| +// then on: a mute is never lost, and the sender simply hears no asks. |
| +func TestVideoAsksFallBackOnAnOldServer(t *testing.T) { |
| + posted := make(chan protocol.Signal, 16) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| + var s protocol.Signal |
| + _ = json.NewDecoder(req.Body).Decode(&s) |
| + var m protocol.MediaState |
| + _ = json.Unmarshal(s.Payload, &m) |
| + posted <- s |
| + if len(m.Video) > 0 { |
| + w.WriteHeader(http.StatusBadRequest) |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + r, err := New(srv.URL, "room", srv.Client(), func(Event) {}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.started = true |
| + r.state.Peer = "self" |
| + t.Cleanup(r.Close) |
| + b := protocol.PeerID("bbbb") |
| + if err := r.receive(roster(protocol.RosterPeer{Peer: "self"}, protocol.RosterPeer{Peer: b, Gen: 1})); err != nil { |
| + t.Fatal(err) |
| + } |
| + nextMedia(t, posted) |
| + _ = r.SetMedia(true, false) |
| + nextMedia(t, posted) |
| + if err := r.SetVideo(map[protocol.PeerID]protocol.VideoLevel{b: protocol.VideoMinimal}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m := nextMedia(t, posted); len(m.Video) != 1 { |
| + t.Fatalf("first report %+v, want the asks", m) |
| + } |
| + if m := nextMedia(t, posted); len(m.Video) != 0 || m.Hearing == nil || !m.Muted { |
| + t.Fatalf("resent %+v, want the same report without asks, hearing kept", m) |
| + } |
| + if err := r.SetVideo(map[protocol.PeerID]protocol.VideoLevel{b: protocol.VideoAudio}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m := nextMedia(t, posted); len(m.Video) != 0 { |
| + t.Fatalf("later report %+v, want no asks", m) |
| + } |
| +} |
diff --git a/callscore/room.go b/callscore/room.go| index f230f3f..210ac90 100644 |
| --- a/callscore/room.go |
| +++ b/callscore/room.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "net/http" |
| "net/url" |
| + "slices" |
| "sort" |
| "sync" |
| "time" |
| @@ -67,6 +68,9 @@ type Room struct { |
| // hears (it predates §15.24), so reports go without the key, and the |
| // people on new clients fall back to their own evidence about us. |
| plainHearing bool |
| + // plainVideo: the server refused a report carrying §15.30's video |
| + // asks — one from before it — so they are left out from then on. |
| + plainVideo bool |
| // report is the latest hello's report token (spec §15.26): a resumed |
| // hello carries the same one, a fresh participation a new one. Kept |
| // past Close, for the after-call window (report.go). |
| @@ -352,6 +356,33 @@ func (r *Room) SetHearing(peers []protocol.PeerID) error { |
| return r.reportMedia() |
| } |
| +// SetVideo records what this client, as a receiver, asks each sender for |
| +// (spec §15.30) and reports it with the rest of its media state. Roster |
| +// peers other than this client only, at most protocol.MaxVideo, and only |
| +// the levels the wire has: an entry for "normal", or for anything else, is |
| +// dropped, because normal is the absence of an entry. |
| +func (r *Room) SetVideo(asks map[protocol.PeerID]protocol.VideoLevel) error { |
| + r.mu.Lock() |
| + var next map[protocol.PeerID]protocol.VideoLevel |
| + for _, p := range r.state.Peers { |
| + level, ok := asks[p.Peer] |
| + if p.Peer == r.state.Peer || !ok || !slices.Contains(protocol.VideoLevels, level) || len(next) >= protocol.MaxVideo { |
| + continue |
| + } |
| + if next == nil { |
| + next = map[protocol.PeerID]protocol.VideoLevel{} |
| + } |
| + next[p.Peer] = level |
| + } |
| + if (protocol.MediaState{Video: next}).Equal(protocol.MediaState{Video: r.media.Video}) { |
| + r.mu.Unlock() |
| + return nil |
| + } |
| + r.media.Video = next |
| + r.mu.Unlock() |
| + return r.reportMedia() |
| +} |
| + |
| func (r *Room) reportMedia() error { |
| r.mu.Lock() |
| report := r.state.Phase == "admitted" && !r.stopped |
| @@ -384,12 +415,16 @@ func (r *Room) wireMediaLocked() protocol.MediaState { |
| if r.plainHearing { |
| report.Hearing = nil |
| } |
| + if r.plainVideo { |
| + report.Video = nil |
| + } |
| return report |
| } |
| -// refusedExtras is a server from before §15.24 or §15.21 refusing a media |
| -// report because of a key it does not know: the newest key goes first — |
| -// hearing, which every report from this core carries — and the report is |
| +// refusedExtras is a server from before §15.30, §15.24 or §15.21 refusing a |
| +// media report because of a key it does not know: the newest key goes |
| +// first — §15.30's video asks when the report had any, then hearing, which |
| +// every report from this core carries — and the report is |
| // sent again without it; a second refusal, of a report naming stalled |
| // screens, takes those off too. From then on reports go without them, so |
| // a mute is never lost to an old server. Without hearing, the people on |
| @@ -402,7 +437,10 @@ func (r *Room) refusedExtras(s protocol.Signal) bool { |
| } |
| r.mu.Lock() |
| dropped := false |
| - if sent.Hearing != nil && !r.plainHearing { |
| + if len(sent.Video) > 0 && !r.plainVideo { |
| + r.plainVideo = true |
| + dropped = true |
| + } else if sent.Hearing != nil && !r.plainHearing { |
| r.plainHearing = true |
| dropped = true |
| } else if len(sent.ScreenStalled) > 0 && !r.plainScreen { |
diff --git a/cmd/quality-summary/detail.go b/cmd/quality-summary/detail.go| index de1be4c..d7922ab 100644 |
| --- a/cmd/quality-summary/detail.go |
| +++ b/cmd/quality-summary/detail.go |
| @@ -6,6 +6,8 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| ) |
| // The per-peer lines (spec §15.29, 2026-10-28): one `calls: quality peer` |
| @@ -36,6 +38,9 @@ type side struct { |
| rttAvgN int |
| concealedMax, bufferMax float64 |
| out, in map[string]*stream // "Camera", "Screen" |
| + // §15.30: seconds this side asked the other for each lower level, and |
| + // sent the other less because it asked (reduced, minimal, audio). |
| + asked, sent [protocol.VideoLevelCount]float64 |
| } |
| // stream is one video stream in one direction, from one side's account. |
| @@ -100,6 +105,10 @@ func (c *call) addPeerLine(l line) { |
| s.rttAvgSum += v |
| s.rttAvgN++ |
| } |
| + for i, name := range [protocol.VideoLevelCount]string{"Reduced", "Minimal", "Audio"} { |
| + s.asked[i] += n("asked" + name) |
| + s.sent[i] += n("sent" + name) |
| + } |
| s.concealedMax = max(s.concealedMax, n("inAudioConcealedPct")) |
| s.bufferMax = max(s.bufferMax, n("inAudioJitterBufferMs")) |
| for _, kind := range []string{"Camera", "Screen"} { |
| @@ -394,4 +403,23 @@ func (c *call) printSides(out io.Writer) { |
| fmt.Fprintln(out, m) |
| } |
| } |
| + |
| + // §15.30: who asked whom for less video, and for how long; and the |
| + // sender's own account of sending it. |
| + var levels []string |
| + for _, k := range keys { |
| + s := c.sides[k] |
| + if v := videoLevels(s.asked); v != "" { |
| + levels = append(levels, fmt.Sprintf(" %s asked %s for %s", short(k[0]), short(k[1]), v)) |
| + } |
| + if v := videoLevels(s.sent); v != "" { |
| + levels = append(levels, fmt.Sprintf(" %s sent %s %s because they asked", short(k[0]), short(k[1]), v)) |
| + } |
| + } |
| + if len(levels) > 0 { |
| + fmt.Fprintln(out, " Video levels") |
| + for _, l := range levels { |
| + fmt.Fprintln(out, l) |
| + } |
| + } |
| } |
diff --git a/cmd/quality-summary/main.go b/cmd/quality-summary/main.go| index a1e0706..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. |
| @@ -376,6 +454,10 @@ type direction struct { |
| reconnectingSeconds float64 |
| noSound, stalled, blocked int |
| screenSteps float64 |
| + // §15.30: seconds the first asked the second for each lower level |
| + // (reduced, minimal, audio), and seconds the first sent the second less |
| + // because the second asked. |
| + asked, sent [protocol.VideoLevelCount]float64 |
| } |
| type event struct { |
| @@ -471,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{} |
| } |
| @@ -545,6 +628,16 @@ func (c *call) addQuality(p *person, l line) { |
| } |
| } |
| if e := q.Events; e != nil { |
| + for i, x := range e.AskedSeconds { |
| + if i < len(d.asked) { |
| + d.asked[i] += val(x) |
| + } |
| + } |
| + for i, x := range e.SentSeconds { |
| + if i < len(d.sent) { |
| + d.sent[i] += val(x) |
| + } |
| + } |
| d.cantHear += val(e.CantHearSeconds) |
| d.reconnecting += val(e.Reconnecting) |
| d.reconnectingSeconds += val(e.ReconnectingSeconds) |
| @@ -617,8 +710,14 @@ func (c *call) print(out io.Writer, loc *time.Location) { |
| if s := headScreen(h); s != "" { |
| fmt.Fprintf(out, ", screen %s", s) |
| } |
| + if h["videoAsked"] > 0 || h["videoSent"] > 0 { |
| + fmt.Fprintf(out, ", asked someone for less video %s, sent someone less %s", minutes(h["videoAsked"]), minutes(h["videoSent"])) |
| + } |
| 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)") |
| @@ -648,6 +747,12 @@ func (c *call) print(out io.Writer, loc *time.Location) { |
| if d.screenSteps > 0 { |
| fmt.Fprintf(out, ", screen recovery steps %g", d.screenSteps) |
| } |
| + if s := videoLevels(d.asked); s != "" { |
| + fmt.Fprintf(out, ", %s asked %s for %s", short(k[0]), short(k[1]), s) |
| + } |
| + if s := videoLevels(d.sent); s != "" { |
| + fmt.Fprintf(out, ", %s sent %s %s because they asked", short(k[0]), short(k[1]), s) |
| + } |
| fmt.Fprintln(out) |
| } |
| } |
| @@ -674,6 +779,24 @@ func (c *call) print(out io.Writer, loc *time.Location) { |
| fmt.Fprintln(out) |
| } |
| +// videoLevels is §15.30's seconds at each level in words — "Minimal for |
| +// 4m0s, Audio only for 30s" — or "" when it was normal throughout. |
| +func videoLevels(secs [protocol.VideoLevelCount]float64) string { |
| + names := [protocol.VideoLevelCount]string{"Reduced", "Minimal", "Audio only"} |
| + var parts []string |
| + for i, v := range secs { |
| + if v > 0 { |
| + parts = append(parts, names[i]+" for "+minutes(v)) |
| + } |
| + } |
| + return strings.Join(parts, ", ") |
| +} |
| + |
| +// minutes is a number of seconds as a duration, to the second. |
| +func minutes(secs float64) string { |
| + return (time.Duration(secs * float64(time.Second))).Round(time.Second).String() |
| +} |
| + |
| // headScreen is a quality line's screen fields in words (spec §15.22's |
| // ladder and the receiver's watch), or "" when there are none. |
| func headScreen(h map[string]float64) string { |
diff --git a/cmd/quality-summary/main_test.go b/cmd/quality-summary/main_test.go| index 4460b63..837e628 100644 |
| --- a/cmd/quality-summary/main_test.go |
| +++ b/cmd/quality-summary/main_test.go |
| @@ -13,8 +13,8 @@ import ( |
| // report in two parts, and a text line the summary must skip. |
| const fixture = `2026-10-03 14:39:30 [app] calls.bds.oncarlos.com time=2026-10-03T14:39:30.000Z level=INFO msg="rastrillo: serving" |
| 2026-10-03 14:40:00 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:40:00Z","level":"INFO","msg":"calls: quality","call":"oldcalloldcall22","peer":"zzzzzzzzzzzzzzzz","app":"web","seconds":30,"report":{"seconds":30}} |
| -2026-10-03 14:41:00 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:00Z","level":"INFO","msg":"calls: quality","call":"callcallcallcall","peer":"aaaaaaaaaaaaaaaa","app":"mac","version":"0.4.9","os":"macos","osVersion":"26.0.1","final":false,"seconds":30,"report":{"seconds":30,"devices":{"input":"bluetooth","output":"built-in"},"peers":[{"peer":"bbbbbbbbbbbbbbbb","path":{"local":"srflx","remote":"relay","protocol":"udp"},"rtt":48,"in":{"audio":{"packets":1490,"lost":10,"samples":1440000,"concealed":14400},"video":{"packets":900,"lost":100,"freezes":2,"freezeSeconds":1.5}},"events":{"reconnecting":1,"reconnectingSeconds":4.2}}]}} |
| -2026-10-03 14:41:05 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:05Z","level":"INFO","msg":"calls: quality","call":"callcallcallcall","peer":"bbbbbbbbbbbbbbbb","app":"web","version":"de04e2d","browser":"chrome","browserVersion":"141.0","os":"windows","osVersion":"10.0","seconds":30,"report":{"seconds":30,"peers":[{"peer":"aaaaaaaaaaaaaaaa","path":{"local":"relay","remote":"srflx","protocol":"tls"},"rtt":180,"in":{"audio":{"packets":1500,"lost":0}},"events":{"cantHearSeconds":3}}]}} |
| +2026-10-03 14:41:00 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:00Z","level":"INFO","msg":"calls: quality","call":"callcallcallcall","peer":"aaaaaaaaaaaaaaaa","app":"mac","version":"0.4.9","os":"macos","osVersion":"26.0.1","final":false,"seconds":30,"report":{"seconds":30,"devices":{"input":"bluetooth","output":"built-in"},"peers":[{"peer":"bbbbbbbbbbbbbbbb","path":{"local":"srflx","remote":"relay","protocol":"udp"},"rtt":48,"in":{"audio":{"packets":1490,"lost":10,"samples":1440000,"concealed":14400},"video":{"packets":900,"lost":100,"freezes":2,"freezeSeconds":1.5}},"events":{"reconnecting":1,"reconnectingSeconds":4.2,"sentSeconds":[0,24,0]}}]}} |
| +2026-10-03 14:41:05 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:05Z","level":"INFO","msg":"calls: quality","call":"callcallcallcall","peer":"bbbbbbbbbbbbbbbb","app":"web","version":"de04e2d","browser":"chrome","browserVersion":"141.0","os":"windows","osVersion":"10.0","seconds":30,"videoAsked":24,"report":{"seconds":30,"peers":[{"peer":"aaaaaaaaaaaaaaaa","path":{"local":"relay","remote":"srflx","protocol":"tls"},"rtt":180,"in":{"audio":{"packets":1500,"lost":0}},"events":{"cantHearSeconds":3,"askedSeconds":[0,24,0]}}]}} |
| 2026-10-03 14:41:30 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:30Z","level":"INFO","msg":"calls: quality","call":"callcallcallcall","peer":"aaaaaaaaaaaaaaaa","app":"mac","version":"0.4.9","os":"macos","osVersion":"26.0.1","final":true,"seconds":30,"report":{"seconds":30,"peers":[{"peer":"bbbbbbbbbbbbbbbb","path":{"local":"host","remote":"host","protocol":"udp"},"rtt":20}]}} |
| 2026-10-03 14:41:20 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:20Z","level":"WARN","msg":"calls: problem report","ref":"K7Q2M9PD","call":"callcallcallcall","peer":"aaaaaaaaaaaaaaaa","app":"mac","version":"0.4.9","os":"macos","live":true,"note":"video froze","parts":2} |
| 2026-10-03 14:41:20 [app] calls.bds.oncarlos.com {"time":"2026-10-03T14:41:20Z","level":"WARN","msg":"calls: problem report diagnostics","ref":"K7Q2M9PD","call":"callcallcallcall","peer":"aaaaaaaaaaaaaaaa","part":2,"of":2,"text":"second half\n"} |
| @@ -52,6 +52,9 @@ func TestSummaryOfOneCall(t *testing.T) { |
| `15:41:00 aaaaaa: "Reconnecting to bbbbbb…" (4.2 s)`, |
| `15:41:05 bbbbbb: "aaaaaa can't hear you yet" (3.0 s)`, |
| "15:41:30 aaaaaa left (final report)", |
| + // §15.30: who asked whom for less video, and for how long. |
| + "bbbbbb asked aaaaaa for Minimal for 24s", |
| + "aaaaaa sent bbbbbb Minimal for 24s because they asked", |
| `Problem K7Q2M9PD at 15:41:20 from aaaaaa (mac): "video froze"`, |
| } { |
| if !strings.Contains(out, want) { |
| @@ -79,7 +82,7 @@ func TestSummaryByCallTagAndAProblemReport(t *testing.T) { |
| // `report` at all. Diagnostics text that looks like fields (" in=1", |
| // " time=") must stay text. |
| const carlosFixture = `2026-10-21 14:38:52 [app] calls.bds.oncarlos.com calls: quality app=mac call=ayhk4nffb2gz7eur final=false freezes=4 maxLossPct=0.1 maxRtt=195.9 os=macos osVersion=27.0.0 peer=p2pq7kdbzubekeu6 reconnecting=0 relay=false remotes=1 screenRebuilds=1 screenStalls=0 seconds=30.9 time=2026-10-21T14:38:52.887559374Z version=0.4.10 |
| -2026-10-21 14:39:06 [app] calls.bds.oncarlos.com calls: quality app=web browser=safari browserVersion=26.5 call=ayhk4nffb2gz7eur final=false freezes=0 maxLossPct=0 maxRtt=141 os=macos peer=ce5xx2f463fimkpi reconnecting=0 relay=false remotes=1 screenStalls=2 screenStallsUndecoded=2 seconds=30.2 time=2026-10-21T14:39:06.364245764Z version=882eab8 |
| +2026-10-21 14:39:06 [app] calls.bds.oncarlos.com calls: quality app=web browser=safari browserVersion=26.5 call=ayhk4nffb2gz7eur final=false freezes=0 maxLossPct=0 maxRtt=141 os=macos peer=ce5xx2f463fimkpi reconnecting=0 relay=false remotes=1 screenStalls=2 screenStallsUndecoded=2 seconds=30.2 time=2026-10-21T14:39:06.364245764Z version=882eab8 videoAsked=240 videoSetting=low |
| 2026-10-21 15:06:37 [app] calls.bds.oncarlos.com calls: problem report app=mac call=ayhk4nffb2gz7eur live=true note=it froze, then a=b os=macos osVersion=27.0.0 parts=2 peer=p2pq7kdbzubekeu6 ref=6BPJVTGF time=2026-10-21T15:06:37.899381736Z version=0.4.10 |
| 2026-10-21 15:06:37 [app] calls.bds.oncarlos.com calls: problem report diagnostics call=ayhk4nffb2gz7eur of=2 part=1 peer=p2pq7kdbzubekeu6 ref=6BPJVTGF text=Calls diagnostics — a call's details |
| ## Devices |
| @@ -132,6 +135,8 @@ func TestCarlosPrintedQualityHeadlines(t *testing.T) { |
| "screen 1 rebuilds", |
| "ce5xx2 web 882eab8 safari 26.5 on macos 1 reports", |
| "screen 2 stalls reported here, 2 arriving, not decoded", |
| + // §15.30's headline: time asked for less video. |
| + "asked someone for less video 4m0s, sent someone less 0s", |
| "Problem 6BPJVTGF", |
| } { |
| if !strings.Contains(out, want) { |
diff --git a/cmd/quality-summary/relayed_test.go b/cmd/quality-summary/relayed_test.go| index 61e87d1..8235230 100644 |
| --- a/cmd/quality-summary/relayed_test.go |
| +++ b/cmd/quality-summary/relayed_test.go |
| @@ -131,3 +131,42 @@ func TestWhyRelayed(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Spec §15.30: the levels from the peer lines, both sides' accounts, |
| +// whether read as JSON or as carlos prints them. |
| +func TestVideoLevelsFromThePeerLines(t *testing.T) { |
| + fixture := strings.Replace(relayedFixture, `"autoRestarts":2}`, `"autoRestarts":2,"askedMinimal":240,"askedAudio":30}`, 1) |
| + fixture = strings.Replace(fixture, `"inCameraCodec":"h264"}`, `"inCameraCodec":"h264","sentMinimal":238}`, 1) |
| + for name, text := range map[string]string{"json": fixture, "carlos": carlosPrint(t, fixture)} { |
| + out := runOnText(t, text, "--call", "relayedcall2f7ab") |
| + for _, want := range []string{ |
| + " Video levels", |
| + "ssssaf asked mmmmmm for Minimal for 4m0s, Audio only for 30s", |
| + "mmmmmm sent ssssaf Minimal for 3m58s because they asked", |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("%s: missing %q in\n%s", name, want, out) |
| + } |
| + } |
| + } |
| + if out := runOnText(t, relayedFixture, "--call", "relayedcall2f7ab"); strings.Contains(out, "Video levels") { |
| + 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 5dd166f..ec2e073 100644 |
| --- a/docs/superpowers/specs/2026-09-07-meet-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-meet-design.md |
| @@ -3287,3 +3287,168 @@ gate's `quality` scenario forces one automatic report |
| 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. |
| + |
| +### 15.30 §15.19, §15.26, §5.4 — video that steps down for a weak connection, and back up (2026-10-28) |
| + |
| +**Why.** A Dublin–London call: the guest on café Wi-Fi in Safari, relayed, |
| +round trips of 840–1300 ms, and 0–7 freezes every thirty seconds in Paul's |
| +video on the guest's side. Audio mattered most, and nothing gave way to it. |
| +Paul, 2026-10-28, approved: "Low-bandwidth with auto-switching up and down." |
| + |
| +**Decision: receiver-driven, per sender.** The call is a mesh, so every pair |
| +has its own sender, and the one who can see a picture suffering is the |
| +person receiving it. Each receiver watches what arrives from each sender |
| +and asks that sender for one of four levels; the sender sets that one |
| +connection's sender parameters (`maxBitrate`, `maxFramerate`, |
| +`scaleResolutionDownBy`, `active`, and for a screen the degradation |
| +preference). Sender parameters only: nothing renegotiates. Audio is never |
| +reduced, and keeps Opus's in-band FEC, whose packet-loss expectation |
| +libwebrtc already takes from the receiver's own reports (neither WebRTC |
| +build offers a sender parameter for it). |
| + |
| +| Level | Camera | Shared screen | |
| +|---|---|---| |
| +| normal | as before (§5.4's cap beside a screen) | as before (§5.4, §15.27) | |
| +| reduced | at most 640×360, 15 fps, 350 kbit/s; while sharing, as minimal | its size kept, 10 fps, at most 1.2 Mbit/s | |
| +| minimal | at most 320×180, 8 fps, 120 kbit/s; while sharing, none | 5 fps, at most 500 kbit/s, long side at most 1280 | |
| +| audio | none to this receiver (`active=false`) | as minimal: never paused | |
| + |
| +The camera is fitted by its long and short sides, so a portrait camera is |
| +boxed 360×640. A screen gives up frame rate first and holds resolution |
| +under pressure (`maintain-resolution`), because a screen is for reading; |
| +the apps' level fit for H.264 (§15.21, §15.27) is kept wherever it is the |
| +larger scale. If a screen cannot fit, the camera goes first. |
| + |
| +**The watch** (room.js `adapt*`, the apps' `VideoAdapt`, twins with the |
| +same named constants and unit tests on a fake clock either side). Once a |
| +second, from the stats walk each client already makes for the quality |
| +report, one sample per sender: camera freezes and their duration, the |
| +keyframes this side asked for the camera (PLI and FIR), packets and loss |
| +across audio, camera and screen, the selected pair's round trip, the audio |
| +jitter buffer's mean delay, frames decoded and dropped. Freezes and |
| +keyframe asks count only while the camera is watched — on, and the page or |
| +app in front: a still screen's gaps, and a hidden tab's unpainted frames, |
| +are not freezes. A second with nothing arriving and nothing measured is no |
| +news either way (a connection that is down is §15.28's). |
| + |
| +- *Trouble*, over the last 10 s at the current level: 2 or more freezes, |
| + 2 s or more frozen, 3 or more keyframe asks, more than 5% loss, a median |
| + round trip of 600 ms or more with a freeze, a jitter buffer of 500 ms or |
| + more, or a quarter of frames dropped (at least ten). *Severe*: 5 freezes, |
| + 4 s frozen, or more than 15% loss. |
| +- *Down*: one level once the window at a level has been trouble for 10 s; |
| + two at once for severe trouble after 5 s. The watch starts again from |
| + nothing at each new level. |
| +- *Up*: one level after 45 s of clean seconds in a row (no freeze, no |
| + keyframe ask, loss at most 2%, round trip under 400 ms, jitter buffer |
| + under 300 ms), as a probe. Trouble within 20 s of a probe (judged on at |
| + least 5 s of it) steps straight back and doubles the wait before the |
| + 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 |
| +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* |
| +(minimal from everyone, or lower if the watch says so), *Audio only* |
| +(audio from everyone, and this client's own camera to nobody, reported as |
| +camera off). |
| + |
| +**Signalling.** §15.19's `media` report gains one more optional member, |
| +`video`: an object of peer id to `"reduced"`, `"minimal"` or `"audio"`, |
| +listing only the peers asked for less than normal. Validated as |
| +`noSoundFrom` is held, by a token walk: an object (never `null`, never an |
| +array), well-formed peer ids, none repeated, at most fifteen, each value |
| +one of the three strings; anything else 400. Ids are checked for shape, |
| +not presence. `{}` and absent are both "normal from everyone" and compare |
| +equal; a change in any entry is a change. Re-encoded last, keys in order |
| +(`muted`, `cameraOff`, `audioBlocked`, `noSoundFrom`, `screenStalled`, |
| +`hearing`, `video`). The raw payload cap is 4 KB: every list and the map |
| +full is about 2,450 bytes. A sender reads its own id in each report it is |
| +given — the roster's and every `media` event — and applies the level to |
| +that connection, and to a connection made later, once it settles. |
| + |
| +**What is shown.** |
| + |
| +- On the receiver, the tile of anyone this client asks for less: a quiet |
| + "Low bandwidth" badge by the name (the vendored badge on the web), its |
| + title and the tile's VoiceOver label saying why ("Asking Ana for less |
| + video while your connection is weak", or "…as your Video quality setting |
| + says"). At audio only, the camera-off cover's shape with "Video paused to |
| + keep audio clear". |
| +- On the sender, once per change for the worse and for eight seconds: "Sending |
| + reduced video to David (their connection is weak)" — "Sending only audio |
| + to …" when it is all audio — the web's quiet status line, the apps' |
| + toast, said politely to a screen reader. Nothing is said on the way back |
| + up. |
| + |
| +**Mixed versions.** Old clients ignore the member (§15.19's decoders drop |
| +unknown keys; the apps' `PeerMedia` reads it leniently, so a malformed one |
| +costs nothing). A server from before this section refuses a report |
| +carrying it (400): the browser drops every extra for the page (§15.20), and |
| +the apps' core drops `video` first and resends the report, keeping |
| +`hearing`, then the rest as before. An app from before 0.4.15 receives the |
| +asks and ignores them, so it cannot be made to send less: a receiver at |
| +audio only still covers its picture (saving this device's work, not the |
| +connection), and the cover adds "Their app can't send less video, so it's |
| +only hidden here". A browser is always new. |
| + |
| +**Telemetry.** §15.26's per-peer `events` gain `askedSeconds` (how long |
| +this client asked the peer for reduced, minimal and audio, in that order) |
| +and `sentSeconds` (how long it sent the peer less because the peer asked): |
| +exactly three numbers each when present, bounded as seconds are, anything |
| +else 400. The call's `events` gain `videoSetting` (`low`, `audio`; absent |
| +for Auto). §15.29's `calls: quality peer` line carries them flat — |
| +`askedReduced`, `askedMinimal`, `askedAudio`, `sentReduced`, `sentMinimal`, |
| +`sentAudio`, each only when not zero — and the `calls: quality` head line |
| +carries `videoAsked` and `videoSent` (the sums) and `videoSetting`, only |
| +when not zero or Auto. `quality-summary` prints them per person and, under |
| +"Video levels", per pair ("ssssaf asked mmmmmm for Minimal for 4m0s"). |
| + |
| +**Not logged, not stored.** As §15.19; the levels are logged on the device |
| +(the browser's console, the apps' `connection` log) with six characters of |
| +the peer id. |
diff --git a/internal/calls/hub/media.go b/internal/calls/hub/media.go| index 63a7d7f..b824f51 100644 |
| --- a/internal/calls/hub/media.go |
| +++ b/internal/calls/hub/media.go |
| @@ -3,6 +3,8 @@ package hub |
| import ( |
| "context" |
| "encoding/json" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| ) |
| // SetMedia is §15.19: an admitted peer reports its own microphone and |
| @@ -14,7 +16,8 @@ import ( |
| // |
| // §15.20 adds the receiving half to the same report — audioBlocked and |
| // noSoundFrom, each present only when it has bad news, and 2026-09-28's |
| -// screenStalled beside them, and §15.24's hearing after those — and nothing |
| +// screenStalled beside them, §15.24's hearing after those, and §15.30's |
| +// video asks last — and nothing |
| // about the rules: it is still the sender's own claim, recorded and |
| // carried in rosters, and fanned out only when it changes. |
| // |
| @@ -66,6 +69,15 @@ func (h *Hub) SetMedia(ctx context.Context, sqid, session string, from PeerID, m |
| if m.Hearing != nil { |
| next.Hearing = append(make([]PeerID, 0, len(m.Hearing)), m.Hearing...) |
| } |
| + // §15.30's asks, copied for the same reason as the lists. |
| + if len(m.Video) > 0 { |
| + next.Video = make(map[PeerID]protocol.VideoLevel, len(m.Video)) |
| + for k, v := range m.Video { |
| + next.Video[k] = v |
| + } |
| + } else { |
| + next.Video = nil |
| + } |
| p.Media = &next |
| payload, err := json.Marshal(next) |
| if err != nil { |
diff --git a/internal/calls/hub/media_test.go b/internal/calls/hub/media_test.go| index 480b845..3101eb5 100644 |
| --- a/internal/calls/hub/media_test.go |
| +++ b/internal/calls/hub/media_test.go |
| @@ -9,6 +9,8 @@ import ( |
| "sync" |
| "testing" |
| "time" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| ) |
| // rosterMedia finds one peer's media in a roster, and whether the peer |
| @@ -488,3 +490,61 @@ func TestSetMediaCarriesHearing(t *testing.T) { |
| t.Fatalf("[] must decode as an empty, non-nil list: %+v %v", round, err) |
| } |
| } |
| + |
| +// Spec §15.30: a receiver's video asks are held, carried and fanned out |
| +// as the lists are — the hub's own copy, a change only when the set |
| +// changes, and an empty map the same as none. |
| +func TestSetMediaCarriesVideoAsks(t *testing.T) { |
| + now := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC) |
| + h := testHub(&now) |
| + ctx := context.Background() |
| + a, _ := h.Open("r1", "sa", 1, "Ann", KindMember) |
| + h.Join(ctx, "r1", "sa", a.Peer) |
| + b, _ := h.Open("r1", "sb", 2, "Bob", KindMember) |
| + h.Join(ctx, "r1", "sb", b.Peer) |
| + drain(a.Sub) |
| + drain(b.Sub) |
| + |
| + asks := map[PeerID]protocol.VideoLevel{b.Peer: protocol.VideoMinimal} |
| + if err := h.SetMedia(ctx, "r1", "sa", a.Peer, MediaState{Video: asks}); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := drain(b.Sub) |
| + want := `{"muted":false,"cameraOff":false,"video":{"` + string(b.Peer) + `":"minimal"}}` |
| + if len(got) != 1 || string(got[0].Payload) != want { |
| + t.Fatalf("payload %v, want %s", got, want) |
| + } |
| + asks[b.Peer] = protocol.VideoAudio |
| + c, _ := h.Open("r1", "sc", 3, "Cy", KindMember) |
| + h.Join(ctx, "r1", "sc", c.Peer) |
| + var ro *Roster |
| + for _, ev := range drain(c.Sub) { |
| + if ev.Type == TypeRoster { |
| + ro = ev.Roster |
| + } |
| + } |
| + drain(b.Sub) |
| + m, _ := rosterMedia(ro, a.Peer) |
| + if m == nil || m.Video[b.Peer] != protocol.VideoMinimal { |
| + t.Fatalf("roster media %+v, want the hub's own copy of the asks", m) |
| + } |
| + if err := h.SetMedia(ctx, "r1", "sa", a.Peer, MediaState{Video: map[PeerID]protocol.VideoLevel{b.Peer: protocol.VideoMinimal}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := drain(b.Sub); len(got) != 0 { |
| + t.Fatalf("the same asks again reached Bob: %v", types(got)) |
| + } |
| + if err := h.SetMedia(ctx, "r1", "sa", a.Peer, MediaState{Video: map[PeerID]protocol.VideoLevel{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + got = drain(b.Sub) |
| + if len(got) != 1 || string(got[0].Payload) != `{"muted":false,"cameraOff":false}` { |
| + t.Fatalf("no asks sent %v", got) |
| + } |
| + if err := h.SetMedia(ctx, "r1", "sa", a.Peer, MediaState{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := drain(b.Sub); len(got) != 0 { |
| + t.Fatalf("nil after {} reached Bob: %v", types(got)) |
| + } |
| +} |
diff --git a/internal/calls/quality.go b/internal/calls/quality.go| index 611ae39..f5fc7d6 100644 |
| --- a/internal/calls/quality.go |
| +++ b/internal/calls/quality.go |
| @@ -312,6 +312,12 @@ func validateQuality(raw []byte) (protocol.QualityReport, bool) { |
| if d := q.Devices; d != nil && (!enumOrEmpty(d.Input, protocol.DeviceKinds) || !enumOrEmpty(d.Output, protocol.DeviceKinds)) { |
| return q, false |
| } |
| + 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 |
| } |
| @@ -341,6 +347,9 @@ func validateQuality(raw []byte) (protocol.QualityReport, bool) { |
| } |
| } |
| } |
| + if e := p.Events; e != nil && (!levelSeconds(e.AskedSeconds) || !levelSeconds(e.SentSeconds)) { |
| + return q, false |
| + } |
| } |
| if q.AutoReport != "" && !reportRefPattern.MatchString(q.AutoReport) { |
| return q, false |
| @@ -353,6 +362,23 @@ func validateQuality(raw []byte) (protocol.QualityReport, bool) { |
| return q, true |
| } |
| +// levelSeconds is §15.30's seconds-at-each-level: absent, or exactly one |
| +// number for each level, none of them null (boundNumbers checks the rest). |
| +func levelSeconds(v []*float64) bool { |
| + if v == nil { |
| + return true |
| + } |
| + if len(v) != protocol.VideoLevelCount { |
| + return false |
| + } |
| + for _, x := range v { |
| + if x == nil { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| func validClient(c *protocol.ReportClient) bool { |
| if !slices.Contains(reportApps, c.App) { |
| return false |
| @@ -378,7 +404,8 @@ func enumOrEmpty(v string, allowed []string) bool { return v == "" || slices.Con |
| func numberCeiling(name string) float64 { |
| switch name { |
| case "seconds", "reconnectingSeconds", "cantHearSeconds", "freezeSeconds", |
| - "limitedBandwidthSeconds", "limitedCpuSeconds": |
| + "limitedBandwidthSeconds", "limitedCpuSeconds", |
| + "askedSeconds", "sentSeconds": |
| return protocol.MaxQualitySeconds |
| case "rtt", "jitter", "jitterBufferMs", "rttAvg", "rttMax", "jitterAvg", "jitterMax": |
| return protocol.MaxQualityMillis |
| @@ -386,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 |
| } |
| @@ -482,6 +515,34 @@ func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) { |
| if q.AutoReport != "" { |
| attrs = append(attrs, slog.String("autoReport", q.AutoReport)) |
| } |
| + // §15.30's, the same way: how long this client asked someone for less |
| + // video, how long it sent someone less, and the person's own setting. |
| + for _, f := range sum.video { |
| + if f.v > 0 { |
| + attrs = append(attrs, slog.Float64(f.name, f.v)) |
| + } |
| + } |
| + 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() |
| @@ -640,6 +701,17 @@ func peerAttrs(rep hub.Reporter, p protocol.PeerQuality, region string) []slog.A |
| flag("screenStalled", e.ScreenStalled) |
| num("autoRestarts", e.AutoRestarts) |
| num("autoRebuilds", e.AutoRebuilds) |
| + // §15.30: seconds at each level below normal, asked of them and |
| + // sent to them, flattened, only those that were not zero. |
| + levels := [protocol.VideoLevelCount]string{"Reduced", "Minimal", "Audio"} |
| + for i, name := range levels { |
| + if i < len(e.AskedSeconds) && e.AskedSeconds[i] != nil && *e.AskedSeconds[i] > 0 { |
| + num("asked"+name, e.AskedSeconds[i]) |
| + } |
| + if i < len(e.SentSeconds) && e.SentSeconds[i] != nil && *e.SentSeconds[i] > 0 { |
| + num("sent"+name, e.SentSeconds[i]) |
| + } |
| + } |
| } |
| return attrs |
| } |
| @@ -665,6 +737,7 @@ type qualitySummary struct { |
| relay bool |
| lossPct, rtt, freezes, reconnecting float64 |
| screen []screenHead |
| + video []screenHead |
| } |
| // screenHead is one of the quality line's screen fields. |
| @@ -723,6 +796,18 @@ func summarize(q protocol.QualityReport) qualitySummary { |
| {"screenKeyframes", keyframes}, {"screenRebuilds", rebuilds}, {"screenReshares", reshares}, |
| {"screenFailures", failures}, {"screenDamped", damped}, {"screenEncoderStalls", encoderStalls}, |
| } |
| + var asked, sent float64 |
| + for _, p := range q.Peers { |
| + if e := p.Events; e != nil { |
| + for _, x := range e.AskedSeconds { |
| + asked += val(x) |
| + } |
| + for _, x := range e.SentSeconds { |
| + sent += val(x) |
| + } |
| + } |
| + } |
| + s.video = []screenHead{{"videoAsked", math.Round(asked*10) / 10}, {"videoSent", math.Round(sent*10) / 10}} |
| for _, p := range q.Peers { |
| if p.Path != nil && (p.Path.Local == "relay" || p.Path.Remote == "relay") { |
| s.relay = true |
diff --git a/internal/calls/signal.go b/internal/calls/signal.go| index 1edfc73..9843d96 100644 |
| --- a/internal/calls/signal.go |
| +++ b/internal/calls/signal.go |
| @@ -7,6 +7,7 @@ import ( |
| "io" |
| "net/http" |
| "regexp" |
| + "slices" |
| "strconv" |
| "unicode/utf8" |
| @@ -185,16 +186,16 @@ func exactKeys(raw json.RawMessage, want ...string) bool { |
| } |
| // maxMediaBytes bounds §15.19's payload before it is decoded. The |
| -// longest honest one — both booleans false, audioBlocked, and full |
| +// longest honest one — both booleans false, audioBlocked, full |
| // noSoundFrom, screenStalled and hearing lists of fifteen 32-character |
| -// peer ids each (§15.20, §15.21, §15.24) — is a little over 1,700 bytes; |
| -// the rest is room |
| +// peer ids each (§15.20, §15.21, §15.24), and a full §15.30 video map of |
| +// fifteen ids at "reduced" — is about 2,450 bytes; the rest is room |
| // for whitespace a client's encoder might add, and nothing a peer can use |
| // to put more on anyone's stream: what goes out is re-encoded from the |
| // validated values. |
| -const maxMediaBytes = 3072 |
| +const maxMediaBytes = 4096 |
| -// validateMedia is §15.19's shape as §15.20, §15.21 and §15.24 extend it: |
| +// validateMedia is §15.19's shape as §15.20, §15.21, §15.24 and §15.30 extend it: |
| // "muted" and "cameraOff", both booleans and both required; "audioBlocked", |
| // a boolean, and "noSoundFrom", "screenStalled" and "hearing", each an |
| // array of at most fifteen distinct peer ids, all optional. An empty |
| @@ -212,7 +213,7 @@ func validateMedia(raw json.RawMessage) (protocol.MediaState, int, string) { |
| if len(raw) > maxMediaBytes { |
| return protocol.MediaState{}, http.StatusRequestEntityTooLarge, "size" |
| } |
| - if !memberKeys(raw, []string{"muted", "cameraOff"}, []string{"audioBlocked", "noSoundFrom", "screenStalled", "hearing"}) { |
| + if !memberKeys(raw, []string{"muted", "cameraOff"}, []string{"audioBlocked", "noSoundFrom", "screenStalled", "hearing", "video"}) { |
| return protocol.MediaState{}, http.StatusBadRequest, "shape" |
| } |
| var p struct { |
| @@ -222,6 +223,7 @@ func validateMedia(raw json.RawMessage) (protocol.MediaState, int, string) { |
| NoSoundFrom json.RawMessage `json:"noSoundFrom"` |
| ScreenStalled json.RawMessage `json:"screenStalled"` |
| Hearing json.RawMessage `json:"hearing"` |
| + Video json.RawMessage `json:"video"` |
| } |
| if err := json.Unmarshal(raw, &p); err != nil || p.Muted == nil || p.CameraOff == nil { |
| return protocol.MediaState{}, http.StatusBadRequest, "shape" |
| @@ -247,9 +249,64 @@ func validateMedia(raw json.RawMessage) (protocol.MediaState, int, string) { |
| if p.Hearing != nil && m.Hearing == nil { |
| m.Hearing = []hub.PeerID{} |
| } |
| + if m.Video, ok = videoAsks(p.Video); !ok { |
| + return protocol.MediaState{}, http.StatusBadRequest, "shape" |
| + } |
| return m, 0, "" |
| } |
| +// videoAsks is §15.30's optional "video": an object (never null, never an |
| +// array) whose members are well-formed peer ids, none repeated — judged |
| +// by a token walk, because a decode into a map keeps the last of two |
| +// equal keys and says nothing — each with one of protocol.VideoLevels as |
| +// a string, at most protocol.MaxVideo of them. Absent and {} are both nil, |
| +// "normal from everyone", so they compare equal. As with the lists, an id |
| +// is checked for shape and not presence. |
| +func videoAsks(raw json.RawMessage) (map[hub.PeerID]protocol.VideoLevel, bool) { |
| + if raw == nil { |
| + return nil, true |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(raw)) |
| + open, err := dec.Token() |
| + if err != nil { |
| + return nil, false |
| + } |
| + if d, ok := open.(json.Delim); !ok || d != '{' { |
| + return nil, false |
| + } |
| + out := map[hub.PeerID]protocol.VideoLevel{} |
| + for dec.More() { |
| + key, err := dec.Token() |
| + if err != nil { |
| + return nil, false |
| + } |
| + name, ok := key.(string) |
| + id := hub.PeerID(name) |
| + if !ok || !validPeerID(id) { |
| + return nil, false |
| + } |
| + if _, dup := out[id]; dup || len(out) >= protocol.MaxVideo { |
| + return nil, false |
| + } |
| + value, err := dec.Token() |
| + if err != nil { |
| + return nil, false |
| + } |
| + level, ok := value.(string) |
| + if !ok || !slices.Contains(protocol.VideoLevels, protocol.VideoLevel(level)) { |
| + return nil, false |
| + } |
| + out[id] = protocol.VideoLevel(level) |
| + } |
| + if _, err := dec.Token(); err != nil || dec.More() { |
| + return nil, false |
| + } |
| + if len(out) == 0 { |
| + return nil, true |
| + } |
| + return out, true |
| +} |
| + |
| // peerList is one of the media report's optional lists of peer ids: |
| // absent is nil, and present is an array (never null) of at most max |
| // well-formed ids with no repeats. Empty is the ordinary report, and is |
diff --git a/internal/calls/static/calls.css b/internal/calls/static/calls.css| index f378f2e..14b6b3d 100644 |
| --- a/internal/calls/static/calls.css |
| +++ b/internal/calls/static/calls.css |
| @@ -761,7 +761,7 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| translate: 0 calc(-1 * var(--calls-lift)); |
| } |
| /* What the stage's camera-off cover keeps clear of: that caption, lifted. */ |
| -.calls-window #tiles[data-layout='speaker'] > [data-stage] > .calls-tile-off { |
| +.calls-window #tiles[data-layout='speaker'] > [data-stage] > .calls-tile-off, .calls-window #tiles[data-layout='speaker'] > [data-stage] > .calls-tile-pause { |
| --calls-caption-clear: calc(12px + 2rem + var(--calls-band) + var(--calls-lift)); |
| } |
| @@ -883,7 +883,7 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| } |
| .calls-tile-muted .icon { inline-size: 1em; block-size: 1em; } |
| .calls-tile-muted[hidden], |
| -.calls-tile-off[hidden] { display: none; } |
| +.calls-tile-off[hidden], .calls-tile-pause[hidden] { display: none; } |
| /* A camera that is off sends black frames, or holds the last one. The |
| cover says what that is instead of leaving a frozen face or a black |
| @@ -898,7 +898,7 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| caption's clearance (--calls-caption-clear), when flexbox holds it at |
| that and gives the rest to the upper one. The native apps' |
| PlaceholderPlacement is the same rule. */ |
| -.calls-tile-off { |
| +.calls-tile-off, .calls-tile-pause { |
| --calls-caption-clear: 2.75rem; |
| position: absolute; |
| inset: 0; |
| @@ -909,17 +909,27 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| color: rgb(255 255 255 / 0.8); |
| font-size: var(--rst-fs-sm); |
| } |
| -.calls-tile-off::before, |
| -.calls-tile-off::after { |
| +.calls-tile-off::before, .calls-tile-pause::before, |
| +.calls-tile-off::after, .calls-tile-pause::after { |
| content: ''; |
| flex: 1 1 0; |
| } |
| -.calls-tile-off::after { min-block-size: var(--calls-caption-clear); } |
| -.calls-tile-off > * { flex: none; } |
| -.calls-tile-off > * + * { margin-block-start: 8px; } |
| -.calls-tile-off .icon { inline-size: 2rem; block-size: 2rem; } |
| +.calls-tile-off::after, .calls-tile-pause::after { min-block-size: var(--calls-caption-clear); } |
| +.calls-tile-off > *, .calls-tile-pause > * { flex: none; } |
| +.calls-tile-off > * + *, .calls-tile-pause > * + * { margin-block-start: 8px; } |
| +.calls-tile-off .icon, .calls-tile-pause .icon { inline-size: 2rem; block-size: 2rem; } |
| .calls-tile-camera-off .calls-tile-name { z-index: 1; } |
| +/* Spec §15.30: "Low bandwidth" beside the name while this browser asks |
| + that person for less video — the vendored badge's word, quiet like |
| + Muted — and, at Audio only, the camera-off cover's shape with its own |
| + words, and a smaller line for an app too old to send less. */ |
| +.calls-tile-low { display: inline-flex; align-items: center; flex: none; } |
| +.calls-tile-low[hidden] { display: none; } |
| +.calls-tile-video-paused .calls-tile-name { z-index: 1; } |
| +.calls-tile-paused-old { max-inline-size: 18rem; text-align: center; font-size: var(--rst-fs-xs); opacity: 0.8; } |
| +.calls-tile-paused-old[hidden] { display: none; } |
| + |
| /* Our own preview, when the browser will not play it (room.js's |
| self-view watch, 2026-10-21): never a black box with nothing said. |
| The whole tile is the button, because the floating self view on a |
| @@ -1023,8 +1033,16 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| font-size: var(--rst-fs-xs); |
| } |
| .calls-tile-name > span:first-child { flex: 0 1 auto; min-inline-size: 0; } |
| - .calls-tile-off { --calls-caption-clear: 2rem; } |
| + .calls-tile-off, .calls-tile-pause { --calls-caption-clear: 2rem; } |
| .calls-tile-name > :not(:first-child) { flex: none; } |
| + .calls-tile-low:not([hidden]) { |
| + position: absolute; |
| + inline-size: 1px; |
| + block-size: 1px; |
| + overflow: hidden; |
| + clip-path: inset(50%); |
| + white-space: nowrap; |
| + } |
| .calls-tile-muted > :not(svg) { |
| position: absolute; |
| inline-size: 1px; |
| @@ -1035,7 +1053,7 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| } |
| } |
| @container (max-width: 15rem) { |
| - .calls-tile-off > :not(svg) { |
| + .calls-tile-off > :not(svg), .calls-tile-pause > :not(svg) { |
| position: absolute; |
| inline-size: 1px; |
| block-size: 1px; |
| @@ -1045,7 +1063,7 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| } |
| } |
| @container (max-width: 9rem) { |
| - .calls-tile-off .icon { inline-size: 1.25rem; block-size: 1.25rem; } |
| + .calls-tile-off .icon, .calls-tile-pause .icon { inline-size: 1.25rem; block-size: 1.25rem; } |
| } |
| /* The speaking light on the name, which replaced the ring round the |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 4dd4a69..b030d5d 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -111,6 +111,9 @@ |
| const rawInput = rawRow ? rawRow.querySelector('input[type="checkbox"]') : null; |
| const shareModeRow = $('share-mode-row'); |
| const pickShareMode = $('pick-share-mode'); |
| + // §15.30's own choice: Auto, Low bandwidth, Audio only. |
| + const videoQualityRow = $('video-quality-row'); |
| + const pickVideoQuality = $('pick-video-quality'); |
| const DEVICE_KEY = 'meet.devices'; |
| const BACKOFF_MIN = 500; |
| @@ -411,6 +414,60 @@ |
| const AUTO_REPORTS_PER_CALL = 3; |
| const AUTO_REPORT_EVERY = 600000; |
| const AUTO_BODY_MAX = 65024; |
| + // §15.30 (2026-10-28): adaptive video. Every receiver watches what |
| + // arrives from each sender and asks that sender, through its own media |
| + // report, for one of four levels; the sender applies it to that one |
| + // connection's sender parameters. Down quickly, up slowly, and a probe up |
| + // that fails doubles the wait before the next. The apps' VideoAdapt has |
| + // the same numbers; test/browser/room-adapt.test.mjs and |
| + // VideoAdaptTests hold both. |
| + const ADAPT_LEVELS = ['normal', 'reduced', 'minimal', 'audio']; |
| + const ADAPT_WINDOW = 10000; // the trouble window, and the time at a level before a step down |
| + const ADAPT_SEVERE_AFTER = 5000; // severe trouble steps two levels after this long |
| + const ADAPT_DOWN_FREEZES = 2; // camera freezes in the window |
| + const ADAPT_DOWN_LOSS = 0.05; // packets lost in the window, of all inbound |
| + const ADAPT_DOWN_RTT = 600; // ms, counted with at least one freeze |
| + const ADAPT_DOWN_JITTER_BUFFER = 500; // ms, the audio jitter buffer's mean delay |
| + const ADAPT_DOWN_DROPPED = 0.25; // frames dropped, of decoded and dropped, at least ADAPT_DOWN_DROPPED_MIN |
| + const ADAPT_DOWN_DROPPED_MIN = 10; |
| + const ADAPT_DOWN_FREEZE_SECONDS = 2; // seconds frozen in the window: a picture stuck a fifth of the time |
| + const ADAPT_DOWN_KEYFRAME_ASKS = 3; // keyframes this side asked the camera for (PLI, FIR) in the window |
| + const ADAPT_SEVERE_FREEZES = 5; |
| + const ADAPT_SEVERE_FREEZE_SECONDS = 4; // seconds frozen in the window |
| + const ADAPT_SEVERE_LOSS = 0.15; |
| + const ADAPT_CLEAN_LOSS = 0.02; // a clean second: no freeze, loss at most this, |
| + const ADAPT_CLEAN_RTT = 400; // a round trip under this (ms), |
| + const ADAPT_CLEAN_JITTER_BUFFER = 300; // and the jitter buffer under this (ms) |
| + const ADAPT_UP_AFTER = 45000; // clean this long at a level, then probe one up |
| + 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 |
| + // only at minimal is it made smaller; it is never paused. |
| + const ADAPT_CAMERA = [null, |
| + { maxBitrate: 350000, maxFramerate: 15, long: 640, short: 360 }, |
| + { maxBitrate: 120000, maxFramerate: 8, long: 320, short: 180 }]; |
| + const ADAPT_SCREEN = [null, |
| + { maxBitrate: 1200000, maxFramerate: 10 }, |
| + { maxBitrate: 500000, maxFramerate: 5, long: 1280 }]; |
| + // An app older than this ignores a request; its video can only be hidden |
| + // here, which saves this device's work and not the connection. |
| + const ADAPT_MIN_NATIVE_VERSION = '0.4.15'; |
| + // How long the sender's "Sending reduced video to …" stays up. |
| + const ADAPT_NOTICE_FOR = 8000; |
| + // The person's own choice, in the Devices panel: Auto, Low bandwidth |
| + // (minimal from everyone), Audio only (no video either way). |
| + const VIDEO_SETTINGS = [['auto', 'Auto'], ['low', 'Low bandwidth'], ['audio', 'Audio only']]; |
| // §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. |
| @@ -484,6 +541,22 @@ |
| const screenSeen = new Map(); |
| let screenStalled = []; |
| const screenAsks = new Map(); |
| + // §15.30: peer id -> the adaptive watch's record of what arrives from |
| + // them; the asks this tab last put in its report (peer id -> level); |
| + // what each connection is sending at, as asked (on the entry); the |
| + // sender's notice and its timer; seconds at each level for the report; |
| + // and, for the gate, the watch's up wait. |
| + const adapt = new Map(); |
| + let videoAsks = {}; |
| + let adaptNoticeTimer = 0; |
| + 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, forced: '' }; |
| + let adaptPolledAt = 0; |
| let shareRecovery = ''; |
| let screenStallTestUntil = 0; |
| // §15.22: each arriving screen's statistics at the last poll and when |
| @@ -848,19 +921,31 @@ |
| // tuneShare puts one connection's screen and camera where the mode |
| // wants them: the screen at its plan, the camera capped beside it — |
| // or, with nothing shared, the camera back at its defaults. |
| + // |
| + // §15.30: at the level this connection's peer asks of us |
| + // (entry.sentLevel), and with no camera at all to anyone while the |
| + // person's own Video quality is Audio only. |
| function tuneShare(entry) { |
| if (!entry) return; |
| const sharing = !!(share && entry.shareTx); |
| + const level = entry.sentLevel || 0; |
| if (sharing) { |
| const s = share.track.getSettings ? share.track.getSettings() : {}; |
| - const plan = sharePlan(shareMode(), s.width, s.height); |
| + const plan = screenAtLevel(sharePlan(shareMode(), s.width, s.height), level, s.width, s.height); |
| tuneSender(entry.shareTx.sender, plan.encoding, plan.degradationPreference); |
| } |
| const camera = senderFor(entry, 'video'); |
| const track = camera && camera.sender && camera.sender.track; |
| if (!track) return; |
| const settings = track.getSettings ? track.getSettings() : {}; |
| - tuneSender(camera.sender, cameraCap(sharing, 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; |
| + tuneSender(camera.sender, encoding); |
| } |
| // startLocal walks down a ladder: the remembered devices, then the |
| @@ -2062,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 |
| @@ -2071,6 +2158,10 @@ |
| addShareTo(entry); |
| upgradeWhenQuiet(entry); |
| adoptWhenQuiet(id, entry); |
| + // §15.30: a connection that settles is given what its peer asks of |
| + // us, and the person's own Audio only — a new connection's senders |
| + // have no parameters to set until it has. |
| + if (pc.signalingState === 'stable' && (entry.sentLevel || videoSetting() === 'audio')) tuneShare(entry); |
| // And it is when an ask the negotiation rounds ran out on gets |
| // its turn (Codex S4-8): a connection that was mid-negotiation is |
| // the usual reason they ran out, and this is it settling. |
| @@ -4416,6 +4507,19 @@ |
| } |
| out.hearing = ids; |
| } |
| + // §15.30: what they ask each sender for, the wire's levels only. |
| + if (value.video && typeof value.video === 'object' && !Array.isArray(value.video)) { |
| + const asks = {}; |
| + let n = 0; |
| + for (const [id, level] of Object.entries(value.video)) { |
| + if (n >= 15) break; |
| + if (/^[0-9a-f]{32}$/.test(id) && ['reduced', 'minimal', 'audio'].includes(level)) { |
| + asks[id] = level; |
| + n += 1; |
| + } |
| + } |
| + if (n) out.video = asks; |
| + } |
| return out; |
| } |
| @@ -4433,6 +4537,9 @@ |
| if (m.noSoundFrom && m.noSoundFrom.length) key += ':' + m.noSoundFrom.slice().sort().join(','); |
| if (m.screenStalled && m.screenStalled.length) key += '/' + m.screenStalled.slice().sort().join(','); |
| if (Array.isArray(m.hearing)) key += '|' + m.hearing.slice().sort().join(','); |
| + if (m.video && Object.keys(m.video).length) { |
| + key += '>' + Object.keys(m.video).sort().map((id) => id + '=' + m.video[id]).join(','); |
| + } |
| return key; |
| } |
| @@ -4442,7 +4549,9 @@ |
| function localMedia() { |
| const hasAudio = !!(local && local.getAudioTracks().length); |
| const hasVideo = !!(local && local.getVideoTracks().length); |
| - return { muted: !!prefs.muted || !hasAudio, cameraOff: !!prefs.cameraOff || !hasVideo }; |
| + // §15.30: Audio only stops the camera going to anyone, so it is off as |
| + // far as anyone watching can tell. |
| + return { muted: !!prefs.muted || !hasAudio, cameraOff: !!prefs.cameraOff || !hasVideo || videoSetting() === 'audio' }; |
| } |
| // mediaPayload is the report itself: §15.19's two booleans, and |
| @@ -4451,7 +4560,7 @@ |
| // is good news, and its presence tells the others this tab says who it |
| // hears. `plain` is a server that has refused the extras once. Pure, |
| // and lifted by name in the node test. |
| - function mediaPayload(mine, blocked, silentFrom, plain, stalled, heard) { |
| + function mediaPayload(mine, blocked, silentFrom, plain, stalled, heard, asks) { |
| const out = { muted: !!mine.muted, cameraOff: !!mine.cameraOff }; |
| if (plain) return out; |
| if (blocked) out.audioBlocked = true; |
| @@ -4459,6 +4568,8 @@ |
| // §15.21: whose screens have stalled here, bad news only, like the rest. |
| if (stalled && stalled.length) out.screenStalled = stalled.slice(0, 15); |
| if (Array.isArray(heard)) out.hearing = heard.slice(0, 15); |
| + // §15.30: what this tab asks each sender for, only those below normal. |
| + if (asks && Object.keys(asks).length) out.video = Object.assign({}, asks); |
| return out; |
| } |
| @@ -4474,7 +4585,7 @@ |
| // as muted or not matters more than being heard as unable to hear. |
| function reportMedia() { |
| if (!state.admitted || state.stopped || !state.peer) return; |
| - const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList()); |
| + const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks); |
| const key = mediaKey(now); |
| if (key === mediaSent) return; |
| mediaSent = key; |
| @@ -4504,10 +4615,13 @@ |
| learnMedia(rp.peer, rp.media); |
| continue; |
| } |
| - const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList()); |
| + const now = mediaPayload(localMedia(), audioBlocked, noSoundList(), !mediaExtras, screenStalled, hearingList(), videoAsks); |
| mediaSent = sameMedia(mediaFrom(rp.media), now) ? mediaKey(now) : ''; |
| } |
| reportMedia(); |
| + // §15.30: and what each of them asks of us now. |
| + answerVideoAsks(); |
| + for (const id of pcs.keys()) markAdapt(id); |
| } |
| // learnMedia records a roster's or a peer event's word on one peer. |
| @@ -4530,6 +4644,485 @@ |
| announceMedia(mediaChange(msg.name || names.get(id) || 'Someone', before, next)); |
| markTile(id, next); |
| answerScreenStalls(); |
| + answerVideoAsks(); |
| + markAdapt(id); |
| + } |
| + |
| + // --------------------------------------------------------------- |
| + // Adaptive video (§15.30, 2026-10-28) |
| + // --------------------------------------------------------------- |
| + // |
| + // Paul, after a Dublin–London call whose guest was on café Wi-Fi in |
| + // Safari, relayed, at 840–1300 ms round trips, seeing up to seven |
| + // freezes every thirty seconds in his video: "Low-bandwidth with |
| + // auto-switching up and down." Audio mattered most. |
| + // |
| + // It is a mesh, so every pair has its own sender, and the one who can |
| + // see the trouble is the receiver. So each receiver watches what arrives |
| + // from each sender — camera freezes, packet loss, the jitter buffer, the |
| + // round trip, frames dropped — and asks that sender for a level in its |
| + // own media report (`video`, peer id -> level, only the ones below |
| + // normal). The sender reads its own id in each report and sets that one |
| + // connection's sender parameters: no renegotiation, and audio is never |
| + // touched. A shared screen keeps its size and gives up frame rate first, |
| + // and is never paused; while one is going, the camera gives way first. |
| + |
| + // adaptRecord is one sender's watch, on the receiving side. `upAfter` is |
| + // the clean time before the first probe up (ADAPT_UP_AFTER, shortened |
| + // only by the gate's hook). Pure, as is everything down to adaptAsks; |
| + // test/browser/room-adapt.test.mjs lifts them by name. |
| + function adaptRecord(upAfter) { |
| + const base = upAfter || ADAPT_UP_AFTER; |
| + return { level: 0, since: null, samples: [], cleanSince: null, upBase: base, upWait: base, |
| + probeAt: null, probeFrom: 0, downs: 0, ups: 0 }; |
| + } |
| + |
| + // adaptSample is one second of what arrived from a sender, from |
| + // qualityPeer's deltas: camera freezes (only while the camera is to be |
| + // watched — on, and the tab visible — because a still screen's gaps and |
| + // a hidden tab's unpainted frames are not freezes), packets and loss |
| + // across audio, camera and screen, the round trip, the audio jitter |
| + // buffer, and frames decoded and dropped. Null when nothing at all |
| + // arrived and nothing was measured: a connection that is down is |
| + // §15.28's to mend, and says nothing about the link's width. |
| + // |
| + // `keyframeAsks` is the PLIs and FIRs this side sent for their camera in |
| + // the second: a decoder that keeps losing its picture asks for a new one, |
| + // and on a thin link that, not a freeze, can be all there is to see — a |
| + // picture at five frames a second, every one a keyframe. |
| + function adaptSample(q, cameraWatched, keyframeAsks) { |
| + const inb = (q && q.in) || {}; |
| + const a = inb.audio || {}; |
| + const v = inb.video || {}; |
| + const s = inb.screen || {}; |
| + const packets = (a.packets || 0) + (v.packets || 0) + (s.packets || 0); |
| + const lost = (a.lost || 0) + (v.lost || 0) + (s.lost || 0); |
| + const rtt = q && typeof q.rtt === 'number' ? q.rtt : null; |
| + if (packets + lost === 0 && rtt === null) return null; |
| + return { |
| + freezes: cameraWatched ? v.freezes || 0 : 0, |
| + freezeSeconds: cameraWatched ? v.freezeSeconds || 0 : 0, |
| + keyframeAsks: cameraWatched ? keyframeAsks || 0 : 0, |
| + packets, |
| + lost, |
| + rtt, |
| + jitterBufferMs: typeof a.jitterBufferMs === 'number' ? a.jitterBufferMs : null, |
| + decoded: (v.decoded || 0) + (s.decoded || 0), |
| + dropped: (v.dropped || 0) + (s.dropped || 0), |
| + }; |
| + } |
| + |
| + // adaptWindow sums the samples in the window: counts added up, the |
| + // 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, 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; |
| + w.dropped += x.dropped; |
| + if (x.rtt !== null) rtts.push(x.rtt); |
| + if (x.jitterBufferMs !== null) jbs.push(x.jitterBufferMs); |
| + } |
| + if (rtts.length) { |
| + rtts.sort((p, q) => p - q); |
| + w.rtt = rtts[Math.floor(rtts.length / 2)]; |
| + } |
| + if (jbs.length) w.jitterBuffer = jbs.reduce((p, q) => p + q, 0) / jbs.length; |
| + w.loss = w.packets + w.lost > 0 ? w.lost / (w.packets + w.lost) : 0; |
| + return w; |
| + } |
| + |
| + // adaptTrouble is a window's verdict: 'severe', 'trouble' or ''. |
| + function adaptTrouble(w) { |
| + if (w.freezes >= ADAPT_SEVERE_FREEZES || w.freezeSeconds >= ADAPT_SEVERE_FREEZE_SECONDS || |
| + w.loss > ADAPT_SEVERE_LOSS) { |
| + 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.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))) { |
| + return 'trouble'; |
| + } |
| + 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 && !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); |
| + } |
| + |
| + // adaptMove changes the level, and starts the watch again from nothing: |
| + // the new level is judged on what it does, not on what the old one did. |
| + function adaptMove(rec, now, level, up) { |
| + if (up) rec.ups += 1; |
| + else rec.downs += 1; |
| + rec.level = level; |
| + rec.since = now; |
| + rec.samples = []; |
| + rec.cleanSince = null; |
| + if (!up) rec.probeAt = null; |
| + return level; |
| + } |
| + |
| + // adaptStep is one look, about once a second, with that second's sample |
| + // (or null for none). Returns the level, 0 normal to 3 audio only. |
| + // |
| + // down one level once the window at this level has been trouble for |
| + // ADAPT_WINDOW; two at once for severe trouble, after |
| + // ADAPT_SEVERE_AFTER |
| + // up one level after `upWait` of clean seconds in a row, as a |
| + // probe: trouble within ADAPT_PROBE_WATCH of it (judged on at |
| + // least ADAPT_PROBE_JUDGE) steps straight back and doubles the |
| + // wait, to at most ADAPT_UP_MAX; a probe that holds puts the |
| + // wait back to its base |
| + function adaptStep(rec, now, sample) { |
| + if (rec.since === null) rec.since = now; |
| + if (!sample) return rec.level; |
| + 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 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 { |
| + rec.cleanSince = null; |
| + } |
| + const top = ADAPT_LEVELS.length - 1; |
| + if (rec.probeAt !== null) { |
| + if (now - rec.probeAt < ADAPT_PROBE_WATCH) { |
| + if (verdict && observed >= ADAPT_PROBE_JUDGE) { |
| + rec.upWait = Math.min(rec.upWait * 2, ADAPT_UP_MAX); |
| + return adaptMove(rec, now, rec.probeFrom, false); |
| + } |
| + } else { |
| + rec.probeAt = null; |
| + rec.upWait = rec.upBase; |
| + } |
| + } |
| + if (verdict === 'severe' && observed >= ADAPT_SEVERE_AFTER && rec.level < top) { |
| + return adaptMove(rec, now, Math.min(top, rec.level + 2), false); |
| + } |
| + if (verdict && observed >= ADAPT_WINDOW && rec.level < top) { |
| + return adaptMove(rec, now, rec.level + 1, false); |
| + } |
| + if (rec.level > 0 && rec.cleanSince !== null && now - rec.cleanSince >= rec.upWait) { |
| + const from = rec.level; |
| + adaptMove(rec, now, from - 1, true); |
| + rec.probeAt = now; |
| + rec.probeFrom = from; |
| + } |
| + return rec.level; |
| + } |
| + |
| + // videoFloor is the person's own setting as a level: Low bandwidth asks |
| + // everyone for minimal, Audio only for no video; Auto leaves it to the |
| + // watch. |
| + function videoFloor(setting) { |
| + if (setting === 'audio') return 3; |
| + if (setting === 'low') return 2; |
| + return 0; |
| + } |
| + |
| + // adaptAsks is the `video` object for the report: every peer whose level |
| + // — the watch's or the setting's, whichever is lower — is below normal. |
| + // `levels` is peer id -> the watch's level. |
| + function adaptAsks(levels, setting) { |
| + const out = {}; |
| + const floor = videoFloor(setting); |
| + for (const [id, level] of levels) { |
| + const at = Math.max(level || 0, floor); |
| + if (at > 0 && Object.keys(out).length < 15) out[id] = ADAPT_LEVELS[at]; |
| + } |
| + return out; |
| + } |
| + |
| + // askedOf is what one peer's report asks of us, as a level index. |
| + function askedOf(media, me) { |
| + const at = media && media.video && me ? ADAPT_LEVELS.indexOf(media.video[me]) : -1; |
| + return at > 0 ? at : 0; |
| + } |
| + |
| + // cameraAtLevel is the camera's encoding for one receiver at a level. |
| + // While a screen is going out the camera gives way first: normal is |
| + // §5.4's cap beside the screen, and every level below is one lower for |
| + // the camera, so a receiver at minimal gets the screen and no camera. |
| + // `width` and `height` are the camera's own, fitted by their long and |
| + // short sides so a portrait camera is boxed the right way round. |
| + function cameraAtLevel(level, sharing, width, height) { |
| + const at = sharing && level > 0 ? Math.min(3, level + 1) : level; |
| + if (at <= 0) return Object.assign({ maxFramerate: undefined, active: true }, cameraCap(sharing, height || 0)); |
| + const c = ADAPT_CAMERA[Math.min(at, 2)]; |
| + const long = Math.max(width || 0, height || 0); |
| + const short = Math.min(width || 0, height || 0); |
| + return { |
| + maxBitrate: c.maxBitrate, |
| + maxFramerate: c.maxFramerate, |
| + scaleResolutionDownBy: Math.max(1, long / c.long, short / c.short), |
| + active: at < 3, |
| + }; |
| + } |
| + |
| + // screenAtLevel is sharePlan's answer for one receiver at a level: the |
| + // frame rate and bitrate lowered first, the size kept, and only at |
| + // minimal and below the long side brought to ADAPT_SCREEN's. Resolution |
| + // is held under pressure from then on (maintain-resolution), because a |
| + // screen is for reading. Never paused. |
| + function screenAtLevel(plan, level, width, height) { |
| + if (level <= 0) return plan; |
| + const c = ADAPT_SCREEN[Math.min(level, 2)]; |
| + const encoding = Object.assign({}, plan.encoding, { |
| + maxFramerate: c.maxFramerate, |
| + maxBitrate: Math.min(plan.encoding.maxBitrate || c.maxBitrate, c.maxBitrate), |
| + }); |
| + if (c.long) { |
| + const longest = Math.max(width || 0, height || 0); |
| + encoding.scaleResolutionDownBy = Math.max(plan.encoding.scaleResolutionDownBy || 1, longest > c.long ? longest / c.long : 1); |
| + } |
| + return { contentHint: plan.contentHint, degradationPreference: 'maintain-resolution', encoding }; |
| + } |
| + |
| + // honoursAsks is whether a peer's client acts on a request: every |
| + // browser (its page is this server's), and an app from |
| + // ADAPT_MIN_NATIVE_VERSION on. |
| + function honoursAsks(client) { |
| + const c = parseClient(client || ''); |
| + if (!c) return !client; |
| + return compareVersions(c.version, ADAPT_MIN_NATIVE_VERSION) >= 0; |
| + } |
| + |
| + // adaptNoticeWords is the sender's quiet notice for the people it is |
| + // sending less to, by name: '' for nobody. |
| + function adaptNoticeWords(people) { |
| + if (!people.length) return ''; |
| + const names = people.map((p) => p.name); |
| + const list = names.length === 1 ? names[0] |
| + : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; |
| + const weak = names.length === 1 ? '(their connection is weak)' : '(their connections are weak)'; |
| + if (people.every((p) => p.level >= 3)) return 'Sending only audio to ' + list + ' ' + weak; |
| + return 'Sending reduced video to ' + list + ' ' + weak; |
| + } |
| + |
| + // videoSetting is the person's choice, Auto unless they made one. |
| + function videoSetting() { |
| + return VIDEO_SETTINGS.some(([v]) => v === prefs.videoQuality) ? prefs.videoQuality : 'auto'; |
| + } |
| + |
| + // adaptLook is one connection's second, from the stats walk pollFrames |
| + // already makes and the reading §15.29's sampler takes of it |
| + // (entry.statsReading): the delta from the last one, by qualityPeer, and |
| + // a step of that sender's watch. |
| + function adaptLook(id, entry, stats, now) { |
| + const reading = entry.statsReading || qualityReading(stats, (r) => qualityKind(id, entry, r)); |
| + const prev = entry.adaptReading; |
| + entry.adaptReading = { pc: entry.pc, reading, at: now, stats }; |
| + if (!prev || prev.pc !== entry.pc || now <= prev.at) return; |
| + const q = qualityPeer(prev.reading, reading, (now - prev.at) / 1000); |
| + 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, 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)' : ' (' + (rec.why || '') + ')')); |
| + } |
| + } |
| + |
| + // keyframeAsksFor is the PLIs and FIRs this side sent for one peer's |
| + // camera between two stats walks, by report id (a new stream counts from |
| + // nothing); the screen is not counted. |
| + function keyframeAsksFor(id, entry, before, after) { |
| + const count = (stats) => { |
| + const out = new Map(); |
| + if (!stats || typeof stats.forEach !== 'function') return out; |
| + stats.forEach((r) => { |
| + if (r.type === 'inbound-rtp' && r.kind === 'video' && frameKey(id, entry, r.mid || '') === id) { |
| + out.set(r.id, (r.pliCount || 0) + (r.firCount || 0)); |
| + } |
| + }); |
| + return out; |
| + }; |
| + const was = count(before); |
| + let n = 0; |
| + for (const [key, x] of count(after)) n += Math.max(0, x - (was.get(key) || 0)); |
| + return n; |
| + } |
| + |
| + // answerAdapt runs after each stats walk: the asks this tab makes, sent |
| + // 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.forced || pressure.state) >= 2)); |
| + if (localAdapt.level !== was) { |
| + console.info('calls: own camera ' + ADAPT_LEVELS[was] + ' -> ' + ADAPT_LEVELS[localAdapt.level] + |
| + ' (compute pressure ' + (pressure.forced || 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); |
| + const asks = adaptAsks(levels, videoSetting()); |
| + const changed = JSON.stringify(Object.entries(asks).sort()) !== JSON.stringify(Object.entries(videoAsks).sort()); |
| + videoAsks = asks; |
| + if (changed) { |
| + reportMedia(); |
| + for (const id of pcs.keys()) markAdapt(id); |
| + } |
| + const step = Math.min(Math.max(0, dt || 0), 2000) / 1000; |
| + for (const [id, entry] of pcs) { |
| + const asked = ADAPT_LEVELS.indexOf(asks[id] || 'normal'); |
| + const sent = entry.sentLevel || 0; |
| + if (!step || (asked <= 0 && sent <= 0)) continue; |
| + let t = videoTime.get(id); |
| + if (!t) { |
| + t = { asked: [0, 0, 0], sent: [0, 0, 0] }; |
| + videoTime.set(id, t); |
| + } |
| + if (asked > 0) t.asked[asked - 1] += step; |
| + if (sent > 0) t.sent[sent - 1] += step; |
| + } |
| + } |
| + |
| + // answerVideoAsks is the sender's half: each connection's senders set |
| + // to what that peer last asked of us, and the notice when it changes. |
| + function answerVideoAsks() { |
| + let moved = false; |
| + for (const [id, entry] of pcs) { |
| + const level = askedOf(remoteMedia.get(id), state.peer); |
| + if ((entry.sentLevel || 0) === level) continue; |
| + console.info('calls: ' + id.slice(0, 6) + ' asks for ' + ADAPT_LEVELS[level] + ' video'); |
| + if (level > (entry.sentLevel || 0)) moved = true; |
| + entry.sentLevel = level; |
| + tuneShare(entry); |
| + } |
| + const people = []; |
| + for (const [id, entry] of pcs) { |
| + if (entry.sentLevel > 0) people.push({ name: names.get(id) || 'Someone', level: entry.sentLevel }); |
| + } |
| + const words = adaptNoticeWords(people); |
| + if (!words) { |
| + showAdaptNotice(''); |
| + } else if (moved && words !== adaptNoticeShown) { |
| + showAdaptNotice(words); |
| + } |
| + } |
| + |
| + // applyVideoSetting is the person's choice taking effect: what this tab |
| + // asks of everyone, its own camera to everyone, and its report. |
| + function applyVideoSetting() { |
| + console.info('calls: video quality ' + videoSetting()); |
| + answerAdapt(Date.now(), 0); |
| + for (const entry of pcs.values()) tuneShare(entry); |
| + applyToggles(); |
| + for (const id of pcs.keys()) markAdapt(id); |
| + } |
| + |
| + // adaptWire is, for the gate, what one connection's last stats walk says |
| + // is on the wire: our camera going out to them (its size, rate, bytes and |
| + // whether the encoding is active) and their audio arriving here. |
| + function adaptWire(id, entry) { |
| + const out = { cameraHeight: 0, cameraFps: 0, cameraBytes: 0, audioPackets: 0, videoFreezes: 0 }; |
| + const stats = entry.statsReport; |
| + if (!stats || typeof stats.forEach !== 'function') return out; |
| + stats.forEach((r) => { |
| + if (r.type === 'outbound-rtp' && r.kind === 'video' && !(entry.shareTx && entry.shareTx.mid && r.mid === entry.shareTx.mid)) { |
| + out.cameraHeight = r.frameHeight || 0; |
| + out.cameraFps = r.framesPerSecond || 0; |
| + out.cameraBytes += r.bytesSent || 0; |
| + if (typeof r.active === 'boolean') out.cameraActive = r.active; |
| + } else if (r.type === 'inbound-rtp' && r.kind === 'audio') { |
| + out.audioPackets += r.packetsReceived || 0; |
| + } else if (r.type === 'inbound-rtp' && r.kind === 'video' && qualityKind(id, entry, r) === 'video') { |
| + out.videoFreezes += r.freezeCount || 0; |
| + } |
| + }); |
| + return out; |
| + } |
| + |
| + // showAdaptNotice puts the sender's notice up for ADAPT_NOTICE_FOR, once |
| + // per change, and says it to a screen reader politely. |
| + function showAdaptNotice(words) { |
| + adaptNoticeShown = words; |
| + const el = $('video-notice'); |
| + if (adaptNoticeTimer) clearTimeout(adaptNoticeTimer); |
| + adaptNoticeTimer = 0; |
| + if (!el) return; |
| + el.textContent = words; |
| + el.hidden = !words; |
| + if (!words) return; |
| + announceMedia(words); |
| + adaptNoticeTimer = setTimeout(() => { |
| + el.hidden = true; |
| + el.textContent = ''; |
| + }, ADAPT_NOTICE_FOR); |
| + } |
| + |
| + // markAdapt draws one tile's level: the badge in its caption while this |
| + // tab asks that person for less than normal, and, at audio only, the |
| + // cover over their picture — which also hides it here for an app too |
| + // old to send less. |
| + function markAdapt(id) { |
| + const t = tiles.get(id); |
| + if (!t || !t.lowBadge) return; |
| + const level = ADAPT_LEVELS.indexOf(videoAsks[id] || 'normal'); |
| + const who = names.get(id) || 'them'; |
| + const own = videoSetting() !== 'auto'; |
| + t.lowBadge.hidden = level <= 0; |
| + t.lowBadge.title = level <= 0 ? '' : (own |
| + ? 'Asking ' + who + ' for less video, as your Video quality setting says' |
| + : 'Asking ' + who + ' for less video while your connection is weak'); |
| + t.lowBadge.setAttribute('aria-label', level <= 0 ? '' : 'Low bandwidth: ' + t.lowBadge.title); |
| + const media = remoteMedia.get(id) || null; |
| + const paused = level >= 3 && !(media && media.cameraOff); |
| + t.videoPaused.hidden = !paused; |
| + if (t.videoPausedOld) t.videoPausedOld.hidden = !paused || honoursAsks(clients.get(id) || ''); |
| + t.figure.classList.toggle('calls-tile-video-paused', paused); |
| } |
| // --------------------------------------------------------------- |
| @@ -5403,6 +5996,19 @@ |
| return { call, peers }; |
| } |
| + // withVideoTime adds §15.30's seconds at each level, asked and sent, to |
| + // one peer's events, only where there were any. Pure, and lifted by name |
| + // in the node test. |
| + function withVideoTime(events, t) { |
| + if (!t) return events; |
| + const out = Object.assign({}, events || {}); |
| + for (const k of ['asked', 'sent']) { |
| + if (!t[k].some((x) => x > 0)) continue; |
| + out[k + 'Seconds'] = t[k].map((x) => Math.round(Math.min(x, QUALITY_MAX_SECONDS) * 10) / 10); |
| + } |
| + return Object.keys(out).length ? out : events; |
| + } |
| + |
| // qualityReport is the body POSTed to /m/{sqid}/quality |
| // (protocol.QualityReport). `o.peers` is [{id, prev, now, ladder, |
| // reattaches, events}]: the two readings, the §15.22 ladder's steps |
| @@ -5426,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; |
| @@ -5661,15 +6271,19 @@ |
| ladder: shareCountsBy.get(id) || null, |
| reattaches: reattachesBy.get(id) || 0, |
| stalls: stallsBy.get(id) || null, |
| - events: events.peers.get(id) || null, |
| + events: withVideoTime(events.peers.get(id) || null, videoTime.get(id)), |
| }); |
| } |
| + videoTime.clear(); |
| + if (videoSetting() !== 'auto') events.call.videoSetting = videoSetting(); |
| for (const id of Array.from(qualityPrev.keys())) if (!pcs.has(id)) qualityPrev.delete(id); |
| shareCountsBy.clear(); |
| reattachesBy.clear(); |
| stallsBy.clear(); |
| qualitySamples.clear(); |
| refreshOutputKind(); |
| + const pressureWorst = pressure.worst; |
| + pressure.worst = pressure.state; |
| const track = local && local.getAudioTracks()[0]; |
| const report = qualityReport({ |
| final, |
| @@ -5682,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. |
| @@ -5776,7 +6391,7 @@ |
| } |
| for (const [id, entry] of pcs) { |
| if (!entry.statsReport) continue; |
| - const reading = qualityReading(entry.statsReport, (r) => qualityKind(id, entry, r)); |
| + const reading = entry.statsReading || qualityReading(entry.statsReport, (r) => qualityKind(id, entry, r)); |
| qualitySamples.set(id, qualitySample(qualitySamples.get(id) || null, reading)); |
| } |
| if (now - qualityFrom >= qualityEvery) sendQuality(false); |
| @@ -6746,6 +7361,31 @@ |
| return { muted, off }; |
| } |
| + // adaptMarks are §15.30's: the "Low bandwidth" badge, the vendored |
| + // badge from the page's template so the state is a word and not a |
| + // colour, and the cover for a person whose video is paused to keep their |
| + // audio clear, with the line for an app too old to send less. |
| + function adaptMarks() { |
| + const badge = document.createElement('span'); |
| + badge.className = 'calls-tile-low'; |
| + badge.hidden = true; |
| + const badgeMark = $('tile-low-bandwidth'); |
| + if (badgeMark) badge.append(badgeMark.content.cloneNode(true)); |
| + else badge.textContent = 'Low bandwidth'; |
| + const cover = document.createElement('div'); |
| + cover.className = 'calls-tile-pause calls-tile-video-paused-cover'; |
| + cover.hidden = true; |
| + const coverMark = $('tile-video-paused'); |
| + if (coverMark) cover.append(coverMark.content.cloneNode(true)); |
| + else cover.textContent = 'Video paused to keep audio clear'; |
| + const old = document.createElement('span'); |
| + old.className = 'calls-tile-paused-old'; |
| + old.textContent = 'Their app can’t send less video, so it’s only hidden here'; |
| + old.hidden = true; |
| + cover.append(old); |
| + return { badge, cover, old }; |
| + } |
| + |
| // markTile shows or hides one tile's marks. `media` null is unknown. |
| function markTile(key, media) { |
| const t = tiles.get(key); |
| @@ -6753,6 +7393,7 @@ |
| t.muted.hidden = !(media && media.muted); |
| t.off.hidden = !(media && media.cameraOff); |
| t.figure.classList.toggle('calls-tile-camera-off', !!(media && media.cameraOff)); |
| + if (t.lowBadge) markAdapt(key); |
| drawHearing(key); |
| } |
| @@ -7538,7 +8179,7 @@ |
| // live-looking select that silently does nothing is the worse half |
| // of that, so they are disabled and say so. |
| if (devicesToggle) devicesToggle.disabled = !on; |
| - for (const el of [pickCamera, pickMic, pickSpeaker, rawInput, pickShareMode]) { |
| + for (const el of [pickCamera, pickMic, pickSpeaker, rawInput, pickShareMode, pickVideoQuality]) { |
| if (el) el.disabled = !on; |
| } |
| } |
| @@ -7740,9 +8381,16 @@ |
| paused.append(said, show); |
| paused.addEventListener('click', () => playSelf(t)); |
| } |
| + // §15.30's two, on another person's tile: the badge while this tab |
| + // asks them for less video, and the cover at audio only. |
| + const low = marks && !isSelf ? adaptMarks() : null; |
| if (marks) { |
| nameEl.after(marks.muted); |
| figure.append(marks.off); |
| + if (low) { |
| + marks.muted.after(low.badge); |
| + figure.append(low.cover); |
| + } |
| if (paused) figure.append(paused); |
| // After Play, so the caption's buttons keep their order. |
| label.append(hear.box, hear.notice); |
| @@ -7754,6 +8402,7 @@ |
| t = { |
| figure, video, label, nameEl, note, retry, play, |
| muted: marks && marks.muted, off: marks && marks.off, |
| + lowBadge: low && low.badge, videoPaused: low && low.cover, videoPausedOld: low && low.old, |
| hear, hearShown: '', |
| remove: null, stream: null, track: null, self: isSelf, |
| // What judgeRender remembers between polls: the element's own |
| @@ -8182,6 +8831,25 @@ |
| }); |
| } |
| + // §15.30's "Video quality". Applied at once: the asks this tab makes of |
| + // everyone, and — for Audio only — no camera to anyone, reported as off. |
| + // Remembered with the devices, so the next call starts the same way. |
| + if (pickVideoQuality && videoQualityRow) { |
| + for (const [value, label] of VIDEO_SETTINGS) { |
| + const option = document.createElement('option'); |
| + option.value = value; |
| + option.textContent = label; |
| + pickVideoQuality.append(option); |
| + } |
| + pickVideoQuality.value = videoSetting(); |
| + videoQualityRow.hidden = false; |
| + pickVideoQuality.addEventListener('change', () => { |
| + prefs.videoQuality = pickVideoQuality.value; |
| + savePrefs(); |
| + applyVideoSetting(); |
| + }); |
| + } |
| + |
| // §5.4's gesture. The handler is not async: a rejection escaping one |
| // goes where neither a person nor a gate could see it, so the work is |
| // a named function with a catch of its own — the same shape as the |
| @@ -8573,7 +9241,7 @@ |
| // an iPhone's camera paused. Disabled (camera off) is the person's |
| // own doing, and no more a stall. |
| if (!tx || !sends || !track || track.readyState === 'ended' || track.muted || |
| - track.enabled === false || |
| + track.enabled === false || entry.cameraPaused || |
| !report || typeof report.framesEncoded !== 'number') { |
| entry.cameraFrames = -1; |
| entry.cameraStalls = 0; |
| @@ -8838,6 +9506,10 @@ |
| // §15.26: the quality report reads this walk rather than making |
| // one of its own. |
| entry.statsReport = stats; |
| + // Parsed once, here: §15.29's sampler (qualityTick) and §15.30's |
| + // adaptive watch both read this walk's reading. |
| + entry.statsReading = qualityReading(stats, (r) => qualityKind(id, entry, r)); |
| + adaptLook(id, entry, stats, Date.now()); |
| const outbound = []; |
| // What the decoder is delivering, per tile: the fallback frame |
| // count where there is no requestVideoFrameCallback, and — in |
| @@ -8889,6 +9561,10 @@ |
| } |
| watchScreens(screens, screenReports); |
| answerScreenStalls(); |
| + const at = Date.now(); |
| + answerAdapt(at, adaptPolledAt ? at - adaptPolledAt : 0); |
| + adaptPolledAt = at; |
| + answerVideoAsks(); |
| qualityTick(); |
| } |
| @@ -9056,6 +9732,22 @@ |
| recoveryForTest(on) { |
| recoveryOn = !!on; |
| }, |
| + // §15.30, for the gate: the clean time before the watch's first probe |
| + // 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.forced = 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(), localAdapt]) { |
| + r.upBase = adaptUpAfter; |
| + r.upWait = Math.min(r.upWait, adaptUpAfter); |
| + } |
| + }, |
| stallScreenForTest(ms) { |
| screenStallTestUntil = Date.now() + Math.max(0, Math.min(Number(ms) || 0, 60000)); |
| }, |
| @@ -9160,6 +9852,22 @@ |
| shareMode: shareMode(), |
| shareSend: Object.fromEntries( |
| Array.from(pcs, ([id, entry]) => [id, entry.shareSend || null])), |
| + // §15.30: per peer, the watch's level and what this tab asks of |
| + // them; what each asks of us and what we send them at; the |
| + // person's setting; and the sender's notice as it stands. |
| + adapt: Object.fromEntries(Array.from(pcs.keys(), (id) => { |
| + const r = adapt.get(id); |
| + const e = pcs.get(id); |
| + 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), |
| + 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.forced || 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. |
| media: localMedia(), |
| @@ -9241,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/calls/templates/room.html b/internal/calls/templates/room.html| index 0665fdf..7b5536a 100644 |
| --- a/internal/calls/templates/room.html |
| +++ b/internal/calls/templates/room.html |
| @@ -71,6 +71,9 @@ |
| <p id="share-recovery" class="calls-share-recovery" role="status" hidden></p> |
| </div> |
| <p id="status" class="calls-status" role="status"></p> |
| + {{/* Spec §15.30: the sender's quiet notice, for a few seconds after |
| + someone asks for less of its video. */}} |
| + <p id="video-notice" class="calls-status calls-video-notice" role="status" data-quiet hidden></p> |
| {{/* §5.5's relay notice, once a session: call-window.js shows it on |
| the first visit of a tab's session and it stays until it is put |
| away. */}} |
| @@ -164,6 +167,10 @@ |
| {{/* §5.4: what a shared screen gives up first when the connection |
| cannot carry all of it. room.js fills the options, remembers the |
| choice and reveals the row in a browser that can share. */}} |
| + {{/* Spec §15.30: Auto lowers and raises the video each person sends |
| + here as the connection allows; the other two are the person's |
| + own floor. room.js fills the options and remembers the choice. */}} |
| + <div id="video-quality-row" hidden>{{template "field-select" dict "ID" "pick-video-quality" "Name" "video-quality" "Label" "Video quality" "Help" "Auto lowers video when a connection is weak and raises it again when it recovers. Low bandwidth asks everyone for small video. Audio only pauses video both ways, to keep sound clear."}}</div> |
| <div id="share-mode-row" hidden>{{template "field-select" dict "ID" "pick-share-mode" "Name" "share-mode" "Label" "Optimise shared screen for" "Help" "Balanced keeps text readable and keeps up with scrolling. Text and detail keeps small print sharp; movement may look jerky. Motion and video keeps movement smooth; text may look softer."}}</div> |
| {{/* Device messages get a live region of their own, like the relay |
| warning: renderStatus owns #status and rewrites it on every |
| @@ -235,6 +242,10 @@ |
| plain one; the icon is on top of it, never instead. */}} |
| <template id="tile-muted">{{icon "mic-off"}}{{template "badge" dict "Label" "Muted"}}</template> |
| <template id="tile-camera-off">{{icon "video-off"}}<span>Camera off</span></template> |
| + {{/* Spec §15.30: while this browser asks someone for less video, the |
| + badge by their name; at Audio only, the cover over their picture. */}} |
| + <template id="tile-low-bandwidth">{{template "badge" dict "Label" "Low bandwidth"}}</template> |
| + <template id="tile-video-paused">{{icon "video-off"}}<span>Video paused to keep audio clear</span></template> |
| {{/* Each tile's arrangement buttons, which call-layout.js clones and |
| names: a Pinned badge while the tile is pinned, and ⋯, which opens |
| #tile-menu for that tile. */}} |
diff --git a/internal/callstest/browser_test.go b/internal/callstest/browser_test.go| index ea66243..7fa4a8d 100644 |
| --- a/internal/callstest/browser_test.go |
| +++ b/internal/callstest/browser_test.go |
| @@ -130,6 +130,8 @@ var scenarios = []string{ |
| "autoplay", |
| "connecting", |
| "quality", |
| + "lowbandwidth", |
| + "audioonly", |
| "selfview", |
| "selfviewwebkit", |
| "scriptless", |
diff --git a/internal/callstest/media_test.go b/internal/callstest/media_test.go| index 229607f..5955f98 100644 |
| --- a/internal/callstest/media_test.go |
| +++ b/internal/callstest/media_test.go |
| @@ -162,7 +162,7 @@ func TestMediaShapes(t *testing.T) { |
| } |
| }) |
| t.Run("padded past the cap", func(t *testing.T) { |
| - payload := `{"muted":true,` + strings.Repeat(" ", 3072) + `"cameraOff":false}` |
| + payload := `{"muted":true,` + strings.Repeat(" ", 4096) + `"cameraOff":false}` |
| res, rb := a.signalRaw(sqid, `{"peer":"`+pa+`","type":"media","payload":`+payload+`}`) |
| if res.StatusCode != http.StatusRequestEntityTooLarge || !strings.Contains(string(rb), `"error":"too-large"`) { |
| t.Fatalf("%d %s, want 413 too-large", res.StatusCode, rb) |
| @@ -170,6 +170,52 @@ func TestMediaShapes(t *testing.T) { |
| }) |
| } |
| +// TestMediaVideoShapes is §15.30's video asks, refused as hard as the |
| +// lists are; a pair of its own, because the shapes above already spend |
| +// most of one peer's signalling budget. |
| +func TestMediaVideoShapes(t *testing.T) { |
| + a, sqid, pa, _ := chatPair(t) |
| + bad := []struct { |
| + name, payload string |
| + }{ |
| + // §15.30's video asks: an object of well-formed ids to known levels. |
| + {"video null", `{"muted":true,"cameraOff":false,"video":null}`}, |
| + {"video an array", `{"muted":true,"cameraOff":false,"video":["` + strings.Repeat("a", 32) + `"]}`}, |
| + {"video a string", `{"muted":true,"cameraOff":false,"video":"minimal"}`}, |
| + {"video a short id", `{"muted":true,"cameraOff":false,"video":{"abc":"minimal"}}`}, |
| + {"video an upper-case id", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("A", 32) + `":"minimal"}}`}, |
| + {"video normal", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":"normal"}}`}, |
| + {"video an unknown level", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":"tiny"}}`}, |
| + {"video a capitalised level", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":"Minimal"}}`}, |
| + {"video a number", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":2}}`}, |
| + {"video a null level", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":null}}`}, |
| + {"video an object level", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":{}}}`}, |
| + {"video a repeated id", `{"muted":true,"cameraOff":false,"video":{"` + strings.Repeat("a", 32) + `":"minimal","` + strings.Repeat("a", 32) + `":"audio"}}`}, |
| + {"video sixteen ids", `{"muted":true,"cameraOff":false,"video":{` + sixteenVideo() + `}}`}, |
| + {"video twice", `{"muted":true,"cameraOff":false,"video":{},"video":{}}`}, |
| + {"video capitalised", `{"muted":true,"cameraOff":false,"Video":{}}`}, |
| + {"video alone", `{"video":{}}`}, |
| + } |
| + for _, c := range bad { |
| + t.Run(c.name, func(t *testing.T) { |
| + body := `{"peer":"` + pa + `","type":"media","payload":` + c.payload + `}` |
| + res, rb := a.signalRaw(sqid, body) |
| + if res.StatusCode != http.StatusBadRequest || !strings.Contains(string(rb), `"error":"bad-request"`) { |
| + t.Fatalf("%d %s, want 400 bad-request", res.StatusCode, rb) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// sixteenVideo is a §15.30 video map one entry too long. |
| +func sixteenVideo() string { |
| + ids := strings.Split(sixteenIDs(), ",") |
| + for i := range ids { |
| + ids[i] += `:"reduced"` |
| + } |
| + return strings.Join(ids, ",") |
| +} |
| + |
| func sixteenIDs() string { |
| ids := make([]string, 16) |
| for i := range ids { |
| @@ -314,6 +360,63 @@ func TestMediaCarriesWhoTheReceiverHears(t *testing.T) { |
| } |
| } |
| +// Spec §15.30: a receiver's asks of each sender ride the same report — an |
| +// object of peer ids to levels, re-encoded with its keys in order after |
| +// everything else, {} the same as absent, and a change in it a change. |
| +func TestMediaCarriesVideoAsks(t *testing.T) { |
| + a, sqid, pa, sb := chatPair(t) |
| + x := strings.Repeat("0", 31) + "4" |
| + y := strings.Repeat("0", 31) + "2" |
| + res, rb := a.signalRaw(sqid, `{"peer":"`+pa+`","type":"media","payload":{"video":{"`+x+`":"audio","`+y+`":"minimal"},"muted":false,"cameraOff":false,"hearing":[]}}`) |
| + if res.StatusCode != http.StatusOK { |
| + t.Fatalf("video: %d %s", res.StatusCode, rb) |
| + } |
| + _, data, ok := sb.nextOf("media", 2*time.Second) |
| + want := `"payload":{"muted":false,"cameraOff":false,"hearing":[],"video":{"` + y + `":"minimal","` + x + `":"audio"}}` |
| + if !ok || !strings.Contains(string(data), want) { |
| + t.Fatalf("envelope %s, want %s", data, want) |
| + } |
| + // The same asks in another order are the same report: nothing goes out. |
| + res, _ = a.signalRaw(sqid, `{"peer":"`+pa+`","type":"media","payload":{"muted":false,"cameraOff":false,"hearing":[],"video":{"`+y+`":"minimal","`+x+`":"audio"}}}`) |
| + if res.StatusCode != http.StatusOK { |
| + t.Fatalf("repeat: %d", res.StatusCode) |
| + } |
| + if _, data, ok := sb.nextOf("media", 300*time.Millisecond); ok { |
| + t.Fatalf("an unchanged ask went out again: %s", data) |
| + } |
| + // A level changed is a change. |
| + res, _ = a.signal(sqid, pa, `{"type":"media","payload":{"muted":false,"cameraOff":false,"hearing":[],"video":{"`+y+`":"reduced"}}}`) |
| + if res.StatusCode != http.StatusOK { |
| + t.Fatalf("reduced: %d", res.StatusCode) |
| + } |
| + _, data, ok = sb.nextOf("media", 2*time.Second) |
| + if !ok || !strings.Contains(string(data), `"video":{"`+y+`":"reduced"}}`) { |
| + t.Fatalf("changed ask %s", data) |
| + } |
| + // Every list and the video map full at once fits the cap. |
| + ids := strings.Split(sixteenIDs(), ",")[:15] |
| + video := strings.Split(sixteenVideo(), ",")[:15] |
| + full := `{"muted":false,"cameraOff":false,"audioBlocked":true,"noSoundFrom":[` + strings.Join(ids, ",") + `],"screenStalled":[` + |
| + strings.Join(ids, ",") + `],"hearing":[` + strings.Join(ids, ",") + `],"video":{` + strings.Join(video, ",") + `}}` |
| + res, rb = a.signal(sqid, pa, `{"type":"media","payload":`+full+`}`) |
| + if res.StatusCode != http.StatusOK { |
| + t.Fatalf("everything full: %d %s", res.StatusCode, rb) |
| + } |
| + _, data, ok = sb.nextOf("media", 2*time.Second) |
| + if !ok || !strings.Contains(string(data), `"payload":`+full) { |
| + t.Fatalf("full report %s", data) |
| + } |
| + // {} is "normal from everyone", and goes out without the key. |
| + res, _ = a.signal(sqid, pa, `{"type":"media","payload":{"muted":false,"cameraOff":false,"hearing":[],"video":{}}}`) |
| + if res.StatusCode != http.StatusOK { |
| + t.Fatalf("empty: %d", res.StatusCode) |
| + } |
| + _, data, ok = sb.nextOf("media", 2*time.Second) |
| + if !ok || !strings.Contains(string(data), `"payload":{"muted":false,"cameraOff":false,"hearing":[]}`) || strings.Contains(string(data), "video") { |
| + t.Fatalf("empty asks %s", data) |
| + } |
| +} |
| + |
| // A waiting guest has nobody to tell: its report is the usual 404, and |
| // it hears nothing of the room's. |
| func TestMediaFromAWaitingGuestIsTheUsual404(t *testing.T) { |
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 dabeaeb..ebefca5 100644 |
| --- a/internal/callstest/quality_test.go |
| +++ b/internal/callstest/quality_test.go |
| @@ -269,6 +269,95 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| } |
| } |
| +// Spec §15.30: the time asked for, and sent, less video is in the report |
| +// per peer and summed on the line's top level, with the person's own |
| +// setting, so `carlos logs` shows it without the report member. |
| +func TestQualityReportsCarryAdaptiveVideo(t *testing.T) { |
| + r := newReportRig(t, "") |
| + q := sampleQuality(r.peerB) |
| + q.Events.VideoSetting = "low" |
| + q.Peers[0].Events.AskedSeconds = []*float64{num(0), num(24.04), num(0)} |
| + q.Peers[0].Events.SentSeconds = []*float64{num(6), num(0), num(0)} |
| + 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) |
| + } |
| + lines := r.reports.lines(t, "calls: quality") |
| + if len(lines) != 1 { |
| + t.Fatalf("%d lines", len(lines)) |
| + } |
| + l := lines[0] |
| + if l["videoAsked"] != 24.0 || l["videoSent"] != 6.0 || l["videoSetting"] != "low" { |
| + t.Errorf("headline videoAsked=%v videoSent=%v videoSetting=%v", l["videoAsked"], l["videoSent"], l["videoSetting"]) |
| + } |
| + // §15.29's per-peer line carries them flat, only those not zero. |
| + peers := r.reports.lines(t, "calls: quality peer") |
| + if len(peers) != 1 { |
| + t.Fatalf("%d peer lines", len(peers)) |
| + } |
| + p := peers[0] |
| + if p["askedMinimal"] != 24.0 || p["sentReduced"] != 6.0 { |
| + t.Errorf("per peer askedMinimal=%v sentReduced=%v", p["askedMinimal"], p["sentReduced"]) |
| + } |
| + for _, k := range []string{"askedReduced", "askedAudio", "sentMinimal", "sentAudio"} { |
| + if _, ok := p[k]; ok { |
| + t.Errorf("a zero level put %q on the peer line", k) |
| + } |
| + } |
| + // A quiet report names none of it. |
| + r.x.advance(10 * time.Second) |
| + if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sampleQuality(r.peerB))); resp.StatusCode != http.StatusAccepted { |
| + t.Fatalf("quiet report: %d", resp.StatusCode) |
| + } |
| + quiet := r.reports.lines(t, "calls: quality")[1] |
| + for _, k := range []string{"videoAsked", "videoSent", "videoSetting"} { |
| + if _, ok := quiet[k]; ok { |
| + t.Errorf("a quiet report put %q on the line", k) |
| + } |
| + } |
| + for _, k := range []string{"askedReduced", "askedMinimal", "askedAudio", "sentReduced", "sentMinimal", "sentAudio"} { |
| + if _, ok := r.reports.lines(t, "calls: quality peer")[1][k]; ok { |
| + t.Errorf("a quiet report put %q on the peer line", k) |
| + } |
| + } |
| + 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 { |
| @@ -302,9 +391,26 @@ func TestQualityReportSchemaIsStrict(t *testing.T) { |
| "a billion rebuilds and more": func(m map[string]any) { |
| peer0(m)["events"].(map[string]any)["autoRebuilds"] = 1e10 |
| }, |
| - "restarts as words": func(m map[string]any) { peer0(m)["events"].(map[string]any)["autoRestarts"] = "many" }, |
| - "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" }, |
| + "restarts as words": func(m map[string]any) { peer0(m)["events"].(map[string]any)["autoRestarts"] = "many" }, |
| + // §15.30's seconds at each level: three numbers, nothing else. |
| + "two levels": func(m map[string]any) { peer0(m)["events"].(map[string]any)["askedSeconds"] = []any{1, 2} }, |
| + "four levels": func(m map[string]any) { peer0(m)["events"].(map[string]any)["sentSeconds"] = []any{1, 2, 3, 4} }, |
| + "a null level": func(m map[string]any) { peer0(m)["events"].(map[string]any)["askedSeconds"] = []any{1, nil, 3} }, |
| + "a level as words": func(m map[string]any) { peer0(m)["events"].(map[string]any)["askedSeconds"] = []any{1, "two", 3} }, |
| + "a negative level": func(m map[string]any) { peer0(m)["events"].(map[string]any)["sentSeconds"] = []any{1, -2, 3} }, |
| + "an hour at a level": func(m map[string]any) { peer0(m)["events"].(map[string]any)["askedSeconds"] = []any{0, 3600, 0} }, |
| + "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 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++ { |
| @@ -370,6 +476,9 @@ func TestTheLargestQualityLineFitsThePlatformsLine(t *testing.T) { |
| Decoded: big(), Dropped: big(), Width: num(16384), Height: num(16384), FPS: num(240), Reattaches: big()} |
| } |
| 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{ |
| @@ -382,7 +491,9 @@ func TestTheLargestQualityLineFitsThePlatformsLine(t *testing.T) { |
| }, |
| Events: &protocol.PeerEvents{Reconnecting: big(), ReconnectingSeconds: num(599.9), CantHearSeconds: num(599.9), |
| NoSound: true, NoSoundFromUs: true, AudioBlocked: true, ScreenStalled: true, |
| - AutoRestarts: big(), AutoRebuilds: big()}, |
| + AutoRestarts: big(), AutoRebuilds: big(), |
| + AskedSeconds: []*float64{num(599.9), num(599.9), num(599.9)}, |
| + SentSeconds: []*float64{num(599.9), num(599.9), num(599.9)}}, |
| }) |
| } |
| if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { |
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift| index ee59b7d..44cb5a1 100644 |
| --- a/native/apple/Sources/CallsKit/Call.swift |
| +++ b/native/apple/Sources/CallsKit/Call.swift |
| @@ -2,6 +2,9 @@ import Combine |
| import Foundation |
| #if os(iOS) |
| import AVFoundation |
| + import UIKit |
| +#else |
| + import AppKit |
| #endif |
| // Go serializes this API with a mutex; Objective-C bindings carry no Sendable annotation. |
| @preconcurrency import CallsBridge |
| @@ -122,6 +125,35 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| private var heardFrom: [String: (epoch: Int64, heard: Bool)] = [:] |
| private var ackedBy: [String: Int64] = [:] |
| private var reportedHearing: [String] = [] |
| + /// Spec §15.30: each sender's adaptive watch, the counters it last read |
| + /// them from (per connection generation), when it last looked, and the |
| + /// asks last reported. |
| + private var adapt: [String: VideoAdapt] = [:] |
| + private var adaptCounters: [String: (generation: Int64, counters: QualityCounters)] = [:] |
| + private var adaptLookedAt: Double? |
| + private var reportedVideo: [String: String] = [:] |
| + /// What this app asks each person for, as the tiles show it: peer id to |
| + /// level, only those below normal. |
| + @Published public private(set) var videoAsks: [String: String] = [:] |
| + /// The sender's notice while it lasts: "Sending reduced video to …". |
| + @Published public private(set) var videoNotice = "" |
| + /// The person's own Video quality (device panel), remembered. |
| + @Published public var videoQuality: VideoQualitySetting = .remembered { |
| + didSet { |
| + guard videoQuality != oldValue else { return } |
| + VideoQualitySetting.remembered = videoQuality |
| + CallLog.info("video quality: \(videoQuality.rawValue)") |
| + 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, |
| /// the running totals the last report was taken from, the loop that |
| /// sends one every `qualityInterval`, and whether the server has said to |
| @@ -421,6 +453,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| guard epoch == joiningEpoch, bridge === client else { throw CancellationError() } |
| localTrack = media.localVideo |
| cameraChanged() |
| + media.ownAudioOnly = videoQuality == .audio |
| reportMedia() |
| media.audio.reduceNoise = reduceNoise |
| audioProcessing = media.audio.report() |
| @@ -524,7 +557,10 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| /// each toggle and once the tracks exist, and nowhere else. No track at |
| /// all is muted, or off, as far as anyone listening can tell. |
| private func reportMedia() { |
| - try? bridge?.setMedia(muted || media.localAudio == nil, cameraOff: cameraOff || media.localVideo == nil) |
| + // §15.30: Audio only sends no camera to anyone, so it is off. |
| + try? bridge?.setMedia( |
| + muted || media.localAudio == nil, |
| + cameraOff: cameraOff || media.localVideo == nil || videoQuality == .audio) |
| } |
| /// A remote peer's reported state, or nil when it has not reported. |
| @@ -533,6 +569,19 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| public func isMuted(_ peer: String) -> Bool { peerMedia(peer)?.muted ?? false } |
| /// Whether a remote peer has said its camera is off. Unknown is not off. |
| public func isCameraOff(_ peer: String) -> Bool { peerMedia(peer)?.cameraOff ?? false } |
| + /// Spec §15.30: whether this app is asking a peer for less video — the |
| + /// tile's "Low bandwidth" badge. |
| + public func isLowBandwidth(_ peer: String) -> Bool { videoAsks[peer] != nil } |
| + /// Whether a peer's picture is paused to keep their audio clear: this app |
| + /// asks them for audio only, and their camera is not off anyway. |
| + public func isVideoPaused(_ peer: String) -> Bool { videoAsks[peer] == VideoLevel.audio.wire && !isCameraOff(peer) } |
| + /// What a paused tile says: the words, and for an app too old to send |
| + /// less, that it is only hidden here. |
| + public func videoPausedWords(_ peer: String) -> String { |
| + let client = state?.peers.first { $0.peer == peer }?.client |
| + return VideoAdapt.honours(client: client) |
| + ? VideoAdapt.pausedWords : VideoAdapt.pausedWords + ". " + VideoAdapt.oldAppWords |
| + } |
| nonisolated static func peerMedia(_ peer: String, in state: RoomState?) -> PeerMedia? { |
| state?.peers.first { $0.peer == peer }?.media |
| } |
| @@ -674,6 +723,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| self.sampleMic(now: now) |
| if tick % 2 == 0 { await self.samplePeers(stats: tick % 10 == 0, now: now) } |
| if tick % 10 == 5 { await self.watchRemoteScreens(now: now) } |
| + if tick % 10 == 7 { await self.watchAdapt(now: now) } |
| } |
| } |
| } |
| @@ -681,6 +731,15 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| private func endLevelWatch() { |
| levelWatch?.cancel() |
| levelWatch = nil |
| + adapt = [:] |
| + adaptCounters = [:] |
| + adaptLookedAt = nil |
| + localAdapt = VideoAdapt() |
| + ownCameraLevel = .normal |
| + built?.localLevel = .normal |
| + reportedVideo = [:] |
| + videoAsks = [:] |
| + videoNotice = "" |
| screenReceiveWatch = ScreenReceiveWatch() |
| reportedStalled = [] |
| screenReceived = [:] |
| @@ -1040,6 +1099,8 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| ice = nil |
| } |
| if let ice { media.reconcile(state: state, ice: ice) } |
| + // §15.30: and what each of them asks of us now. |
| + answerVideoAsks(state) |
| case "ice": |
| guard let config = event.ice else { return } |
| let renewing = ice != nil |
| @@ -1379,6 +1440,8 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| // they cannot hear you yet, and how many this app reports it hears. |
| values["connectingJoining"] = UInt64(connectingWatch.joining.count) |
| values["connectingShown"] = UInt64(connectingPeers.count) |
| + // §15.30: the level this device's own trouble holds its camera at. |
| + values["ownCameraLevel"] = UInt64(ownCameraLevel.rawValue) |
| values["hearing"] = UInt64(reportedHearing.count) |
| // This app's own screen, as it leaves: the slowest connection's. |
| if let screen = screenReport { |
| @@ -1461,6 +1524,126 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| } |
| } |
| +// --------------------------------------------------------------- |
| +// Adaptive video (§15.30) |
| +// --------------------------------------------------------------- |
| + |
| +extension Call { |
| + /// One look by every sender's watch, once a second from the level watch: |
| + /// the quality report's own reading of each connection, the second since |
| + /// the last, a step of that sender's watch; then the asks this app makes, |
| + /// reported on a change; and the seconds at each level, asked and sent, |
| + /// for the next quality report. |
| + fileprivate func watchAdapt(now: Double) async { |
| + guard let state, state.phase == "admitted" || state.phase == "reconnecting" else { return } |
| + let samples = await media.qualitySamples() |
| + guard levelWatch != nil, let current = self.state else { return } |
| + let dt = adaptLookedAt.map { min(max(now - $0, 0), 2) } ?? 0 |
| + adaptLookedAt = now |
| + #if os(macOS) |
| + let watching = NSApplication.shared.isActive || !NSApplication.shared.isHidden |
| + #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 } |
| + adaptCounters[id] = (sample.generation, counters) |
| + guard let before else { continue } |
| + var watch = adapt[id] ?? VideoAdapt(upAfter: adaptUpAfter) |
| + let was = watch.level |
| + let cameraWatched = watching && !isCameraOff(id) |
| + // 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)" : "")") |
| + } |
| + } |
| + for id in Array(adapt.keys) where samples[id] == nil { adapt.removeValue(forKey: id) } |
| + 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 { |
| + let asked = videoAsks[id].flatMap(VideoLevel.init(wire:)) ?? .normal |
| + qualityTally.video(asked: asked, sent: sent[id] ?? .normal, seconds: dt, for: id) |
| + } |
| + } |
| + |
| + /// The asks, from every watch's level and the person's own setting, |
| + /// reported when they change (off the main thread, as the lists are). |
| + fileprivate func reportVideo() { |
| + let levels = adapt.mapValues(\.level).merging( |
| + Dictionary(uniqueKeysWithValues: media.sentLevels.keys.map { ($0, VideoLevel.normal) }) |
| + ) { a, _ in a } |
| + let asks = VideoAdapt.asks(levels, setting: videoQuality) |
| + if videoAsks != asks { videoAsks = asks } |
| + guard asks != reportedVideo, let client = bridge else { return } |
| + reportedVideo = asks |
| + let body = json(asks) ?? "{}" |
| + noSoundQueue.async { try? client.setVideo(body) } |
| + } |
| + |
| + /// The sender's half: each connection's senders set to what that peer |
| + /// last asked of us, and the notice when someone asks for less. |
| + fileprivate func answerVideoAsks(_ state: RoomState) { |
| + let me = state.peer |
| + let before = media.sentLevels |
| + var lowered = false |
| + for person in state.peers where person.peer != me { |
| + let level = VideoAdapt.asked(person.media, me: me) |
| + let was = before[person.peer] ?? .normal |
| + guard before[person.peer] != nil, level != was else { continue } |
| + CallLog.info("\(person.peer.prefix(6)) asks for \(level.wire) video") |
| + if level > was { lowered = true } |
| + media.setSentLevel(person.peer, level) |
| + } |
| + let sent = media.sentLevels |
| + let people = state.peers.compactMap { p -> (name: String, level: VideoLevel)? in |
| + guard p.peer != me, let level = sent[p.peer], level > .normal else { return nil } |
| + return (p.name, level) |
| + } |
| + let words = VideoAdapt.noticeWords(people) |
| + if words.isEmpty { |
| + videoNotice = "" |
| + } else if lowered, words != videoNotice { |
| + videoNotice = words |
| + say(words, for: 8) |
| + } |
| + } |
| + |
| + /// The person's choice taking effect: no camera to anyone at Audio only, |
| + /// reported as off; the asks of everyone; and the tiles. |
| + fileprivate func applyVideoQuality() { |
| + guard bridge != nil else { return } |
| + media.ownAudioOnly = videoQuality == .audio |
| + reportMedia() |
| + reportVideo() |
| + } |
| +} |
| + |
| // --------------------------------------------------------------- |
| // Quality and problem reports (§15.26) |
| // --------------------------------------------------------------- |
| @@ -1523,9 +1706,11 @@ extension Call { |
| /// its reference. |
| private func sendQualityWindow(samples: [String: QualityPeerSample], client: BridgeClient) { |
| let now = ProcessInfo.processInfo.systemUptime |
| - let report = qualityBuilder.build( |
| + var report = qualityBuilder.build( |
| at: now, samples: samples, events: &qualityTally, client: QualityClientInfo.current(), |
| devices: qualityDevices(), final: false, 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)) |
| let facts = QualityTrouble.facts(report) |
| let trigger = AutoReportDecision.trigger( |
| previous: qualityFacts, now: facts, gate: autoReportGate, at: now, enabled: QualityReporting.enabled(), |
| @@ -1573,10 +1758,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/DevicePanel.swift b/native/apple/Sources/CallsKit/DevicePanel.swift| index 0d11a2a..99faf96 100644 |
| --- a/native/apple/Sources/CallsKit/DevicePanel.swift |
| +++ b/native/apple/Sources/CallsKit/DevicePanel.swift |
| @@ -60,6 +60,8 @@ import SwiftUI |
| AudioSelfTestButton(call: call).buttonStyle(.bordered) |
| + videoQualitySection |
| + |
| screenSection |
| audioFoot |
| @@ -256,6 +258,24 @@ import SwiftUI |
| } |
| } |
| + /// Spec §15.30: Auto, Low bandwidth or Audio only, remembered. |
| + private var videoQualitySection: some View { |
| + VStack(alignment: .leading, spacing: 4) { |
| + Picker("Video quality", selection: $call.videoQuality) { |
| + ForEach(VideoQualitySetting.allCases) { setting in |
| + Text(setting.title).tag(setting) |
| + } |
| + } |
| + .accessibilityIdentifier("videoQuality") |
| + #if os(macOS) |
| + .pickerStyle(.menu) |
| + #endif |
| + Text(VideoQualitySetting.explanation) |
| + .font(.footnote).foregroundStyle(.secondary) |
| + .fixedSize(horizontal: false, vertical: true) |
| + } |
| + } |
| + |
| /// "Optimise for", and while this app is sharing, one line saying how |
| /// the screen is actually leaving — the answer to "it isn't keeping up". |
| private var screenSection: some View { |
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/InviteLinkCopy.swift b/native/apple/Sources/CallsKit/InviteLinkCopy.swift| index aa6ab1e..c970cdf 100644 |
| --- a/native/apple/Sources/CallsKit/InviteLinkCopy.swift |
| +++ b/native/apple/Sources/CallsKit/InviteLinkCopy.swift |
| @@ -64,13 +64,13 @@ extension Call { |
| } |
| /// A short message over the call that goes by itself: never a dialog. |
| - func say(_ text: String) { |
| + func say(_ text: String, for seconds: Double = 2.5) { |
| toastSerial += 1 |
| let serial = toastSerial |
| toast = text |
| AccessibilityNotification.Announcement(text).post() |
| Task { @MainActor [weak self] in |
| - try? await Task.sleep(for: .seconds(2.5)) |
| + try? await Task.sleep(for: .seconds(seconds)) |
| guard let self, self.toastSerial == serial else { return } |
| self.toast = nil |
| } |
diff --git a/native/apple/Sources/CallsKit/MacCallView.swift b/native/apple/Sources/CallsKit/MacCallView.swift| index d20f409..67e26fc 100644 |
| --- a/native/apple/Sources/CallsKit/MacCallView.swift |
| +++ b/native/apple/Sources/CallsKit/MacCallView.swift |
| @@ -227,7 +227,9 @@ |
| case .camera(let peer): |
| return MacVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), muted: call.isMuted(peer), |
| - cameraOff: call.isCameraOff(peer), cornerRadius: cornerRadius, compact: compact, |
| + cameraOff: call.isCameraOff(peer), lowBandwidth: call.isLowBandwidth(peer), |
| + videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil, |
| + cornerRadius: cornerRadius, compact: compact, |
| labelLift: labelLift, backdrop: backdrop, audio: call.tileAudio(peer), onStage: onStage, |
| pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer]) |
| } |
diff --git a/native/apple/Sources/CallsKit/MacVideoTile.swift b/native/apple/Sources/CallsKit/MacVideoTile.swift| index 5880f6d..d0e27c4 100644 |
| --- a/native/apple/Sources/CallsKit/MacVideoTile.swift |
| +++ b/native/apple/Sources/CallsKit/MacVideoTile.swift |
| @@ -10,6 +10,10 @@ |
| var muted = false |
| var mirrored = false |
| var cameraOff = false |
| + /// Spec §15.30: this app is asking them for less video ("Low |
| + /// bandwidth"), and, at audio only, the words in place of the picture. |
| + var lowBandwidth = false |
| + var videoPaused: String? = nil |
| /// A shared screen (§5.4). Shown whole rather than cropped to fill: |
| /// the edge of a screen is where its menu bar and its scroll bars are, |
| /// and a face survives losing its margins where a document does not. |
| @@ -67,7 +71,7 @@ |
| .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| FixtureVideo(picture: fixturePicture, screen: screen) |
| - } else if let track, !cameraOff, placeholder == nil { |
| + } else if let track, !cameraOff, placeholder == nil, videoPaused == nil { |
| // A screen on the stage is fitted whole, and so is a camera of |
| // another shape than its tile (a phone held upright, in a |
| // landscape window); around it, the same picture soft and |
| @@ -83,7 +87,7 @@ |
| .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else { |
| TilePlaceholder( |
| - symbol: cameraOff |
| + symbol: cameraOff || videoPaused != nil |
| ? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle", |
| words: iconOnly ? nil : waiting, iconFont: iconOnly ? .title2 : .largeTitle, |
| reserve: labelBlock) |
| @@ -94,6 +98,7 @@ |
| TileAudioNotices(info) |
| HStack(spacing: 6) { |
| TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow) |
| + if lowBandwidth { LowBandwidthBadge(compact: compact) } |
| TileAudioStatus(info) |
| } |
| } |
| @@ -106,9 +111,13 @@ |
| .overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(10) } } |
| .clipShape(RoundedRectangle(cornerRadius: cornerRadius)) |
| .accessibilityElement(children: .ignore) |
| - .accessibilityLabel(stageLabel(tileAccessibilityLabel(label, muted: muted, audio: info), onStage: onStage, pinned: pinned)) |
| + .accessibilityLabel( |
| + stageLabel( |
| + tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""), |
| + onStage: onStage, pinned: pinned)) |
| .accessibilityHint(info?.detail ?? "") |
| - .accessibilityValue(cameraOff ? "Camera off" : track == nil || placeholder != nil ? waiting : "Video on") |
| + .accessibilityValue( |
| + cameraOff ? "Camera off" : track == nil || placeholder != nil || videoPaused != nil ? waiting : "Video on") |
| } |
| /// The backdrop's fade when a picture turns between filling and |
| /// fitted; none under Reduce Motion. |
| @@ -118,7 +127,8 @@ |
| private var waiting: String { |
| cameraOff |
| - ? "Camera off" : placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video") |
| + ? "Camera off" |
| + : videoPaused ?? placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video") |
| } |
| } |
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift| index 31a1c74..7a15efd 100644 |
| --- a/native/apple/Sources/CallsKit/Media.swift |
| +++ b/native/apple/Sources/CallsKit/Media.swift |
| @@ -24,6 +24,8 @@ import LiveKitWebRTC |
| didSet { applySendPolicy() } |
| } |
| private var screenSize = (width: 0, height: 0) |
| + /// The screen's source size, for §15.30's minimal fit. |
| + var screenSourceSize: (width: Int, height: Int) { screenSize } |
| /// The audio device module and processing behind the factory. See CallAudio. |
| let audio: CallAudio |
| @@ -240,6 +242,28 @@ import LiveKitWebRTC |
| func applySendPolicy() { |
| for peer in peers.values { peer.applySendPolicy() } |
| } |
| + |
| + /// Spec §15.30: the level one peer asks of us, applied to that one |
| + /// connection's senders. Kept on the peer, so a connection that settles |
| + /// later is given it too. |
| + func setSentLevel(_ peer: String, _ level: VideoLevel) { |
| + guard let p = peers[peer], p.sentLevel != level else { return } |
| + 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 } |
| @@ -580,6 +604,12 @@ struct PeerAudioReading: Equatable, Sendable { |
| // with it; and the mid, so the statistics can count the two video |
| // streams apart. |
| private var clues = ScreenClues() |
| + /// 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 |
| @@ -712,7 +742,12 @@ struct PeerAudioReading: Equatable, Sendable { |
| let plan = engine.screenPlanFor |
| let nudge = self.nudge |
| let cameraTrack = engine.localVideo |
| - let camera = ScreenSendPolicy.camera(sharing: screenTx != nil) |
| + // §15.30: at the level this peer asks of us, and no camera at all while |
| + // the person's own Video quality is Audio only. |
| + let level = sentLevel |
| + let size = engine.screenSourceSize |
| + 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 |
| @@ -720,7 +755,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| let fmtp = screen.parameters.codecs.first.flatMap { codec -> [String: String]? in |
| codec.name.uppercased() == "H264" ? codec.parameters as? [String: String] : nil |
| } |
| - var screenPlan = plan(fmtp) |
| + var screenPlan = VideoAdapt.screen(plan(fmtp), level, width: size.width, height: size.height) |
| if nudge > 1 { screenPlan.scaleResolutionDownBy = (screenPlan.scaleResolutionDownBy ?? 1) * nudge } |
| screen.apply(screenPlan) |
| } |
| @@ -774,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/MiniWindow.swift b/native/apple/Sources/CallsKit/MiniWindow.swift| index 92b4921..2ff455c 100644 |
| --- a/native/apple/Sources/CallsKit/MiniWindow.swift |
| +++ b/native/apple/Sources/CallsKit/MiniWindow.swift |
| @@ -546,6 +546,8 @@ |
| MacVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), |
| muted: call.isMuted(peer), cameraOff: call.isCameraOff(peer), |
| + lowBandwidth: call.isLowBandwidth(peer), |
| + videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil, |
| audio: call.tileAudio(peer), fixtureVideo: fixtureFeeds[peer]) |
| case nil: |
| MacVideoTile( |
diff --git a/native/apple/Sources/CallsKit/MutedBadge.swift b/native/apple/Sources/CallsKit/MutedBadge.swift| index 47af48a..5cae5ae 100644 |
| --- a/native/apple/Sources/CallsKit/MutedBadge.swift |
| +++ b/native/apple/Sources/CallsKit/MutedBadge.swift |
| @@ -16,6 +16,29 @@ public struct MutedBadge: View { |
| } |
| } |
| +/// Spec §15.30: the quiet mark beside a person's name while this app asks |
| +/// them for less video. A word, never a colour; the tile's own label says |
| +/// "low bandwidth", so this hides itself from assistive technology. |
| +public struct LowBandwidthBadge: View { |
| + var compact = false |
| + public init(compact: Bool = false) { self.compact = compact } |
| + public var body: some View { |
| + Group { |
| + if compact { |
| + Image(systemName: "wifi.exclamationmark") |
| + } else { |
| + Label(VideoAdapt.badgeWord, systemImage: "wifi.exclamationmark") |
| + } |
| + } |
| + .font(.caption.weight(.semibold)).foregroundStyle(.white) |
| + .padding(.horizontal, 7).padding(.vertical, 3) |
| + .callOverlaySurface(Capsule()) |
| + .help("Calls is asking for less video while the connection is weak") |
| + .accessibilityHidden(true) |
| + .accessibilityIdentifier("lowBandwidth") |
| + } |
| +} |
| + |
| /// What a tile's accessibility label says: the name, and "muted" when it |
| /// is. Shared by the Mac and iPhone tiles so VoiceOver hears one phrase. |
| public func tileAccessibilityLabel(_ label: String, muted: Bool) -> String { |
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift| index f9a324a..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" |
| } |
| @@ -98,6 +103,9 @@ public struct QualityDevices: Encodable, Equatable, Sendable { |
| public struct QualityCallEvents: Encodable, Equatable, Sendable { |
| public var reconnecting: Double? |
| public var reconnectingSeconds: Double? |
| + /// §15.30: "low" or "audio", the person's own Video quality; absent for |
| + /// Auto. |
| + public var videoSetting: String? |
| } |
| public struct QualityPeer: Encodable, Equatable, Sendable { |
| @@ -233,6 +241,11 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable { |
| /// §15.28: ICE restarts and rebuilds this app's recovery made. |
| public var autoRestarts: Double? |
| public var autoRebuilds: Double? |
| + /// §15.30: seconds this app asked them for each level below normal |
| + /// (reduced, minimal, audio), and seconds it sent them less because they |
| + /// asked; three numbers, or absent. |
| + public var askedSeconds: [Double]? |
| + public var sentSeconds: [Double]? |
| } |
| // MARK: - The snapshot |
| @@ -346,6 +359,9 @@ struct QualityCounters: Equatable, Sendable { |
| /// CoderKinds and Codecs. |
| var decoder: String? |
| var codec: String? |
| + /// PLIs and FIRs this side sent for it (spec §15.30's watch; not |
| + /// reported). |
| + var keyframeAsks: Double? |
| } |
| var outAudio: Out? |
| var outVideo: Out? |
| @@ -432,6 +448,9 @@ struct QualityCounters: Equatable, Sendable { |
| impl: stat.strings["decoderImplementation"], |
| powerEfficient: stat.numbers["powerEfficientDecoder"].map { $0 != 0 }) |
| v.codec = QualityWords.codec(mimeType: Self.mimeType(of: stat, in: stats)) |
| + if stat.numbers["pliCount"] != nil || stat.numbers["firCount"] != nil { |
| + v.keyframeAsks = (stat.numbers["pliCount"] ?? 0) + (stat.numbers["firCount"] ?? 0) |
| + } |
| // 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 { |
| @@ -575,6 +594,7 @@ struct QualityCounters: Equatable, Sendable { |
| a.fps = most(a.fps, b.fps) |
| a.decoder = a.decoder ?? b.decoder |
| a.codec = a.codec ?? b.codec |
| + a.keyframeAsks = sum(a.keyframeAsks, b.keyframeAsks) |
| return a |
| } |
| } |
| @@ -680,6 +700,8 @@ public struct QualityEventTally: Equatable, Sendable { |
| /// The connection's own recovery (§15.28). |
| var autoRestarts = 0 |
| var autoRebuilds = 0 |
| + /// §15.30's seconds at each level, asked and sent. |
| + var video = VideoTime() |
| } |
| /// The longest a look is taken to cover: the level watch looks five |
| @@ -693,6 +715,8 @@ public struct QualityEventTally: Equatable, Sendable { |
| private(set) var callReconnecting = 0 |
| private(set) var callSeconds = 0.0 |
| private(set) var peers: [String: Peer] = [:] |
| + /// §15.30: the person's own Video quality, when it is not Auto. |
| + var videoSetting: VideoQualitySetting = .auto |
| public init() {} |
| @@ -722,6 +746,12 @@ public struct QualityEventTally: Equatable, Sendable { |
| for id in screenStalled { peers[id, default: Peer()].screenStalled = true } |
| } |
| + /// §15.30: time at the levels asked of and sent to one peer. |
| + mutating func video(asked: VideoLevel, sent: VideoLevel, seconds: Double, for peer: String) { |
| + guard asked > .normal || sent > .normal, seconds > 0 else { return } |
| + peers[peer, default: Peer()].video.add(asked: asked, sent: sent, seconds: seconds) |
| + } |
| + |
| public mutating func count(_ step: Step, for peer: String) { |
| switch step { |
| case .keyframe: peers[peer, default: Peer()].keyframes += 1 |
| @@ -837,10 +867,11 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| var report = QualityReport( |
| isFinal: final ? true : nil, seconds: Self.bound(seconds, QualityBounds.seconds) ?? QualityBounds.seconds, |
| client: client, devices: devices) |
| - if events.callReconnecting > 0 || events.callSeconds > 0 { |
| + if events.callReconnecting > 0 || events.callSeconds > 0 || events.videoSetting != .auto { |
| report.events = QualityCallEvents( |
| reconnecting: Self.steps(events.callReconnecting), |
| - reconnectingSeconds: events.callSeconds > 0 ? Self.bound(events.callSeconds, QualityBounds.seconds) : nil) |
| + reconnectingSeconds: events.callSeconds > 0 ? Self.bound(events.callSeconds, QualityBounds.seconds) : nil, |
| + videoSetting: events.videoSetting == .auto ? nil : events.videoSetting.rawValue) |
| } |
| let ids = Set(samples.keys).union(events.peers.keys).sorted() |
| var peers: [QualityPeer] = [] |
| @@ -912,6 +943,8 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| if e.screenStalled { events.screenStalled = true } |
| events.autoRestarts = steps(e.autoRestarts) |
| events.autoRebuilds = steps(e.autoRebuilds) |
| + events.askedSeconds = VideoTime.seconds(e.video.asked) |
| + events.sentSeconds = VideoTime.seconds(e.video.sent) |
| if events != QualityPeerEvents() { peer.events = events } |
| // The sharer's recovery steps toward this peer belong with the screen |
| // going out to them, even in a window where it sent nothing. |
diff --git a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift| index 5373be3..4471434 100644 |
| --- a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift |
| +++ b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift |
| @@ -55,6 +55,9 @@ struct EncodingPlan: Equatable { |
| var bitratePriority = 1.0 |
| var highPriority = false |
| var degradation: Degradation? |
| + /// Whether the encoding sends at all (spec §15.30: a receiver that asked |
| + /// for audio only gets no camera). True everywhere else. |
| + var active = true |
| } |
| /// The sender parameters for a screen and for the camera beside it. |
| @@ -253,6 +256,7 @@ extension RTCRtpSender { |
| encoding.scaleResolutionDownBy = NSNumber(value: plan.scaleResolutionDownBy ?? 1) |
| encoding.bitratePriority = plan.bitratePriority |
| encoding.networkPriority = plan.highPriority ? .high : .low |
| + encoding.isActive = plan.active |
| switch plan.degradation { |
| case .maintainResolution?: |
| parameters.degradationPreference = NSNumber(value: RTCDegradationPreference.maintainResolution.rawValue) |
| @@ -273,7 +277,7 @@ extension RTCRtpSender { |
| return [ |
| e.maxBitrateBps?.stringValue, e.maxFramerate?.stringValue, e.scaleResolutionDownBy?.stringValue, |
| String(e.bitratePriority), String(e.networkPriority.rawValue), |
| - parameters.degradationPreference?.stringValue, |
| + parameters.degradationPreference?.stringValue, String(e.isActive), |
| ].map { $0 ?? "-" }.joined(separator: ",") |
| } |
| } |
diff --git a/native/apple/Sources/CallsKit/VideoAdapt.swift b/native/apple/Sources/CallsKit/VideoAdapt.swift| new file mode 100644 |
| index 0000000..66aec3e |
| --- /dev/null |
| +++ b/native/apple/Sources/CallsKit/VideoAdapt.swift |
| @@ -0,0 +1,408 @@ |
| +import Foundation |
| + |
| +/// Spec §15.30 (2026-10-28): adaptive video, room.js's `adapt*` twins |
| +/// number for number (test/browser/room-adapt.test.mjs and VideoAdaptTests |
| +/// hold both). |
| +/// |
| +/// Paul, after a Dublin–London call whose guest was on café Wi-Fi, relayed, |
| +/// at 840–1300 ms round trips and up to seven freezes every thirty seconds: |
| +/// "Low-bandwidth with auto-switching up and down." It is a mesh, so every |
| +/// pair has its own sender, and the one who can see the trouble is the |
| +/// receiver. Each receiver watches what arrives from each sender and asks |
| +/// that sender, in its own media report, for one of these levels; the |
| +/// sender sets that one connection's sender parameters. Audio is never |
| +/// touched; a shared screen keeps its size, loses frame rate first, and is |
| +/// never paused, and while one is going the camera gives way first. |
| +public enum VideoLevel: Int, CaseIterable, Comparable, Sendable { |
| + case normal, reduced, minimal, audio |
| + |
| + /// The wire's word; normal is never sent (it is the absence of an entry). |
| + public var wire: String { |
| + switch self { |
| + case .normal: return "normal" |
| + case .reduced: return "reduced" |
| + case .minimal: return "minimal" |
| + case .audio: return "audio" |
| + } |
| + } |
| + |
| + init?(wire: String) { |
| + guard let level = Self.allCases.first(where: { $0.wire == wire }), level != .normal else { return nil } |
| + self = level |
| + } |
| + |
| + public static func < (a: Self, b: Self) -> Bool { a.rawValue < b.rawValue } |
| +} |
| + |
| +/// The person's own "Video quality", in the device panel and remembered: |
| +/// Auto leaves it to the watch, Low bandwidth asks everyone for minimal, |
| +/// Audio only asks everyone for no video and sends no camera to anyone. |
| +public enum VideoQualitySetting: String, CaseIterable, Identifiable, Sendable { |
| + case auto, low, audio |
| + |
| + public var id: String { rawValue } |
| + |
| + public var title: String { |
| + switch self { |
| + case .auto: return "Auto" |
| + case .low: return "Low bandwidth" |
| + case .audio: return "Audio only" |
| + } |
| + } |
| + |
| + public static let explanation = |
| + "Auto lowers video when a connection is weak and raises it again when it recovers. Low bandwidth asks everyone for small video. Audio only pauses video both ways, to keep sound clear." |
| + |
| + /// The lowest level asked of anyone while this is chosen. |
| + var floor: VideoLevel { |
| + switch self { |
| + case .auto: return .normal |
| + case .low: return .minimal |
| + case .audio: return .audio |
| + } |
| + } |
| + |
| + static let key = "videoQuality" |
| + |
| + /// The remembered choice, Auto until someone picks another. |
| + public static var remembered: VideoQualitySetting { |
| + get { UserDefaults.standard.string(forKey: key).flatMap(Self.init(rawValue:)) ?? .auto } |
| + set { UserDefaults.standard.set(newValue.rawValue, forKey: key) } |
| + } |
| +} |
| + |
| +/// One sender's watch, on the receiving side: down quickly, up slowly, and |
| +/// a probe up that fails doubling the wait before the next. |
| +struct VideoAdapt: Equatable, Sendable { |
| + // The thresholds, as room.js has them (ADAPT_*). |
| + static let window = 10.0 // s: the trouble window, and the time at a level before a step down |
| + static let severeAfter = 5.0 // s: severe trouble steps two levels after this long |
| + static let downFreezes = 2.0 // camera freezes in the window |
| + static let downFreezeSeconds = 2.0 // seconds frozen in the window |
| + static let downKeyframeAsks = 3.0 // PLIs and FIRs this side sent for the camera |
| + static let downLoss = 0.05 // of all inbound packets |
| + static let downRTT = 600.0 // ms, with at least one freeze |
| + static let downJitterBuffer = 500.0 // ms, the audio jitter buffer's mean delay |
| + static let downDropped = 0.25 // frames dropped, of decoded and dropped, |
| + static let downDroppedMin = 10.0 // at least this many |
| + static let severeFreezes = 5.0 |
| + static let severeFreezeSeconds = 4.0 |
| + static let severeLoss = 0.15 |
| + static let cleanLoss = 0.02 // a clean second: no freeze, loss at most this, |
| + static let cleanRTT = 400.0 // a round trip under this, |
| + static let cleanJitterBuffer = 300.0 // and the jitter buffer under this |
| + static let upAfter = 45.0 // s clean at a level, then probe one up |
| + 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 { |
| + var freezes = 0.0 |
| + var freezeSeconds = 0.0 |
| + var keyframeAsks = 0.0 |
| + var packets = 0.0 |
| + var lost = 0.0 |
| + var rtt: Double? |
| + 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 |
| + private var since: Double? |
| + private var samples: [(at: Double, sample: Sample)] = [] |
| + private var cleanSince: Double? |
| + let upBase: Double |
| + private(set) var upWait: Double |
| + private var probeAt: Double? |
| + private var probeFrom = VideoLevel.normal |
| + private(set) var downs = 0 |
| + private(set) var ups = 0 |
| + |
| + init(upAfter: Double = Self.upAfter) { |
| + upBase = upAfter |
| + upWait = upAfter |
| + } |
| + |
| + static func == (a: Self, b: Self) -> Bool { |
| + a.level == b.level && a.since == b.since && a.upWait == b.upWait && a.downs == b.downs && a.ups == b.ups |
| + } |
| + |
| + /// A window's sums: counts added, the round trip as their median (one |
| + /// 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? |
| + var loss: Double { packets + lost > 0 ? lost / (packets + lost) : 0 } |
| + } |
| + |
| + static func window(_ samples: [Sample]) -> Window { |
| + var w = Window() |
| + var rtts: [Double] = [] |
| + var jbs: [Double] = [] |
| + for x in samples { |
| + 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 |
| + w.dropped += x.dropped |
| + if let r = x.rtt { rtts.append(r) } |
| + if let j = x.jitterBufferMs { jbs.append(j) } |
| + } |
| + if !rtts.isEmpty { w.rtt = rtts.sorted()[rtts.count / 2] } |
| + if !jbs.isEmpty { w.jitterBuffer = jbs.reduce(0, +) / Double(jbs.count) } |
| + return w |
| + } |
| + |
| + enum Verdict: Equatable { case none, trouble, severe } |
| + |
| + static func verdict(_ w: Window) -> Verdict { |
| + if w.freezes >= severeFreezes || w.freezeSeconds >= severeFreezeSeconds || w.loss > severeLoss { |
| + return .severe |
| + } |
| + if w.freezes >= downFreezes || w.freezeSeconds >= downFreezeSeconds || w.loss > downLoss |
| + || 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)) |
| + { |
| + return .trouble |
| + } |
| + return .none |
| + } |
| + |
| + static func clean(_ x: Sample) -> Bool { |
| + let n = x.packets + x.lost |
| + 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) |
| + } |
| + |
| + private mutating func move(to next: VideoLevel, at now: Double, up: Bool) { |
| + if up { ups += 1 } else { downs += 1 } |
| + level = next |
| + since = now |
| + samples = [] |
| + cleanSince = nil |
| + if !up { probeAt = nil } |
| + } |
| + |
| + /// One look, about once a second (`now` in seconds), with that second's |
| + /// sample or nil for none: a connection that is down is §15.28's to |
| + /// mend and says nothing about the link. Returns the level. |
| + @discardableResult mutating func observe(at now: Double, _ sample: Sample?) -> VideoLevel { |
| + if since == nil { since = now } |
| + guard let sample else { return level } |
| + samples.append((now, sample)) |
| + samples.removeAll { $0.at <= now - Self.window } |
| + let observed = now - (since ?? now) |
| + let verdict = Self.verdict(Self.window(samples.map(\.sample))) |
| + if Self.clean(sample) { |
| + if cleanSince == nil { cleanSince = now } |
| + } else { |
| + cleanSince = nil |
| + } |
| + if let probeAt { |
| + if now - probeAt < Self.probeWatch { |
| + if verdict != .none, observed >= Self.probeJudge { |
| + upWait = min(upWait * 2, Self.upMax) |
| + move(to: probeFrom, at: now, up: false) |
| + return level |
| + } |
| + } else { |
| + self.probeAt = nil |
| + upWait = upBase |
| + } |
| + } |
| + if verdict == .severe, observed >= Self.severeAfter, level < .audio { |
| + move(to: VideoLevel(rawValue: min(VideoLevel.audio.rawValue, level.rawValue + 2)) ?? .audio, at: now, up: false) |
| + return level |
| + } |
| + if verdict != .none, observed >= Self.window, level < .audio, let next = VideoLevel(rawValue: level.rawValue + 1) { |
| + move(to: next, at: now, up: false) |
| + return level |
| + } |
| + if level > .normal, let cleanSince, now - cleanSince >= upWait, let next = VideoLevel(rawValue: level.rawValue - 1) { |
| + let from = level |
| + move(to: next, at: now, up: true) |
| + probeAt = now |
| + probeFrom = from |
| + } |
| + return level |
| + } |
| + |
| + // MARK: - What arrives, one second of it |
| + |
| + /// One second from two readings of the quality report's counters: camera |
| + /// freezes and keyframe asks only while the camera is watched (on, and |
| + /// the app in front — a still screen's gaps and an unseen tile's frames |
| + /// are not freezes), packets and loss across audio, camera and screen, |
| + /// the round trip, the audio jitter buffer, and frames decoded and |
| + /// dropped. Nil when nothing at all arrived and nothing was measured. |
| + static func sample(_ now: QualityCounters, _ before: QualityCounters?, cameraWatched: Bool) -> Sample? { |
| + func d(_ a: Double?, _ b: Double?) -> Double { QualityReportBuilder.delta(a, b) ?? 0 } |
| + var s = Sample() |
| + s.packets = |
| + d(now.inAudio?.packets, before?.inAudio?.packets) + d(now.inVideo?.packets, before?.inVideo?.packets) |
| + + d(now.inScreen?.packets, before?.inScreen?.packets) |
| + s.lost = |
| + d(now.inAudio?.lost, before?.inAudio?.lost) + d(now.inVideo?.lost, before?.inVideo?.lost) |
| + + d(now.inScreen?.lost, before?.inScreen?.lost) |
| + s.rtt = now.rtt |
| + if s.packets + s.lost == 0, s.rtt == nil { return nil } |
| + if cameraWatched { |
| + s.freezes = d(now.inVideo?.freezes, before?.inVideo?.freezes) |
| + s.freezeSeconds = d(now.inVideo?.freezeSeconds, before?.inVideo?.freezeSeconds) |
| + s.keyframeAsks = d(now.inVideo?.keyframeAsks, before?.inVideo?.keyframeAsks) |
| + } |
| + if let delay = QualityReportBuilder.delta(now.inAudio?.bufferDelay, before?.inAudio?.bufferDelay), |
| + let emitted = QualityReportBuilder.delta(now.inAudio?.emitted, before?.inAudio?.emitted), emitted > 0 |
| + { |
| + s.jitterBufferMs = delay / emitted * 1000 |
| + } |
| + s.decoded = d(now.inVideo?.decoded, before?.inVideo?.decoded) + d(now.inScreen?.decoded, before?.inScreen?.decoded) |
| + s.dropped = d(now.inVideo?.dropped, before?.inVideo?.dropped) + d(now.inScreen?.dropped, before?.inScreen?.dropped) |
| + return s |
| + } |
| + |
| + // MARK: - What is asked, and what is sent |
| + |
| + /// The `video` report: every peer whose level — the watch's or the |
| + /// setting's, whichever is lower — is below normal, at most fifteen. |
| + static func asks(_ levels: [String: VideoLevel], setting: VideoQualitySetting) -> [String: String] { |
| + var out: [String: String] = [:] |
| + for (id, level) in levels.sorted(by: { $0.key < $1.key }) { |
| + let at = max(level, setting.floor) |
| + if at > .normal, out.count < 15 { out[id] = at.wire } |
| + } |
| + return out |
| + } |
| + |
| + /// What one peer's report asks of us. |
| + static func asked(_ media: PeerMedia?, me: String) -> VideoLevel { |
| + guard !me.isEmpty, let word = media?.video?[me] else { return .normal } |
| + return VideoLevel(wire: word) ?? .normal |
| + } |
| + |
| + // The sender's half, as room.js has it (ADAPT_CAMERA, ADAPT_SCREEN). |
| + static let reducedCamera = (bitrate: 350_000, fps: 15, long: 640.0, short: 360.0) |
| + static let minimalCamera = (bitrate: 120_000, fps: 8, long: 320.0, short: 180.0) |
| + static let reducedScreen = (bitrate: 1_200_000, fps: 10) |
| + static let minimalScreen = (bitrate: 500_000, fps: 5, long: 1280.0) |
| + |
| + /// The camera's encoding for one receiver at a level. While a screen |
| + /// goes out the camera gives way first: normal is the cap beside the |
| + /// screen (ScreenSendPolicy.camera), and every level below is one lower |
| + /// for the camera, so a receiver at minimal gets the screen and no |
| + /// camera. Fitted by the camera's long and short sides, so a portrait |
| + /// camera is boxed the right way round. |
| + static func camera(_ level: VideoLevel, sharing: Bool, width: Int = 640, height: Int = 480) -> EncodingPlan { |
| + let at = sharing && level > .normal ? VideoLevel(rawValue: min(3, level.rawValue + 1)) ?? .audio : level |
| + if at == .normal { return ScreenSendPolicy.camera(sharing: sharing, height: height) } |
| + let c = at == .reduced ? reducedCamera : minimalCamera |
| + let long = Double(max(width, height)) |
| + let short = Double(min(width, height)) |
| + let scale = max(1, long / c.long, short / c.short) |
| + var plan = EncodingPlan(maxBitrate: c.bitrate, maxFramerate: c.fps, scaleResolutionDownBy: scale > 1 ? scale : nil) |
| + plan.active = at != .audio |
| + return plan |
| + } |
| + |
| + /// The screen's plan for one receiver at a level: frame rate and bitrate |
| + /// lowered, the size kept, and only at minimal and below the long side |
| + /// brought to 1280; resolution held under pressure from then on. Never |
| + /// paused. The level-fit scale the plan carries (ScreenSendPolicy's H.264 |
| + /// rules) is kept whenever it is larger. |
| + static func screen(_ plan: EncodingPlan, _ level: VideoLevel, width: Int, height: Int) -> EncodingPlan { |
| + guard level > .normal else { return plan } |
| + var out = plan |
| + out.degradation = .maintainResolution |
| + out.active = true |
| + if level == .reduced { |
| + out.maxFramerate = reducedScreen.fps |
| + out.maxBitrate = min(plan.maxBitrate ?? reducedScreen.bitrate, reducedScreen.bitrate) |
| + } else { |
| + out.maxFramerate = minimalScreen.fps |
| + out.maxBitrate = min(plan.maxBitrate ?? minimalScreen.bitrate, minimalScreen.bitrate) |
| + let longest = Double(max(width, height)) |
| + let fit = longest > minimalScreen.long ? longest / minimalScreen.long : 1 |
| + let scale = max(plan.scaleResolutionDownBy ?? 1, fit) |
| + out.scaleResolutionDownBy = scale > 1 ? scale : nil |
| + } |
| + return out |
| + } |
| + |
| + /// An app older than this ignores a request: its video can only be hidden |
| + /// here, which saves this device's work and not the connection. |
| + static let minNativeVersion = "0.4.15" |
| + |
| + /// Whether a peer's client acts on a request: every browser (its page is |
| + /// the server's own), and an app from `minNativeVersion` on. |
| + static func honours(client: String?) -> Bool { |
| + guard let client, !client.isEmpty else { return true } |
| + let parts = client.split(separator: " ") |
| + guard parts.count == 2, ["mac", "iphone", "ipad"].contains(String(parts[0])) else { return false } |
| + return ClientVersion.compare(String(parts[1]), minNativeVersion) >= 0 |
| + } |
| + |
| + /// The sender's quiet notice, for the people it is sending less to. |
| + static func noticeWords(_ people: [(name: String, level: VideoLevel)]) -> String { |
| + guard !people.isEmpty else { return "" } |
| + let names = people.map(\.name) |
| + let list = names.count == 1 ? names[0] : names.dropLast().joined(separator: ", ") + " and " + names[names.count - 1] |
| + let weak = names.count == 1 ? "(their connection is weak)" : "(their connections are weak)" |
| + if people.allSatisfy({ $0.level >= .audio }) { return "Sending only audio to \(list) \(weak)" } |
| + return "Sending reduced video to \(list) \(weak)" |
| + } |
| + |
| + /// The tile's words at audio only. |
| + static let pausedWords = "Video paused to keep audio clear" |
| + static let oldAppWords = "Their app can’t send less video, so it’s only hidden here" |
| + static let badgeWord = "Low bandwidth" |
| +} |
| + |
| +/// §15.30's seconds at each level below normal, asked of and sent to each |
| +/// peer, for the quality report. |
| +struct VideoTime: Equatable, Sendable { |
| + var asked: [Double] = [0, 0, 0] |
| + var sent: [Double] = [0, 0, 0] |
| + |
| + mutating func add(asked a: VideoLevel, sent s: VideoLevel, seconds: Double) { |
| + if a > .normal { asked[a.rawValue - 1] += seconds } |
| + if s > .normal { sent[s.rawValue - 1] += seconds } |
| + } |
| + |
| + /// The report's arrays: three numbers, or nil when all are zero. |
| + static func seconds(_ v: [Double]) -> [Double]? { |
| + guard v.contains(where: { $0 > 0 }) else { return nil } |
| + return v.map { QualityReportBuilder.bound($0, QualityBounds.seconds) ?? 0 } |
| + } |
| +} |
diff --git a/native/apple/Sources/CallsKit/Wire.swift b/native/apple/Sources/CallsKit/Wire.swift| index 7f4157a..6703aef 100644 |
| --- a/native/apple/Sources/CallsKit/Wire.swift |
| +++ b/native/apple/Sources/CallsKit/Wire.swift |
| @@ -32,10 +32,16 @@ public struct PeerMedia: Decodable, Equatable, Sendable { |
| /// Nil (absent) is a client that does not say; empty is one that hears |
| /// nobody yet. |
| public let hearing: [String]? |
| + /// What it asks each sender for (spec §15.30): peer id to "reduced", |
| + /// "minimal" or "audio", only those below normal. Nil (absent) is normal |
| + /// from everyone, which is also what a client from before it means. Read |
| + /// leniently: a value of any other shape is taken as absent rather than |
| + /// costing the roster its decode. |
| + public let video: [String: String]? |
| public init( |
| muted: Bool, cameraOff: Bool, audioBlocked: Bool? = nil, noSoundFrom: [String]? = nil, |
| - screenStalled: [String]? = nil, hearing: [String]? = nil |
| + screenStalled: [String]? = nil, hearing: [String]? = nil, video: [String: String]? = nil |
| ) { |
| self.muted = muted |
| self.cameraOff = cameraOff |
| @@ -43,6 +49,22 @@ public struct PeerMedia: Decodable, Equatable, Sendable { |
| self.noSoundFrom = noSoundFrom |
| self.screenStalled = screenStalled |
| self.hearing = hearing |
| + self.video = video |
| + } |
| + |
| + private enum CodingKeys: String, CodingKey { |
| + case muted, cameraOff, audioBlocked, noSoundFrom, screenStalled, hearing, video |
| + } |
| + |
| + public init(from decoder: Decoder) throws { |
| + let c = try decoder.container(keyedBy: CodingKeys.self) |
| + muted = try c.decode(Bool.self, forKey: .muted) |
| + cameraOff = try c.decode(Bool.self, forKey: .cameraOff) |
| + audioBlocked = try c.decodeIfPresent(Bool.self, forKey: .audioBlocked) |
| + noSoundFrom = try c.decodeIfPresent([String].self, forKey: .noSoundFrom) |
| + screenStalled = try c.decodeIfPresent([String].self, forKey: .screenStalled) |
| + hearing = try c.decodeIfPresent([String].self, forKey: .hearing) |
| + video = (try? c.decodeIfPresent([String: String].self, forKey: .video)) ?? nil |
| } |
| } |
| public struct RoomState: Decodable { |
diff --git a/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift| new file mode 100644 |
| index 0000000..d05e51a |
| --- /dev/null |
| +++ b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift |
| @@ -0,0 +1,344 @@ |
| +import Foundation |
| +import XCTest |
| + |
| +@testable import CallsKit |
| + |
| +/// Spec §15.30: the receiver's watch (down fast, up slow, a failed probe |
| +/// doubling the wait), what a sender sends at each level (the camera giving |
| +/// way before a shared screen, a screen never paused), the media report's |
| +/// `video`, and the quality report's seconds — on a fake clock. The twin of |
| +/// test/browser/room-adapt.test.mjs, number for number. |
| +final class VideoAdaptTests: XCTestCase { |
| + typealias Sample = VideoAdapt.Sample |
| + |
| + private func clean( |
| + freezes: Double = 0, freezeSeconds: Double = 0, keyframeAsks: Double = 0, packets: Double = 100, |
| + lost: Double = 0, rtt: Double? = 80, jitterBufferMs: Double? = 60, decoded: Double = 30, dropped: Double = 0 |
| + ) -> Sample { |
| + Sample( |
| + freezes: freezes, freezeSeconds: freezeSeconds, keyframeAsks: keyframeAsks, packets: packets, lost: lost, |
| + rtt: rtt, jitterBufferMs: jitterBufferMs, decoded: decoded, dropped: dropped) |
| + } |
| + |
| + /// Trouble that is not severe: a freeze every four seconds. |
| + private func freezing(_ t: Int) -> Sample { clean(freezes: t % 4 == 0 ? 1 : 0) } |
| + |
| + /// Once a second from `from` to `to`; the seconds the level changed at. |
| + @discardableResult |
| + private func run(_ watch: inout VideoAdapt, _ from: Int, _ to: Int, _ at: (Int) -> Sample?) -> [[Int]] { |
| + var changes: [[Int]] = [] |
| + for t in from...to { |
| + let before = watch.level |
| + watch.observe(at: Double(t), at(t)) |
| + if watch.level != before { changes.append([t, watch.level.rawValue]) } |
| + } |
| + return changes |
| + } |
| + |
| + func testTheNumbersAreTheApprovedOnes() { |
| + XCTAssertEqual(VideoAdapt.upAfter, 45) |
| + XCTAssertEqual(VideoAdapt.upMax, 300) |
| + XCTAssertEqual(VideoAdapt.window, 10) |
| + XCTAssertEqual(VideoAdapt.probeWatch, 20) |
| + } |
| + |
| + func testTroubleThatLastsStepsDownEveryTenSecondsToAudioOnly() { |
| + var w = VideoAdapt() |
| + XCTAssertEqual(run(&w, 0, 60, freezing), [[10, 1], [20, 2], [30, 3]]) |
| + XCTAssertEqual(w.level, .audio) |
| + XCTAssertEqual(w.downs, 3) |
| + } |
| + |
| + func testSevereTroubleStepsTwoLevelsFiveSecondsIn() { |
| + var w = VideoAdapt() |
| + XCTAssertEqual(run(&w, 0, 12) { _ in self.clean(freezes: 2) }, [[5, 2], [10, 3]]) |
| + var lossy = VideoAdapt() |
| + XCTAssertEqual(run(&lossy, 0, 6) { _ in self.clean(packets: 80, lost: 20) }, [[5, 2]]) |
| + } |
| + |
| + func testOccasionalTroubleIsNotTrouble() { |
| + var rare = VideoAdapt() |
| + XCTAssertEqual(run(&rare, 0, 60) { t in self.clean(freezes: t % 11 == 0 ? 1 : 0) }, []) |
| + var lossy = VideoAdapt() |
| + XCTAssertEqual(run(&lossy, 0, 60) { _ in self.clean(packets: 97, lost: 3) }, []) |
| + var slow = VideoAdapt() |
| + XCTAssertEqual(run(&slow, 0, 60) { _ in self.clean(rtt: 900) }, []) |
| + } |
| + |
| + func testEachKindOfTroubleStepsDown() { |
| + let kinds: [(String, (Int) -> Sample)] = [ |
| + ("loss", { _ in self.clean(packets: 94, lost: 6) }), |
| + ("one freeze on a 700 ms round trip", { t in self.clean(freezes: t == 5 ? 1 : 0, rtt: 700) }), |
| + ("the jitter buffer", { _ in self.clean(jitterBufferMs: 650) }), |
| + ("frames dropped", { _ in self.clean(decoded: 20, dropped: 10) }), |
| + ("one long freeze", { t in self.clean(freezes: t == 5 ? 1 : 0, freezeSeconds: t == 5 ? 2.5 : 0) }), |
| + ("a keyframe asked for every three seconds", { t in self.clean(keyframeAsks: t % 3 == 0 ? 1 : 0) }), |
| + ] |
| + for (what, sample) in kinds { |
| + var w = VideoAdapt() |
| + XCTAssertEqual(run(&w, 0, 10, sample), [[10, 1]], what) |
| + } |
| + } |
| + |
| + func testTheRoundTripIsTheMedian() { |
| + var w = VideoAdapt() |
| + XCTAssertEqual( |
| + run(&w, 0, 30) { t in self.clean(freezes: t % 10 == 3 ? 1 : 0, rtt: t % 10 == 3 ? 2000 : 100) }, []) |
| + } |
| + |
| + func testNothingMeasuredIsNoNews() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 9, freezing) |
| + XCTAssertEqual(run(&w, 10, 40) { _ in nil }, []) |
| + XCTAssertEqual(w.level, .normal) |
| + XCTAssertNil(VideoAdapt.sample(QualityCounters(), QualityCounters(), cameraWatched: true)) |
| + } |
| + |
| + func testFreezesCountOnlyWhileTheCameraIsWatched() { |
| + var before = QualityCounters() |
| + before.inAudio = .init(packets: 100, lost: 1, bufferDelay: 3000, emitted: 48000) |
| + before.inVideo = .init(packets: 200, freezes: 1, freezeSeconds: 0.5, decoded: 100, dropped: 0, keyframeAsks: 1) |
| + before.inScreen = .init(packets: 50, lost: 0, decoded: 10) |
| + var now = before |
| + now.inAudio = .init(packets: 150, lost: 2, bufferDelay: 6360, emitted: 96000) |
| + now.inVideo = .init(packets: 290, freezes: 3, freezeSeconds: 2, decoded: 130, dropped: 1, keyframeAsks: 3) |
| + now.inScreen = .init(packets: 60, lost: 1, decoded: 11) |
| + now.rtt = 50 |
| + let s = VideoAdapt.sample(now, before, cameraWatched: true) |
| + XCTAssertEqual(s?.freezes, 2) |
| + XCTAssertEqual(s?.freezeSeconds, 1.5) |
| + XCTAssertEqual(s?.keyframeAsks, 2) |
| + XCTAssertEqual(s?.packets, 150) |
| + XCTAssertEqual(s?.lost, 2) |
| + XCTAssertEqual(s?.rtt, 50) |
| + XCTAssertEqual(s?.jitterBufferMs ?? 0, 70, accuracy: 0.01) |
| + XCTAssertEqual(s?.decoded, 31) |
| + XCTAssertEqual(s?.dropped, 1) |
| + let off = VideoAdapt.sample(now, before, cameraWatched: false) |
| + XCTAssertEqual(off?.freezes, 0) |
| + XCTAssertEqual(off?.keyframeAsks, 0) |
| + XCTAssertEqual(off?.packets, 150) |
| + } |
| + |
| + func testCleanSecondsStepUpAfterFortyFiveAndAgain() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 20, freezing) |
| + XCTAssertEqual(w.level, .minimal) |
| + XCTAssertEqual(run(&w, 21, 200) { _ in self.clean() }, [[66, 1], [112, 0]]) |
| + XCTAssertEqual(w.upWait, VideoAdapt.upAfter) |
| + } |
| + |
| + func testAKeyframeAskedForIsNotACleanSecond() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 10, freezing) |
| + XCTAssertEqual(run(&w, 11, 120) { t in self.clean(keyframeAsks: t == 30 ? 1 : 0) }, [[76, 0]]) |
| + } |
| + |
| + func testOneBadSecondResetsTheCleanRun() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 10, freezing) |
| + XCTAssertEqual(run(&w, 11, 120) { t in self.clean(lost: t == 40 ? 10 : 0) }, [[86, 0]]) |
| + } |
| + |
| + func testAFailedProbeStepsBackAndDoublesTheWaitToFiveMinutes() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 10, freezing) |
| + XCTAssertEqual(w.level, .reduced) |
| + var changes: [[Int]] = [] |
| + for t in 11...1200 { |
| + let before = w.level |
| + w.observe(at: Double(t), w.level == .normal ? clean(freezes: 1) : clean()) |
| + if w.level != before { changes.append([t, w.level.rawValue]) } |
| + } |
| + XCTAssertEqual(changes.filter { $0[1] == 0 }.map { $0[0] }, [56, 152, 338, 644, 950]) |
| + XCTAssertEqual(changes.filter { $0[1] == 1 }.map { $0[0] }, [61, 157, 343, 649, 955]) |
| + XCTAssertEqual(w.upWait, VideoAdapt.upMax) |
| + } |
| + |
| + func testTroubleAfterTheProbeWatchIsAnOrdinaryStepDown() { |
| + var w = VideoAdapt() |
| + run(&w, 0, 10, freezing) |
| + run(&w, 11, 56) { _ in self.clean() } |
| + XCTAssertEqual(w.level, .normal) |
| + XCTAssertEqual(run(&w, 57, 100) { t in t >= 80 ? self.freezing(t) : self.clean() }, [[84, 1], [94, 2]]) |
| + XCTAssertEqual(w.upWait, VideoAdapt.upAfter) |
| + } |
| + |
| + func testTheSettingIsAFloorAndOnlyLevelsBelowNormalAreAsked() { |
| + let a = String(repeating: "a", count: 32) |
| + let b = String(repeating: "b", count: 32) |
| + XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .auto), [b: "reduced"]) |
| + XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .low), [a: "minimal", b: "minimal"]) |
| + XCTAssertEqual(VideoAdapt.asks([a: .audio], setting: .low), [a: "audio"]) |
| + XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .audio), [a: "audio", b: "audio"]) |
| + XCTAssertEqual(VideoAdapt.asks([a: .normal], setting: .auto), [:]) |
| + var many: [String: VideoLevel] = [:] |
| + for i in 0..<20 { many[String(format: "%032x", i)] = .minimal } |
| + XCTAssertEqual(VideoAdapt.asks(many, setting: .auto).count, 15) |
| + } |
| + |
| + func testASenderReadsOnlyItsOwnIdAndTheWiresLevels() { |
| + let me = String(repeating: "a", count: 32) |
| + XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: me), .minimal) |
| + XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: "b"), .normal) |
| + XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "tiny"]), me: me), .normal) |
| + XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false), me: me), .normal) |
| + XCTAssertEqual(VideoAdapt.asked(nil, me: me), .normal) |
| + } |
| + |
| + func testTheCameraAtEachLevel() { |
| + XCTAssertEqual(VideoAdapt.camera(.normal, sharing: false), EncodingPlan()) |
| + let reduced = VideoAdapt.camera(.reduced, sharing: false, width: 640, height: 480) |
| + XCTAssertEqual(reduced.maxBitrate, 350_000) |
| + XCTAssertEqual(reduced.maxFramerate, 15) |
| + XCTAssertEqual(reduced.scaleResolutionDownBy ?? 0, 480.0 / 360, accuracy: 1e-9) |
| + XCTAssertTrue(reduced.active) |
| + XCTAssertEqual(VideoAdapt.camera(.reduced, sharing: false, width: 720, height: 1280).scaleResolutionDownBy, 2) |
| + let minimal = VideoAdapt.camera(.minimal, sharing: false, width: 640, height: 480) |
| + XCTAssertEqual(minimal.maxBitrate, 120_000) |
| + XCTAssertEqual(minimal.maxFramerate, 8) |
| + XCTAssertEqual(minimal.scaleResolutionDownBy ?? 0, 480.0 / 180, accuracy: 1e-9) |
| + XCTAssertFalse(VideoAdapt.camera(.audio, sharing: false).active) |
| + } |
| + |
| + func testWhileSharingTheCameraGivesWayFirst() { |
| + XCTAssertEqual(VideoAdapt.camera(.normal, sharing: true), ScreenSendPolicy.camera(sharing: true)) |
| + let reduced = VideoAdapt.camera(.reduced, sharing: true) |
| + XCTAssertEqual(reduced.maxBitrate, 120_000) |
| + XCTAssertTrue(reduced.active) |
| + XCTAssertFalse(VideoAdapt.camera(.minimal, sharing: true).active) |
| + XCTAssertFalse(VideoAdapt.camera(.audio, sharing: true).active) |
| + } |
| + |
| + func testAScreenKeepsItsSizeLosesFrameRateFirstAndIsNeverPaused() { |
| + let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080) |
| + XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan) |
| + let reduced = VideoAdapt.screen(plan, .reduced, width: 1920, height: 1080) |
| + XCTAssertEqual(reduced.maxFramerate, 10) |
| + XCTAssertEqual(reduced.maxBitrate, 1_200_000) |
| + XCTAssertEqual(reduced.scaleResolutionDownBy, plan.scaleResolutionDownBy, "the size is kept") |
| + XCTAssertEqual(reduced.degradation, .maintainResolution) |
| + let minimal = VideoAdapt.screen(plan, .minimal, width: 1920, height: 1080) |
| + XCTAssertEqual(minimal.maxFramerate, 5) |
| + XCTAssertEqual(minimal.maxBitrate, 500_000) |
| + XCTAssertEqual(minimal.scaleResolutionDownBy, 1.5) |
| + let audio = VideoAdapt.screen(plan, .audio, width: 1920, height: 1080) |
| + XCTAssertEqual(audio, minimal) |
| + XCTAssertTrue(audio.active) |
| + // A level-fit scale larger than minimal's is kept (the H.264 rules). |
| + let capped = ScreenSendPolicy.screen(.motion, width: 3840, height: 2160, screencast: false) |
| + XCTAssertGreaterThanOrEqual( |
| + VideoAdapt.screen(capped, .minimal, width: 3840, height: 2160).scaleResolutionDownBy ?? 0, |
| + capped.scaleResolutionDownBy ?? 0) |
| + } |
| + |
| + func testBrowsersAndNewAppsHonourAnAsk() { |
| + XCTAssertTrue(VideoAdapt.honours(client: nil)) |
| + XCTAssertTrue(VideoAdapt.honours(client: "")) |
| + XCTAssertTrue(VideoAdapt.honours(client: "mac 0.4.15")) |
| + XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.14")) |
| + XCTAssertTrue(VideoAdapt.honours(client: "iphone 0.5")) |
| + XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.13")) |
| + XCTAssertFalse(VideoAdapt.honours(client: "native")) |
| + XCTAssertFalse(VideoAdapt.honours(client: "something else")) |
| + } |
| + |
| + func testTheSendersNotice() { |
| + XCTAssertEqual(VideoAdapt.noticeWords([]), "") |
| + XCTAssertEqual( |
| + VideoAdapt.noticeWords([("David", .minimal)]), "Sending reduced video to David (their connection is weak)") |
| + XCTAssertEqual(VideoAdapt.noticeWords([("David", .audio)]), "Sending only audio to David (their connection is weak)") |
| + XCTAssertEqual( |
| + VideoAdapt.noticeWords([("David", .reduced), ("Ana", .audio), ("Cy", .minimal)]), |
| + "Sending reduced video to David, Ana and Cy (their connections are weak)") |
| + } |
| + |
| + func testTheMediaReportReadsTheAsksLeniently() throws { |
| + let me = String(repeating: "a", count: 32) |
| + let ok = try JSONDecoder().decode( |
| + PeerMedia.self, from: Data(#"{"muted":false,"cameraOff":false,"video":{"\#(me)":"audio"}}"#.utf8)) |
| + XCTAssertEqual(ok.video, [me: "audio"]) |
| + let odd = try JSONDecoder().decode( |
| + PeerMedia.self, from: Data(#"{"muted":true,"cameraOff":false,"video":["\#(me)"],"hearing":[]}"#.utf8)) |
| + XCTAssertNil(odd.video, "a video member of another shape is taken as absent") |
| + XCTAssertEqual(odd.muted, true) |
| + XCTAssertEqual(odd.hearing, []) |
| + } |
| + |
| + func testTheQualityReportCarriesTheSecondsAtEachLevel() throws { |
| + var tally = QualityEventTally() |
| + tally.videoSetting = .low |
| + tally.video(asked: .minimal, sent: .normal, seconds: 1, for: "p") |
| + tally.video(asked: .minimal, sent: .reduced, seconds: 1.04, for: "p") |
| + tally.video(asked: .normal, sent: .normal, seconds: 1, for: "q") |
| + var builder = QualityReportBuilder() |
| + builder.start(at: 0) |
| + let report = builder.build( |
| + at: 30, samples: [:], events: &tally, client: QualityClient(app: "mac", version: "0.4.15"), devices: nil, |
| + final: false) |
| + let body = try XCTUnwrap(report.encoded()) |
| + XCTAssertTrue(body.contains(#""askedSeconds":[0,2,0]"#), body) |
| + XCTAssertTrue(body.contains(#""sentSeconds":[1,0,0]"#), body) |
| + 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/native/bridge/bridge.go b/native/bridge/bridge.go| index ad6586c..c730aaa 100644 |
| --- a/native/bridge/bridge.go |
| +++ b/native/bridge/bridge.go |
| @@ -166,6 +166,20 @@ func (c *Client) SetHearing(peersJSON string) error { |
| return c.room.SetHearing(ids) |
| } |
| +// SetVideo is spec §15.30: what this app, as a receiver, asks each sender |
| +// for, as a JSON object of peer id to "reduced", "minimal" or "audio". |
| +// Only peers asked for less than normal are listed; "{}" or "" is normal |
| +// from everyone. Reported with the rest of this app's media state. |
| +func (c *Client) SetVideo(asksJSON string) error { |
| + var asks map[protocol.PeerID]protocol.VideoLevel |
| + if asksJSON != "" { |
| + if err := json.Unmarshal([]byte(asksJSON), &asks); err != nil { |
| + return errors.New("invalid video asks") |
| + } |
| + } |
| + return c.room.SetVideo(asks) |
| +} |
| + |
| // SendQuality posts one quality report (spec §15.26), a |
| // protocol.QualityReport as JSON, with the hello's report token. It |
| // answers what became of it, as a word — gomobile hands Swift every error |
diff --git a/native/ios/Sources/CallsPhone.swift b/native/ios/Sources/CallsPhone.swift| index 8765504..258786a 100644 |
| --- a/native/ios/Sources/CallsPhone.swift |
| +++ b/native/ios/Sources/CallsPhone.swift |
| @@ -190,7 +190,9 @@ struct PhoneCall: View { |
| case .camera(let peer): |
| return PhoneVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), muted: call.isMuted(peer), |
| - cameraOff: call.isCameraOff(peer), cornerRadius: cornerRadius, compact: compact, |
| + cameraOff: call.isCameraOff(peer), lowBandwidth: call.isLowBandwidth(peer), |
| + videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil, |
| + cornerRadius: cornerRadius, compact: compact, |
| labelInsets: labelInsets, backdrop: backdrop, audio: call.tileAudio(peer), |
| onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer]) |
| } |
| @@ -400,6 +402,10 @@ struct PhoneVideoTile: View { |
| var muted = false |
| var mirrored = false |
| var cameraOff = false |
| + /// Spec §15.30: this app is asking them for less video ("Low |
| + /// bandwidth"), and, at audio only, the words in place of the picture. |
| + var lowBandwidth = false |
| + var videoPaused: String? = nil |
| /// A shared screen (§5.4), shown whole rather than cropped: on a phone |
| /// more than anywhere, cropping a laptop's screen to a portrait tile |
| /// would leave the middle third of it. |
| @@ -451,7 +457,7 @@ struct PhoneVideoTile: View { |
| .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| FixtureVideo(picture: fixturePicture, screen: screen) |
| - } else if let track, !cameraOff, placeholder == nil { |
| + } else if let track, !cameraOff, placeholder == nil, videoPaused == nil { |
| // A screen on the stage is fitted whole, and so is a camera of |
| // another shape than its tile (a landscape Mac on an upright |
| // phone); around it, the same picture soft and dimmed rather than |
| @@ -467,9 +473,9 @@ struct PhoneVideoTile: View { |
| .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else { |
| TilePlaceholder( |
| - symbol: cameraOff |
| + symbol: cameraOff || videoPaused != nil |
| ? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle", |
| - words: cameraOff || iconOnly ? nil : placeholder, wordsFont: .caption, spacing: 6, |
| + words: cameraOff || iconOnly ? nil : videoPaused ?? placeholder, wordsFont: .caption, spacing: 6, |
| reserve: labelBlock) |
| } |
| } |
| @@ -478,6 +484,7 @@ struct PhoneVideoTile: View { |
| TileAudioNotices(info) |
| HStack(spacing: 5) { |
| TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow) |
| + if lowBandwidth { LowBandwidthBadge(compact: compact) } |
| TileAudioStatus(info) |
| } |
| } |
| @@ -490,12 +497,16 @@ struct PhoneVideoTile: View { |
| .overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(8) } } |
| .clipShape(RoundedRectangle(cornerRadius: cornerRadius)) |
| .accessibilityElement(children: .ignore) |
| - .accessibilityLabel(stageLabel(tileAccessibilityLabel(label, muted: muted, audio: info), onStage: onStage, pinned: pinned)) |
| + .accessibilityLabel( |
| + stageLabel( |
| + tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""), |
| + onStage: onStage, pinned: pinned)) |
| .accessibilityHint(info?.detail ?? "") |
| .accessibilityValue( |
| cameraOff |
| ? "Camera off" |
| - : placeholder ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on")) |
| + : videoPaused ?? placeholder |
| + ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on")) |
| } |
| } |
| extension PhoneVideoTile { |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 8c8fc50..e74d97a 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -10,7 +10,7 @@ settings: |
| base: |
| SWIFT_VERSION: '5.0' |
| CODE_SIGN_STYLE: Automatic |
| - MARKETING_VERSION: '0.4.14' |
| + MARKETING_VERSION: '0.4.15' |
| CURRENT_PROJECT_VERSION: '1' |
| # The App Group the app and its broadcast extension share: the socket |
| # the iPhone's screen crosses lives in its container. One setting |
diff --git a/protocol/messages.go b/protocol/messages.go| index 8b9618b..3d452a5 100644 |
| --- a/protocol/messages.go |
| +++ b/protocol/messages.go |
| @@ -159,8 +159,41 @@ type MediaState struct { |
| // omitted only when nil (omitzero), and an empty list travels as []. |
| // At most MaxHearing, each a peer id, none repeated. |
| Hearing []PeerID `json:"hearing,omitzero"` |
| + // Video (spec §15.30, 2026-10-28): what this client, as a receiver, |
| + // asks each sender for — the level of video it can take from them over |
| + // its own connection to them, chosen by its automatic watch or by the |
| + // person's own "Video quality" setting. Only peers asked for less than |
| + // normal are listed; nil (absent) is "normal from everyone", which is |
| + // also what a client from before this section means. A sender that |
| + // reads its own id here sends that receiver less video, by sender |
| + // parameters alone; audio is never reduced. At most MaxVideo entries, |
| + // each a peer id with one of the VideoLevels. |
| + Video map[PeerID]VideoLevel `json:"video,omitempty"` |
| } |
| +// VideoLevel is what a receiver asks one sender for (spec §15.30). |
| +type VideoLevel string |
| + |
| +const ( |
| + // VideoReduced: the camera at most 640×360, 15 fps, about 350 kbit/s; |
| + // a shared screen at a lower frame rate, at full size. |
| + VideoReduced VideoLevel = "reduced" |
| + // VideoMinimal: the camera at most 320×180, 8 fps, about 120 kbit/s |
| + // (paused instead while a screen is shared); a shared screen at a few |
| + // frames a second, smaller if it must be. |
| + VideoMinimal VideoLevel = "minimal" |
| + // VideoAudio: no camera at all to this receiver. A shared screen is |
| + // never paused for it: it goes as at minimal. |
| + VideoAudio VideoLevel = "audio" |
| +) |
| + |
| +// VideoLevels are the values MediaState.Video may carry. Normal is never |
| +// sent: it is the absence of an entry. |
| +var VideoLevels = []VideoLevel{VideoReduced, VideoMinimal, VideoAudio} |
| + |
| +// MaxVideo bounds MediaState.Video, for the same reason as MaxNoSoundFrom. |
| +const MaxVideo = 15 |
| + |
| // MaxNoSoundFrom bounds MediaState.NoSoundFrom: a room holds at most |
| // sixteen participations (§4.2), so fifteen others is every one there |
| // could be. |
| @@ -183,7 +216,21 @@ func (m MediaState) Equal(o MediaState) bool { |
| return false |
| } |
| return samePeers(m.NoSoundFrom, o.NoSoundFrom) && samePeers(m.ScreenStalled, o.ScreenStalled) && |
| - samePeers(m.Hearing, o.Hearing) |
| + samePeers(m.Hearing, o.Hearing) && sameVideo(m.Video, o.Video) |
| +} |
| + |
| +// sameVideo compares two §15.30 asks as sets: an empty map and a nil one |
| +// both say "normal from everyone". |
| +func sameVideo(a, b map[PeerID]VideoLevel) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for k, v := range a { |
| + if w, ok := b[k]; !ok || w != v { |
| + return false |
| + } |
| + } |
| + return true |
| } |
| func samePeers(a, b []PeerID) bool { |
diff --git a/protocol/quality.go b/protocol/quality.go| index 04f6d66..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 { |
| @@ -86,8 +108,15 @@ type CallEvents struct { |
| Reconnecting *float64 `json:"reconnecting,omitempty"` // times "Reconnecting…" was shown |
| ReconnectingSeconds *float64 `json:"reconnectingSeconds,omitempty"` // for how long |
| AudioBlocked bool `json:"audioBlocked,omitempty"` |
| + // VideoSetting is the person's own "Video quality" choice (spec |
| + // §15.30), when it is not Auto: "low" (Low bandwidth) or "audio" |
| + // (Audio only). VideoSettings. |
| + VideoSetting string `json:"videoSetting,omitempty"` |
| } |
| +// VideoSettings are the values CallEvents.VideoSetting may carry. |
| +var VideoSettings = []string{"low", "audio"} |
| + |
| // PeerQuality is one remote peer's connection, from this side. |
| type PeerQuality struct { |
| // Peer is the remote peer's id as this client knows it. The server |
| @@ -273,8 +302,21 @@ type PeerEvents struct { |
| // rebuilt from nothing (a `reset`). Older servers drop both. |
| AutoRestarts *float64 `json:"autoRestarts,omitempty"` |
| AutoRebuilds *float64 `json:"autoRebuilds,omitempty"` |
| + // Adaptive video (spec §15.30) during the window, as seconds at each |
| + // level below normal in the order reduced, minimal, audio: AskedSeconds |
| + // is how long this client, receiving, asked the peer for each; SentSeconds |
| + // how long this client, sending, sent the peer less because the peer |
| + // asked. Exactly three numbers when present (VideoLevelCount), arrays |
| + // rather than six members because the largest line has to fit the |
| + // platform's 8 KB. Older servers drop both. |
| + AskedSeconds []*float64 `json:"askedSeconds,omitempty"` |
| + SentSeconds []*float64 `json:"sentSeconds,omitempty"` |
| } |
| +// VideoLevelCount is the length of PeerEvents.AskedSeconds and |
| +// SentSeconds: one number for each of VideoLevels. |
| +const VideoLevelCount = 3 |
| + |
| // ProblemReport is "Report a problem": what the person typed, and the |
| // text "Copy call diagnostics" would copy, with the people in the call |
| // named by short peer ids rather than their names. |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index 2f28740..2bbe12e 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -340,6 +340,96 @@ const consoleLines = new Map(); // label -> string[] |
| // `via` is the browser to open the context in, for the one scenario |
| // (autoplay) that needs a Chromium launched under a different policy. |
| +// downlinkCap is §15.30's thin link, for the lowbandwidth scenario: every |
| +// video frame arriving in this page passes a token bucket of `kbit/s` (2 s |
| +// of burst) or is dropped before the decoder — and after a drop, every |
| +// frame until a keyframe fits, which is what a decoder downstream of a |
| +// lossy link has to work with, and what makes it freeze and ask for one. |
| +// window.__capDownlink(kbps) sets the cap (0 lifts it) and answers how many |
| +// video receivers are behind it; window.__capCounts is what passed and what |
| +// was dropped. On the main thread, through insertable streams: every sender |
| +// and receiver of a connection made with them must be piped, so the |
| +// others pass straight through. The gate's, never the page's. |
| +function downlinkCap() { |
| + const Native = window.RTCPeerConnection; |
| + if (!Native || typeof RTCRtpSender === 'undefined' || !('createEncodedStreams' in RTCRtpSender.prototype)) return; |
| + const bucket = { cap: 0, tokens: 0, last: 0, lost: false, passed: 0, dropped: 0 }; |
| + let receivers = 0; |
| + const piped = new WeakSet(); |
| + window.__capCounts = bucket; |
| + window.__capDownlink = (kbps) => { |
| + bucket.cap = Number(kbps) || 0; |
| + bucket.tokens = bucket.cap * 125 * 2; |
| + bucket.last = performance.now(); |
| + bucket.lost = false; |
| + return receivers; |
| + }; |
| + const pass = (end) => { |
| + if (!end || piped.has(end)) return; |
| + piped.add(end); |
| + const { readable, writable } = end.createEncodedStreams(); |
| + readable.pipeTo(writable).catch(() => {}); |
| + }; |
| + const capped = (receiver) => { |
| + if (piped.has(receiver)) return; |
| + piped.add(receiver); |
| + const { readable, writable } = receiver.createEncodedStreams(); |
| + readable.pipeThrough(new TransformStream({ |
| + transform(f, c) { |
| + const b = bucket; |
| + if (!b.cap) { |
| + b.passed += 1; |
| + c.enqueue(f); |
| + return; |
| + } |
| + const now = performance.now(); |
| + b.tokens = Math.min(b.cap * 125 * 2, b.tokens + ((now - b.last) / 1000) * b.cap * 125); |
| + b.last = now; |
| + if (b.lost && f.type !== 'key') { |
| + b.dropped += 1; |
| + return; |
| + } |
| + if (b.tokens >= f.data.byteLength) { |
| + b.tokens -= f.data.byteLength; |
| + b.lost = false; |
| + b.passed += 1; |
| + c.enqueue(f); |
| + } else { |
| + b.lost = true; |
| + b.dropped += 1; |
| + } |
| + }, |
| + })).pipeTo(writable).catch(() => {}); |
| + receivers += 1; |
| + }; |
| + const insertable = (config) => Object.assign({}, config || {}, { encodedInsertableStreams: true }); |
| + window.RTCPeerConnection = class extends Native { |
| + constructor(config, ...rest) { |
| + super(insertable(config), ...rest); |
| + this.addEventListener('track', (ev) => { |
| + try { |
| + if (ev.track.kind === 'video') capped(ev.receiver); |
| + else pass(ev.receiver); |
| + if (ev.transceiver) pass(ev.transceiver.sender); |
| + } catch { |
| + // Piped already, or a connection closing. |
| + } |
| + }); |
| + } |
| + setConfiguration(config) { return super.setConfiguration(insertable(config)); } |
| + addTrack(...args) { |
| + const sender = super.addTrack(...args); |
| + try { pass(sender); } catch {} |
| + return sender; |
| + } |
| + addTransceiver(...args) { |
| + const tx = super.addTransceiver(...args); |
| + try { pass(tx.sender); } catch {} |
| + return tx; |
| + } |
| + }; |
| +} |
| + |
| async function newContext(label, { cookie = null, javaScriptEnabled = true, via = browser, options = {} } = {}) { |
| const ctx = await via.newContext({ javaScriptEnabled, ...options }); |
| if (cookie) { |
| @@ -416,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. |
| @@ -612,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, |
| @@ -4173,10 +4271,18 @@ const run = { |
| // after it was sent: "that peer is not here", arriving with a third |
| // of the message's budget left. |
| await ctxA.route('**/signal', async (route) => { |
| - if (!firstAt) firstAt = Date.now(); |
| - signals += 1; |
| const m = (route.request().postData() || '').match(/"type":"([a-z-]+)"/); |
| posted.push(m ? m[1] : '?'); |
| + // A media report is state on the broadcast lane, not part of the |
| + // recovery under test: §15.30's asks change when the picture from B |
| + // stops, and again when B is let go. It is answered like the rest |
| + // and not counted. |
| + if (m && m[1] === 'media') { |
| + await route.fulfill({ status: 404, contentType: 'application/json', body: '{"error":"not-found"}' }); |
| + return; |
| + } |
| + if (!firstAt) firstAt = Date.now(); |
| + signals += 1; |
| await sleep(20000); |
| await route.fulfill({ status: 404, contentType: 'application/json', body: '{"error":"not-found"}' }); |
| }); |
| @@ -4211,7 +4317,7 @@ const run = { |
| // scenario sent is the only thing A ever posted, and it is still the |
| // only thing ten seconds later. |
| const atDrop = signals; |
| - check(atDrop === 1, 'the offer was the only thing A posted (' + atDrop + ': ' + posted.join(', ') + ')'); |
| + check(atDrop === 1, 'the offer was the only message A posted (' + atDrop + ': ' + posted.join(', ') + ')'); |
| check(dropped && dropped.stale && dropped.stale.includes(pair.b.peer), |
| 'and A holds the target marked stale, waiting for a roster rather than asking again (' + |
| JSON.stringify(dropped && dropped.stale) + ')'); |
| @@ -6600,6 +6706,263 @@ const run = { |
| await ctxB.close(); |
| }, |
| + // Spec §15.30: adaptive video. B's downlink is capped — every video |
| + // frame arriving at B passes a token bucket in an encoded transform, so |
| + // what does not fit the cap is dropped before B's decoder, which is what |
| + // a thin link does to a picture — and B's watch has to ask A for less, |
| + // A has to send less, B's tile has to say so, and audio has to keep |
| + // arriving. Then the cap is lifted and B has to climb back: the first |
| + // step on the real 45 s, the rest on the gate's shortened wait. The |
| + // levels over time are printed, once a second, as the evidence. |
| + async lowbandwidth() { |
| + // What the gate's fake camera sends: about 100–300 kbit/s at normal and |
| + // reduced, 20–60 at minimal (measured 2026-10-28). The cap sits between. |
| + const CAP_KBPS = Number(process.env.CALLS_CAP_KBPS) || 60; |
| + const state = (page) => page.evaluate(() => window.meet.state()); |
| + const ctxA = await newContext('member A', { cookie: cookieA }); |
| + const ctxB = await newContext('member B', { cookie: cookieB }); |
| + await ctxB.addInitScript(downlinkCap); |
| + const pageA = await openRoom(ctxA); |
| + const pageB = await openRoom(ctxB); |
| + const pair = await assertPair(pageA, pageB, 'member A', 'member B'); |
| + if (!pair) return; |
| + const a = pair.a.peer; |
| + const b = pair.b.peer; |
| + const t0 = Date.now(); |
| + const timeline = []; |
| + let lastBytes = null; |
| + const look = async (what) => { |
| + const sa = await pageA.evaluate(() => window.meet.state()); |
| + const sb = await pageB.evaluate(() => window.meet.state()); |
| + const cap = await pageB.evaluate(() => window.__capCounts ? { passed: window.__capCounts.passed, dropped: window.__capCounts.dropped } : null); |
| + const x = sb.adapt[a] || {}; |
| + const y = sa.adapt[b] || {}; |
| + const row = { |
| + t: Math.round((Date.now() - t0) / 1000), what, |
| + bWatch: x.level, bAsks: x.asked, aSends: y.sent, |
| + aCamera: y.wire ? y.wire.cameraHeight + 'p@' + Math.round(y.wire.cameraFps || 0) : '-', |
| + bAudioIn: x.wire ? x.wire.audioPackets : 0, bFreezes: x.wire ? x.wire.videoFreezes : 0, |
| + notice: sa.videoNotice, aAsks: JSON.stringify(sa.videoAsks), bLast: x.last, |
| + cap, |
| + aKbps: y.wire && lastBytes ? Math.round(((y.wire.cameraBytes - lastBytes.bytes) * 8) / (Date.now() - lastBytes.at)) : 0, |
| + }; |
| + if (y.wire) lastBytes = { bytes: y.wire.cameraBytes, at: Date.now() }; |
| + timeline.push(row); |
| + line('levels ' + JSON.stringify(row)); |
| + return { sa, sb, row }; |
| + }; |
| + // A few seconds for A's camera to ramp up past what the cap carries. |
| + for (let i = 0; i < 6; i++) { |
| + await look('open'); |
| + await sleep(1000); |
| + } |
| + const capped = await pageB.evaluate((k) => window.__capDownlink(k), CAP_KBPS); |
| + check(capped, 'B’s video receivers are behind the downlink cap (' + capped + ')'); |
| + let down = null; |
| + for (let i = 0; i < 40 && !down; i++) { |
| + const { row } = await look('capped at ' + CAP_KBPS + ' kbit/s'); |
| + if (row.bAsks === 'minimal' || row.bAsks === 'audio') down = row; |
| + else await sleep(1000); |
| + } |
| + check(down, 'B, capped, asks A for minimal video within 40 s (' + JSON.stringify(timeline[timeline.length - 1]) + ')'); |
| + const firstDown = timeline.find((r) => r.bAsks !== 'normal' && r.what.startsWith('capped')); |
| + check(firstDown && firstDown.t - timeline.find((r) => r.what.startsWith('capped')).t <= 25, |
| + 'the first step down came within 25 s of the cap (' + JSON.stringify(firstDown) + ')'); |
| + // The sender's half, over the wire. |
| + const sent = await until(async () => { |
| + const { row } = await look('capped, sender'); |
| + return row.aSends === row.bAsks && row.aSends !== 'normal' ? row : false; |
| + }, 5000); |
| + check(sent, 'A sends B what B asks for (' + JSON.stringify(timeline[timeline.length - 1]) + ')'); |
| + // Minimal is a camera at 180 lines or fewer; audio only is none at all |
| + // (severe trouble at reduced steps two levels, straight there). |
| + if (down.bAsks === 'minimal') { |
| + const small = await until(async () => { |
| + const { sa } = await look('capped, encoder'); |
| + const w = sa.adapt[b] && sa.adapt[b].wire; |
| + return w && w.cameraHeight > 0 && w.cameraHeight <= 180 ? w : false; |
| + }, 15000); |
| + check(small, 'A’s camera to B is encoded at 180 lines or fewer (' + JSON.stringify(timeline[timeline.length - 1]) + ')'); |
| + } else { |
| + const idle = await until(async () => { |
| + const w1 = (await state(pageA)).adapt[b].wire; |
| + await sleep(2000); |
| + const w2 = (await state(pageA)).adapt[b].wire; |
| + return (await state(pageA)).adapt[b].cameraPaused && w2.cameraBytes - w1.cameraBytes < 2000 ? [w1.cameraBytes, w2.cameraBytes] : false; |
| + }, 12000); |
| + check(idle, 'A’s camera to B is paused at audio only, and sends nothing (' + JSON.stringify(idle) + ')'); |
| + } |
| + const notice = (await state(pageA)).videoNotice || ''; |
| + check(/^Sending (reduced video|only audio) to .+ \(their connection is weak\)$/.test(notice), |
| + 'A is told it is sending B less (' + notice + ')'); |
| + const badge = await pageB.evaluate((id) => { |
| + const el = document.querySelector('#tiles figure[data-tile="' + id + '"] .calls-tile-low'); |
| + return el && !el.hidden ? { text: el.textContent.trim(), label: el.getAttribute('aria-label') || '' } : null; |
| + }, a); |
| + check(badge && badge.text === 'Low bandwidth' && /less video/.test(badge.label), |
| + 'B’s tile for A says Low bandwidth, with words for a screen reader (' + JSON.stringify(badge) + ')'); |
| + const aBadge = await pageA.evaluate((id) => { |
| + const el = document.querySelector('#tiles figure[data-tile="' + id + '"] .calls-tile-low'); |
| + return { shown: !!(el && !el.hidden), asks: window.meet.state().videoAsks[id] || 'normal' }; |
| + }, b); |
| + check(aBadge.shown === (aBadge.asks !== 'normal'), |
| + 'A’s badge on B’s tile follows what A itself asks of B (' + JSON.stringify(aBadge) + ')'); |
| + const audioBefore = (await look('capped, audio')).row.bAudioIn; |
| + await sleep(3000); |
| + const audioAfter = (await look('capped, audio')).row.bAudioIn; |
| + check(audioAfter - audioBefore >= 100, 'audio from A keeps arriving at B (' + audioBefore + ' -> ' + audioAfter + ' packets in 3 s)'); |
| + const hears = await pageB.evaluate((id) => window.meet.state().hearingList.includes(id), a); |
| + check(hears, 'B still hears A'); |
| + // Lift the cap: the first step up on the real wait, counted from the |
| + // last step down or the last second that was not clean since, whichever |
| + // is later — at audio only nothing arrives to suffer, and a headless |
| + // freeze at minimal starts the clean run again, as it should. |
| + await pageB.evaluate(() => window.__capDownlink(0)); |
| + const levels = ['normal', 'reduced', 'minimal', 'audio']; |
| + const from = (await look('lifted')).row.bAsks; |
| + let lastDown = 0; |
| + for (let i = 1; i < timeline.length; i++) { |
| + if (levels.indexOf(timeline[i].bAsks) > levels.indexOf(timeline[i - 1].bAsks)) lastDown = timeline[i].t; |
| + } |
| + const unclean = (x) => !!x && (x.freezes > 0 || x.freezeSeconds > 0 || x.keyframeAsks > 0 || x.load || |
| + (x.packets + x.lost > 0 && x.lost / (x.packets + x.lost) > 0.02) || (x.rtt !== null && x.rtt >= 400)); |
| + const quietFrom = () => timeline.reduce((m, r) => (r.t > lastDown && unclean(r.bLast) ? Math.max(m, r.t) : m), lastDown); |
| + let up = null; |
| + while (!up && (Date.now() - t0) / 1000 - quietFrom() < 70) { |
| + await sleep(1000); |
| + const { row } = await look('lifted'); |
| + if (row.bAsks !== from) up = row; |
| + } |
| + const since = quietFrom(); |
| + const upAfter = up ? up.t - since : -1; |
| + check(up && levels.indexOf(up.bAsks) === levels.indexOf(from) - 1 && upAfter >= 43 && upAfter <= 62, |
| + 'B steps A’s video up one level 45–60 s after its last step down or trouble (' + from + ' -> ' + (up && up.bAsks) + |
| + ' ' + upAfter + ' s after ' + since + ' s; last step down at ' + lastDown + ' s)'); |
| + // The rest on a shortened wait, all the way back to normal. |
| + await pageB.evaluate(() => window.meet.adaptForTest({ upAfter: 4000 })); |
| + const normal = await until(async () => { |
| + const { row } = await look('lifted, short wait'); |
| + return row.bAsks === 'normal' && row.aSends === 'normal' ? row : false; |
| + }, 30000); |
| + check(normal, 'B climbs back to normal and A sends normal again (' + JSON.stringify(timeline[timeline.length - 1]) + ')'); |
| + const cleared = await pageB.evaluate((id) => { |
| + const el = document.querySelector('#tiles figure[data-tile="' + id + '"] .calls-tile-low'); |
| + return !el || el.hidden; |
| + }, a); |
| + check(cleared, 'the badge goes when B asks for normal again'); |
| + check(!(await state(pageA)).videoNotice, 'A’s notice is gone once B asks for normal'); |
| + check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')'); |
| + check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')'); |
| + await leaveRoom(pageA); |
| + await leaveRoom(pageB); |
| + await ctxA.close(); |
| + await ctxB.close(); |
| + }, |
| + |
| + // Spec §15.30: the person's own Video quality. Audio only on B: B asks |
| + // A for no video and stops sending its own camera; A's camera encoding |
| + // to B goes inactive, B's tile for A says the video is paused, A sees B |
| + // as camera off, and audio keeps flowing both ways. Low bandwidth asks |
| + // for minimal, and Auto goes back. The choice is remembered. |
| + async audioonly() { |
| + const full = (page) => page.evaluate(() => window.meet.state()); |
| + const ctxA = await newContext('member A', { cookie: cookieA }); |
| + const ctxB = await newContext('member B', { cookie: cookieB }); |
| + const pageA = await openRoom(ctxA); |
| + const pageB = await openRoom(ctxB); |
| + const pair = await assertPair(pageA, pageB, 'member A', 'member B'); |
| + if (!pair) return; |
| + const a = pair.a.peer; |
| + const b = pair.b.peer; |
| + await pageB.click('#devices-toggle'); |
| + const picker = pageB.locator('#pick-video-quality'); |
| + check(await pageB.getByLabel('Video quality', { exact: true }).count() === 1, 'the Devices panel has a Video quality picker, labelled'); |
| + const options = await pageB.locator('#pick-video-quality option').allTextContents(); |
| + check(JSON.stringify(options) === JSON.stringify(['Auto', 'Low bandwidth', 'Audio only']), |
| + 'its choices are Auto, Low bandwidth and Audio only (' + options + ')'); |
| + check(await picker.inputValue() === 'auto', 'Auto is the default'); |
| + |
| + await picker.selectOption('audio'); |
| + const asked = await until(async () => { |
| + const sa = await full(pageA); |
| + const x = sa.adapt[b] || {}; |
| + return x.sent === 'audio' && x.cameraPaused ? sa : false; |
| + }, 8000); |
| + check(asked, 'A pauses its camera to B when B asks for audio only (' + JSON.stringify((await full(pageA)).adapt[b]) + ')'); |
| + const idle = await until(async () => { |
| + const w1 = (await full(pageA)).adapt[b].wire; |
| + await sleep(2000); |
| + const w2 = (await full(pageA)).adapt[b].wire; |
| + return w2.cameraBytes - w1.cameraBytes < 2000 ? [w1.cameraBytes, w2.cameraBytes] : false; |
| + }, 12000); |
| + check(idle, 'A’s camera to B sends nothing (' + JSON.stringify(idle) + ')'); |
| + const cover = await pageB.evaluate((id) => { |
| + const el = document.querySelector('#tiles figure[data-tile="' + id + '"] .calls-tile-video-paused-cover'); |
| + return el && !el.hidden ? el.innerText.trim().replace(/\s+/g, ' ') : ''; |
| + }, a); |
| + check(cover === 'Video paused to keep audio clear', 'B’s tile for A says the video is paused, and nothing about an old app (' + cover + ')'); |
| + const bOff = await until(async () => { |
| + const m = (await full(pageA)).remoteMedia[b]; |
| + return m && m.cameraOff ? m : false; |
| + }, 5000); |
| + check(bOff, 'A sees B’s camera as off: B sends no camera to anyone'); |
| + const bSendsNothing = await until(async () => { |
| + const sb = await full(pageB); |
| + return sb.adapt[a] && sb.adapt[a].cameraPaused ? true : false; |
| + }, 5000); |
| + check(bSendsNothing, 'B’s own camera to A is paused'); |
| + const aIn1 = (await full(pageA)).adapt[b].wire.audioPackets; |
| + const bIn1 = (await full(pageB)).adapt[a].wire.audioPackets; |
| + await sleep(3000); |
| + const aIn2 = (await full(pageA)).adapt[b].wire.audioPackets; |
| + const bIn2 = (await full(pageB)).adapt[a].wire.audioPackets; |
| + check(aIn2 - aIn1 >= 100 && bIn2 - bIn1 >= 100, 'audio flows both ways (' + [aIn1, aIn2, bIn1, bIn2] + ')'); |
| + check(!(await state(pageA)).terminal && (await state(pageA)).connection[b] === 'connected', 'the connection was not rebuilt for it'); |
| + |
| + await picker.selectOption('low'); |
| + const low = await until(async () => { |
| + const x = (await full(pageA)).adapt[b] || {}; |
| + return x.sent === 'minimal' && !x.cameraPaused ? x : false; |
| + }, 8000); |
| + check(low, 'Low bandwidth asks A for minimal, and A’s camera to B is on again (' + JSON.stringify((await full(pageA)).adapt[b]) + ')'); |
| + const back = await until(async () => { |
| + const m = (await full(pageA)).remoteMedia[b]; |
| + return m && !m.cameraOff ? m : false; |
| + }, 5000); |
| + check(back, 'B’s camera goes to A again once B is no longer on Audio only'); |
| + check(await pageB.evaluate(() => JSON.parse(localStorage.getItem('meet.devices') || '{}').videoQuality) === 'low', |
| + 'the choice is remembered in this browser'); |
| + |
| + await picker.selectOption('auto'); |
| + const auto = await until(async () => ((await full(pageA)).adapt[b] || {}).sent === 'normal', 8000); |
| + check(auto, 'Auto asks A for normal again'); |
| + |
| + // 2026-10-29, the sender's own half: B's device under serious compute |
| + // pressure lowers B's own camera to everyone, by the same watch, |
| + // whatever A asks of it. |
| + await pageB.evaluate(() => window.meet.adaptForTest({ pressure: 'serious' })); |
| + const own = await until(async () => { |
| + const sb = await full(pageB); |
| + return sb.ownCamera === 'reduced' ? sb : false; |
| + }, 16000); |
| + check(own, 'serious pressure on B lowers B’s own camera a level, whatever A asks (' + (own && own.ownCamera) + |
| + ', A asks ' + (own && own.adapt[a].sent) + ')'); |
| + const lowered = await until(async () => { |
| + const h = (await full(pageB)).adapt[a].wire.cameraHeight; |
| + return h > 0 && h <= 360 ? h : false; |
| + }, 8000); |
| + check(lowered, 'B’s camera to A goes out at 360 lines or fewer (' + lowered + ')'); |
| + await pageB.evaluate(() => window.meet.adaptForTest({ pressure: 'nominal', upAfter: 2000 })); |
| + const calm = await until(async () => (await full(pageB)).ownCamera === 'normal', 10000); |
| + check(calm, 'calm again, B’s own camera goes back to normal'); |
| + check(errorsFor('member A') === '', 'no console errors in A (' + errorsFor('member A') + ')'); |
| + check(errorsFor('member B') === '', 'no console errors in B (' + errorsFor('member B') + ')'); |
| + await leaveRoom(pageA); |
| + await leaveRoom(pageB); |
| + await ctxA.close(); |
| + await ctxB.close(); |
| + }, |
| + |
| // The self view, in Chromium and in WebKit (2026-10-21: on an iPhone |
| // in Safari the floating self view was black for a whole call while |
| // the camera was being sent perfectly well). Every way the local |
diff --git a/test/browser/native.mjs b/test/browser/native.mjs| index a10abfd..4069def 100644 |
| --- a/test/browser/native.mjs |
| +++ b/test/browser/native.mjs |
| @@ -249,6 +249,57 @@ try { |
| assert.equal(sample.stats.peerConnections, 1, 'recovering the camera keeps the same peer connection'); |
| console.log('PASS a stalled camera was restarted and the far side kept its picture'); |
| } |
| + // Spec §15.30, the app as the sender: the browser's own Video quality |
| + // asks the app for minimal, and the app's camera to the browser drops to |
| + // 180 lines or fewer — measured where it arrives — then Audio only stops |
| + // it, and Auto brings it back, all without a new connection. |
| + if (mode === 'member') { |
| + const arriving = () => page.evaluate(async () => { |
| + let height = 0, bytes = 0; |
| + for (const pc of window.__nativeInteropPCs) { |
| + if (pc.connectionState === 'closed') continue; |
| + for (const r of (await pc.getStats()).values()) { |
| + if (r.type === 'inbound-rtp' && r.kind === 'video') { |
| + height = Math.max(height, r.frameHeight || 0); |
| + bytes += r.bytesReceived || 0; |
| + } |
| + } |
| + } |
| + return { height, bytes }; |
| + }); |
| + const pick = async (value) => { |
| + await page.evaluate((v) => { |
| + const panel = document.getElementById('room-devices'); |
| + if (panel && panel.hidden) document.getElementById('devices-toggle').click(); |
| + const el = document.getElementById('pick-video-quality'); |
| + el.value = v; |
| + el.dispatchEvent(new Event('change', { bubbles: true })); |
| + }, value); |
| + }; |
| + // What the app sends when nothing is asked of it, unless its own |
| + // watch holds its camera down (a busy gate machine: §15.30's sender |
| + // half, which the app reports as ownCameraLevel). |
| + const full = (await arriving()).height; |
| + console.log(`the app's camera arrives at ${full} lines before anything is asked; its own level ${sample?.stats.ownCameraLevel}`); |
| + await pick('low'); |
| + await wait(async () => (await arriving()).height > 0 && (await arriving()).height <= 180, |
| + 'the app sends its camera at 180 lines or fewer when the browser asks for minimal', 20); |
| + const low = (await arriving()).height; |
| + console.log(`PASS the app applies a requested level: its camera arrives at ${low} lines, from ${full}`); |
| + await pick('audio'); |
| + await new Promise(r => setTimeout(r, 3000)); |
| + const paused = (await arriving()).bytes; |
| + await new Promise(r => setTimeout(r, 3000)); |
| + assert.ok((await arriving()).bytes - paused < 3000, 'the app sends no camera to a browser that asks for audio only'); |
| + await wait(() => sample?.stats.audioBytesReceived > 0, 'audio still arrives at the app'); |
| + console.log('PASS the app pauses its camera for a browser on Audio only, and audio carries on'); |
| + await pick('auto'); |
| + // Back to what it sent before anything was asked, or more. |
| + await wait(async () => (await arriving()).height >= Math.min(full, 181) && (await arriving()).height > 0, |
| + 'the app sends its camera as before once the browser is back on Auto', 20); |
| + assert.equal(sample.stats.peerConnections, 1, 'changing levels keeps the same peer connection'); |
| + console.log('PASS the app goes back to full video for Auto, on the same connection'); |
| + } |
| // Chat is not replayed to a recipient whose stream is renewing (§6), and |
| // in this mode the stream renews every ten seconds, so a line that lands |
| // in a renewal's gap is lost by design. Since the camera steps above went |
diff --git a/test/browser/room-adapt.test.mjs b/test/browser/room-adapt.test.mjs| new file mode 100644 |
| index 0000000..dcb12c0 |
| --- /dev/null |
| +++ b/test/browser/room-adapt.test.mjs |
| @@ -0,0 +1,315 @@ |
| +// room-adapt.test.mjs — adaptive video (spec §15.30, 2026-10-28), gated |
| +// without a browser. |
| +// |
| +// node --test test/browser/room-adapt.test.mjs |
| +// |
| +// The receiver's watch (adaptStep and its helpers: down fast, up slow, a |
| +// probe up that fails doubling the wait), what a sender sends at each level |
| +// (the camera giving way before a shared screen, a screen never paused), |
| +// and the report's `video` member, lifted out of the shipped room.js by |
| +// name with the constants they read, on a fake clock. The apps' |
| +// VideoAdaptTests are the twin of these, number for number. |
| +import { test } from 'node:test'; |
| +import assert from 'node:assert/strict'; |
| +import { readFileSync } from 'node:fs'; |
| +import { fileURLToPath } from 'node:url'; |
| + |
| +const src = readFileSync(fileURLToPath(new URL('../../internal/calls/static/room.js', import.meta.url)), 'utf8'); |
| + |
| +function lift(name) { |
| + const start = src.indexOf('function ' + name + '('); |
| + assert.notEqual(start, -1, name + ' is not in room.js any more — this test is stale, not passing'); |
| + let depth = 0; |
| + for (let i = src.indexOf('{', start); i < src.length; i++) { |
| + if (src[i] === '{') depth += 1; |
| + else if (src[i] === '}') { |
| + depth -= 1; |
| + if (depth === 0) return src.slice(start, i + 1); |
| + } |
| + } |
| + assert.fail('unbalanced braces reading ' + name); |
| +} |
| +function liftConst(name) { |
| + const m = src.match(new RegExp('const ' + name + ' = ([^;]+);')); |
| + assert.ok(m, name + ' is not a const in room.js any more'); |
| + 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_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', '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 |
| +const r = new Function(CONSTS + '\n' + NAMES.map(lift).join('\n') + '; return { ' + NAMES.join(', ') + |
| + ', ADAPT_UP_AFTER, ADAPT_UP_MAX };')(); |
| + |
| +const P1 = 'a'.repeat(32); |
| +const P2 = 'b'.repeat(32); |
| + |
| +// Trouble that is not severe: a freeze every four seconds, two or three in |
| +// any ten. |
| +const freezing = (t) => clean({ freezes: t % 4 === 0 ? 1 : 0 }); |
| + |
| +// One second's sample: clean unless told otherwise. |
| +const clean = (o = {}) => Object.assign({ freezes: 0, freezeSeconds: 0, packets: 100, lost: 0, rtt: 80, |
| + jitterBufferMs: 60, decoded: 30, dropped: 0 }, o); |
| + |
| +// Once a second from `from` to `to` seconds (inclusive), each second's |
| +// sample from `at(t)`; the level after every look, and the seconds it |
| +// changed at. |
| +function run(rec, from, to, at) { |
| + const changes = []; |
| + for (let t = from; t <= to; t++) { |
| + const before = rec.level; |
| + r.adaptStep(rec, t * 1000, at(t)); |
| + if (rec.level !== before) changes.push([t, rec.level]); |
| + } |
| + return changes; |
| +} |
| + |
| +test('the numbers are the approved ones', () => { |
| + assert.equal(r.ADAPT_UP_AFTER, 45000); |
| + assert.equal(r.ADAPT_UP_MAX, 300000); |
| +}); |
| + |
| +test('trouble that lasts steps down one level every ten seconds, to audio only, and no further', () => { |
| + const rec = r.adaptRecord(); |
| + const seen = run(rec, 0, 60, freezing); |
| + assert.deepEqual(seen, [[10, 1], [20, 2], [30, 3]]); |
| + assert.equal(rec.level, 3); |
| + assert.equal(rec.downs, 3); |
| +}); |
| + |
| +test('severe trouble steps two levels at once, five seconds in', () => { |
| + const rec = r.adaptRecord(); |
| + assert.deepEqual(run(rec, 0, 12, () => clean({ freezes: 2 })), [[5, 2], [10, 3]]); |
| + const lossy = r.adaptRecord(); |
| + assert.deepEqual(run(lossy, 0, 6, () => clean({ packets: 80, lost: 20 })), [[5, 2]]); |
| +}); |
| + |
| +test('a freeze now and then, a little loss, or a slow link alone is not trouble', () => { |
| + const rare = r.adaptRecord(); |
| + assert.deepEqual(run(rare, 0, 60, (t) => clean({ freezes: t % 11 === 0 ? 1 : 0 })), []); |
| + const lossy = r.adaptRecord(); |
| + assert.deepEqual(run(lossy, 0, 60, () => clean({ packets: 97, lost: 3 })), []); |
| + const slow = r.adaptRecord(); |
| + assert.deepEqual(run(slow, 0, 60, () => clean({ rtt: 900 })), []); |
| +}); |
| + |
| +test('loss over five percent, a slow link with freezes, a deep jitter buffer and dropped frames each step down', () => { |
| + for (const [what, sample] of [ |
| + ['loss', () => clean({ packets: 94, lost: 6 })], |
| + ['one freeze on a 700 ms round trip', (t) => clean({ rtt: 700, freezes: t === 5 ? 1 : 0 })], |
| + ['the jitter buffer', () => clean({ jitterBufferMs: 650 })], |
| + ['frames dropped', () => clean({ decoded: 20, dropped: 10 })], |
| + ['one long freeze', (t) => clean({ freezes: t === 5 ? 1 : 0, freezeSeconds: t === 5 ? 2.5 : 0 })], |
| + ['a keyframe asked for every three seconds', (t) => clean({ keyframeAsks: t % 3 === 0 ? 1 : 0 })], |
| + ]) { |
| + const rec = r.adaptRecord(); |
| + assert.deepEqual(run(rec, 0, 10, sample), [[10, 1]], what); |
| + } |
| +}); |
| + |
| +test('the round trip is the window median: one spike is not a slow link', () => { |
| + const rec = r.adaptRecord(); |
| + assert.deepEqual(run(rec, 0, 30, (t) => clean({ rtt: t % 10 === 3 ? 2000 : 100, freezes: t % 10 === 3 ? 1 : 0 })), []); |
| +}); |
| + |
| +test('a second with nothing measured is no news either way', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 9, freezing); |
| + assert.deepEqual(run(rec, 10, 40, () => null), []); |
| + assert.equal(rec.level, 0, 'a connection that is down says nothing about the link'); |
| + assert.equal(r.adaptSample({}, true), null); |
| + assert.equal(r.adaptSample({ in: { audio: { packets: 0 } } }, true), null); |
| +}); |
| + |
| +test('freezes count only while the camera is watched', () => { |
| + const q = { rtt: 50, in: { audio: { packets: 50, lost: 1, jitterBufferMs: 70 }, video: { packets: 90, freezes: 2, freezeSeconds: 1.5, decoded: 30, dropped: 1 }, |
| + screen: { packets: 10, lost: 1, decoded: 1 } } }; |
| + assert.deepEqual(r.adaptSample(q, true, 2), { freezes: 2, freezeSeconds: 1.5, keyframeAsks: 2, packets: 150, lost: 2, rtt: 50, jitterBufferMs: 70, decoded: 31, dropped: 1 }); |
| + const off = r.adaptSample(q, false, 2); |
| + assert.equal(off.freezes, 0); |
| + assert.equal(off.keyframeAsks, 0); |
| + assert.equal(off.freezeSeconds, 0); |
| + assert.equal(off.packets, 150); |
| +}); |
| + |
| +test('clean seconds step up one level after forty-five, and again after another forty-five', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 20, freezing); |
| + assert.equal(rec.level, 2); |
| + // Clean from 21 s: up at 21 + 45; the probe holds, and the next clean run |
| + // starts the second after the step, so up again at 67 + 45. |
| + const seen = run(rec, 21, 200, () => clean()); |
| + assert.deepEqual(seen, [[66, 1], [112, 0]]); |
| + assert.equal(rec.upWait, r.ADAPT_UP_AFTER, 'a probe that holds puts the wait back'); |
| +}); |
| + |
| +test('a keyframe asked for is not a clean second', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 10, freezing); |
| + const seen = run(rec, 11, 120, (t) => clean({ keyframeAsks: t === 30 ? 1 : 0 })); |
| + assert.deepEqual(seen, [[76, 0]]); |
| +}); |
| + |
| +test('one bad second resets the clean run', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 10, freezing); |
| + assert.equal(rec.level, 1); |
| + const seen = run(rec, 11, 120, (t) => clean({ lost: t === 40 ? 10 : 0, packets: 100 })); |
| + assert.deepEqual(seen, [[86, 0]], 'clean from 41 s, so up at 86 s'); |
| +}); |
| + |
| +test('a probe that fails within twenty seconds steps straight back and doubles the wait, to five minutes at most', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 10, freezing); |
| + assert.equal(rec.level, 1); |
| + // The link carries Reduced and not Normal: clean at 1, freezing at 0. |
| + const at = () => (rec.level === 0 ? clean({ freezes: 1 }) : clean()); |
| + const seen = run(rec, 11, 1200, at); |
| + const ups = seen.filter(([, l]) => l === 0).map(([t]) => t); |
| + const backs = seen.filter(([, l]) => l === 1).map(([t]) => t); |
| + // Up after 45 s clean, back 5 s later; then 90, 180, 300, 300 … of |
| + // clean seconds counted from the second after each step back. |
| + assert.deepEqual(ups, [56, 152, 338, 644, 950]); |
| + assert.deepEqual(backs, [61, 157, 343, 649, 955]); |
| + assert.equal(rec.upWait, r.ADAPT_UP_MAX); |
| +}); |
| + |
| +test('trouble after the probe watch is an ordinary step down, and the wait is back to its base', () => { |
| + const rec = r.adaptRecord(); |
| + run(rec, 0, 10, freezing); |
| + run(rec, 11, 56, () => clean()); |
| + assert.equal(rec.level, 0); |
| + const seen = run(rec, 57, 100, (t) => (t >= 80 ? freezing(t) : clean())); |
| + assert.deepEqual(seen, [[84, 1], [94, 2]], 'freezes at 80 and 84 s: the window is trouble at 84, and ten seconds on'); |
| + assert.equal(rec.upWait, r.ADAPT_UP_AFTER); |
| +}); |
| + |
| +test('the person’s own setting is a floor under the watch, and only levels below normal are asked', () => { |
| + const levels = new Map([[P1, 0], [P2, 1]]); |
| + assert.deepEqual(r.adaptAsks(levels, 'auto'), { [P2]: 'reduced' }); |
| + assert.deepEqual(r.adaptAsks(levels, 'low'), { [P1]: 'minimal', [P2]: 'minimal' }); |
| + assert.deepEqual(r.adaptAsks(new Map([[P1, 3]]), 'low'), { [P1]: 'audio' }); |
| + assert.deepEqual(r.adaptAsks(levels, 'audio'), { [P1]: 'audio', [P2]: 'audio' }); |
| + assert.deepEqual(r.adaptAsks(new Map([[P1, 0]]), 'auto'), {}); |
| + const many = new Map(Array.from({ length: 20 }, (_, i) => [i.toString(16).padStart(32, '0'), 2])); |
| + assert.equal(Object.keys(r.adaptAsks(many, 'auto')).length, 15); |
| +}); |
| + |
| +test('a sender reads only its own id, and only the wire’s levels', () => { |
| + assert.equal(r.askedOf({ video: { [P1]: 'minimal' } }, P1), 2); |
| + assert.equal(r.askedOf({ video: { [P1]: 'minimal' } }, P2), 0); |
| + assert.equal(r.askedOf({ video: { [P1]: 'tiny' } }, P1), 0); |
| + assert.equal(r.askedOf(null, P1), 0); |
| + assert.equal(r.askedOf({ muted: false }, P1), 0); |
| +}); |
| + |
| +test('the camera at each level, fitted by its long and short sides', () => { |
| + assert.deepEqual(r.cameraAtLevel(0, false, 640, 480), { maxFramerate: undefined, active: true, maxBitrate: undefined, scaleResolutionDownBy: 1 }); |
| + assert.deepEqual(r.cameraAtLevel(1, false, 640, 480), { maxBitrate: 350000, maxFramerate: 15, scaleResolutionDownBy: 480 / 360, active: true }); |
| + assert.deepEqual(r.cameraAtLevel(1, false, 1280, 720), { maxBitrate: 350000, maxFramerate: 15, scaleResolutionDownBy: 2, active: true }); |
| + // A portrait camera is boxed the right way round: 360 × 640 at most. |
| + assert.equal(r.cameraAtLevel(1, false, 720, 1280).scaleResolutionDownBy, 2); |
| + assert.deepEqual(r.cameraAtLevel(2, false, 640, 480), { maxBitrate: 120000, maxFramerate: 8, scaleResolutionDownBy: 480 / 180, active: true }); |
| + assert.equal(r.cameraAtLevel(3, false, 640, 480).active, false); |
| + // Unknown size: no scaling, the rest as the level says. |
| + assert.equal(r.cameraAtLevel(2, false, 0, 0).scaleResolutionDownBy, 1); |
| +}); |
| + |
| +test('while a screen is shared the camera gives way first', () => { |
| + // Normal: §5.4's cap beside the screen. |
| + assert.deepEqual(r.cameraAtLevel(0, true, 640, 720), Object.assign({ maxFramerate: undefined, active: true }, r.cameraCap(true, 720))); |
| + // Reduced asks the camera for minimal, and minimal for none. |
| + assert.equal(r.cameraAtLevel(1, true, 640, 480).maxBitrate, 120000); |
| + assert.equal(r.cameraAtLevel(1, true, 640, 480).active, true); |
| + assert.equal(r.cameraAtLevel(2, true, 640, 480).active, false); |
| + assert.equal(r.cameraAtLevel(3, true, 640, 480).active, false); |
| +}); |
| + |
| +test('a screen keeps its size and gives up frame rate first, is made smaller only at minimal, and is never paused', () => { |
| + const plan = r.sharePlan('balanced', 1920, 1080); |
| + assert.deepEqual(r.screenAtLevel(plan, 0, 1920, 1080), plan); |
| + const reduced = r.screenAtLevel(plan, 1, 1920, 1080); |
| + assert.equal(reduced.encoding.maxFramerate, 10); |
| + assert.equal(reduced.encoding.maxBitrate, 1200000); |
| + assert.equal(reduced.encoding.scaleResolutionDownBy, plan.encoding.scaleResolutionDownBy, 'the size is kept'); |
| + assert.equal(reduced.degradationPreference, 'maintain-resolution'); |
| + const minimal = r.screenAtLevel(plan, 2, 1920, 1080); |
| + assert.equal(minimal.encoding.maxFramerate, 5); |
| + assert.equal(minimal.encoding.maxBitrate, 500000); |
| + assert.equal(minimal.encoding.scaleResolutionDownBy, 1.5); |
| + const audio = r.screenAtLevel(plan, 3, 1920, 1080); |
| + assert.deepEqual(audio, minimal, 'audio only sends the screen as minimal does'); |
| + assert.notEqual(audio.encoding.active, false); |
| + // Motion's own smaller cap is kept where it is smaller still. |
| + const motion = r.sharePlan('motion', 3840, 2160); |
| + assert.equal(r.screenAtLevel(motion, 2, 3840, 2160).encoding.scaleResolutionDownBy, 3840 / 1280); |
| + // The plan it was given is not changed under it. |
| + assert.equal(plan.encoding.maxFramerate, 30); |
| +}); |
| + |
| +test('browsers and new apps act on an ask; an app that does not say, or an old one, does not', () => { |
| + assert.equal(r.honoursAsks(''), true); |
| + assert.equal(r.honoursAsks('mac 0.4.15'), true); |
| + assert.equal(r.honoursAsks('mac 0.4.14'), false); |
| + assert.equal(r.honoursAsks('iphone 0.5'), true); |
| + assert.equal(r.honoursAsks('mac 0.4.13'), false); |
| + assert.equal(r.honoursAsks('native'), false); |
| + assert.equal(r.honoursAsks('something else'), false); |
| +}); |
| + |
| +test('the sender’s notice names the people, and says audio only only when that is all it is', () => { |
| + assert.equal(r.adaptNoticeWords([]), ''); |
| + assert.equal(r.adaptNoticeWords([{ name: 'David', level: 2 }]), 'Sending reduced video to David (their connection is weak)'); |
| + assert.equal(r.adaptNoticeWords([{ name: 'David', level: 3 }]), 'Sending only audio to David (their connection is weak)'); |
| + assert.equal(r.adaptNoticeWords([{ name: 'David', level: 1 }, { name: 'Ana', level: 3 }, { name: 'Cy', level: 2 }]), |
| + 'Sending reduced video to David, Ana and Cy (their connections are weak)'); |
| +}); |
| + |
| +test('the report carries the seconds at each level, asked and sent, only when there were any', () => { |
| + assert.equal(r.withVideoTime(null, undefined), null); |
| + assert.deepEqual(r.withVideoTime(null, { asked: [0, 24.04, 0], sent: [0, 0, 0] }), { askedSeconds: [0, 24, 0] }); |
| + assert.deepEqual(r.withVideoTime({ noSound: true }, { asked: [0, 0, 0], sent: [5, 0, 1] }), { noSound: true, sentSeconds: [5, 0, 1] }); |
| + assert.equal(r.withVideoTime(null, { asked: [0, 0, 0], sent: [0, 0, 0] }), null); |
| +}); |
| + |
| +test('the media report carries the asks, and reads them back leniently', () => { |
| + const mine = { muted: false, cameraOff: false }; |
| + assert.deepEqual(r.mediaPayload(mine, false, [], false, [], [], { [P1]: 'minimal' }), |
| + { muted: false, cameraOff: false, hearing: [], video: { [P1]: 'minimal' } }); |
| + assert.deepEqual(r.mediaPayload(mine, false, [], false, [], [], {}), { muted: false, cameraOff: false, hearing: [] }); |
| + assert.deepEqual(r.mediaPayload(mine, false, [], true, [], [], { [P1]: 'minimal' }), mine, 'an old server gets the two keys'); |
| + const back = r.mediaFrom({ muted: false, cameraOff: false, video: { [P1]: 'audio', [P2]: 'tiny', short: 'minimal' } }); |
| + assert.deepEqual(back.video, { [P1]: 'audio' }); |
| + assert.equal(r.mediaFrom({ muted: false, cameraOff: false, video: [P1] }).video, undefined); |
| + // The same asks in another order are the same report; a level changed is not. |
| + const a = r.mediaKey({ muted: false, cameraOff: false, video: { [P1]: 'audio', [P2]: 'reduced' } }); |
| + const b = r.mediaKey({ muted: false, cameraOff: false, video: { [P2]: 'reduced', [P1]: 'audio' } }); |
| + const c = r.mediaKey({ muted: false, cameraOff: false, video: { [P2]: 'minimal', [P1]: 'audio' } }); |
| + assert.equal(a, b); |
| + 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); |
| +}); |
diff --git a/test/browser/room-mute.test.mjs b/test/browser/room-mute.test.mjs| index 9cf47d6..f54405e 100644 |
| --- a/test/browser/room-mute.test.mjs |
| +++ b/test/browser/room-mute.test.mjs |
| @@ -171,6 +171,12 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false }, |
| '\nlet mediaExtras = true;' + |
| '\nlet audioBlocked = false;' + |
| '\nlet screenStalled = [];' + |
| + // §15.30: the asks this tab makes, and the sender's half, which a |
| + // roster also runs; neither is under test here. |
| + '\nlet videoAsks = env.asks = {};' + |
| + '\nconst pcs = new Map();' + |
| + '\nconst answerVideoAsks = () => {};' + |
| + '\nconst markAdapt = () => {};' + |
| // §15.28: rosterMedia also records each peer's client. |
| '\nconst clients = env.clients = new Map();' + |
| '\nconst noSoundList = () => env.noSound;' + |