iax2 0.2.2

Native Rust implementation of the Inter-Asterisk eXchange v2 (IAX2, RFC 5456) protocol: sans-io core with MD5 auth and call-token, G.711 codec and an adaptive jitter buffer, plus an optional async UDP driver and cross-platform audio.
Documentation
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
//! softphone — driver multilinea / multi-PBX.
//!
//! ## Uso
//! Singolo account (compatibile con regdaemon):
//!   softphone <host> <user> <secret> [port] [refresh] [nome]
//! Multi-account da file:
//!   softphone accounts.conf
//!

use std::collections::HashMap;
use std::env;
use std::sync::Arc;
use std::time::{Duration, Instant};

use iax2::audio::AudioIo;
use iax2::client::CallState;
use iax2::g711;
use iax2::jitter::{JitterBuffer, Pull};
use iax2::{Command, Config, Event, PbxClient};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::time::{interval, sleep};

const IAX_PORT_DEFAULT: u16 = 4569;
const FRAME_SAMPLES: usize = 160; // 20 ms @ 8 kHz

struct Account {
    cfg: Config,
    host: String,
    port: u16,
}

struct App {
    clients: Vec<PbxClient>,
    sockets: Vec<Arc<UdpSocket>>,
    audio: AudioIo,
    /// (indice PBX, call number) della chiamata il cui audio e' live.
    active: Option<(usize, u16)>,
    /// PBX su cui finiscono i `dial`.
    selected: usize,
    /// Jitter buffer della sola chiamata attiva (reset al cambio).
    jb: JitterBuffer,
    /// Ultimo frame PCM riprodotto, per il packet-loss concealment.
    last_pcm: Vec<i16>,
    jb_log_tick: u32,
}

impl App {
    fn now() -> Instant {
        Instant::now()
    }

    /// Spedisce tutti i datagrammi pronti del client `idx` sul suo socket.
    async fn flush_tx(&mut self, idx: usize) {
        let mut batch = Vec::new();
        while let Some(b) = self.clients[idx].poll_transmit() {
            batch.push(b);
        }
        for b in batch {
            let _ = self.sockets[idx].send(&b).await;
        }
    }

    /// Processa gli eventi del client `idx` (audio, stato, stampa).
    async fn handle_events(&mut self, idx: usize) {
        let name = self.clients[idx].name().to_string();
        loop {
            let Some(ev) = self.clients[idx].poll_event() else { break };
            match ev {
                Event::Registered => println!("[\u{2713}] [{name}] REGISTERED"),
                Event::RegisterLost { reason } => println!("[!] [{name}] lost registration: {reason}"),
                Event::Incoming { call, from, to } => {
                    println!("[\u{260E}] [{name}] INCOMING CALL #{call} from '{from}' to '{to}'  —  press 'a'+<ENTER> to answer");
                }
                Event::Dialing { call, to } => println!("[>] [{name}] chiamo '{to}' (#{call})"),
                Event::Ringing { call } => println!("[i] [{name}] #{call} is ringing ..."),
                Event::Answered { call } => {
                    println!("[\u{2713}] [{name}] #{call} connected — audio on");
                    // diventa la chiamata attiva; metti in attesa le altre Up
                    self.make_active(idx, call).await;
                }
                Event::Voice { call, ts, ulaw } => {
                    if self.active == Some((idx, call)) {
                        // eprintln!("[voice-in] ts={} len={}", ts, ulaw.len());
                        self.jb.push(ts, ulaw, Self::now());
                    }
                }
                Event::Ended { call, reason } => {
                    println!("[i] [{name}] #{call} ended: {reason}");
                    if self.active == Some((idx, call)) {
                        let st = self.jb.stats();
                        eprintln!("[jb@end] target_ms={} jitter_stats={:?}", st.target_ms, st);
                        self.active = None;
                        self.jb.reset();
                        self.last_pcm.clear();
                        self.audio.flush();
                    }
                }
                Event::Dtmf { call, digit } => println!("[#] [{name}] #{call} DTMF received: {digit}"),
                Event::Log(s) => println!("[i] [{name}] {s}"),
                _ => {}
            }
        }
    }

