rvoip-sip 0.2.4

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
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
//! Core types for rvoip-sip
//!
//! This module defines the fundamental types used throughout the rvoip-sip crate.
//! It includes identifiers, events, and common data structures.

use serde::{Deserialize, Serialize};
use std::fmt;
use uuid::Uuid;

// Re-export types from api::types for backwards compatibility
pub use crate::api::types::{
    AudioFrame, AudioStreamConfig, CallDecision, CallDirection, CallSession, IncomingCall,
    MediaInfo, PreparedCall, Session, SessionRole, SessionStats, StatusCode, TerminationReason,
};

// Re-export the ID types from state_table::types for convenience
pub use crate::state_table::types::{DialogId, MediaSessionId, SessionId};

/// Reasons for call failure
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum FailureReason {
    Timeout,
    Rejected,
    NetworkError,
    MediaError,
    ProtocolError,
    Other,
}

impl fmt::Display for FailureReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FailureReason::Timeout => write!(f, "Timeout"),
            FailureReason::Rejected => write!(f, "Rejected"),
            FailureReason::NetworkError => write!(f, "Network error"),
            FailureReason::MediaError => write!(f, "Media error"),
            FailureReason::ProtocolError => write!(f, "Protocol error"),
            FailureReason::Other => write!(f, "Other error"),
        }
    }
}

/// Call states
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum CallState {
    Idle,
    Initiating,
    /// Local user requested cancel before a provisional response. RFC 3261
    /// forbids sending CANCEL until a provisional response has arrived.
    CancelPending,
    /// CANCEL has been sent, or a late 200 OK is being ACK/BYE cleaned up.
    Cancelling,
    Ringing,
    Answering, // UAS accepted call, sending 200 OK, waiting for ACK
    /// UAS sent 200 OK and local hangup was requested before ACK arrived.
    AnsweringHangupPending,
    EarlyMedia,
    Active,
    /// Sent a hold re-INVITE, awaiting 2xx (RFC 3261 §14.1). Session
    /// parameters remain as they were in `Active` until the peer confirms.
    HoldPending,
    OnHold,
    Resuming,
    Muted,
    Bridged, // Two endpoint calls bridged together
    Transferring,
    TransferringCall, // Transfer recipient processing transfer
    ConsultationCall,
    Terminating,
    Terminated,
    Cancelled,
    Failed(FailureReason),

    // Registration states
    Registering,
    Registered,
    Unregistering,

    // Subscription/Presence states
    Subscribing,
    Subscribed,
    Publishing,

    // Authentication flow
    Authenticating, // Processing authentication challenge

    // Messaging
    Messaging, // Handling SIP MESSAGE requests
}

impl CallState {
    /// Check if this is a final state (call is over)
    pub fn is_final(&self) -> bool {
        matches!(
            self,
            CallState::Terminated | CallState::Cancelled | CallState::Failed(_)
        )
    }

    /// Check if the call is in progress
    pub fn is_in_progress(&self) -> bool {
        matches!(
            self,
            CallState::Initiating
                | CallState::CancelPending
                | CallState::Cancelling
                | CallState::Ringing
                | CallState::Answering
                | CallState::AnsweringHangupPending
                | CallState::Active
                | CallState::HoldPending
                | CallState::OnHold
                | CallState::EarlyMedia
                | CallState::Resuming
                | CallState::Muted
                | CallState::Bridged
                | CallState::Transferring
                | CallState::TransferringCall
                | CallState::ConsultationCall
        )
    }
}

