sipmon 0.1.5

Passive SIP/RTP signaling & media quality monitoring (pcap/live, TUI + JSONL export)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use std::collections::{HashMap, VecDeque};

use crate::diagnostics::Diagnostic;
use crate::model::media::StreamSummary;
use crate::model::sip::{Call, CallState, HangupBy, Method, Outcome, SipMsg};
use crate::store::ipstats::{IpStats, IpStatsStore};

/// Focused-call detail payload for the Call Detail page.
#[derive(Debug, Clone, Default)]
pub struct Focus {
    pub call_id: String,
    pub state: Option<CallState>,
    pub from_user: Option<String>,
    pub to_user: Option<String>,
    /// Caller-side UA string (User-Agent of the initial INVITE).
    pub caller_ua: Option<String>,
    /// Callee-side UA string (Server/User-Agent of the first response).
    pub callee_ua: Option<String>,
    /// Caller signaling address (src of the initial INVITE).
    pub caller_addr: Option<std::net::SocketAddr>,
    /// Caller signaling IP (from the initial INVITE; survives message trimming
    /// via the call's `invite_key`). Used to split media into TX/RX.
    pub caller_ip: Option<std::net::IpAddr>,
    /// Callee signaling address (src of the first response).
    pub callee_addr: Option<std::net::SocketAddr>,
    pub messages: Vec<SipMsg>,
    pub streams: Vec<StreamSummary>,
    pub diagnostics: Vec<Diagnostic>,
    pub negotiated_endpoints: Vec<std::net::SocketAddr>,
    /// Call timing / outcome details for the header block.
    pub pdd_ms: Option<u32>,
    pub setup_ms: Option<u32>,
    pub ring_ms: Option<u32>,
    /// True if early media (183 with SDP) was negotiated.
    pub early_media: bool,
    /// Milestone timestamps for the setup timeline (chrome-devtools-style).
    pub invite_ts: Option<u64>,
    pub trying_ts: Option<u64>,
    pub ringing_ts: Option<u64>,
    pub answer_ts: Option<u64>,
    pub bye_ts: Option<u64>,
    pub end_ts: Option<u64>,
    pub hangup_by: Option<HangupBy>,
    pub hangup_code: Option<u32>,
    pub hangup_reason: Option<String>,
}

/// One RTP/RTCP stream keyed by (5-tuple, ssrc).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StreamKey {
    pub flow: crate::model::packet::Flow5Tuple,
    pub ssrc: u32,
}

/// Recent-activity ordering helper.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CallSummary {
    pub call_id: String,
    pub from_user: Option<String>,
    pub to_user: Option<String>,
    /// Source IP of the initial INVITE (the caller side).
    pub caller_ip: Option<std::net::IpAddr>,
    pub state: CallState,
    pub outcome: Outcome,
    pub invite_ts: Option<u64>,
    pub duration_ms: Option<u64>,
    pub pdd_ms: Option<u32>,
    pub setup_ms: Option<u32>,
    /// Ringing duration (ring → answer).
    pub ring_ms: Option<u32>,
    /// Provisional code that started ringing: 180 or 183.
    pub ring_code: Option<u16>,
    /// True if early media (183 with SDP) was negotiated.
    pub early_media: bool,
    /// Who initiated the hangup.
    pub hangup_by: Option<HangupBy>,
    pub hangup_code: Option<u32>,
    pub pkts_sip: u64,
    pub pkts_rtp: u64,
    pub best_mos: Option<f64>,
    pub warn_count: u32,
    pub critical_count: u32,
    pub stream_count: usize,
    /// True if the call's media traversed a learned TURN relay.
    pub via_turn: bool,
    /// Distinct IPs involved in the call (drill-down from the IP page).
    pub ips: Vec<std::net::IpAddr>,
}

/// Lightweight immutable snapshot for the TUI/export.
#[derive(Debug, Clone, Default)]
pub struct Snapshot {
    pub source: String,
    pub elapsed_us: Option<u64>,
    pub pps: f64,
    pub pkts_total: u64,
    #[allow(dead_code)]
    pub pkts_dropped: u64,
    pub calls_total: u64,
    pub active: usize,
    pub completed: usize,
    pub failed: usize,
    pub avg_pdd_ms: f64,
    pub avg_setup_ms: f64,
    pub avg_jitter_ms: f64,
    pub avg_loss_pct: f64,
    pub avg_rtt_ms: f64,
    pub avg_mos: f64,
    pub asr: f64,
    pub calls: Vec<CallSummary>,
    pub streams: Vec<StreamSummary>,
    pub events: VecDeque<String>,
    /// Diagnostics for the focused call (filtered by the UI).
    pub diagnostics: Vec<Diagnostic>,
    /// Per-IP network stats (IP page).
    pub ip_stats: Vec<IpStats>,
    /// Heatmap cells: (bucket_us, key, metrics).
    pub buckets: Vec<(u64, String, crate::model::stats::MetricSet)>,
    /// Focused call detail (set by the UI via Correlator focus hint).
    pub focus: Option<Focus>,
    #[allow(dead_code)]
    pub paused: bool,
}

