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
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
//! Config-backed performance recipe loading and application.
//!
//! The recipe values live in YAML so deployments and release gates can tune
//! server shapes without changing library source. The library owns parsing,
//! validation, and application to [`Config`].

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::api::unified::{
    Config, MediaMode, MediaSessionControllerConfig, RtpSessionBufferConfig,
    RtpTransportBufferConfig,
};
use crate::errors::{Result, SessionError};

const DEFAULT_RECIPE_BOOK: &str = include_str!("../../config/performance-recipes.yaml");

/// Parameterized performance recipe selection.
///
/// `profile` is resolved from a YAML recipe book. When `recipe_path` is
/// omitted, rvoip-sip uses its bundled default recipe book. When `recipe_path`
/// is set, that YAML file is loaded instead.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerformanceConfig {
    /// Recipe name from the selected YAML recipe book.
    pub profile: String,
    /// Expected burst or active-call capacity for capacity-driven recipes.
    pub capacity: Option<usize>,
    /// SDP RTP port used by signaling-only recipes.
    pub signaling_only_rtp_port: Option<u16>,
    /// Optional YAML recipe book path.
    pub recipe_path: Option<PathBuf>,
}

impl PerformanceConfig {
    /// Create a performance config for a named recipe profile.
    pub fn profile(profile: impl Into<String>) -> Self {
        Self {
            profile: profile.into(),
            capacity: None,
            signaling_only_rtp_port: None,
            recipe_path: None,
        }
    }

    /// Endpoint recipe. This is also the implicit endpoint default.
    pub fn endpoint() -> Self {
        Self::profile("endpoint")
    }

    /// PBX-style media server recipe.
    pub fn pbx_media_server(capacity: usize) -> Self {
        Self::profile("pbx-media-server").with_capacity(capacity)
    }

    /// High-performance signaling-only server recipe.
    pub fn signaling_only_server_high_performance(capacity: usize) -> Self {
        Self::profile("signaling-only-server-high-performance")
            .with_capacity(capacity)
            .with_signaling_only_rtp_port(9)
    }

    /// Set the capacity parameter.
    pub fn with_capacity(mut self, capacity: usize) -> Self {
        self.capacity = Some(capacity);
        self
    }

    /// Set the signaling-only SDP RTP port parameter.
    pub fn with_signaling_only_rtp_port(mut self, port: u16) -> Self {
        self.signaling_only_rtp_port = Some(port);
        self
    }

    /// Load recipes from this YAML path instead of the bundled default book.
    pub fn with_recipe_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.recipe_path = Some(path.into());
        self
    }
}

/// YAML performance recipe book.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerformanceRecipeBook {
    /// Recipe schema version.
    pub version: u32,
    /// Named performance profiles.
    pub performance_profiles: BTreeMap<String, PerformanceRecipe>,
}

impl PerformanceRecipeBook {
    /// Parse the bundled default recipe book.
    pub fn bundled() -> Result<Self> {
        Self::from_yaml_str(DEFAULT_RECIPE_BOOK, "bundled default performance recipes")
    }

    /// Load a recipe book from a YAML file.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let text = fs::read_to_string(path).map_err(|e| {
            SessionError::ConfigError(format!(
                "failed to read performance recipe file '{}': {e}",
                path.display()
            ))
        })?;
        Self::from_yaml_str(&text, &path.display().to_string())
    }

    /// Parse a YAML recipe book string.
    pub fn from_yaml_str(text: &str, source: &str) -> Result<Self> {
        let book: Self = serde_yaml::from_str(text).map_err(|e| {
            SessionError::ConfigError(format!(
                "failed to parse performance recipe book {source}: {e}"
            ))
        })?;
        if book.version != 1 {
            return Err(SessionError::ConfigError(format!(
                "unsupported performance recipe book version {}; expected 1",
                book.version
            )));
        }
        Ok(book)
    }

    /// Apply a named performance config to an existing [`Config`].
    pub fn apply(&self, config: Config, performance: &PerformanceConfig) -> Result<Config> {
        let recipe = self
            .performance_profiles
            .get(&performance.profile)
            .ok_or_else(|| {
                let mut names = self
                    .performance_profiles
                    .keys()
                    .cloned()
                    .collect::<Vec<_>>();
                names.sort();
                SessionError::ConfigError(format!(
                    "unknown performance profile '{}'; available profiles: {}",
                    performance.profile,
                    names.join(", ")
                ))
            })?;
        recipe.apply(config, performance)
    }
}