    /// Rende attiva (idx,call): mette in HOLD l'eventuale chiamata attiva
    /// precedente (se ancora connessa), fa UNHOLD della target se era in
    /// attesa, resetta il jitter buffer (nuovo stream) e spinge i frame sui
    /// PBX toccati.
    async fn make_active(&mut self, idx: usize, call: u16) {
        let now = Self::now();
        let mut touched: Vec<usize> = Vec::new();
        if let Some((pidx, pcall)) = self.active {
            if (pidx, pcall) != (idx, call)
                && self.clients[pidx].call_state(pcall) == Some(CallState::Up)
            {
                self.clients[pidx].handle_command(Command::Hold { call: pcall }, now);
                touched.push(pidx);
            }
        }
        if self.clients[idx].call_state(call) == Some(CallState::Held) {
            self.clients[idx].handle_command(Command::Unhold { call }, now);
        }
        touched.push(idx);
        let switching = self.active != Some((idx, call));
        self.active = Some((idx, call));
        if switching {
            self.jb.reset();
            self.last_pcm.clear();
        }
        self.audio.flush();
        touched.sort_unstable();
        touched.dedup();
        for i in touched {
            self.flush_tx(i).await;
        }
    }

    /// Estrae un frame da 20 ms dal jitter buffer della chiamata attiva e lo
    /// manda all'altoparlante. Sui buchi (frame perso/in ritardo) fa PLC
    /// ripetendo l'ultimo frame attenuato; in starvation riproduce silenzio.
    fn pump_playout(&mut self) {
        let active_up = match self.active {
            Some((idx, call)) => self.clients[idx].call_state(call) == Some(CallState::Up),
            None => false,
        };
        if !active_up {
            return;
        }
        match self.jb.pull() {
            Pull::Play(ulaw) => {
                let mut pcm = Vec::with_capacity(ulaw.len());
                g711::decode_block(&ulaw, &mut pcm);
                self.audio.play_pcm_8k(&pcm);
                self.last_pcm = pcm;
            }
            Pull::Conceal => {
                // ripeti l'ultimo frame attenuato (PLC povero ma efficace);
                // poi sfuma verso il silenzio se i buchi continuano
                if !self.last_pcm.is_empty() {
                    for s in self.last_pcm.iter_mut() {
                        *s = (*s as i32 / 2) as i16;
                    }
                    self.audio.play_pcm_8k(&self.last_pcm);
                }
            }
            Pull::Silence => {
                // niente in coda: l'altoparlante va a silenzio da solo
            }
        }
    }

    /// Cattura microfono e invia audio alla chiamata attiva (se Up).
    fn pump_mic(&mut self, now: Instant) -> Option<usize> {
        let (idx, call) = self.active?;
        if self.clients[idx].call_state(call) != Some(CallState::Up) {
            // svuota comunque il mic per non accumulare latenza
            let _ = self.audio.take_frames_8k(FRAME_SAMPLES);
            return None;
        }
        for pcm in self.audio.take_frames_8k(FRAME_SAMPLES) {
            let mut ulaw = Vec::with_capacity(FRAME_SAMPLES);
            g711::encode_block(&pcm, &mut ulaw);
            self.clients[idx].handle_command(Command::SendVoice { call, ulaw }, now);
        }
        Some(idx)
    }

    /// Prossimo risveglio (minimo tra tutti i client).
    fn next_wake(&self) -> Instant {
        let now = Self::now();
        let mut t = now + Duration::from_secs(3600);
        for c in &self.clients {
            if let Some(x) = c.poll_timeout() {
                if x < t {
                    t = x;
                }
            }
        }
        t
    }

    /// Elenco stabile (PBX idx, call) di tutte le chiamate vive, nello stesso
    /// ordine mostrato da `list()`: per PBX, poi per call-number crescente.
    fn calls_index(&self) -> Vec<(usize, u16)> {
        let mut v = Vec::new();
        for (idx, c) in self.clients.iter().enumerate() {
            for call in c.call_ids() {
                v.push((idx, call));
            }
        }
        v
    }