/// In-memory application state. Updated by the pipeline thread, snapshotted by
/// the UI/export thread.
pub struct Registry {
    pub calls: HashMap<String, Call>,
    /// Insertion order for stable recent-first listing.
    pub order: Vec<String>,
    pub streams: HashMap<StreamKey, crate::correlate::stream::RtpStream>,
    /// call_id per stream (reverse lookup).
    pub stream_call: HashMap<StreamKey, String>,
    /// SDP-advertised media endpoint -> call_id (for RTP association).
    pub endpoint_call: HashMap<std::net::SocketAddr, String>,
    pub events: VecDeque<String>,
    pub source: String,
    pub start_us: Option<u64>,
    pub last_us: Option<u64>,
    pub pkts_total: u64,
    #[allow(dead_code)]
    pub pkts_dropped: u64,
    pub pkts_last_window: u64,
    pub window_start_us: Option<u64>,
    pub pps: f64,
    pub completed: u64,
    pub failed: u64,
    /// Diagnostic ring buffer.
    pub diagnostics: VecDeque<Diagnostic>,
    /// Heatmap aggregation buckets.
    pub heatmap: crate::store::heatmap::Heatmap,
    /// UI focus hint: call id whose detail should be included in snapshots.
    pub focus_hint: Option<String>,
    /// Call-ids removed by eviction since the last drain (lets the correlator
    /// prune its own per-call maps like `invite_rr` / `terminal_done`, keeping
    /// long-running sessions bounded).
    pub removed: VecDeque<String>,
    /// Heatmap bucket window in microseconds (older buckets are pruned).
    pub heatmap_retain_us: u64,
    /// Per-call stream index (call_id -> stream keys): keeps per-packet and
    /// per-call paths O(streams-in-call) instead of O(total streams).
    pub stream_index: HashMap<String, Vec<StreamKey>>,
    /// SSRC -> stream keys: O(1) RTCP sample attachment (no full scan).
    pub ssrc_index: HashMap<u32, Vec<StreamKey>>,
    /// Per-IP packet/loss statistics (updated on the RTP hot path + 5s flush).
    pub ipstats: IpStatsStore,
    /// Stream summaries reconstructed from a replay/import (no RTP packets are
    /// re-fed then, so they come straight from the evlog's StreamSnap records).
    pub imported_streams: Vec<StreamSummary>,
    pub max_calls: usize,
    pub max_streams: usize,
    pub max_diagnostics: usize,
}

impl Default for Registry {
    fn default() -> Self {
        Self {
            calls: HashMap::new(),
            order: Vec::new(),
            streams: HashMap::new(),
            stream_call: HashMap::new(),
            endpoint_call: HashMap::new(),
            events: VecDeque::with_capacity(512),
            source: String::new(),
            start_us: None,
            last_us: None,
            pkts_total: 0,
            pkts_dropped: 0,
            pkts_last_window: 0,
            window_start_us: None,
            pps: 0.0,
            completed: 0,
            failed: 0,
            diagnostics: VecDeque::new(),
            heatmap: crate::store::heatmap::Heatmap::new(900),
            focus_hint: None,
            stream_index: HashMap::new(),
            ssrc_index: HashMap::new(),
            ipstats: IpStatsStore::new(),
            imported_streams: Vec::new(),
            removed: VecDeque::new(),
            heatmap_retain_us: 24 * 3600 * 1_000_000,
            max_calls: 100_000,
            max_streams: 50_000,
            max_diagnostics: 50_000,
        }
    }
}

impl Registry {
    pub fn with_source(source: String) -> Self {
        Self {
            source,
            ..Self::default()
        }
    }

    pub fn set_caps(&mut self, max_calls: usize, max_streams: usize, max_diagnostics: usize) {
        self.max_calls = max_calls;
        self.max_streams = max_streams;
        self.max_diagnostics = max_diagnostics;
    }