/// One named performance recipe from YAML.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerformanceRecipe {
    /// Human-readable recipe description.
    pub description: Option<String>,
    /// Whether `PerformanceConfig.capacity` is required.
    pub requires_capacity: Option<bool>,
    /// Config field values to apply.
    pub config: PerformanceRecipeConfig,
}

impl PerformanceRecipe {
    fn apply(&self, mut config: Config, performance: &PerformanceConfig) -> Result<Config> {
        if self.requires_capacity.unwrap_or(false) {
            let capacity = performance.capacity.ok_or_else(|| {
                SessionError::ConfigError(format!(
                    "performance profile '{}' requires capacity",
                    performance.profile
                ))
            })?;
            if capacity == 0 {
                return Err(SessionError::ConfigError(
                    "performance capacity must be at least 1".to_string(),
                ));
            }
        }

        let params = RecipeParams {
            capacity: performance.capacity,
            signaling_only_rtp_port: performance.signaling_only_rtp_port,
        };
        self.config.apply(&mut config, &params)?;
        config.validate()?;
        Ok(config)
    }
}

/// Config mutations supported by YAML performance recipes.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerformanceRecipeConfig {
    /// Capacity for the standard SIP signaling queues.
    pub channel_capacity: Option<RecipeUsize>,
    /// Whether automatic `180 Ringing` is sent for inbound INVITEs.
    pub auto_180_ringing: Option<bool>,
    /// Whether automatic `100 Trying` timer tasks are armed.
    pub auto_100_trying: Option<bool>,
    /// Whether inbound INVITEs are accepted before app callbacks.
    pub fast_auto_accept_incoming_calls: Option<bool>,
    /// Enable SIP UDP transport and duplicate-recovery diagnostics.
    pub sip_udp_diagnostics: Option<bool>,
    /// Enable high-cardinality transaction timing diagnostics.
    pub sip_transaction_timing_diagnostics: Option<bool>,
    /// Enable high-cardinality dialog timing diagnostics.
    pub sip_dialog_timing_diagnostics: Option<bool>,
    /// Enable media setup/teardown timing diagnostics.
    pub media_setup_diagnostics: Option<bool>,
    /// Enable cleanup-stage timing diagnostics.
    pub cleanup_diagnostics: Option<bool>,
    /// Enable per-operation cleanup diagnostic log lines.
    pub cleanup_diagnostic_events: Option<bool>,
    /// Active inbound no-RTP watchdog timeout in seconds.
    pub active_call_no_media_timeout_secs: Option<u64>,
    /// Active inbound RTP idle watchdog timeout in seconds.
    pub active_call_media_idle_timeout_secs: Option<u64>,
    /// SIP UDP receive socket buffer size in bytes.
    pub sip_udp_recv_buffer_size: Option<usize>,
    /// SIP UDP send socket buffer size in bytes.
    pub sip_udp_send_buffer_size: Option<usize>,
    /// UDP parse worker count.
    pub sip_udp_parse_workers: Option<usize>,
    /// Per-worker UDP parse queue capacity.
    pub sip_udp_parse_queue_capacity: Option<RecipeUsize>,
    /// UDP parse dispatch strategy.
    pub sip_udp_parse_dispatch: Option<RecipeUdpParseDispatch>,
    /// Transport-manager event dispatch worker count.
    pub sip_transport_dispatch_workers: Option<usize>,
    /// Transport-manager event dispatch queue capacity.
    pub sip_transport_dispatch_queue_capacity: Option<RecipeUsize>,
    /// Transaction-manager ingress dispatch worker count.
    pub sip_transaction_dispatch_workers: Option<usize>,
    /// Transaction-manager ingress dispatch queue capacity.
    pub sip_transaction_dispatch_queue_capacity: Option<RecipeUsize>,
    /// Transaction-manager ACK/BYE priority burst limit.
    pub sip_transaction_dispatch_priority_burst_max: Option<usize>,
    /// INVITE 2xx retransmit due-item budget per maintenance tick.
    pub sip_invite_2xx_retransmit_max_due_per_tick: Option<usize>,
    /// Per-transaction command channel capacity.
    pub sip_transaction_command_channel_capacity: Option<usize>,
    /// Dialog-core transaction-event dispatch worker count.
    pub sip_dialog_dispatch_workers: Option<usize>,
    /// Dialog-core transaction-event dispatch queue capacity.
    pub sip_dialog_dispatch_queue_capacity: Option<RecipeUsize>,
    /// App-session event dispatcher worker count.
    pub session_event_dispatcher_workers: Option<usize>,
    /// Per-worker app-session event dispatcher queue capacity.
    pub session_event_dispatcher_channel_capacity: Option<RecipeUsize>,
    /// Media behavior.
    pub media_mode: Option<RecipeMediaMode>,
    /// SDP RTP port for signaling-only media mode.
    pub signaling_only_rtp_port: Option<RecipeU16>,
    /// RTP media port range by start and requested capacity.
    pub media_port_capacity: Option<RecipeMediaPortCapacity>,
    /// Media-core session and RTP allocator capacity hint.
    pub media_session_capacity: Option<RecipeUsize>,
    /// RTP session queue sizing.
    pub rtp_session_buffer_config: Option<RecipeRtpSessionBufferConfig>,
    /// RTP transport event and receive buffer sizing.
    pub rtp_transport_buffer_config: Option<RecipeRtpTransportBufferConfig>,
    /// Media-core controller pool and capacity tuning.
    pub media_session_controller_config: Option<RecipeMediaSessionControllerConfig>,
    /// Server-side active call capacity hint.
    pub server_call_capacity: Option<RecipeUsize>,
    /// Server-side inbound call admission limit.
    pub server_call_admission_limit: Option<RecipeUsize>,
    /// Server-side inbound call admission soft pacing threshold.
    pub server_call_admission_soft_limit: Option<RecipeUsize>,
    /// Delay in milliseconds while above the soft admission threshold.
    pub server_call_admission_pacing_delay_ms: Option<u64>,
    /// Retry-After seconds for server overload rejections.
    pub server_overload_retry_after_secs: Option<u32>,
}