    fn list(&self) {
        println!("--- PBXes List ---");
        for (i, c) in self.clients.iter().enumerate() {
            let sel = if i == self.selected { "*" } else { " " };
            let reg = if c.is_registered() { "OK" } else { "--" };
            println!(" {sel}{}) {} [{reg}]", i + 1, c.name());
        }
        let calls = self.calls_index();
        if calls.is_empty() {
            println!("--- No active calls online ---");
            return;
        }
        println!("--- CALLS (press call IDnum+<ENTER> to connect the call) ---");
        for (n, (idx, call)) in calls.iter().enumerate() {
            let c = &self.clients[*idx];
            let st = match c.call_state(*call) {
                Some(CallState::Trying) => "trying",
                Some(CallState::Ringing) => "ringing",
                Some(CallState::Up) => "on line",
                Some(CallState::Held) => "on hold",
                None => "?",
            };
            let peer = c.call_peer(*call).unwrap_or("?");
            let here = if self.active == Some((*idx, *call)) { "  <== attiva" } else { "" };
            println!(" {}) [{}] #{call} {peer}{st}{here}", n + 1, c.name());
        }
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("uso:");
        eprintln!("  {} <host> <user> <secret> [port] [refresh] [nome]", args[0]);
        eprintln!("  {} accounts.conf", args[0]);
        std::process::exit(2);
    }

    let accounts = if std::path::Path::new(&args[1]).is_file() {
        match parse_accounts(&args[1]) {
            Ok(a) if !a.is_empty() => a,
            Ok(_) => {
                eprintln!("[x] no account in file");
                std::process::exit(2);
            }
            Err(e) => {
                eprintln!("[x] config: {e}");
                std::process::exit(2);
            }
        }
    } else {
        if args.len() < 4 {
            eprintln!("use single account: {} <host> <user> <secret> [port] [refresh] [nome]", args[0]);
            std::process::exit(2);
        }
        let host = args[1].clone();
        let user = args[2].clone();
        let secret = args[3].clone();
        let port = args.get(4).and_then(|s| s.parse().ok()).unwrap_or(IAX_PORT_DEFAULT);
        let refresh = args.get(5).and_then(|s| s.parse().ok()).unwrap_or(60);
        let name = args.get(6).cloned().unwrap_or_else(|| host.clone());
        let mut cfg = Config::new(name, user, secret);
        cfg.refresh = refresh;
        vec![Account { cfg, host, port }]
    };

    let audio = match AudioIo::new() {
        Ok(a) => a,
        Err(e) => {
            eprintln!("[x] audio not available: {e}");
            std::process::exit(1);
        }
    };
    println!("[i] audio: in {}Hz/{}ch  out {}Hz/{}ch", audio.in_rate, audio.in_ch, audio.out_rate, audio.out_ch);

    // socket + client + reader task per PBX
    let (tx, mut rx) = mpsc::channel::<(usize, Vec<u8>)>(256);
    let mut clients = Vec::new();
    let mut sockets = Vec::new();
    for (idx, acc) in accounts.into_iter().enumerate() {
        let remote = format!("{}:{}", acc.host, acc.port);
        let sock = match UdpSocket::bind("0.0.0.0:0").await {
            Ok(s) => s,
            Err(e) => {
                eprintln!("[x] bind {remote}: {e}");
                std::process::exit(1);
            }
        };
        if let Err(e) = sock.connect(&remote).await {
            eprintln!("[x] connect {remote}: {e}");
            std::process::exit(1);
        }
        println!("[i] [{}] {} -> {remote} (user {})", acc.cfg.name, sock.local_addr().unwrap(), acc.cfg.username);
        let sock = Arc::new(sock);
        let reader = sock.clone();
        let txc = tx.clone();
        tokio::spawn(async move {
            let mut buf = [0u8; 4096];
            loop {
                match reader.recv(&mut buf).await {
                    Ok(n) => {
                        if txc.send((idx, buf[..n].to_vec())).await.is_err() {
                            break;
                        }
                    }
                    Err(_) => break,
                }
            }
        });
        clients.push(PbxClient::new(acc.cfg));
        sockets.push(sock);
    }
    drop(tx);

    let mut app = App { clients, sockets, audio, active: None, selected: 0, jb: JitterBuffer::new(), last_pcm: Vec::new(), jb_log_tick: 0 };