impl fmt::Display for CallState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CallState::Idle => write!(f, "Idle"),
            CallState::Initiating => write!(f, "Initiating"),
            CallState::CancelPending => write!(f, "CancelPending"),
            CallState::Cancelling => write!(f, "Cancelling"),
            CallState::Ringing => write!(f, "Ringing"),
            CallState::Answering => write!(f, "Answering"),
            CallState::AnsweringHangupPending => write!(f, "AnsweringHangupPending"),
            CallState::EarlyMedia => write!(f, "EarlyMedia"),
            CallState::Active => write!(f, "Active"),
            CallState::HoldPending => write!(f, "HoldPending"),
            CallState::OnHold => write!(f, "OnHold"),
            CallState::Resuming => write!(f, "Resuming"),
            CallState::Muted => write!(f, "Muted"),
            CallState::Bridged => write!(f, "Bridged"),
            CallState::Transferring => write!(f, "Transferring"),
            CallState::TransferringCall => write!(f, "TransferringCall"),
            CallState::ConsultationCall => write!(f, "ConsultationCall"),
            CallState::Terminating => write!(f, "Terminating"),
            CallState::Terminated => write!(f, "Terminated"),
            CallState::Cancelled => write!(f, "Cancelled"),
            CallState::Failed(reason) => write!(f, "Failed({})", reason),

            // Registration states
            CallState::Registering => write!(f, "Registering"),
            CallState::Registered => write!(f, "Registered"),
            CallState::Unregistering => write!(f, "Unregistering"),

            // Subscription/Presence states
            CallState::Subscribing => write!(f, "Subscribing"),
            CallState::Subscribed => write!(f, "Subscribed"),
            CallState::Publishing => write!(f, "Publishing"),

            // Authentication and routing states
            CallState::Authenticating => write!(f, "Authenticating"),
            CallState::Messaging => write!(f, "Messaging"),
        }
    }
}

/// Call information for active calls
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallInfo {
    pub session_id: SessionId,
    pub from: String,
    pub to: String,
    pub state: CallState,
    pub start_time: std::time::SystemTime,
    pub media_active: bool,
}

/// Session information for queries
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    pub session_id: SessionId,
    pub from: String,
    pub to: String,
    pub state: CallState,
    pub start_time: std::time::SystemTime,
    pub media_active: bool,
}

/// Audio frame subscriber for receiving decoded audio frames
pub struct AudioFrameSubscriber {
    /// Session ID this subscriber is associated with
    pub session_id: SessionId,
    /// Receiver for audio frames
    pub receiver: tokio::sync::mpsc::Receiver<rvoip_media_core::types::AudioFrame>,
}

impl AudioFrameSubscriber {
    /// Create a new audio frame subscriber
    pub fn new(
        session_id: SessionId,
        receiver: tokio::sync::mpsc::Receiver<rvoip_media_core::types::AudioFrame>,
    ) -> Self {
        Self {
            session_id,
            receiver,
        }
    }

    /// Receive the next audio frame (async)
    pub async fn recv(&mut self) -> Option<rvoip_media_core::types::AudioFrame> {
        self.receiver.recv().await
    }

    /// Try to receive an audio frame (non-blocking)
    pub fn try_recv(
        &mut self,
    ) -> Result<rvoip_media_core::types::AudioFrame, tokio::sync::mpsc::error::TryRecvError> {
        self.receiver.try_recv()
    }
}

/// Session events that flow through the system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SessionEvent {
    /// Incoming call received
    IncomingCall {
        from: String,
        to: String,
        call_id: String,
        dialog_id: DialogId,
        sdp: Option<String>,
    },
    /// Call progress update
    CallProgress {
        dialog_id: DialogId,
        status_code: u16,
        reason: Option<String>,
    },
    /// Call was answered
    CallAnswered {
        dialog_id: DialogId,
        sdp: Option<String>,
    },
    /// Call was terminated
    CallTerminated {
        dialog_id: DialogId,
        reason: Option<String>,
    },
    /// Call failed
    CallFailed { dialog_id: DialogId, reason: String },
    /// Media state changed
    MediaStateChanged {
        media_id: MediaSessionId,
        state: MediaState,
    },
    /// DTMF digit received
    DtmfReceived { dialog_id: DialogId, digit: char },
    /// Hold request
    HoldRequest { dialog_id: DialogId },
    /// Resume request
    ResumeRequest { dialog_id: DialogId },
    /// Transfer request
    TransferRequest {
        dialog_id: DialogId,
        target: String,
        attended: bool,
    },
    /// Registration started
    RegistrationStarted {
        dialog_id: DialogId,
        uri: String,
        expires: u32,
    },
    /// Registration successful
    RegistrationSuccess {
        dialog_id: DialogId,
        uri: String,
        expires: u32,
    },
    /// Registration failed
    RegistrationFailed {
        dialog_id: DialogId,
        reason: String,
        status_code: u16,
    },
    /// Unregistration complete
    UnregistrationComplete { dialog_id: DialogId },
    /// Subscription started
    SubscriptionStarted {
        dialog_id: DialogId,
        uri: String,
        event_package: String,
        expires: u32,
    },
    /// Subscription accepted
    SubscriptionAccepted { dialog_id: DialogId, expires: u32 },
    /// Subscription failed
    SubscriptionFailed {
        dialog_id: DialogId,
        reason: String,
        status_code: u16,
    },
    /// NOTIFY received
    NotifyReceived {
        dialog_id: DialogId,
        event_package: String,
        body: Option<String>,
    },
    /// MESSAGE sent
    MessageSent {
        dialog_id: DialogId,
        to: String,
        body: String,
    },
    /// MESSAGE received
    MessageReceived {
        dialog_id: DialogId,
        from: String,
        body: String,
    },
    /// MESSAGE delivery confirmed
    MessageDelivered { dialog_id: DialogId },
    /// MESSAGE delivery failed
    MessageDeliveryFailed {
        dialog_id: DialogId,
        reason: String,
        status_code: u16,
    },
}