impl PerformanceRecipeConfig {
    fn apply(&self, config: &mut Config, params: &RecipeParams) -> Result<()> {
        if let Some(capacity) = &self.channel_capacity {
            *config = config
                .clone()
                .with_channel_capacity(capacity.resolve(params, "channelCapacity")?);
        }
        if let Some(enabled) = self.auto_180_ringing {
            config.auto_180_ringing = enabled;
        }
        if let Some(enabled) = self.auto_100_trying {
            config.auto_100_trying = enabled;
        }
        if let Some(enabled) = self.fast_auto_accept_incoming_calls {
            config.fast_auto_accept_incoming_calls = enabled;
        }
        if let Some(enabled) = self.sip_udp_diagnostics {
            config.sip_udp_diagnostics = enabled;
        }
        if let Some(enabled) = self.sip_transaction_timing_diagnostics {
            config.sip_transaction_timing_diagnostics = enabled;
        }
        if let Some(enabled) = self.sip_dialog_timing_diagnostics {
            config.sip_dialog_timing_diagnostics = enabled;
        }
        if let Some(enabled) = self.media_setup_diagnostics {
            config.media_setup_diagnostics = enabled;
        }
        if let Some(enabled) = self.cleanup_diagnostics {
            config.cleanup_diagnostics = enabled;
        }
        if let Some(enabled) = self.cleanup_diagnostic_events {
            config.cleanup_diagnostic_events = enabled;
        }
        if let Some(seconds) = self.active_call_no_media_timeout_secs {
            config.active_call_no_media_timeout_secs = seconds;
        }
        if let Some(seconds) = self.active_call_media_idle_timeout_secs {
            config.active_call_media_idle_timeout_secs = seconds;
        }
        if let Some(size) = self.sip_udp_recv_buffer_size {
            config.sip_udp_recv_buffer_size = Some(size);
        }
        if let Some(size) = self.sip_udp_send_buffer_size {
            config.sip_udp_send_buffer_size = Some(size);
        }
        if let Some(workers) = self.sip_udp_parse_workers {
            config.sip_udp_parse_workers = Some(workers);
        }
        if let Some(capacity) = &self.sip_udp_parse_queue_capacity {
            config.sip_udp_parse_queue_capacity =
                Some(capacity.resolve(params, "sipUdpParseQueueCapacity")?);
        }
        if let Some(dispatch) = self.sip_udp_parse_dispatch {
            config.sip_udp_parse_dispatch = Some(dispatch.into());
        }
        if let Some(workers) = self.sip_transport_dispatch_workers {
            config.sip_transport_dispatch_workers = Some(workers);
        }
        if let Some(capacity) = &self.sip_transport_dispatch_queue_capacity {
            config.sip_transport_dispatch_queue_capacity =
                Some(capacity.resolve(params, "sipTransportDispatchQueueCapacity")?);
        }
        if let Some(workers) = self.sip_transaction_dispatch_workers {
            config.sip_transaction_dispatch_workers = Some(workers);
        }
        if let Some(capacity) = &self.sip_transaction_dispatch_queue_capacity {
            config.sip_transaction_dispatch_queue_capacity =
                Some(capacity.resolve(params, "sipTransactionDispatchQueueCapacity")?);
        }
        if let Some(max_burst) = self.sip_transaction_dispatch_priority_burst_max {
            config.sip_transaction_dispatch_priority_burst_max = Some(max_burst);
        }
        if let Some(max_due_per_tick) = self.sip_invite_2xx_retransmit_max_due_per_tick {
            config.sip_invite_2xx_retransmit_max_due_per_tick = Some(max_due_per_tick);
        }
        if let Some(capacity) = self.sip_transaction_command_channel_capacity {
            config.sip_transaction_command_channel_capacity = Some(capacity);
        }
        if let Some(workers) = self.sip_dialog_dispatch_workers {
            config.sip_dialog_dispatch_workers = Some(workers);
        }
        if let Some(capacity) = &self.sip_dialog_dispatch_queue_capacity {
            config.sip_dialog_dispatch_queue_capacity =
                Some(capacity.resolve(params, "sipDialogDispatchQueueCapacity")?);
        }
        if let Some(workers) = self.session_event_dispatcher_workers {
            config.session_event_dispatcher_workers = workers;
        }
        if let Some(capacity) = &self.session_event_dispatcher_channel_capacity {
            config.session_event_dispatcher_channel_capacity =
                capacity.resolve(params, "sessionEventDispatcherChannelCapacity")?;
        }
        if let Some(capacity) = &self.server_call_capacity {
            config.server_call_capacity = Some(capacity.resolve(params, "serverCallCapacity")?);
        }
        if let Some(limit) = &self.server_call_admission_limit {
            config.server_call_admission_limit =
                Some(limit.resolve(params, "serverCallAdmissionLimit")?);
        }
        if let Some(limit) = &self.server_call_admission_soft_limit {
            config.server_call_admission_soft_limit =
                Some(limit.resolve(params, "serverCallAdmissionSoftLimit")?);
        }
        if let Some(delay_ms) = self.server_call_admission_pacing_delay_ms {
            config.server_call_admission_pacing_delay_ms = Some(delay_ms);
        }
        if let Some(seconds) = self.server_overload_retry_after_secs {
            config.server_overload_retry_after_secs = Some(seconds);
        }
        if let Some(port_capacity) = &self.media_port_capacity {
            *config = config.clone().with_media_port_capacity(
                port_capacity.start,
                port_capacity
                    .capacity
                    .resolve(params, "mediaPortCapacity.capacity")?,
            );
        }
        if let Some(capacity) = &self.media_session_capacity {
            config.media_session_capacity = Some(capacity.resolve(params, "mediaSessionCapacity")?);
        }
        if let Some(recipe_config) = &self.media_session_controller_config {
            let mut controller_config = config.media_session_controller_config.clone();
            recipe_config.apply(&mut controller_config, params)?;
            config.media_session_controller_config = controller_config;
            config.rtp_session_buffer_config = config
                .media_session_controller_config
                .rtp_session_buffer_config;
            config.rtp_transport_buffer_config = config
                .media_session_controller_config
                .rtp_transport_buffer_config;
        }
        if let Some(recipe_config) = &self.rtp_session_buffer_config {
            let mut rtp_config = config.rtp_session_buffer_config;
            recipe_config.apply(&mut rtp_config, params)?;
            config.rtp_session_buffer_config = rtp_config;
            config
                .media_session_controller_config
                .rtp_session_buffer_config = rtp_config;
        }
        if let Some(recipe_config) = &self.rtp_transport_buffer_config {
            let mut rtp_config = config.rtp_transport_buffer_config;
            recipe_config.apply(&mut rtp_config, params)?;
            config.rtp_transport_buffer_config = rtp_config;
            config
                .media_session_controller_config
                .rtp_transport_buffer_config = rtp_config;
        }
        if let Some(mode) = self.media_mode {
            config.media_mode = match mode {
                RecipeMediaMode::Enabled => MediaMode::Enabled,
                RecipeMediaMode::SignalingOnly => {
                    let port = self
                        .signaling_only_rtp_port
                        .as_ref()
                        .map(|p| p.resolve(params, "signalingOnlyRtpPort"))
                        .transpose()?
                        .unwrap_or(9);
                    MediaMode::SignalingOnly { sdp_rtp_port: port }
                }
            };
        }
        Ok(())
    }
}