    println!("[i] READY.");
    println!("[i] --------------------------------------------");
    println!("[i] COMMAND KEYS ( press key+<ENTER> ) :");
    println!("[i]   a           - Answer a call");
    println!("[i]   h           - Hangup");
    println!("[i]   d <num>     - Call <num>"); 
    println!("[i]   p <n>       - Select  PBX"); 
    println!("[i]   <n>         - Connect to call <n> "); 
    println!("[i]   l           - Get calls/Pbxes list"); 
    println!("[!]   t <digits>  - Send digit(s)  (0-9 * # A-D)");
    println!("[i]   q           - Quit");
    println!("[i] --------------------------------------------");
    println!(" ");

    let mut audio_tick = interval(Duration::from_millis(20));
    let mut stdin = BufReader::new(tokio::io::stdin()).lines();

    // primo giro di registrazione subito
    let now = App::now();
    for i in 0..app.clients.len() {
        app.clients[i].handle_timeout(now);
        app.flush_tx(i).await;
        app.handle_events(i).await;
    }

    loop {
        let wake = app.next_wake();
        let dur = wake.saturating_duration_since(App::now());
        tokio::select! {
            // datagrammi da uno qualsiasi dei PBX
            Some((idx, dg)) = rx.recv() => {
                let now = App::now();
                app.clients[idx].handle_input(&dg, now);
                app.flush_tx(idx).await;
                app.handle_events(idx).await;
            }

            // scadenza timer: re-register / keepalive / ritrasmissioni
            _ = sleep(dur) => {
                let now = App::now();
                for i in 0..app.clients.len() {
                    app.clients[i].handle_timeout(now);
                    app.flush_tx(i).await;
                    app.handle_events(i).await;
                }
            }

            // tick 20 ms: microfono -> chiamata attiva, e jitter buffer -> altoparlante
            _ = audio_tick.tick() => {
                let now = App::now();
                if let Some(idx) = app.pump_mic(now) {
                    app.flush_tx(idx).await;
                }
                app.pump_playout();
                app.jb_log_tick += 1;
                if app.jb_log_tick % 50 == 0 {          // ogni ~1s (50 tick × 20ms)
                    let st = app.jb.stats();
                    eprintln!("[jb] played={} concealed={} late={} overflow={} target_ms={} buffered={}",
                    st.played, st.concealed, st.late, st.overflow, st.target_ms, st.buffered
                    );
                }
            }

            // tastiera
            line = stdin.next_line() => {
                let now = App::now();
                let Ok(Some(line)) = line else { break };
                let line = line.trim().to_string();
                if line.is_empty() { continue; }
                if !app.dispatch(&line, now).await { break; }
            }
        }
    }
    println!("[i] exit.");
}