/// Media session state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MediaState {
    /// Media not initialized
    Idle,
    /// Negotiating media
    Negotiating,
    /// Media is active
    Active,
    /// Media is on hold
    OnHold,
    /// Media failed
    Failed(String),
    /// Media session ended
    Terminated,
}

/// Transfer status
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransferStatus {
    /// Transfer initiated
    Initiated,
    /// Transfer in progress
    InProgress,
    /// Transfer completed
    Completed,
    /// Transfer failed
    Failed(String),
}

/// Media direction for hold/resume
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MediaDirection {
    /// Send and receive media
    SendRecv,
    /// Send only (remote on hold)
    SendOnly,
    /// Receive only (local on hold)
    RecvOnly,
    /// No media flow (both on hold)
    Inactive,
}

/// Registration state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RegistrationState {
    /// Not registered
    Unregistered,
    /// Registration in progress
    Registering,
    /// Successfully registered
    Registered,
    /// Registration failed
    Failed(String),
    /// Unregistering
    Unregistering,
}

/// Presence status types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PresenceStatus {
    /// Available
    Available,
    /// Away
    Away,
    /// Busy
    Busy,
    /// Do not disturb
    DoNotDisturb,
    /// Offline
    Offline,
    /// Custom status
    Custom(String),
}

/// User credentials for authentication
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Credentials {
    /// Username/account
    pub username: String,
    /// Password
    pub password: String,
    /// Optional realm
    pub realm: Option<String>,
}

impl Credentials {
    /// Create new credentials
    pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
        Self {
            username: username.into(),
            password: password.into(),
            realm: None,
        }
    }

    /// Set the realm
    pub fn with_realm(mut self, realm: impl Into<String>) -> Self {
        self.realm = Some(realm.into());
        self
    }
}

/// Audio device information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioDevice {
    /// Device ID
    pub id: String,
    /// Device name
    pub name: String,
    /// Is input device
    pub is_input: bool,
    /// Is output device
    pub is_output: bool,
    /// Sample rates supported
    pub sample_rates: Vec<u32>,
    /// Number of channels
    pub channels: u8,
}

/// Conference identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ConferenceId(pub Uuid);

impl ConferenceId {
    /// Create a new conference ID
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }
}

impl Default for ConferenceId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for ConferenceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Call detail record for billing/logging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallDetailRecord {
    /// Session ID
    pub session_id: SessionId,
    /// Dialog ID
    pub dialog_id: DialogId,
    /// Caller
    pub from: String,
    /// Called party
    pub to: String,
    /// Start time
    pub start_time: std::time::SystemTime,
    /// End time
    pub end_time: Option<std::time::SystemTime>,
    /// Duration in seconds
    pub duration: Option<u64>,
    /// Termination reason
    pub termination_reason: Option<String>,
    /// SIP Call-ID
    pub call_id: String,
}

/// Information about an incoming call
#[derive(Debug, Clone)]
pub struct IncomingCallInfo {
    /// Session ID assigned to this call
    pub session_id: SessionId,
    /// Dialog ID for this call
    pub dialog_id: DialogId,
    /// Caller URI
    pub from: String,
    /// Called party URI
    pub to: String,
    /// SIP Call-ID
    pub call_id: String,
    /// `P-Asserted-Identity` header value (RFC 3325 §9.1) when the inbound
    /// INVITE carried one — typical on calls coming from a carrier trunk
    /// or trusted PBX. The string is the wire form of the header value
    /// (e.g. `"\"Alice\" <sip:alice@example.com>, <tel:+14155551234>"`);
    /// callers wanting structured access can re-parse with
    /// `rvoip_sip_core::types::p_asserted_identity::PAssertedIdentity::from_str`.
    pub p_asserted_identity: Option<String>,
}