struct RecipeParams {
    capacity: Option<usize>,
    signaling_only_rtp_port: Option<u16>,
}

/// Recipe value that can be a literal integer or `$capacity`.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum RecipeUsize {
    /// Literal value.
    Literal(usize),
    /// Variable reference.
    Variable(String),
}

impl RecipeUsize {
    fn resolve(&self, params: &RecipeParams, field: &str) -> Result<usize> {
        match self {
            Self::Literal(value) => Ok(*value),
            Self::Variable(name) if name == "$capacity" || name == "capacity" => {
                params.capacity.ok_or_else(|| {
                    SessionError::ConfigError(format!("{field} requires performance capacity"))
                })
            }
            Self::Variable(name) if name == "$capacity90Percent" || name == "capacity90Percent" => {
                params
                    .capacity
                    .map(|capacity| capacity.saturating_mul(90).div_ceil(100).max(1))
                    .ok_or_else(|| {
                        SessionError::ConfigError(format!("{field} requires performance capacity"))
                    })
            }
            Self::Variable(name) => Err(SessionError::ConfigError(format!(
                "unsupported variable '{name}' in performance recipe field {field}"
            ))),
        }
    }
}

/// Recipe value that can be a literal port or `$signalingOnlyRtpPort`.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum RecipeU16 {
    /// Literal value.
    Literal(u16),
    /// Variable reference.
    Variable(String),
}