    pub fn set_bucket(&mut self, bucket_secs: u64) {
        let heat = std::mem::replace(
            &mut self.heatmap,
            crate::store::heatmap::Heatmap::new(bucket_secs),
        );
        if heat.bucket_secs() != bucket_secs {
            // Buckets are incompatible; rebuild empty (v1: heatmap is
            // forward-accumulating only).
        }
    }

    /// Reset all runtime state (the `x` / clear shortcut): calls, streams,
    /// diagnostics, events, heatmap, per-IP stats and counters. The evlog
    /// writer keeps its own file and is unaffected.
    pub fn clear(&mut self) {
        self.calls.clear();
        self.order.clear();
        self.streams.clear();
        self.stream_call.clear();
        self.endpoint_call.clear();
        self.stream_index.clear();
        self.ssrc_index.clear();
        self.events.clear();
        self.diagnostics.clear();
        self.heatmap = crate::store::heatmap::Heatmap::new(self.heatmap.bucket_secs());
        self.ipstats.clear();
        self.imported_streams.clear();
        self.pkts_total = 0;
        self.pkts_last_window = 0;
        self.window_start_us = None;
        self.start_us = None;
        self.last_us = None;
        self.pps = 0.0;
        self.completed = 0;
        self.failed = 0;
        self.focus_hint = None;
    }

    /// Record that `key` belongs to `call_id` (called on stream creation).
    pub fn note_stream(&mut self, call_id: &str, key: StreamKey) {
        self.stream_index
            .entry(call_id.to_string())
            .or_default()
            .push(key);
        self.ssrc_index.entry(key.ssrc).or_default().push(key);
    }

    /// Remove a stream key from the per-call index (and reverse maps).
    fn forget_stream(&mut self, key: &StreamKey) {
        if let Some(cid) = self.stream_call.remove(key)
            && let Some(v) = self.stream_index.get_mut(&cid)
        {
            v.retain(|k| k != key);
            if v.is_empty() {
                self.stream_index.remove(&cid);
            }
        }
        if let Some(v) = self.ssrc_index.get_mut(&key.ssrc) {
            v.retain(|k| k != key);
            if v.is_empty() {
                self.ssrc_index.remove(&key.ssrc);
            }
        }
    }

