forked from babblevoice/projectrtp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactor.rs
More file actions
1386 lines (1279 loc) · 51.8 KB
/
Copy pathactor.rs
File metadata and controls
1386 lines (1279 loc) · 51.8 KB
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Channel actor — the tokio task that owns ChannelState while Local.
//
// The actor has two modes:
//
// Local — owns Box<ChannelState> + Subsystems and runs its own 20 ms
// ticker. Handles every command in-process.
// Mixed — state + subs have migrated into a MixGroup actor. The channel
// actor becomes a forwarder: JS commands get relayed into the
// mixer via `MixHandle::forward()`. Close / LeaveMix pull the
// Member back out of the mixer and restore Local ownership.
//
// This is the "bite the bullet" design the MIGRATE.md note describes: the
// mixer owns the tick so all the cross-channel math (summed_minus, DTMF fan-
// out) runs in lockstep, free of the old deposit/emit race.
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::time::{interval, Interval, MissedTickBehavior};
use tokio_util::sync::CancellationToken;
use super::commands::{Command, Handle};
use super::dtmf::{DtmfReceiver, DtmfSender};
use super::mixer::{Member, MixHandle};
use super::player::Player;
use super::recorder::{FinishReason, Recorder, RecorderConfig, RecorderState};
use super::state::{ChannelState, CloseInfo};
use super::tick::{self, TickOutcome};
pub const TICK_MS: u64 = 20;
pub const DEFAULT_CMD_QUEUE_DEPTH: usize = 64;
/// RFC 3550 quality summary attached to the Close event. `in_*` is our
/// reception of the peer's stream (from `RxStats`); `out_*` is the peer's
/// reported reception of the stream we send (from its SR/RR, in `RemoteReport`).
#[derive(Debug, Clone, Default)]
pub struct RtcpSummary {
/// Whether we have latched an inbound source (received at least one RTP
/// packet). When false the `in_*` figures are zeroed, not meaningful — the
/// mirror of `remote_valid` for the outbound direction.
pub in_valid: bool,
pub in_cumulative_lost: i32,
pub in_fraction_lost: u8,
pub in_jitter: u32,
/// Whether the peer has sent us at least one report about our stream.
pub remote_valid: bool,
pub out_fraction_lost: u8,
pub out_cumulative_lost: i32,
pub out_jitter: u32,
/// Round-trip time in ms, or `None` until the peer echoes one of our SRs.
pub rtt_ms: Option<f64>,
}
/// Events the actor emits back to the outside world. The JS facade (Task #9)
/// will bridge these into a napi `ThreadsafeFunction`.
#[derive(Debug, Clone, Default)]
pub struct ChannelStats {
pub in_count: u64,
pub in_dropped: u64,
pub in_skip: u64,
pub out_count: u64,
/// `None` until the channel has RTCP data (received RTP or a peer report).
pub rtcp: Option<RtcpSummary>,
}
impl ChannelStats {
/// Compute MOS from packet loss, using the ITU-T G.107 inspired formula
/// from the C++ codebase (originally borrowed from FreeSWITCH).
/// Returns 0.0 when no packets were received.
pub fn mos(&self) -> f64 {
if self.in_count == 0 {
return 0.0;
}
// `saturating_sub`: `in_skip` now carries real RFC 3550 loss, which a
// pathological stream could in principle drive above `in_count`.
let received = self.in_count.saturating_sub(self.in_skip);
let r = (received as f64 / self.in_count as f64) * 100.0;
let r = r.clamp(0.0, 100.0);
1.0 + (0.035 * r) + (0.000007 * r * (r - 60.0) * (100.0 - r))
}
}
/// Snapshot the channel's stats for a Close event. Shared by the Local
/// (`actor.rs`) and Mixed (`mixer.rs`) close paths so the two never drift.
///
/// Routes the real RFC 3550 cumulative-loss figure into `in_skip` — the field
/// is otherwise never incremented, so `mos()` used to read near-perfect for
/// every call regardless of actual loss.
pub fn build_channel_stats(state: &ChannelState) -> ChannelStats {
let in_count = state.in_count.load(Ordering::Relaxed);
// `fraction_lost_session` is non-mutating: reading it here must not disturb
// the per-interval counters that `rtcp_tx`'s periodic report blocks consume.
let (in_lost, in_jitter, in_fraction, have_source) = {
let rx = state.rx_stats.lock();
(
rx.cumulative_lost(),
rx.jitter(),
rx.fraction_lost_session(),
rx.remote_ssrc.is_some(),
)
};
let remote = *state.remote_report.lock();
let rtcp = if have_source || remote.valid {
Some(RtcpSummary {
in_valid: have_source,
// Zeroed until an inbound source is latched, so a send-only channel
// doesn't report a phantom loss of 1 (`expected()` is 1 before the
// first packet while `received` is still 0).
in_cumulative_lost: if have_source { in_lost } else { 0 },
in_fraction_lost: if have_source { in_fraction } else { 0 },
in_jitter: if have_source { in_jitter } else { 0 },
remote_valid: remote.valid,
out_fraction_lost: remote.fraction_lost,
out_cumulative_lost: remote.cumulative_lost,
out_jitter: remote.jitter,
rtt_ms: remote.rtt_ms,
})
} else {
None
};
// Real inbound loss → in_skip (clamped: never negative, never exceeds the
// number of packets we counted receiving). Only when a source is latched,
// so the phantom pre-first-packet loss never leaks into MOS.
let in_skip = if have_source {
(in_lost.max(0) as u64).min(in_count)
} else {
0
};
ChannelStats {
in_count,
in_dropped: state.in_dropped + state.jitter.lock().dropped,
in_skip,
out_count: state.out_count,
rtcp,
}
}
#[derive(Debug, Clone)]
pub enum Event {
Close {
reason: String,
stats: ChannelStats,
},
Play {
state: PlayState,
reason: Option<String>,
},
Record {
state: RecordState,
reason: Option<String>,
file: Option<String>,
filesize: Option<u64>,
},
Telephone {
digit: char,
},
Mix {
state: String,
},
}
#[derive(Debug, Clone)]
pub enum PlayState {
Start,
End,
}
#[derive(Debug, Clone)]
pub enum RecordState {
Recording,
Finished,
}
/// Abstract sink for events — a trait so tests can capture events into a
/// channel and the napi facade can forward into a ThreadsafeFunction.
pub trait EventSink: Send + Sync + 'static {
fn post(&self, ev: Event);
}
pub struct SpawnConfig {
pub id: u64,
#[allow(dead_code)]
pub bind_addr: SocketAddr,
pub ssrc: u32,
pub events: Arc<dyn EventSink>,
/// `Some` when the port came from the managed pool — handed to
/// ChannelState so the port is returned on actor exit.
pub port_reservation: Option<crate::portpool::PortReservation>,
/// Our own ICE password — used for STUN Binding Request integrity checks.
pub local_icepwd: String,
}
#[cfg(test)]
pub async fn spawn(cfg: SpawnConfig) -> std::io::Result<Handle> {
let rtp_sock = UdpSocket::bind(cfg.bind_addr).await?;
let local_addr = rtp_sock.local_addr()?;
let rtcp_port = local_addr
.port()
.checked_add(1)
.unwrap_or(local_addr.port());
let rtcp_sock = UdpSocket::bind(SocketAddr::new(local_addr.ip(), rtcp_port)).await?;
spawn_with_sockets(cfg, rtp_sock, rtcp_sock, local_addr)
}
/// Sync variant: takes already-bound sockets. Used by the JS facade so
/// openchannel() can return a value (not a Promise) that index.js can read
/// `.local.port` on immediately.
pub fn spawn_with_sockets(
cfg: SpawnConfig,
rtp_sock: UdpSocket,
rtcp_sock: UdpSocket,
local_addr: SocketAddr,
) -> std::io::Result<Handle> {
let mut state = ChannelState::new(cfg.id, local_addr, rtp_sock, rtcp_sock, cfg.ssrc);
state.port_reservation = cfg.port_reservation;
*state.local_icepwd.lock() = cfg.local_icepwd;
let cancel = CancellationToken::new();
// DTLS keying material is published here once the handshake completes so
// the inbound RTCP readers can build their SRTCP decrypt context (Tier 2).
// Both the dedicated P+1 loop and — under rtcp-mux — the RTP recv_loop
// subscribe, so create the watch pair before spawning either.
let (srtp_key_tx, srtp_key_rx) = tokio::sync::watch::channel(None);
state.srtp_key_tx = Some(srtp_key_tx);
// Spawn the recv_loop — reads the RTP socket continuously, classifies
// STUN/DTLS/RTP and feeds jitter/DTLS-mpsc immediately. It also demuxes
// rtcp-mux'd RTCP (RFC 5761) off the RTP port, hence the RTCP accounting
// fields and the SRTCP key subscription.
super::recv_loop::spawn(super::recv_loop::RecvLoopConfig {
sock: state.rtp_sock.clone(),
jitter: state.jitter.clone(),
remote_addr: state.remote_addr.clone(),
in_count: state.in_count.clone(),
rx_stats: state.rx_stats.clone(),
remote_report: state.remote_report.clone(),
local_ssrc: state.ssrc,
local_icepwd: state.local_icepwd.clone(),
dtls_tx: state.dtls_inbound_tx.clone(),
key_rx: srtp_key_rx.clone(),
cancel: cancel.clone(),
});
// Spawn the inbound RTCP reader on the P+1 control socket. It shares the
// recv_loop cancellation token, so the close path stops both at once.
super::rtcp_loop::spawn(super::rtcp_loop::RtcpLoopConfig {
sock: state.rtcp_sock.clone(),
rx_stats: state.rx_stats.clone(),
remote_report: state.remote_report.clone(),
local_ssrc: state.ssrc,
key_rx: srtp_key_rx,
cancel: cancel.clone(),
});
state.recv_cancel = Some(cancel);
let (tx, rx) = mpsc::channel::<Command>(DEFAULT_CMD_QUEUE_DEPTH);
let events = cfg.events;
let handle_cmd = tx.clone();
tokio::spawn(async move { run(Box::new(state), rx, events, handle_cmd).await });
Ok(Handle {
id: cfg.id,
cmd: tx,
})
}
/// Upper bound on the pre-buffer queue — cap is drop-oldest. Sized to hold
/// 30 s at 16 kHz mono, which covers typical IVR prompt lengths (2–15 s) with
/// headroom and bounds memory at ~1 MB per pending recorder. C++ uses an
/// unbounded queue; a bound is deliberate here to protect a multi-channel
/// server from a stuck/runaway prompt.
pub const PREBUFFER_CAPACITY_SAMPLES: usize = 480_000;
/// A recorder configured by `playrecord` but not yet opened. The file isn't
/// created until activation (play-end or barge-in). Holds a cached
/// `file_str` so the activation event has the path after `cfg` is moved
/// into `Recorder::open`.
pub struct PendingRecorder {
pub cfg: RecorderConfig,
pub file_str: String,
}
/// Per-channel subsystems the tick pipeline hands off to. Keeping them in a
/// sibling struct (not in ChannelState) avoids mixing pipeline-owned and
/// control-owned state — the mixer will move ChannelState but leaves these
/// with the channel actor, since they're driven by commands more than ticks.
#[derive(Default)]
pub struct Subsystems {
pub player: Option<Player>,
/// Multiple simultaneous recorders — one ongoing + one power-gated is the
/// primary use case (see test/interface/projectrtprecord.js "dual
/// recording"). Keyed informally by `recorder.file()`; same path replaces
/// the existing recorder, different path coexists.
pub recorders: Vec<Recorder>,
/// Barge-in detector for `playrecord`. When the player is playing and
/// inbound RMS crosses `power_threshold`, the player is interrupted and
/// a `play/end reason=interrupted` event fires. Cleared when the player
/// ends (naturally or via interrupt).
pub bargein: Option<BargeInState>,
/// Recorder queued by `playrecord` but not yet opened. Activated on
/// player-end or on barge-in interrupt (matches C++ `pendingrecorder`).
pub pending_recorder: Option<PendingRecorder>,
/// Inbound samples captured while `pending_recorder` is set — drained
/// into the recorder on activation via `Recorder::write_raw` so they are
/// written regardless of the recorder's start-above-power gate.
pub prebuffer: VecDeque<i16>,
/// JS-initiated dtmf via `channel.dtmf(...)` — targets state.remote_addr.
pub dtmf_send: DtmfSender,
/// Mix-relay dtmf — when a digit is detected on a peer's inbound while
/// mixed, a full RFC 2833 burst is enqueued here and emitted to the
/// local remote on the next tick. Matches the C++ mux DTMF behaviour.
pub dtmf_relay: DtmfSender,
pub dtmf_recv: DtmfReceiver,
/// Live readers — each maps to one JS `createReadStream` consumer.
/// Fed post-decode at the same point as recorders; see audio_reader.rs
/// for the drop policy.
pub readers: Vec<super::audio_reader::AudioReader>,
/// Active writer, if any. Only one outbound source at a time —
/// `createWriteStream` supersedes any running `play`, and vice
/// versa. See audio_writer.rs for the drain / end semantics.
pub writer: Option<super::audio_writer::AudioWriter>,
}
pub struct BargeInState {
pub power_threshold: i32,
pub power_ma: crate::firfilter::MaFilter,
}
/// Activate a `pending_recorder`: open the recorder, flush the pre-buffer
/// via `write_raw` (bypassing the start-above-power gate so barge-in speech
/// is captured), replace any existing recorder at the same path, and queue
/// a `record event:recording` event when not gated.
///
/// Events are pushed into `pending_events` rather than posted directly so
/// the tick-pipeline callers (which drain `state.pending_events` after each
/// tick) can order them alongside the `play/end` that precedes activation.
///
/// No-op (returns false) if no `pending_recorder` is set. Matches C++
/// `activateplayrecordrecorder` (projectrtpchannel.cpp:849-878).
pub(super) async fn activate_pending_recorder(
subs: &mut Subsystems,
pending_events: &mut Vec<Event>,
) -> bool {
let pending = match subs.pending_recorder.take() {
Some(p) => p,
None => return false,
};
let PendingRecorder { cfg, file_str } = pending;
let is_gated = cfg.start_above_power.is_some();
match Recorder::open(cfg).await {
Ok(mut rec) => {
let drained: Vec<i16> = subs.prebuffer.drain(..).collect();
if !drained.is_empty() {
let frame = if rec.num_channels() == 2 {
let mut inter = Vec::with_capacity(drained.len() * 2);
for s in &drained {
inter.push(*s);
inter.push(*s);
}
inter
} else {
drained
};
let _ = rec.write_raw(&frame).await;
}
if let Some(idx) = subs.recorders.iter().position(|r| r.file() == rec.file()) {
let mut old = subs.recorders.remove(idx);
old.close(FinishReason::ChannelClosed);
}
subs.recorders.push(rec);
if !is_gated {
pending_events.push(Event::Record {
state: RecordState::Recording,
reason: None,
file: Some(file_str),
filesize: None,
});
}
true
}
Err(e) => {
subs.prebuffer.clear();
pending_events.push(Event::Record {
state: RecordState::Finished,
reason: Some(format!("open-failed: {e}")),
file: Some(file_str),
filesize: None,
});
false
}
}
}
/// Top-level actor ownership. `Local` runs the per-channel ticker; `Mixed`
/// delegates ticks + most commands to the mix actor.
//
// `Local` is the common (non-mixed) case and carries the full `Subsystems`
// inline; `Mixed` is small. Boxing `Local` to equalize the variants would
// add a heap indirection on the hot per-channel path and ripple through the
// mix-migration `Member` type, so we keep it inline deliberately.
#[allow(clippy::large_enum_variant)]
enum Mode {
Local {
state: Box<ChannelState>,
subs: Subsystems,
},
Mixed {
mix: MixHandle,
},
}
async fn run(
initial_state: Box<ChannelState>,
mut cmds: mpsc::Receiver<Command>,
events: Arc<dyn EventSink>,
self_cmd: mpsc::Sender<Command>,
) {
let id = initial_state.id;
let mut mode = Mode::Local {
state: initial_state,
subs: Subsystems::default(),
};
let mut ticker = interval(Duration::from_millis(TICK_MS));
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut closing: Option<String> = None;
while closing.is_none() {
match &mut mode {
Mode::Local { state, subs } => {
match step_local(state, subs, &mut cmds, &mut ticker, &events).await {
LocalStep::Continue => {}
LocalStep::Close(reason) => closing = Some(reason),
LocalStep::EnterMix { mix, ack } => {
// Migrate into the mixer. Need to move out of `mode`
// which requires taking ownership — swap to a temp
// Local with a dummy then rebuild the real Mixed.
let (state_out, mut subs_out) = take_local(&mut mode);
// Clear jitter so a remixed channel that restarts
// its SN counter doesn't get rejected as out-of-window.
state_out.jitter.lock().clear();
// Stop any active player — matches C++ mix2 behavior.
// Without this, a ringing player on an existing channel
// leaks into the mix output (e.g. blind transfer: b
// hears ringing while c rings, then c answers and the
// mix is established — the ringing must stop).
if subs_out.player.is_some() {
subs_out.player = None;
subs_out.bargein = None;
events.post(Event::Play {
state: PlayState::End,
reason: Some("mix".into()),
});
}
// Any pending playrecord recorder: no Recording was
// emitted yet, so nothing to finish — just drop.
subs_out.pending_recorder = None;
subs_out.prebuffer.clear();
match mix
.add(Box::new(Member::new(state_out, subs_out, events.clone())))
.await
{
Ok(()) => {
events.post(Event::Mix {
state: "start".to_string(),
});
mode = Mode::Mixed { mix };
let _ = ack.send(());
}
Err(()) => {
// Mixer is gone (shouldn't happen in normal
// flow). Fall back to Local mode — state was
// consumed into the `Member` that got
// dropped. Repopulate a zero-state placeholder
// and close so the channel doesn't hang.
closing = Some("mix-add-failed".to_string());
}
}
}
}
}
Mode::Mixed { mix } => {
match cmds.recv().await {
None => closing = Some("handle-dropped".to_string()),
Some(Command::Close { reason }) => {
if let Some(member) = mix.remove(id).await {
restore_local(&mut mode, member);
events.post(Event::Mix {
state: "finished".to_string(),
});
}
closing = Some(reason);
}
Some(Command::LeaveMix { ack }) => {
if let Some(member) = mix.remove(id).await {
restore_local(&mut mode, member);
events.post(Event::Mix {
state: "finished".to_string(),
});
}
let _ = ack.send(());
}
Some(Command::EnterMix { mix: new_mix, ack }) => {
// Already in a mix. If it's the same one (facade
// re-asserts on same-group mix()), post a fresh
// `mix/start` event so JS sees one per mix() call.
// Different-group migration isn't supported yet.
if new_mix.id == mix.id {
events.post(Event::Mix {
state: "start".to_string(),
});
}
let _ = ack.send(());
}
Some(cmd) => {
// All other commands get forwarded to the mixer for
// application against this member's state/subs.
mix.forward(id, cmd).await;
}
}
}
}
}
let reason = closing.unwrap_or_default();
// If we arrived here via a path that left us mixed (shouldn't happen
// since close/leavemix above pull out first, but be defensive), still
// try to reclaim state for the stats payload. Use a timeout so a dead
// mixer doesn't strand the actor.
if let Mode::Mixed { mix } = &mode {
if let Ok(Some(member)) =
tokio::time::timeout(Duration::from_millis(100), mix.remove(id)).await
{
restore_local(&mut mode, member);
events.post(Event::Mix {
state: "finished".to_string(),
});
}
}
let (state, subs) = match &mut mode {
Mode::Local { state, subs } => (state, subs),
Mode::Mixed { .. } => {
// Last-resort: the defensive `mix.remove(id)` above timed out or
// returned None, so we never transitioned back to Local. Emit a
// minimal Close event without stats — but unregister from the
// registry FIRST (same ordering rule as the Local path below).
// Without this, a mixed channel whose mixer was contended at
// teardown stays in CHANNEL_REGISTRY forever and leaks
// `stats.channel.current` (rtp_open_count) even though the client
// saw a clean Close.
super::facade::unregister_channel(id);
events.post(Event::Close {
reason,
stats: ChannelStats::default(),
});
drop(self_cmd);
return;
}
};
// Player: if still active on close, emit `play/end reason=channelclosed`.
if subs.player.is_some() {
subs.player = None;
subs.bargein = None;
events.post(Event::Play {
state: PlayState::End,
reason: Some("channelclosed".into()),
});
}
for mut rec in subs.recorders.drain(..) {
let file_str = rec.file().to_string_lossy().into_owned();
let size = rec.file_size();
rec.close(FinishReason::ChannelClosed);
events.post(Event::Record {
state: RecordState::Finished,
reason: Some("channelclosed".into()),
file: Some(file_str),
filesize: Some(size),
});
}
// Drop readers — their mpsc senders close, forwarder tasks exit, JS
// `Readable.push(null)` fires `end`. No event emitted here: the
// JS-side Readable already signals `end`/`close` to userland.
subs.readers.clear();
// Writer: same pattern, opposite direction. Dropping it closes the
// Receiver; the JS side's next `push_writer_bytes` will see the
// channel is gone and surface an error on the Writable.
subs.writer = None;
// A pending_recorder was accepted by `playrecord` but never activated —
// the file was never opened, so there are no bytes to report. Still emit
// a Finished event so every `record` start has a matching finish on the
// wire (babble-sip tolerates missing, but the protocol rule is paired).
if let Some(pending) = subs.pending_recorder.take() {
events.post(Event::Record {
state: RecordState::Finished,
reason: Some("channelclosed".into()),
file: Some(pending.file_str),
filesize: Some(0),
});
}
subs.prebuffer.clear();
// RTCP BYE (Tier 2): tell the peer the stream is ending now, before we
// cancel the loops and drop the sockets. Best-effort; encrypted as SRTCP
// on a secure channel.
super::rtcp_tx::send_bye(state).await;
// Abort any in-flight DTLS handshake task. Without this, a handshake
// that hasn't completed (peer disappeared, no response, etc.) outlives
// the channel and busy-spins the runtime: the task's mpsc senders are
// about to drop, and webrtc-dtls's handshake driver re-polls recv on
// every Err. Abort first, then drop the inbound sender — that order
// guarantees the spawned task is gone before any remaining `recv()`
// future would see `None`.
if let Some(abort) = state.dtls_handshake_abort.take() {
abort.abort();
}
*state.dtls_inbound_tx.lock() = None;
// Cancel the recv_loop before collecting stats.
if let Some(cancel) = state.recv_cancel.take() {
cancel.cancel();
}
let stats = build_channel_stats(state);
state.close_info = Some(CloseInfo {
reason: reason.clone(),
});
// Order matters: `unregister_channel` decrements the registry BEFORE
// the Close event is posted. Otherwise a JS `afterEach` that asserts
// `stats.channel.current === 0` races the TSFN queue — the callback
// can fire while the registry still holds this channel.
super::facade::unregister_channel(id);
events.post(Event::Close { reason, stats });
drop(self_cmd);
}
/// Replaces `mode` temporarily with a placeholder Mixed so we can move the
/// owned state + subs out. Caller must immediately rebuild `mode` on the
/// success path. On failure the placeholder Mixed is left in place and the
/// actor proceeds to close.
fn take_local(mode: &mut Mode) -> (Box<ChannelState>, Subsystems) {
// Swap out with a temporary Mixed placeholder — we'll overwrite mode
// right after. The placeholder MixHandle is never used because the
// caller transitions mode before any further command handling runs.
let placeholder = Mode::Mixed {
mix: MixHandle {
id: 0,
cmd: mpsc::channel(1).0,
},
};
let taken = std::mem::replace(mode, placeholder);
match taken {
Mode::Local { state, subs } => (state, subs),
Mode::Mixed { .. } => unreachable!("take_local called from non-Local mode"),
}
}
fn restore_local(mode: &mut Mode, member: Box<Member>) {
let Member { state, subs, .. } = *member;
*mode = Mode::Local { state, subs };
}
enum LocalStep {
Continue,
Close(String),
EnterMix {
mix: MixHandle,
ack: tokio::sync::oneshot::Sender<()>,
},
}
async fn step_local(
state: &mut ChannelState,
subs: &mut Subsystems,
cmds: &mut mpsc::Receiver<Command>,
ticker: &mut Interval,
events: &Arc<dyn EventSink>,
) -> LocalStep {
tokio::select! {
biased;
cmd = cmds.recv() => {
match cmd {
None => LocalStep::Close("handle-dropped".to_string()),
Some(cmd) => match handle_command_local(state, subs, cmd, events).await {
LocalOutcome::Continue => LocalStep::Continue,
LocalOutcome::Close(r) => LocalStep::Close(r),
LocalOutcome::EnterMix { mix, ack } => LocalStep::EnterMix { mix, ack },
}
}
}
_ = ticker.tick() => {
let outcome = tick::run(state, subs).await;
for ev in state.pending_events.drain(..) {
events.post(ev);
}
if outcome == TickOutcome::Stop {
LocalStep::Close("idle-timeout".to_string())
} else {
LocalStep::Continue
}
}
}
}
enum LocalOutcome {
Continue,
Close(String),
EnterMix {
mix: MixHandle,
ack: tokio::sync::oneshot::Sender<()>,
},
}
async fn handle_command_local(
state: &mut ChannelState,
subs: &mut Subsystems,
cmd: Command,
events: &Arc<dyn EventSink>,
) -> LocalOutcome {
match cmd {
Command::Close { reason } => LocalOutcome::Close(reason),
Command::EnterMix { mix, ack } => LocalOutcome::EnterMix { mix, ack },
Command::LeaveMix { ack } => {
// Not in a mix — ack immediately. Matches C++ `unmix()` returning
// true even when the channel wasn't mixed.
let _ = ack.send(());
LocalOutcome::Continue
}
Command::Direction(d) => {
state.direction = d;
LocalOutcome::Continue
}
Command::Echo { enabled } => {
state.echo = enabled;
LocalOutcome::Continue
}
Command::Remote { cfg, ack } => {
state.set_remote_addr(cfg.addr);
state.ticks_without_rtp = 0;
state.remote_pt = cfg.payload_type;
state.rtcpmux = cfg.rtcpmux;
state.codecx.set_negotiated_pt(cfg.payload_type);
if let Some(pt) = cfg.rfc2833_payload_type {
state.rfc2833_pt = pt;
}
if let Some(pt) = cfg.ilbc_payload_type {
state.codecx.set_local_ilbc_pt(pt);
}
if let Some(pwd) = &cfg.icepwd {
state.remote_icepwd = pwd.clone();
}
// DTLS: if the remote config includes DTLS setup, start the handshake.
// The cert is the process-lifetime one whose fingerprint is what
// the peer was promised via SDP — see `dtls::get_certificate`.
if let Some(ref dtls) = cfg.dtls {
// If a previous Remote with DTLS already started a handshake,
// abort it before kicking off a new one — otherwise the old
// task would race against the new one for the same socket.
if let Some(abort) = state.dtls_handshake_abort.take() {
abort.abort();
}
let (dtls_tx, dtls_rx) = mpsc::channel::<Vec<u8>>(64);
*state.dtls_inbound_tx.lock() = Some(dtls_tx);
let h = super::dtls_session::spawn_handshake(
dtls.setup,
state.local_addr,
state.rtp_sock.clone(),
dtls_rx,
crate::dtls::get_certificate(),
state.remote_addr.clone(),
);
state.dtls_result_rx = Some(h.result_rx);
state.dtls_handshake_abort = Some(h.abort);
}
state.remote = Some(cfg);
state.remote_confirmed = true;
let _ = ack.send(());
LocalOutcome::Continue
}
Command::Play { cfg, ack } => {
if subs.player.is_some() {
subs.player = None;
subs.bargein = None;
events.post(Event::Play {
state: PlayState::End,
reason: Some("replaced".into()),
});
}
// A bare `play` supersedes any `playrecord` pending recorder.
// No Recording event was emitted for it yet (activation hasn't
// fired), so no matching Finished is owed.
subs.pending_recorder = None;
subs.prebuffer.clear();
subs.player = Some(Player::new(cfg));
events.post(Event::Play {
state: PlayState::Start,
reason: Some("new".into()),
});
let _ = ack.send(());
LocalOutcome::Continue
}
Command::Record { cfg, ack } => {
// Record at the channel's native rate (16k for G.722, else 8k).
let mut cfg = cfg;
cfg.sample_rate = state.codecx.native_samplerate();
// A bare `record` at a different path leaves a pending recorder
// dangling — clear it so the play-end activation doesn't later
// open it alongside this fresh one.
subs.pending_recorder = None;
subs.prebuffer.clear();
let file_str = cfg.file.to_string_lossy().into_owned();
let is_gated = cfg.start_above_power.is_some();
// If an existing recorder at the same path is paused, resume it
// instead of replacing it — preserves the WAV so both segments
// end up in one file.
if let Some(rec) = subs
.recorders
.iter_mut()
.find(|r| r.file() == cfg.file && r.state() == RecorderState::Paused)
{
rec.resume();
events.post(Event::Record {
state: RecordState::Recording,
reason: None,
file: Some(file_str),
filesize: None,
});
} else {
match Recorder::open(cfg.clone()).await {
Ok(rec) => {
if let Some(idx) =
subs.recorders.iter().position(|r| r.file() == rec.file())
{
let mut old = subs.recorders.remove(idx);
let size = old.file_size();
old.close(FinishReason::ChannelClosed);
events.post(Event::Record {
state: RecordState::Finished,
reason: Some("channelclosed".into()),
file: Some(file_str.clone()),
filesize: Some(size),
});
}
subs.recorders.push(rec);
if !is_gated {
events.post(Event::Record {
state: RecordState::Recording,
reason: None,
file: Some(file_str),
filesize: None,
});
}
}
Err(e) => {
events.post(Event::Record {
state: RecordState::Finished,
reason: Some(format!("open-failed: {e}")),
file: Some(file_str),
filesize: None,
});
}
}
}
let _ = ack.send(());
LocalOutcome::Continue
}
Command::CreateReadStream { id, cfg, sender } => {
subs.readers
.push(super::audio_reader::AudioReader::new(id, cfg, sender));
LocalOutcome::Continue
}
Command::DestroyReadStream { id } => {
subs.readers.retain(|r| r.id() != id);
LocalOutcome::Continue
}
Command::CreateWriteStream { id, cfg, receiver } => {
// A writer supersedes any active player — they share the
// outbound-source slot. Emit `play/end reason=replaced` to
// match what `Command::Play` does when it replaces another
// player.
if subs.player.is_some() {
subs.player = None;
subs.bargein = None;
events.post(Event::Play {
state: PlayState::End,
reason: Some("replaced".into()),
});
}
subs.pending_recorder = None;
subs.prebuffer.clear();
subs.writer = Some(super::audio_writer::AudioWriter::new(id, cfg, receiver));
LocalOutcome::Continue
}
Command::DestroyWriteStream { id } => {
if let Some(w) = subs.writer.as_ref() {
if w.id() == id {
subs.writer = None;
}
}
LocalOutcome::Continue
}
Command::RecordFinish { file } => {
if let Some(idx) = subs.recorders.iter().position(|r| r.file() == file) {
let mut rec = subs.recorders.remove(idx);
let file_str = rec.file().to_string_lossy().into_owned();
let size = rec.file_size();
rec.close(FinishReason::Requested);
events.post(Event::Record {
state: RecordState::Finished,
reason: Some("requested".into()),
file: Some(file_str),
filesize: Some(size),
});
}
LocalOutcome::Continue
}
Command::RecordSetPaused { file, paused } => {
if let Some(rec) = subs.recorders.iter_mut().find(|r| r.file() == file) {
if paused {
rec.pause();
} else {
rec.resume();
}
}
LocalOutcome::Continue
}
Command::PlayRecord { cfg, ack } => {
if subs.player.is_some() {
subs.player = None;
subs.bargein = None;
events.post(Event::Play {
state: PlayState::End,
reason: Some("replaced".into()),
});
}
// Supersede any previously-queued pending recorder — its file was
// never opened, so no Record event is owed (matches C++: no file
// created, no emit). The pre-buffer is cleared so the new
// recording starts fresh when play ends.
subs.pending_recorder = None;
subs.prebuffer.clear();
subs.player = Some(Player::new(cfg.player));
events.post(Event::Play {
state: PlayState::Start,
reason: Some("new".into()),
});
if cfg.interrupt {
if let Some(threshold) = cfg.bargein_power {
let mut ma = crate::firfilter::MaFilter::new();
if let Some(n) = cfg.bargein_packets {
ma.reset(n as usize);
}
subs.bargein = Some(BargeInState {
power_threshold: threshold,
power_ma: ma,
});
}
}
// Queue the recorder — actual `Recorder::open` is deferred until
// play-end (or barge-in). The pre-buffer accumulates inbound
// samples while the player runs; on activation it is flushed
// via `write_raw`. C++ `pendingrecorder` equivalent.
// Record at the channel's native rate (16k for G.722, else 8k).
let mut recorder_cfg = cfg.recorder;
recorder_cfg.sample_rate = state.codecx.native_samplerate();
let file_str = recorder_cfg.file.to_string_lossy().into_owned();
subs.pending_recorder = Some(PendingRecorder {
cfg: recorder_cfg,
file_str,
});