impl RecipeU16 {
    fn resolve(&self, params: &RecipeParams, field: &str) -> Result<u16> {
        match self {
            Self::Literal(value) => Ok(*value),
            Self::Variable(name)
                if name == "$signalingOnlyRtpPort" || name == "signalingOnlyRtpPort" =>
            {
                Ok(params.signaling_only_rtp_port.unwrap_or(9))
            }
            Self::Variable(name) => Err(SessionError::ConfigError(format!(
                "unsupported variable '{name}' in performance recipe field {field}"
            ))),
        }
    }
}

/// UDP parse dispatch strategy in recipe YAML.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RecipeUdpParseDispatch {
    /// Preserve per-source ordering.
    SourceHash,
    /// Spread received datagrams across workers.
    RoundRobin,
}

impl From<RecipeUdpParseDispatch> for rvoip_sip_transport::UdpParseDispatch {
    fn from(value: RecipeUdpParseDispatch) -> Self {
        match value {
            RecipeUdpParseDispatch::SourceHash => Self::SourceHash,
            RecipeUdpParseDispatch::RoundRobin => Self::RoundRobin,
        }
    }
}

/// Media mode in recipe YAML.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RecipeMediaMode {
    /// Use real media-core RTP allocation.
    Enabled,
    /// Generate SDP without media-core RTP allocation.
    SignalingOnly,
}