    /// Streams belonging to a call (empty slice if none).
    pub fn call_stream_keys(&self, call_id: &str) -> &[StreamKey] {
        self.stream_index
            .get(call_id)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// Drain the list of call-ids removed since last call.
    pub fn drain_removed(&mut self) -> Vec<String> {
        self.removed.drain(..).collect()
    }

    /// Prune heatmap buckets older than the retention window.
    pub fn prune_heatmap(&mut self) {
        if let Some(last) = self.last_us {
            let cutoff = last.saturating_sub(self.heatmap_retain_us);
            self.heatmap.prune_older_than(cutoff);
        }
    }

    /// Evict oldest *terminated* calls when above `max_calls`. Falls back to
    /// evicting the oldest active call only if all are still active.
    pub fn evict_if_needed(&mut self) {
        while self.calls.len() > self.max_calls {
            // Find oldest terminated call by invite_ts.
            let target = self
                .order
                .iter()
                .filter_map(|id| self.calls.get(id))
                .filter(|c| {
                    matches!(
                        c.state,
                        CallState::Completed | CallState::Failed | CallState::Canceled
                    )
                })
                .min_by_key(|c| c.invite_ts.unwrap_or(u64::MAX))
                .map(|c| c.call_id.clone());

            let cid = target
                .or_else(|| {
                    // All active; evict oldest by invite_ts.
                    self.order
                        .iter()
                        .filter_map(|id| self.calls.get(id))
                        .min_by_key(|c| c.invite_ts.unwrap_or(u64::MAX))
                        .map(|c| c.call_id.clone())
                })
                .unwrap_or_else(|| self.order.first().cloned().unwrap_or_default());

            if cid.is_empty() {
                break;
            }
            self.remove_call(&cid);
        }

        // Stream eviction.
        if self.streams.len() > self.max_streams {
            let mut keyed: Vec<(StreamKey, u64)> = self
                .streams
                .iter()
                .map(|(k, s)| (*k, s.first_ts_us.unwrap_or(u64::MAX)))
                .collect();
            keyed.sort_by_key(|(_, t)| *t);
            let to_remove: Vec<StreamKey> = keyed
                .into_iter()
                .take(self.streams.len().saturating_sub(self.max_streams))
                .map(|(k, _)| k)
                .collect();
            for k in to_remove {
                self.streams.remove(&k);
                self.forget_stream(&k);
            }
        }
    }

    fn remove_call(&mut self, call_id: &str) {
        self.calls.remove(call_id);
        self.order.retain(|id| id != call_id);
        self.removed.push_back(call_id.to_string());
        // Clean endpoint + stream indices (stream keys come from the index,
        // no full scan).
        self.endpoint_call.retain(|_, v| v != call_id);
        let stream_keys: Vec<StreamKey> = self.stream_index.remove(call_id).unwrap_or_default();
        for k in stream_keys {
            self.streams.remove(&k);
            self.stream_call.remove(&k);
            if let Some(v) = self.ssrc_index.get_mut(&k.ssrc) {
                v.retain(|k2| k2 != &k);
                if v.is_empty() {
                    self.ssrc_index.remove(&k.ssrc);
                }
            }
        }
    }

    pub fn touch_time(&mut self, ts_us: u64) {
        if self.start_us.is_none() {
            self.start_us = Some(ts_us);
        }
        self.last_us = Some(ts_us);
        // pps over a 1s sliding window.
        match self.window_start_us {
            None => self.window_start_us = Some(ts_us),
            Some(w) => {
                if ts_us.saturating_sub(w) >= 1_000_000 {
                    let elapsed_s = (ts_us.saturating_sub(w)) as f64 / 1_000_000.0;
                    self.pps = self.pkts_last_window as f64 / elapsed_s.max(1e-6);
                    self.pkts_last_window = 0;
                    self.window_start_us = Some(ts_us);
                }
            }
        }
        self.pkts_last_window += 1;
    }

    pub fn get_or_create_call(&mut self, call_id: &str) -> &mut Call {
        if !self.calls.contains_key(call_id) {
            self.calls
                .insert(call_id.to_string(), Call::new(call_id.to_string()));
            self.order.push(call_id.to_string());
        }
        self.calls.get_mut(call_id).unwrap()
    }

    pub fn push_event(&mut self, line: String) {
        self.events.push_back(line);
        while self.events.len() > 1000 {
            self.events.pop_front();
        }
    }

    /// Register a stream summary reconstructed from an evlog record (replay
    /// path). These appear in snapshots and call-detail alongside live streams.
    pub fn add_imported_stream(&mut self, s: StreamSummary) {
        if self.imported_streams.len() >= self.max_streams {
            self.imported_streams.remove(0);
        }
        self.imported_streams.push(s);
    }

    /// Build a UI snapshot: recent calls capped to `limit`, streams capped to
    /// 1000 (display only; exports use `snapshot_full`).
    pub fn snapshot(&self, limit: usize) -> Snapshot {
        self.snapshot_with(limit, 1000)
    }

    /// Full-fidelity snapshot for exports / end-of-run output.
    pub fn snapshot_full(&self) -> Snapshot {
        self.snapshot_with(usize::MAX, usize::MAX)
    }

    pub fn snapshot_with(&self, limit: usize, stream_limit: usize) -> Snapshot {
        let mut summaries: Vec<CallSummary> = self
            .order
            .iter()
            .rev()
            .take(limit)
            .filter_map(|id| self.calls.get(id))
            .map(|c| self.summarize(c))
            .collect();

        let (active_n, comp_n, fail_n) =
            summaries
                .iter()
                .fold((0usize, 0usize, 0usize), |(a, c, f), s| match s.state {
                    CallState::Dialing | CallState::Ringing | CallState::Active => (a + 1, c, f),
                    CallState::Completed => (a, c + 1, f),
                    CallState::Failed | CallState::Canceled => (a, c, f + 1),
                });

        // aggregate averages over terminated calls with data.
        let mut pdd = 0.0;
        let mut pdd_n = 0u64;
        let mut setup = 0.0;
        let mut setup_n = 0u64;
        for c in self.calls.values() {
            if let Some(p) = c.pdd_ms {
                pdd += p as f64;
                pdd_n += 1;
            }
            if let Some(s) = c.setup_ms {
                setup += s as f64;
                setup_n += 1;
            }
        }
        let mut jit = 0.0;
        let mut jit_n = 0u64;
        let mut loss = 0.0;
        let mut loss_n = 0u64;
        let mut mos = 0.0;
        let mut mos_n = 0u64;
        let mut rtt = 0.0;
        let mut rtt_n = 0u64;
        for s in self.streams.values() {
            let st = s.summary();
            if let Some(j) = st.jitter_ms {
                jit += j;
                jit_n += 1;
            }
            loss += st.loss_pct;
            loss_n += 1;
            if let Some(m) = st.mos {
                mos += m;
                mos_n += 1;
            }
            if let Some(r) = st.rtt_avg_ms {
                rtt += r;
                rtt_n += 1;
            }
        }
        let avg = |sum: f64, n: u64| if n == 0 { 0.0 } else { sum / n as f64 };
        let calls_total = self.completed + self.failed + active_n as u64;
        let answered = self.completed;
        let asr = if calls_total == 0 {
            0.0
        } else {
            answered as f64 / calls_total as f64 * 100.0
        };

        summaries.sort_by_key(|s| std::cmp::Reverse(s.invite_ts.unwrap_or(0)));

        Snapshot {
            source: self.source.clone(),
            elapsed_us: match (self.start_us, self.last_us) {
                (Some(a), Some(b)) => Some(b.saturating_sub(a)),
                _ => None,
            },
            pps: self.pps,
            pkts_total: self.pkts_total,
            pkts_dropped: self.pkts_dropped,
            calls_total: calls_total.max(self.calls.len() as u64),
            active: active_n,
            completed: comp_n,
            failed: fail_n,
            avg_pdd_ms: avg(pdd, pdd_n),
            avg_setup_ms: avg(setup, setup_n),
            avg_jitter_ms: avg(jit, jit_n),
            avg_loss_pct: avg(loss, loss_n),
            avg_rtt_ms: avg(rtt, rtt_n),
            avg_mos: avg(mos, mos_n),
            asr,
            calls: summaries,
            streams: {
                let mut s: Vec<_> = self
                    .streams
                    .values()
                    .take(stream_limit)
                    .map(|s| s.summary())
                    .collect();
                let remaining = stream_limit.saturating_sub(s.len());
                s.extend(self.imported_streams.iter().take(remaining).cloned());
                s
            },
            events: self.events.clone(),
            diagnostics: self.diagnostics.iter().cloned().collect(),
            ip_stats: self.ipstats.snapshot(),
            buckets: self.heatmap.flat(),
            focus: self
                .focus_hint
                .as_ref()
                .and_then(|id| self.focus_detail(id)),
            paused: false,
        }
    }

    /// Build the focus payload for the Call Detail page.
    fn focus_detail(&self, call_id: &str) -> Option<Focus> {
        let call = self.calls.get(call_id)?;
        let msgs = if call.messages.len() > 1000 {
            call.messages[call.messages.len() - 1000..].to_vec()
        } else {
            call.messages.clone()
        };
        // Party identities from the SIP messages: the initial INVITE identifies
        // the caller, the first response identifies the callee.
        let invite = msgs.iter().find(|m| {
            m.is_request && matches!(m.method, Some(Method::Invite)) && m.to_tag.is_none()
        });
        let response = msgs.iter().find(|m| !m.is_request);
        let caller_ua = invite.and_then(|m| sip_header(&m.raw, "User-Agent"));
        let callee_ua = response
            .and_then(|m| sip_header(&m.raw, "Server"))
            .or_else(|| response.and_then(|m| sip_header(&m.raw, "User-Agent")));
        let caller_addr = invite.map(|m| m.flow.src);
        let callee_addr = response.map(|m| m.flow.src);
        // Caller IP survives message trimming via the call's invite_key.
        let caller_ip = invite
            .map(|m| m.flow.src.ip())
            .or_else(|| call.invite_key.as_deref().and_then(|k| k.parse().ok()));
        let mut streams: Vec<_> = self
            .call_stream_keys(call_id)
            .iter()
            .filter_map(|k| self.streams.get(k))
            .map(|s| s.summary())
            .collect();
        streams.extend(
            self.imported_streams
                .iter()
                .filter(|s| s.call_id.as_deref() == Some(call_id))
                .cloned(),
        );
        let diagnostics = self
            .diagnostics
            .iter()
            .filter(|d| d.call_id == call_id)
            .cloned()
            .collect();
        Some(Focus {
            call_id: call_id.to_string(),
            state: Some(call.state),
            from_user: call.from_user.clone(),
            to_user: call.to_user.clone(),
            caller_ua,
            callee_ua,
            caller_addr,
            caller_ip,
            callee_addr,
            messages: msgs,
            streams,
            diagnostics,
            negotiated_endpoints: call.negotiated.endpoints.clone(),
            pdd_ms: call.pdd_ms,
            setup_ms: call.setup_ms,
            ring_ms: call.ring_ms,
            early_media: call.early_media,
            invite_ts: call.invite_ts,
            trying_ts: call.trying_ts,
            ringing_ts: call.ringing_ts,
            answer_ts: call.answer_ts,
            bye_ts: call.bye_ts,
            end_ts: call.end_ts,
            hangup_by: call.hangup_by,
            hangup_code: call.hangup.code,
            hangup_reason: call.hangup.reason.clone(),
        })
    }

    fn summarize(&self, c: &Call) -> CallSummary {
        let keys = self.call_stream_keys(&c.call_id);
        let imported: Vec<&StreamSummary> = self
            .imported_streams
            .iter()
            .filter(|s| s.call_id.as_deref() == Some(&c.call_id))
            .collect();
        let best_mos = keys
            .iter()
            .filter_map(|k| self.streams.get(k))
            .filter_map(|s| s.summary().mos)
            .chain(imported.iter().filter_map(|s| s.mos))
            .fold(None, |acc: Option<f64>, m| {
                Some(acc.map_or(m, |a| a.min(m)))
            });
        let stream_count = keys.len() + imported.len();
        let imported_pkts_rtp: u64 = imported.iter().map(|s| s.packets).sum();
        CallSummary {
            call_id: c.call_id.clone(),
            from_user: c.from_user.clone(),
            to_user: c.to_user.clone(),
            caller_ip: c.invite_key.as_deref().and_then(|k| k.parse().ok()),
            state: c.state,
            outcome: c.outcome,
            invite_ts: c.invite_ts,
            duration_ms: c.duration_ms(),
            pdd_ms: c.pdd_ms,
            setup_ms: c.setup_ms,
            ring_ms: c.ring_ms,
            ring_code: c.ring_code,
            early_media: c.early_media,
            hangup_by: c.hangup_by,
            hangup_code: c.hangup.code,
            pkts_sip: c.pkts_sip,
            pkts_rtp: c.pkts_rtp + imported_pkts_rtp,
            best_mos,
            warn_count: c.warn_count,
            critical_count: c.critical_count,
            stream_count,
            via_turn: c.via_turn,
            ips: c.ips.clone(),
        }
    }

    /// Call summaries for a specific call (for call-detail view).
    #[allow(dead_code)]
    pub fn call_messages(&self, call_id: &str) -> Option<&[crate::model::sip::SipMsg]> {
        self.calls.get(call_id).map(|c| c.messages.as_slice())
    }
}

/// Extract the value of a single-line SIP header from raw message bytes.
fn sip_header(raw: &[u8], name: &str) -> Option<String> {
    let text = std::str::from_utf8(raw).ok()?;
    text.lines().find_map(|line| {
        let (n, v) = line.split_once(':')?;
        n.trim()
            .eq_ignore_ascii_case(name)
            .then(|| v.trim().to_string())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::media::StreamSummary;

    #[test]
    fn imported_streams_surface_in_snapshot_focus_and_summary() {
        let mut reg = Registry::with_source("replay".into());
        reg.get_or_create_call("c1");
        let mut st = StreamSummary {
            ssrc: 0x1000,
            packets: 500,
            lost: 4,
            loss_pct: 0.8,
            bytes: 4000,
            mos: Some(4.3),
            ..StreamSummary::default()
        };
        st.call_id = Some("c1".into());
        reg.add_imported_stream(st);

        // Snapshot streams include the imported stream.
        let snap = reg.snapshot_full();
        assert_eq!(snap.streams.len(), 1);
        assert_eq!(snap.streams[0].ssrc, 0x1000);

        // Focus detail (Call Detail media table) includes it with flow/pkts.
        reg.focus_hint = Some("c1".into());
        let snap = reg.snapshot_full();
        let focus = snap.focus.expect("focus detail present");
        assert_eq!(focus.streams.len(), 1, "media table must show the stream");
        assert_eq!(focus.streams[0].packets, 500);
        assert_eq!(focus.streams[0].bytes, 4000);

        // Call summary aggregates RTP packets + MOS from imported streams.
        let call = &snap.calls[0];
        assert_eq!(call.pkts_rtp, 500);
        assert_eq!(call.best_mos, Some(4.3));
        assert_eq!(call.stream_count, 1);
    }
}