package main import ( "fmt" "io" "sort" "strconv" "strings" "amadan.net/oficina/calls/protocol" ) // The per-peer lines (spec §15.29, 2026-10-28): one `calls: quality peer` // line per report per remote peer, flat, so that `carlos logs` prints all // of it. This file reads them into what each side said about each other // side, and prints three things the head lines could never say: the path // each side took and the candidates behind it, and so whose network made a // relayed call relayed; each direction's camera and screen, as the sender // sent them and as the receiver got them; and the encoders and decoders. // side is what one person's client said about one remote peer, over every // window it reported. type side struct { windows, relayWindows int paths map[string]int regions map[string]bool // local is how often the selected pair's local end was the relay: // this side's own leg went through it. localRelay int // The candidates, at their most, and whether a kind of pair ever // worked. measured is false for a client before §15.29. measured bool host, srflx, prflx, relay float64 rHost, rSrflx, rPrflx, rRelay float64 directOK, localDirectOK, udpOK bool rttMax, jitterMax float64 rttAvgSum float64 rttAvgN int concealedMax, bufferMax float64 out, in map[string]*stream // "Camera", "Screen" // §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. type stream struct { windows int sizes map[string]int fpsSum, kbpsSum float64 fpsN, kbpsN int freezes, freezeSeconds float64 dropped float64 limits map[string]int limitedBW, limitedCPU float64 coders, codecs, modes map[string]bool stalls, rebuilds, other float64 } func newStream() *stream { return &stream{sizes: map[string]int{}, limits: map[string]int{}, coders: map[string]bool{}, codecs: map[string]bool{}, modes: map[string]bool{}} } func (c *call) addPeerLine(l line) { if l.Remote == "" { return } f := l.Fields key := [2]string{l.Peer, l.Remote} s := c.sides[key] if s == nil { s = &side{paths: map[string]int{}, regions: map[string]bool{}, out: map[string]*stream{}, in: map[string]*stream{}} c.sides[key] = s } s.windows++ num := func(k string) (float64, bool) { v, err := strconv.ParseFloat(f[k], 64) return v, err == nil } n := func(k string) float64 { v, _ := num(k); return v } if loc, rem := f["pathLocal"], f["pathRemote"]; loc != "" || rem != "" { s.paths[fmt.Sprintf("%s→%s %s", orDash(loc), orDash(rem), orDash(f["pathProtocol"]))]++ if loc == "relay" || rem == "relay" { s.relayWindows++ } if loc == "relay" { s.localRelay++ } } if r := f["relayRegion"]; r != "" { s.regions[r] = true } if _, ok := f["udpOk"]; ok { s.measured = true s.host, s.srflx, s.prflx, s.relay = max(s.host, n("candHost")), max(s.srflx, n("candSrflx")), max(s.prflx, n("candPrflx")), max(s.relay, n("candRelay")) s.rHost, s.rSrflx = max(s.rHost, n("candRemoteHost")), max(s.rSrflx, n("candRemoteSrflx")) s.rPrflx, s.rRelay = max(s.rPrflx, n("candRemotePrflx")), max(s.rRelay, n("candRemoteRelay")) s.directOK = s.directOK || f["directOk"] == "true" s.localDirectOK = s.localDirectOK || f["localDirectOk"] == "true" s.udpOK = s.udpOK || f["udpOk"] == "true" } s.rttMax = max(s.rttMax, n("rttMax"), n("rtt")) s.jitterMax = max(s.jitterMax, n("jitterMax")) if v, ok := num("rttAvg"); ok { s.rttAvgSum += v s.rttAvgN++ } 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"} { for dir, m := range map[string]map[string]*stream{"out": s.out, "in": s.in} { pre := dir + kind present := false for k := range f { if strings.HasPrefix(k, pre) { present = true break } } if !present { continue } st := m[kind] if st == nil { st = newStream() m[kind] = st } st.windows++ if w, h := n(pre+"Width"), n(pre+"Height"); w > 0 && h > 0 { st.sizes[fmt.Sprintf("%g×%g", w, h)]++ } if v, ok := num(pre + "Fps"); ok { st.fpsSum += v st.fpsN++ } if v, ok := num(pre + "Kbps"); ok { st.kbpsSum += v st.kbpsN++ } st.freezes += n(pre + "Freezes") st.freezeSeconds += n(pre + "FreezeSeconds") st.dropped += n(pre + "Dropped") if lim := f[pre+"Limit"]; lim != "" { st.limits[lim]++ } st.limitedBW += n(pre + "LimitedBandwidthSeconds") st.limitedCPU += n(pre + "LimitedCpuSeconds") for _, k := range []string{pre + "Encoder", pre + "Decoder"} { if v := f[k]; v != "" { st.coders[v] = true } } if v := f[pre+"Codec"]; v != "" { st.codecs[v] = true } if v := f[pre+"Mode"]; v != "" { st.modes[v] = true } st.stalls += n(pre + "Stalls") st.rebuilds += n(pre+"Rebuilds") + n(pre+"Reshares") st.other += n(pre + "Failures") } } } func set(m map[string]bool) string { var out []string for k := range m { out = append(out, k) } sort.Strings(out) return strings.Join(out, "/") } func most(m map[string]int) string { best, n := "", 0 for k, v := range m { if v > n || (v == n && k < best) { best, n = k, v } } return best } // dominantLimit is what held the encoder back over the call: by the // seconds the clients counted, where they did (§15.29), and otherwise the // reason most windows named. func (st *stream) dominantLimit() string { switch { case st.limitedBW > 0 || st.limitedCPU > 0: if st.limitedBW >= st.limitedCPU { return fmt.Sprintf("bandwidth (%.0f s; cpu %.0f s)", st.limitedBW, st.limitedCPU) } return fmt.Sprintf("cpu (%.0f s; bandwidth %.0f s)", st.limitedCPU, st.limitedBW) case len(st.limits) > 0: return most(st.limits) + " (most windows)" } return "" } func (st *stream) words(sent bool) string { var parts []string if sz := most(st.sizes); sz != "" { parts = append(parts, sz) } if st.fpsN > 0 { parts = append(parts, fmt.Sprintf("%.1f fps", st.fpsSum/float64(st.fpsN))) } if st.kbpsN > 0 { parts = append(parts, fmt.Sprintf("%.0f kbps", st.kbpsSum/float64(st.kbpsN))) } if sent { if lim := st.dominantLimit(); lim != "" { parts = append(parts, "limited by "+lim) } if m := set(st.modes); m != "" { parts = append(parts, "mode "+m) } if c := set(st.coders); c != "" { parts = append(parts, "encoder "+c) } if st.rebuilds+st.other > 0 { parts = append(parts, fmt.Sprintf("%g rebuilds/shares again, %g gave up", st.rebuilds, st.other)) } } else { parts = append(parts, fmt.Sprintf("freezes %g (%.1f s)", st.freezes, st.freezeSeconds)) if st.dropped > 0 { parts = append(parts, fmt.Sprintf("dropped %g", st.dropped)) } if st.stalls > 0 { parts = append(parts, fmt.Sprintf("stalls %g", st.stalls)) } if c := set(st.coders); c != "" { parts = append(parts, "decoder "+c) } } if c := set(st.codecs); c != "" { parts = append(parts, c) } return strings.Join(parts, ", ") } // candidates is a side's own summary in words. func (s *side) candidates() string { if !s.measured { return "not reported (a client from before 2026-10-28)" } yes := func(b bool) string { if b { return "yes" } return "no" } return fmt.Sprintf("gathered host %g, srflx %g, relay %g; offered host %g, srflx %g, relay %g; direct pair worked %s, own network reached out %s, UDP %s", s.host, s.srflx, s.relay, s.rHost, s.rSrflx, s.rRelay, yes(s.directOK), yes(s.localDirectOK), yes(s.udpOK)) } // whyRelayed is the verdict for a pair, a and b being the two sides' // accounts (either may be nil, for a client that sent no peer lines). The // strongest evidence first: a side that found no public address of its own // cannot have been reached directly; a side whose own leg was the relay is // the one that needed it; a pair where both found their addresses and // nothing direct worked is a NAT or a firewall that maps each destination // apart. func whyRelayed(an, bn string, a, b *side) string { noSrflx := func(s *side) bool { return s != nil && s.measured && s.srflx == 0 && s.prflx == 0 } onlyRelay := func(s *side) bool { return s != nil && s.measured && s.host == 0 && s.srflx == 0 && s.relay > 0 } ownLeg := func(s *side) bool { return s != nil && s.localRelay > 0 } var said []string for _, x := range []struct { name string s *side }{{an, a}, {bn, b}} { switch { case onlyRelay(x.s): said = append(said, x.name+" gathered only relay candidates (a relay-only policy, or a network that exposes nothing)") case noSrflx(x.s): said = append(said, x.name+" found no public address (no srflx candidate: UDP to the outside blocked)") case x.s != nil && x.s.measured && !x.s.udpOK: said = append(said, x.name+" had no pair work over UDP") } } switch { case (noSrflx(a) || onlyRelay(a)) && !(noSrflx(b) || onlyRelay(b)): said = append(said, "→ "+an+"'s network forced the relay") case (noSrflx(b) || onlyRelay(b)) && !(noSrflx(a) || onlyRelay(a)): said = append(said, "→ "+bn+"'s network forced the relay") case noSrflx(a) && noSrflx(b): said = append(said, "→ both networks forced it") case ownLeg(a) && !ownLeg(b): said = append(said, "→ "+an+"'s own leg went through the relay: "+an+"'s network is the likelier cause") case ownLeg(b) && !ownLeg(a): said = append(said, "→ "+bn+"'s own leg went through the relay: "+bn+"'s network is the likelier cause") case a != nil && a.measured && b != nil && b.measured && !a.directOK && !b.directOK: said = append(said, "→ both found public addresses and no direct pair worked: a NAT or firewall on one side maps each destination apart") case (a == nil || !a.measured) && (b == nil || !b.measured): said = append(said, "→ unknown: neither side reported its candidates") default: said = append(said, "→ not clear from the candidates") } return strings.Join(said, "; ") } // printSides prints the paths, the relay verdicts and the media, when // there are peer lines to print them from. func (c *call) printSides(out io.Writer) { if len(c.sides) == 0 { return } keys := make([][2]string, 0, len(c.sides)) for k := range c.sides { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { return keys[i][0]+keys[i][1] < keys[j][0]+keys[j][1] }) fmt.Fprintln(out, " Paths (each side's own account)") for _, k := range keys { s := c.sides[k] relay := fmt.Sprintf("relay %.0f%%", 100*float64(s.relayWindows)/float64(s.windows)) if r := set(s.regions); r != "" { relay += " via " + r } fmt.Fprintf(out, " %s → %s path %s, %s", short(k[0]), short(k[1]), orDash(most(s.paths)), relay) if s.rttAvgN > 0 { fmt.Fprintf(out, ", RTT avg %.0f ms", s.rttAvgSum/float64(s.rttAvgN)) } fmt.Fprintf(out, ", RTT max %.0f ms", s.rttMax) if s.jitterMax > 0 { fmt.Fprintf(out, ", jitter max %.0f ms", s.jitterMax) } if s.concealedMax > 0 || s.bufferMax > 0 { fmt.Fprintf(out, ", audio concealed up to %.1f%%, jitter buffer up to %.0f ms", s.concealedMax, s.bufferMax) } fmt.Fprintf(out, "\n %s's candidates: %s\n", short(k[0]), s.candidates()) } // Each unordered pair once, when either side saw the relay. var verdicts []string done := map[[2]string]bool{} for _, k := range keys { pair := [2]string{min(k[0], k[1]), max(k[0], k[1])} if done[pair] { continue } done[pair] = true a, b := c.sides[[2]string{pair[0], pair[1]}], c.sides[[2]string{pair[1], pair[0]}] if (a == nil || a.relayWindows == 0) && (b == nil || b.relayWindows == 0) { continue } verdicts = append(verdicts, fmt.Sprintf(" %s – %s %s", short(pair[0]), short(pair[1]), whyRelayed(short(pair[0]), short(pair[1]), a, b))) } if len(verdicts) > 0 { fmt.Fprintln(out, " Why relayed") for _, v := range verdicts { fmt.Fprintln(out, v) } } // Media, per direction: the sender's account of what it sent and the // receiver's of what arrived. dirs := map[[2]string]bool{} for _, k := range keys { dirs[k], dirs[[2]string{k[1], k[0]}] = true, true } ordered := make([][2]string, 0, len(dirs)) for k := range dirs { ordered = append(ordered, k) } sort.Slice(ordered, func(i, j int) bool { return ordered[i][0]+ordered[i][1] < ordered[j][0]+ordered[j][1] }) var media []string for _, k := range ordered { from, to := k[0], k[1] sent := c.sides[[2]string{from, to}] got := c.sides[[2]string{to, from}] for _, kind := range []string{"Camera", "Screen"} { var o, i *stream if sent != nil { o = sent.out[kind] } if got != nil { i = got.in[kind] } if o == nil && i == nil { continue } line := fmt.Sprintf(" %s → %s %s", short(from), short(to), strings.ToLower(kind)) if o != nil { line += " sent " + o.words(true) } if i != nil { line += " received " + i.words(false) } media = append(media, line) } } if len(media) > 0 { fmt.Fprintln(out, " Media (sender → receiver)") for _, m := range media { fmt.Fprintln(out, m) } } // §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) } } }