/// Media port capacity recipe value.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecipeMediaPortCapacity {
    /// RTP media port range start.
    pub start: u16,
    /// Requested number of ports.
    pub capacity: RecipeUsize,
}

/// RTP session buffer config recipe values.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecipeRtpSessionBufferConfig {
    /// Bounded sender queue capacity in RTP packets.
    pub sender_channel_capacity: Option<RecipeUsize>,
    /// Bounded legacy polling receive queue capacity in RTP packets.
    pub receiver_channel_capacity: Option<RecipeUsize>,
    /// Broadcast ring capacity for RTP session events.
    pub event_channel_capacity: Option<RecipeUsize>,
}

impl RecipeRtpSessionBufferConfig {
    fn apply(&self, config: &mut RtpSessionBufferConfig, params: &RecipeParams) -> Result<()> {
        if let Some(value) = &self.sender_channel_capacity {
            config.sender_channel_capacity =
                value.resolve(params, "rtpSessionBufferConfig.senderChannelCapacity")?;
        }
        if let Some(value) = &self.receiver_channel_capacity {
            config.receiver_channel_capacity =
                value.resolve(params, "rtpSessionBufferConfig.receiverChannelCapacity")?;
        }
        if let Some(value) = &self.event_channel_capacity {
            config.event_channel_capacity =
                value.resolve(params, "rtpSessionBufferConfig.eventChannelCapacity")?;
        }
        Ok(())
    }
}

/// RTP transport buffer config recipe values.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecipeRtpTransportBufferConfig {
    /// Broadcast ring capacity for RTP/RTCP transport events.
    pub event_channel_capacity: Option<RecipeUsize>,
    /// UDP RTP receive buffer size in bytes.
    pub recv_buffer_size: Option<RecipeUsize>,
    /// UDP RTCP receive buffer size in bytes for separate RTCP sockets.
    pub rtcp_recv_buffer_size: Option<RecipeUsize>,
}

impl RecipeRtpTransportBufferConfig {
    fn apply(&self, config: &mut RtpTransportBufferConfig, params: &RecipeParams) -> Result<()> {
        if let Some(value) = &self.event_channel_capacity {
            config.event_channel_capacity =
                value.resolve(params, "rtpTransportBufferConfig.eventChannelCapacity")?;
        }
        if let Some(value) = &self.recv_buffer_size {
            config.recv_buffer_size =
                value.resolve(params, "rtpTransportBufferConfig.recvBufferSize")?;
        }
        if let Some(value) = &self.rtcp_recv_buffer_size {
            config.rtcp_recv_buffer_size =
                value.resolve(params, "rtpTransportBufferConfig.rtcpRecvBufferSize")?;
        }
        Ok(())
    }
}