impl App {
    /// Esegue un comando da tastiera. Ritorna false per uscire.
    async fn dispatch(&mut self, line: &str, now: Instant) -> bool {
        let mut it = line.split_whitespace();
        let cmd = it.next().unwrap_or("");
        match cmd {
            "q" => return false,
            "l" => self.list(),
            "p" => {
                if let Some(n) = it.next().and_then(|s| s.parse::<usize>().ok()) {
                    if n >= 1 && n <= self.clients.len() {
                        self.selected = n - 1;
                        println!("[i] selected PBX: {}", self.clients[self.selected].name());
                    }
                }
            }
            "d" => {
                let number = it.collect::<Vec<_>>().join(" ");
                if number.is_empty() {
                    println!("[!] use: d <num>");
                } else {
                    let idx = self.selected;
                    if !self.clients[idx].is_registered() {
                        println!("[!] [{}] not registered; I'll try anyway", self.clients[idx].name());
                    }
                    self.clients[idx].handle_command(Command::Dial { number }, now);
                    self.flush_tx(idx).await;
                    self.handle_events(idx).await;
                }
            }
            "a" => {
                // prima chiamata che squilla, in qualsiasi PBX
                if let Some((idx, call)) = self.find_ringing() {
                    self.clients[idx].handle_command(Command::Answer { call }, now);
                    self.flush_tx(idx).await;
                    self.handle_events(idx).await;
                } else {
                    println!("[!] no calls are ringing");
                }
            }
            "t" => {
                // invia cifre DTMF sulla chiamata attiva
                let digits = it.collect::<Vec<_>>().join("");
                if digits.is_empty() {
                    println!("[!] use: t <cifre>   (0-9 * # A-D)");
                } else if let Some((idx, call)) = self.active {
                    for d in digits.chars() {
                        self.clients[idx].handle_command(Command::Dtmf { call, digit: d }, now);
                    }
                    self.flush_tx(idx).await;
                    self.handle_events(idx).await;
                    println!("[i] DTMF trasmitted: {digits}");
                } else {
                    println!("[!] no active call");
                }
            }
            "h" => {
                if let Some((idx, call)) = self.active {
                    self.clients[idx].handle_command(Command::Hangup { call }, now);
                    self.flush_tx(idx).await;
                    self.handle_events(idx).await;
                    self.active = None;
                    self.audio.flush();
                } else {
                    println!("[!] no active call");
                }
            }
            other => {
                // <n> (anche "#n") -> rendi attiva la chiamata n della lista
                let key = other.strip_prefix('#').unwrap_or(other);
                if let Ok(n) = key.parse::<usize>() {
                    let calls = self.calls_index();
                    if calls.is_empty() {
                        println!("[!] no active call");
                    } else if n < 1 || n > calls.len() {
                        println!("[!] index out of range: use 1..{} ('l' to get full list)", calls.len());
                    } else {
                        let (idx, call) = calls[n - 1];
                        match self.clients[idx].call_state(call) {
                            Some(CallState::Ringing) => {
                                // squilla ancora: rispondi (Answered -> make_active)
                                self.clients[idx].handle_command(Command::Answer { call }, now);
                                self.flush_tx(idx).await;
                                self.handle_events(idx).await;
                            }
                            Some(_) => {
                                self.make_active(idx, call).await;
                                println!("[i] attiva: [{}] #{call}", self.clients[idx].name());
                            }
                            None => println!("[!] Call {n} is not here"),
                        }
                    }
                } else {
                    println!("[!] unknown command: {other}");
                }
            }
        }
        true
    }

    /// Trova la prima chiamata in stato Ringing (in ingresso) tra tutti i PBX.
    fn find_ringing(&self) -> Option<(usize, u16)> {
        for (idx, c) in self.clients.iter().enumerate() {
            for call in c.call_ids() {
                if c.call_state(call) == Some(CallState::Ringing) {
                    return Some((idx, call));
                }
            }
        }
        None
    }
}

/// Parser INI minimale per il file account.
fn parse_accounts(path: &str) -> Result<Vec<Account>, String> {
    let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
    let mut accounts = Vec::new();
    let mut cur: Option<(String, HashMap<String, String>)> = None;

    let flush = |cur: &mut Option<(String, HashMap<String, String>)>, out: &mut Vec<Account>| -> Result<(), String> {
        if let Some((name, kv)) = cur.take() {
            let host = kv.get("host").cloned().ok_or_else(|| format!("[{name}] missing host"))?;
            let user = kv.get("user").cloned().ok_or_else(|| format!("[{name}] missing user"))?;
            let secret = kv.get("secret").cloned().ok_or_else(|| format!("[{name}] missing secret"))?;
            let port = kv.get("port").and_then(|s| s.parse().ok()).unwrap_or(IAX_PORT_DEFAULT);
            let refresh = kv.get("refresh").and_then(|s| s.parse().ok()).unwrap_or(60);
            let mut cfg = Config::new(name, user, secret);
            cfg.refresh = refresh;
            out.push(Account { cfg, host, port });
        }
        Ok(())
    };

    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
            continue;
        }
        if let Some(name) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
            flush(&mut cur, &mut accounts)?;
            cur = Some((name.trim().to_string(), HashMap::new()));
        } else if let Some((k, v)) = line.split_once('=') {
            if let Some((_, kv)) = cur.as_mut() {
                kv.insert(k.trim().to_lowercase(), v.trim().to_string());
            }
        }
    }
    flush(&mut cur, &mut accounts)?;
    Ok(accounts)
}