/// Media controller buffer and pool config recipe values.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecipeMediaSessionControllerConfig {
    /// Initial capacity for hot session indexes.
    pub capacity_hint: Option<RecipeUsize>,
    /// Shared audio frame pool configuration.
    pub audio_frame_pool: Option<RecipeAudioFramePoolConfig>,
    /// RTP output buffer size in bytes.
    pub rtp_buffer_size: Option<RecipeUsize>,
    /// Initial RTP output buffer count.
    pub rtp_buffer_initial_count: Option<RecipeUsize>,
    /// Maximum RTP output buffer count.
    pub rtp_buffer_max_count: Option<RecipeUsize>,
    /// RTP session queue and reusable send-buffer sizing.
    pub rtp_session_buffer_config: Option<RecipeRtpSessionBufferConfig>,
    /// RTP transport event and receive buffer sizing.
    pub rtp_transport_buffer_config: Option<RecipeRtpTransportBufferConfig>,
}

impl RecipeMediaSessionControllerConfig {
    fn apply(
        &self,
        config: &mut MediaSessionControllerConfig,
        params: &RecipeParams,
    ) -> Result<()> {
        if let Some(value) = &self.capacity_hint {
            config.capacity_hint =
                value.resolve(params, "mediaSessionControllerConfig.capacityHint")?;
        }
        if let Some(pool) = &self.audio_frame_pool {
            pool.apply(config, params)?;
        }
        if let Some(value) = &self.rtp_buffer_size {
            config.rtp_buffer_size =
                value.resolve(params, "mediaSessionControllerConfig.rtpBufferSize")?;
        }
        if let Some(value) = &self.rtp_buffer_initial_count {
            config.rtp_buffer_initial_count =
                value.resolve(params, "mediaSessionControllerConfig.rtpBufferInitialCount")?;
        }
        if let Some(value) = &self.rtp_buffer_max_count {
            config.rtp_buffer_max_count =
                value.resolve(params, "mediaSessionControllerConfig.rtpBufferMaxCount")?;
        }
        if let Some(rtp_config) = &self.rtp_session_buffer_config {
            rtp_config.apply(&mut config.rtp_session_buffer_config, params)?;
        }
        if let Some(rtp_config) = &self.rtp_transport_buffer_config {
            rtp_config.apply(&mut config.rtp_transport_buffer_config, params)?;
        }
        Ok(())
    }
}

/// Audio frame pool config recipe values.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecipeAudioFramePoolConfig {
    /// Initial pool size.
    pub initial_size: Option<RecipeUsize>,
    /// Maximum pool size.
    pub max_size: Option<RecipeUsize>,
    /// Sample rate for pooled frames.
    pub sample_rate: Option<u32>,
    /// Number of channels for pooled frames.
    pub channels: Option<u8>,
    /// Samples per frame.
    pub samples_per_frame: Option<RecipeUsize>,
}

impl RecipeAudioFramePoolConfig {
    fn apply(
        &self,
        config: &mut MediaSessionControllerConfig,
        params: &RecipeParams,
    ) -> Result<()> {
        if let Some(value) = &self.initial_size {
            config.audio_frame_pool.initial_size = value.resolve(
                params,
                "mediaSessionControllerConfig.audioFramePool.initialSize",
            )?;
        }
        if let Some(value) = &self.max_size {
            config.audio_frame_pool.max_size = value.resolve(
                params,
                "mediaSessionControllerConfig.audioFramePool.maxSize",
            )?;
        }
        if let Some(value) = self.sample_rate {
            config.audio_frame_pool.sample_rate = value;
        }
        if let Some(value) = self.channels {
            config.audio_frame_pool.channels = value;
        }
        if let Some(value) = &self.samples_per_frame {
            config.audio_frame_pool.samples_per_frame = value.resolve(
                params,
                "mediaSessionControllerConfig.audioFramePool.samplesPerFrame",
            )?;
        }
        Ok(())
    }
}