aic-sdk 0.25.0

ai-coustics SDK
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
use crate::{energy_vad::EnergyVadContext, error::*, model::Model};

use aic_sdk_sys::{AicProcessorParameter::*, *};

use std::{ffi::CString, marker::PhantomData, ptr};

/// Audio processing configuration passed to [`Processor::initialize`],
/// [`Vad::initialize`](crate::Vad::initialize) and
/// [`Collector::initialize`](crate::Collector::initialize).
///
/// Use [`ProcessorConfig::optimal`] as a starting point, then adjust fields
/// to match your stream layout.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProcessorConfig {
    /// Sample rate in Hz (8000 - 192000).
    pub sample_rate: u32,
    /// Number of samples passed to each [`Processor::process`],
    /// [`Vad::process`](crate::Vad::process) or
    /// [`Collector::buffer`](crate::Collector::buffer) call (the maximum, if
    /// `variable_block_size` is `true`).
    /// Note that using a non-optimal block size increases latency.
    pub block_size: usize,
    /// If `true`, permits shorter calls at the cost of added delay.
    /// Calls larger than `block_size` are always rejected.
    pub variable_block_size: bool,
}

impl ProcessorConfig {
    /// Returns a [`ProcessorConfig`] pre-filled with the model's optimal sample rate and block size.
    ///
    /// `variable_block_size` will be set to `false`. Enable variable block sizes
    /// by using the builder pattern.
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, ProcessorConfig, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let processor = Processor::new(&model, &license_key)?;
    /// let config = ProcessorConfig::optimal(&model).with_variable_block_size(true);
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    ///
    /// If you need to configure a non-optimal sample rate or block size,
    /// construct the [`ProcessorConfig`] struct directly. For example:
    /// ```rust,no_run
    /// # use aic_sdk::{Model, ProcessorConfig};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let config = ProcessorConfig {
    ///     sample_rate: 44100,
    ///     block_size: model.optimal_block_size(44100),
    ///     variable_block_size: true,
    /// };
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn optimal(model: &Model) -> Self {
        let sample_rate = model.optimal_sample_rate();
        let block_size = model.optimal_block_size(sample_rate);
        ProcessorConfig {
            sample_rate,
            block_size,
            variable_block_size: false,
        }
    }

    /// Enables or disables variable block size support.
    ///
    /// When enabled, permits processing calls shorter than `block_size` at the cost of
    /// added latency.
    ///
    /// # Arguments
    ///
    /// * `variable_block_size` - `true` to enable variable block sizes, `false` for fixed size
    pub fn with_variable_block_size(mut self, variable_block_size: bool) -> Self {
        self.variable_block_size = variable_block_size;
        self
    }
}

/// Configurable parameters for audio enhancement
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProcessorParameter {
    /// Controls whether audio processing is bypassed while preserving algorithmic delay.
    ///
    /// When enabled, the input audio passes through unmodified, but the output is still
    /// delayed by the same amount as during normal processing. This ensures seamless
    /// transitions when toggling enhancement on/off without audible clicks or timing shifts.
    ///
    /// **Range:** 0.0 to 1.0
    /// - **0.0:** Enhancement active (normal processing)
    /// - **1.0:** Bypass enabled (latency-compensated passthrough)
    ///
    /// **Default:** 0.0
    Bypass,
    /// A tunable parameter to optimize for specific STT engines, deployment environments,
    /// and user experience requirements.
    ///
    /// The exact behavior depends on the active model:
    /// - **Quail Models:** Controls how aggressively the model suppresses noise. When used
    ///   with Quail Voice Focus, it also suppresses background and competing speech.
    /// - **Rook Models:** Controls the mixback and therefore the intensity of the
    ///   enhancement.
    ///
    /// **Range:** 0.0 to 1.0
    EnhancementLevel,
}

impl From<ProcessorParameter> for AicProcessorParameter::Type {
    fn from(parameter: ProcessorParameter) -> Self {
        match parameter {
            ProcessorParameter::Bypass => AIC_PROCESSOR_PARAMETER_BYPASS,
            ProcessorParameter::EnhancementLevel => AIC_PROCESSOR_PARAMETER_ENHANCEMENT_LEVEL,
        }
    }
}

/// OpenTelemetry configuration for a [`Processor`] or [`Vad`](crate::Vad).
///
/// Pass to [`Processor::with_otel_config`] or [`Vad::with_otel_config`](crate::Vad::with_otel_config)
/// to control telemetry on a per-instance basis. When no [`OtelConfig`] is provided (e.g. when
/// using [`Processor::new`]), telemetry is configured according to the runtime environment
/// (e.g. the `AIC_SDK_OTEL_ENABLE` environment variable).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OtelConfig {
    /// Whether to enable OpenTelemetry telemetry.
    ///
    /// Overrides the `AIC_SDK_OTEL_ENABLE` environment variable.
    pub enable: bool,
    /// Optional session ID for telemetry. If `None`, a random session ID is generated.
    pub session_id: Option<String>,
    /// OpenTelemetry metric export interval in milliseconds.
    ///
    /// Set to `0` to use the SDK default of 60 000 ms.
    pub export_interval_ms: u32,
}

impl OtelConfig {
    /// Returns an [`OtelConfig`] with telemetry disabled.
    pub fn disabled() -> Self {
        Self {
            enable: false,
            session_id: None,
            export_interval_ms: 0,
        }
    }

    /// Returns an [`OtelConfig`] with telemetry enabled.
    pub fn enabled() -> Self {
        Self {
            enable: true,
            session_id: None,
            export_interval_ms: 0,
        }
    }

    /// Returns an [`OtelConfig`] with telemetry enabled and the provided session ID.
    pub fn with_session_id(session_id: impl Into<String>) -> Self {
        Self {
            enable: true,
            session_id: Some(session_id.into()),
            export_interval_ms: 0,
        }
    }
}

/// Thread-safe control handle for a [`Processor`].
///
/// Create one with [`Processor::context`]. Every method on this type maps to an SDK
/// function that can be called from any thread, so a context can be moved to another thread to
/// read and write parameters, query the audio delay, or reset the processor while audio is being
/// processed elsewhere.
///
/// Dropping the context does not destroy the processor it came from, and multiple contexts can be
/// created from the same processor.
pub struct ProcessorContext {
    /// Raw pointer to the C processor context structure
    inner: *mut AicProcessorContext,
}

impl ProcessorContext {
    /// Creates a new Processor context.
    pub(crate) fn new(ctx_ptr: *mut AicProcessorContext) -> Self {
        Self { inner: ctx_ptr }
    }

    fn as_ptr(&self) -> *const AicProcessorContext {
        self.inner as *const AicProcessorContext
    }

    /// Modifies an enhancement parameter.
    ///
    /// All parameters can be changed during audio processing.
    /// This function can be called from any thread.
    ///
    /// This operates on the processor associated with this context handle.
    ///
    /// # Arguments
    ///
    /// * `parameter` - Parameter to modify
    /// * `value` - New parameter value. See parameter documentation for ranges
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success or an [`AicError`] if the parameter cannot be set.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, ProcessorParameter, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let processor = Processor::new(&model, &license_key)?;
    /// # let proc_ctx = processor.context();
    /// proc_ctx.set_parameter(ProcessorParameter::EnhancementLevel, 0.8)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn set_parameter(&self, parameter: ProcessorParameter, value: f32) -> Result<(), AicError> {
        // SAFETY:
        // - `self.as_ptr()` is a valid pointer to a live processor context.
        // - This function can be called from any thread, so we only borrow `&self`.
        let error_code =
            unsafe { aic_processor_context_set_parameter(self.as_ptr(), parameter.into(), value) };
        handle_error(error_code)
    }

    /// Retrieves the current value of a parameter.
    ///
    /// This function can be called from any thread.
    ///
    /// This queries the processor associated with this context handle.
    ///
    /// # Arguments
    ///
    /// * `parameter` - Parameter to query
    ///
    /// # Returns
    ///
    /// Returns the current parameter value.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, ProcessorParameter, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let processor = Processor::new(&model, &license_key)?;
    /// # let processor_context = processor.context();
    /// let enhancement_level = processor_context.parameter(ProcessorParameter::EnhancementLevel);
    /// println!("Current enhancement level: {enhancement_level}");
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn parameter(&self, parameter: ProcessorParameter) -> f32 {
        let mut value: f32 = 0.0;
        // SAFETY:
        // - `self.as_ptr()` is a valid pointer to a live processor context.
        // - `value` points to stack storage for output.
        // - This function can be called from any thread, so we only borrow `&self`.
        let error_code = unsafe {
            aic_processor_context_get_parameter(self.as_ptr(), parameter.into(), &mut value)
        };
        // The wrapper guarantees valid, non-null pointers.
        assert_success(
            error_code,
            "`aic_processor_context_get_parameter` failed. This is a bug, please open an issue on GitHub for further investigation.",
        );
        value
    }

    /// Returns the delay applied to the audio in samples for the current audio configuration.
    ///
    /// This function provides the complete end-to-end latency introduced by the processor,
    /// which includes both algorithmic processing delay and any buffering overhead.
    /// The processed audio leaves [`Processor::process`] this many samples behind its input.
    /// Use this value to synchronize enhanced audio with other streams or to implement
    /// delay compensation in your application.
    ///
    /// **Delay behavior:**
    /// - **Before initialization:** Returns the base processing delay using the model's
    ///   optimal block size at its native sample rate
    /// - **After initialization:** Returns the actual delay for your specific configuration,
    ///   including any additional buffering introduced by a non-optimal block size
    ///
    /// **Important:** The delay value is always expressed in samples at the sample rate
    /// you configured during `initialize`. To convert to time units:
    /// `delay_ms = (delay_samples * 1000) / sample_rate`
    ///
    /// **Note:** Using a block size different from the optimal value returned by
    /// `optimal_block_size` will increase the delay beyond the model's base latency.
    ///
    /// # Returns
    ///
    /// Returns the delay in samples.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let processor = Processor::new(&model, &license_key)?;
    /// # let processor_context = processor.context();
    /// let delay = processor_context.audio_delay();
    /// println!("Audio delay: {} samples", delay);
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn audio_delay(&self) -> usize {
        let mut delay: usize = 0;
        // SAFETY:
        // - `self.as_ptr()` is a valid pointer to a live processor context.
        // - `delay` points to stack storage for output.
        // - This function can be called from any thread, so we only borrow `&self`.
        let error_code =
            unsafe { aic_processor_context_get_audio_delay(self.as_ptr(), &mut delay) };

        // This should never fail. If it does, it's a bug in the SDK.
        // `aic_processor_context_get_audio_delay` is documented to always succeed if given
        // valid pointers.
        assert_success(
            error_code,
            "`aic_processor_context_get_audio_delay` failed. This is a bug, please open an issue on GitHub for further investigation.",
        );

        delay
    }

    /// Clears all internal state and buffers. Any energy VAD is also reset.
    ///
    /// Call this when the audio stream is interrupted or when seeking
    /// to prevent artifacts from previous audio content.
    ///
    /// This operates on the processor associated with this context handle.
    ///
    /// The processor stays initialized to the configured settings.
    ///
    /// # Real-time safety
    ///
    /// Real-time safe. Can be called from audio processing threads.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let processor = Processor::new(&model, &license_key)?;
    /// # let processor_context = processor.context();
    /// processor_context.reset();
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn reset(&self) {
        // SAFETY:
        // - `self.as_ptr()` is a valid pointer to a live processor context.
        // - This function can be called from any thread, so we only borrow `&self`.
        let error_code = unsafe { aic_processor_context_reset(self.as_ptr()) };
        // The wrapper guarantees valid, non-null pointers.
        assert_success(
            error_code,
            "`aic_processor_context_reset` failed. This is a bug, please open an issue on GitHub for further investigation.",
        );
    }

    /// Replaces the bearer token on the running processor.
    ///
    /// Use this when your license key is a JWT and needs to be refreshed
    /// before it expires. Calling this with a renewed token lets you stay authenticated
    /// without tearing down and recreating the processor: audio processing continues
    /// uninterrupted, the context handle stays valid, and the new token is used for all
    /// subsequent authentication against the ai-coustics backend.
    ///
    /// In-place updates are only supported when both the originally configured key and the
    /// new token are JWTs. Other license types cannot be swapped in this way.
    ///
    /// On any error the call is a no-op: the previously active token stays in use and the
    /// telemetry session is unaffected (no backoff, no interruption to processing).
    ///
    /// On success the swap is applied immediately and is **not** gated on backend
    /// acceptance. The token is validated locally for format only; if the backend later
    /// rejects it (e.g. expired or revoked), the SDK retries it under backoff rather than
    /// rolling back to the prior token, and audio processing is eventually disabled if no
    /// accepted token arrives in time. Supplying a known-good token via this call during
    /// that window recovers the session.
    ///
    /// Safe to call concurrently with [`Processor::process`] on the originating processor.
    ///
    /// # Arguments
    ///
    /// * `token` - The new JWT to install.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success or an [`AicError`] if the update fails.
    ///
    /// # Real-time safety
    ///
    /// This function is not real-time safe. It locks a mutex and allocates memory.
    /// Avoid calling it from audio threads.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let processor = Processor::new(&model, &license_key)?;
    /// let processor_context = processor.context();
    /// let renewed_jwt = String::from("<JWT_BEARER_TOKEN>");
    /// processor_context.update_bearer_token(&renewed_jwt)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn update_bearer_token(&self, token: &str) -> Result<(), AicError> {
        let c_token = CString::new(token).map_err(|_| AicError::LicenseFormatInvalid)?;
        // SAFETY:
        // - `self.as_ptr()` is a valid pointer to a live processor context.
        // - `c_token` is a null-terminated CString that outlives the call.
        // - This function can be called from any thread.
        let error_code =
            unsafe { aic_processor_context_update_bearer_token(self.as_ptr(), c_token.as_ptr()) };
        handle_error(error_code)
    }
}

impl Drop for ProcessorContext {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            // SAFETY:
            // - `self.inner` was allocated by the SDK and is still owned by this wrapper.
            // - This function can be called from any thread; `drop` has exclusive
            //   access to this context handle.
            unsafe { aic_processor_context_destroy(self.inner) };
        }
    }
}

// Safety: The underlying C library should be thread-safe for individual ProcessorContext instances
unsafe impl Send for ProcessorContext {}
unsafe impl Sync for ProcessorContext {}

/// High-level wrapper for the ai-coustics audio enhancement processor.
///
/// A processor is created from an enhancement or bypass model. For voice activity detection,
/// create a [`Vad`](crate::Vad) from a VAD model instead.
///
/// This struct provides a safe, Rust-friendly interface to the underlying C library.
/// It handles memory management automatically and converts C-style error codes
/// to Rust `Result` types.
///
/// # Example
///
/// ```rust,no_run
/// use aic_sdk::{Model, ProcessorConfig, Processor};
///
/// let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
/// let model = Model::from_file("/path/to/model.aicmodel")?;
/// let config = ProcessorConfig {
///     block_size: 1024,
///     ..ProcessorConfig::optimal(&model)
/// };
///
/// let mut processor = Processor::new(&model, &license_key)?.with_config(&config)?;
///
/// let mut audio_block = vec![0.0f32; config.block_size];
/// processor.process(&mut audio_block)?;
/// # Ok::<(), aic_sdk::AicError>(())
/// ```
pub struct Processor<'a> {
    /// Raw pointer to the C processor structure
    inner: *mut AicProcessor,
    /// Whether `initialize` has been called
    initialized: bool,
    /// Marker to tie the lifetime of the processor to the lifetime of the model's weights
    marker: PhantomData<&'a [u8]>,
}

impl<'a> Processor<'a> {
    /// Creates a new audio enhancement processor instance.
    ///
    /// Multiple processors can be created to process different audio streams simultaneously
    /// or to switch between different enhancement algorithms during runtime.
    ///
    /// The same [`Model`] may be passed to this function more than once: each call creates an
    /// independent processor that shares the underlying model data internally.
    ///
    /// # Arguments
    ///
    /// * `model` - The loaded model instance. Must be an enhancement or bypass model,
    ///   otherwise [`AicError::ModelTypeUnsupported`] is returned.
    /// * `license_key` - license key for the ai-coustics SDK
    ///   (generate your key at [developers.ai-coustics.com](https://developers.ai-coustics.com/))
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the new `Processor` instance or an [`AicError`] if creation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let processor = Processor::new(&model, &license_key)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn new(model: &Model<'a>, license_key: &str) -> Result<Self, AicError> {
        Self::create(model, license_key, None)
    }

    /// Creates a new audio enhancement processor instance with explicit
    /// OpenTelemetry configuration.
    ///
    /// If provided, telemetry will be sent according to the provided configuration. Otherwise
    /// it will be configured according to the runtime environment.
    ///
    /// This overrides the SDK's environment-based telemetry defaults (e.g.
    /// `AIC_SDK_OTEL_ENABLE`) for this processor.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, OtelConfig, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let otel = OtelConfig::enabled();
    ///
    /// let processor = Processor::with_otel_config(&model, &license_key, &otel)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn with_otel_config(
        model: &Model<'a>,
        license_key: &str,
        otel_config: &OtelConfig,
    ) -> Result<Self, AicError> {
        Self::create(model, license_key, Some(otel_config))
    }

    fn create(
        model: &Model<'a>,
        license_key: &str,
        otel_config: Option<&OtelConfig>,
    ) -> Result<Self, AicError> {
        // Set the wrapper ID as soon as the user attempts to instantiate a processor.
        // SAFETY: `2` is the wrapper ID assigned to this Rust SDK.
        unsafe { crate::set_sdk_id(2) };

        // Session ID must outlive the FFI call so its pointer stays valid.
        let c_session_id = otel_config
            .and_then(|o| o.session_id.as_deref())
            .map(CString::new)
            .transpose()
            .map_err(|_| AicError::Internal)?;

        let c_otel = otel_config.map(|o| AicOtelConfig {
            enable: o.enable,
            session_id: c_session_id.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
            export_interval_ms: o.export_interval_ms,
        });
        let c_otel_ptr = c_otel
            .as_ref()
            .map_or(ptr::null(), |o| o as *const AicOtelConfig);

        let mut processor_ptr: *mut AicProcessor = ptr::null_mut();
        let c_license_key =
            CString::new(license_key).map_err(|_| AicError::LicenseFormatInvalid)?;

        // SAFETY:
        // - `processor_ptr` points to stack storage for output.
        // - `model` is a valid SDK model pointer for the duration of the call.
        // - `c_license_key` is a null-terminated CString.
        // - `c_otel_ptr` is either null or points to a valid `AicOtelConfig` whose
        //   `session_id` field (if non-null) outlives this call.
        // - This function is not thread-safe, but the output pointer is local to
        //   this call and no processor handle exists until it returns.
        let error_code = unsafe {
            aic_processor_create(
                &mut processor_ptr,
                model.as_ptr(),
                c_license_key.as_ptr(),
                c_otel_ptr,
            )
        };

        handle_error(error_code)?;

        // This should never happen if the C library is well-behaved, but let's be defensive
        assert!(
            !processor_ptr.is_null(),
            "C library returned success but null pointer"
        );

        Ok(Self {
            inner: processor_ptr,
            initialized: false,
            marker: PhantomData,
        })
    }

    /// Initializes the processor with the given configuration.
    ///
    /// This is a convenience method that calls [`Processor::initialize`] internally and returns `self`.
    /// The processor is immediately ready to process audio after calling this method, so you don't
    /// need to call [`Processor::initialize`] separately.
    ///
    /// # Arguments
    ///
    /// * `config` - Audio processing configuration
    ///
    /// # Returns
    ///
    /// Returns `Ok(Self)` with the initialized processor, or an [`AicError`] if initialization fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor, ProcessorConfig};
    /// let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let config = ProcessorConfig::optimal(&model);
    ///
    /// let mut processor = Processor::new(&model, &license_key)?.with_config(&config)?;
    ///
    /// // Processor is ready to use - no need to call initialize()
    /// let mut audio_block = vec![0.0f32; config.block_size];
    /// processor.process(&mut audio_block)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn with_config(mut self, config: &ProcessorConfig) -> Result<Self, AicError> {
        self.initialize(config)?;
        Ok(self)
    }

    /// Creates a [`ProcessorContext`] instance.
    /// This can be used to control all parameters and other settings of the processor.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let processor = Processor::new(&model, &license_key)?;
    /// let processor_context = processor.context();
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn context(&self) -> ProcessorContext {
        let mut processor_context: *mut AicProcessorContext = ptr::null_mut();

        // SAFETY:
        // - `processor_context` is valid output storage.
        // - `self.as_ptr()` is a live processor pointer.
        // - This function can be called from any thread, so we only borrow `&self`.
        let error_code =
            unsafe { aic_processor_context_create(&mut processor_context, self.as_ptr()) };

        // This should never fail
        assert!(handle_error(error_code).is_ok());

        // This should never happen if the C library is well-behaved, but let's be defensive
        assert!(
            !processor_context.is_null(),
            "C library returned success but null pointer"
        );

        ProcessorContext::new(processor_context)
    }

    /// Creates an [`EnergyVadContext`] handle for thread-safe control APIs.
    ///
    /// The voice activity detection works automatically as [`Processor::process`] processes audio,
    /// using the enhanced signal before output mixing.
    /// The energy VAD shares the processor's enhancement model and does not run a separate model.
    ///
    /// This uses the energy VAD associated with this processor.
    /// All handles created from a given processor reference the same energy VAD instance.
    ///
    /// Creating a context keeps enhancement inference active even when the processor is bypassed
    /// or the enhancement level is zero. This remains active for the processor's lifetime,
    /// even after all energy VAD context handles are dropped.
    ///
    /// **Important:** If the backing processor is dropped, the energy VAD context will stop
    /// producing new data. It is safe to drop the processor without dropping the context.
    ///
    /// # Returns
    ///
    /// Returns an [`EnergyVadContext`] associated with this processor.
    ///
    /// # Real-time safety
    ///
    /// Do not call from audio processing threads as this allocates memory.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// let model = Model::from_file("/path/to/enhancement_model.aicmodel")?;
    /// let mut processor = Processor::new(&model, &license_key)?;
    /// let vad_ctx = processor.energy_vad_context();
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn energy_vad_context(&mut self) -> EnergyVadContext {
        let mut context_ptr: *mut AicEnergyVadContext = ptr::null_mut();

        // SAFETY:
        // - `self.as_ptr()` points to a live processor.
        // - `context_ptr` is valid output storage and not aliased.
        // - `&mut self` prevents concurrent use or destruction of the processor.
        let error_code = unsafe { aic_energy_vad_context_create(&mut context_ptr, self.as_ptr()) };

        // This should never fail
        assert!(handle_error(error_code).is_ok());

        // This should never happen if the C library is well-behaved, but let's be defensive
        assert!(
            !context_ptr.is_null(),
            "C library returned success but null pointer"
        );

        EnergyVadContext::new(context_ptr)
    }

    /// Configures the processor for specific audio settings.
    ///
    /// This function must be called before processing any audio.
    /// For the lowest delay use the sample rate and block size returned by
    /// [`Model::optimal_sample_rate`] and [`Model::optimal_block_size`].
    ///
    /// # Arguments
    ///
    /// * `config` - Audio processing configuration
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success or an [`AicError`] if initialization fails.
    ///
    /// # Warning
    /// Do not call from audio processing threads as this allocates memory.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor, ProcessorConfig};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let mut processor = Processor::new(&model, &license_key)?;
    /// let config = ProcessorConfig::optimal(&model);
    /// processor.initialize(&config)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn initialize(&mut self, config: &ProcessorConfig) -> Result<(), AicError> {
        // SAFETY:
        // - `self.inner` is a valid pointer to a live processor.
        // - This function is not thread-safe, so we borrow `&mut self`.
        let error_code = unsafe {
            aic_processor_initialize(
                self.inner,
                config.sample_rate,
                config.block_size,
                config.variable_block_size,
            )
        };

        handle_error(error_code)?;
        self.initialized = true;
        Ok(())
    }

    /// Processes mono audio.
    ///
    /// Enhances speech in the provided audio block in-place.
    ///
    /// # Arguments
    ///
    /// * `audio` - Mono audio block to be enhanced in-place. Must match `block_size` from
    ///   initialization, or if `variable_block_size` was enabled, must be less than or equal
    ///   to `block_size`.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success or an [`AicError`] if processing fails.
    ///
    /// # Real-time safety
    ///
    /// Real-time safe. Can be called from audio processing threads.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor, ProcessorConfig};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// # let mut processor = Processor::new(&model, &license_key)?;
    /// let config = ProcessorConfig::optimal(&model);
    /// processor.initialize(&config)?;
    /// let mut audio = vec![0.0f32; config.block_size];
    /// processor.process(&mut audio)?;
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn process(&mut self, audio: &mut [f32]) -> Result<(), AicError> {
        if !self.initialized {
            return Err(AicError::NotInitialized);
        }

        let audio_len = audio.len();

        // SAFETY:
        // - `self.inner` is a valid pointer to a live processor.
        // - `audio` points to a contiguous, writable f32 slice of length `audio_len`.
        // - This function is not thread-safe, so we borrow `&mut self`.
        let error_code =
            unsafe { aic_processor_process(self.inner, audio.as_mut_ptr(), audio_len) };

        handle_error(error_code)
    }

    /// Terminates the telemetry session associated with this processor.
    ///
    /// Once the request has been handled, the processor is no longer allowed to process audio.
    ///
    /// This function is meant to be used in lifecycle management events.
    /// A telemetry session is automatically stopped when a processor is destroyed.
    /// However, in cases where this SDK is integrated with languages with automatic memory
    /// management, object deallocation could be delayed. Use this function to terminate
    /// the session explicitly.
    ///
    /// This function blocks until the telemetry session is terminated, unless another
    /// session is still alive. In that case, this function returns early and termination
    /// happens asynchronously. This keeps lifecycle management smooth while ensuring
    /// all sessions are closed when the last processor is terminated.
    ///
    /// # Real-time safety
    ///
    /// This function is not real-time safe. It may block until the session is terminated.
    /// Avoid calling it from audio threads.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use aic_sdk::{Model, Processor};
    /// # let license_key = std::env::var("AIC_SDK_LICENSE").unwrap();
    /// # let model = Model::from_file("/path/to/model.aicmodel")?;
    /// let mut processor = Processor::new(&model, &license_key)?;
    /// processor.terminate_session();
    /// # Ok::<(), aic_sdk::AicError>(())
    /// ```
    pub fn terminate_session(&mut self) {
        // SAFETY:
        // - `self.inner` is a valid pointer to a live processor.
        // - This function must not run concurrently with any other call taking the same
        //   processor handle, so we borrow `&mut self`.
        let error_code = unsafe { aic_processor_terminate_session(self.inner) };
        // The wrapper guarantees valid, non-null pointers.
        assert_success(
            error_code,
            "`aic_processor_terminate_session` failed. This is a bug, please open an issue on GitHub for further investigation.",
        );
    }

    fn as_ptr(&self) -> *const AicProcessor {
        self.inner as *const AicProcessor
    }
}

impl<'a> Drop for Processor<'a> {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            // SAFETY:
            // - `self.inner` was allocated by the SDK and is still owned by this wrapper.
            // - This function is not thread-safe with concurrent processor use, but
            //   `drop` has exclusive access to `self`.
            unsafe { aic_processor_destroy(self.inner) };
        }
    }
}

// SAFETY: Everything in Processor is Send, with the exception of the inner raw pointer.
// The Processor only uses the raw pointer according to the safety contracts of the
// unsafe APIs that require the pointer, and the Processor does not expose access to the
// raw pointer in any of its methods. Therefore, it safe to implement Send for Processor.
unsafe impl<'a> Send for Processor<'a> {}

// SAFETY: Processor does not expose any interior mutability. The SDK functions that are documented
// as not thread-safe (`aic_processor_initialize`, `aic_processor_process`,
// `aic_processor_terminate_session`, `aic_processor_destroy`) are only reachable through methods
// that take `&mut self` or through `drop`, so Rust's borrow rules serialize them. The only method
// that takes `&self` (`context`) just creates a new context handle from a const
// processor pointer, which is safe to do while the processor is in use on another thread.
// Therefore, it is safe to implement Sync for Processor.
unsafe impl<'a> Sync for Processor<'a> {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{license_key, test_model_path};

    const TEST_MODEL_ID: &str = "rook-s-48khz";

    fn load_test_model() -> Result<(Model<'static>, String), AicError> {
        let model = Model::from_file(test_model_path(TEST_MODEL_ID))?;

        Ok((model, license_key()))
    }

    #[test]
    fn model_creation_and_basic_operations() {
        dbg!(crate::get_sdk_version());
        dbg!(crate::get_compatible_model_version());

        let (model, license_key) = load_test_model().unwrap();
        let config = ProcessorConfig::optimal(&model);

        let mut processor = Processor::new(&model, &license_key)
            .unwrap()
            .with_config(&config)
            .unwrap();

        let mut audio = vec![0.0f32; config.block_size];
        processor.process(&mut audio).unwrap();
    }

    #[test]
    fn process_fixed_block_size() {
        let (model, license_key) = load_test_model().unwrap();
        let config = ProcessorConfig::optimal(&model);

        let mut processor = Processor::new(&model, &license_key)
            .unwrap()
            .with_config(&config)
            .unwrap();

        let mut audio = vec![0.0f32; config.block_size];
        processor.process(&mut audio).unwrap();
    }

    #[test]
    fn process_variable_block_size() {
        let (model, license_key) = load_test_model().unwrap();
        let config = ProcessorConfig::optimal(&model).with_variable_block_size(true);

        let mut processor = Processor::new(&model, &license_key)
            .unwrap()
            .with_config(&config)
            .unwrap();

        let mut audio = vec![0.0f32; config.block_size];
        processor.process(&mut audio).unwrap();

        let mut audio = vec![0.0f32; 20];
        processor.process(&mut audio).unwrap();
    }

    #[test]
    fn process_variable_block_size_fails_when_disabled() {
        let (model, license_key) = load_test_model().unwrap();
        let config = ProcessorConfig::optimal(&model);

        let mut processor = Processor::new(&model, &license_key)
            .unwrap()
            .with_config(&config)
            .unwrap();

        let mut audio = vec![0.0f32; config.block_size];
        processor.process(&mut audio).unwrap();

        let mut audio = vec![0.0f32; 20];
        let result = processor.process(&mut audio);
        assert_eq!(result, Err(AicError::AudioConfigMismatch));
    }

    #[test]
    fn model_can_be_dropped_after_creating_processor() {
        let (model, license_key) = load_test_model().unwrap();
        let config = ProcessorConfig::optimal(&model);

        let mut processor = Processor::new(&model, &license_key)
            .unwrap()
            .with_config(&config)
            .unwrap();
        drop(model); // Inside of the SDK an Arc-Pointer to `Model` is stored in Processor, so it won't be de-allocated

        let mut audio = vec![0.0f32; config.block_size];
        processor.process(&mut audio).unwrap();
    }

    #[test]
    fn processor_is_send_and_sync() {
        // Compile-time check that Processor implements Send and Sync.
        // This ensures the processor can be safely moved to another thread.
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Send>() {}

        assert_send::<Processor>();
        assert_sync::<Processor>();
    }

    struct MyModel {
        _model: Model<'static>,
        _processor: Processor<'static>,
    }

    impl MyModel {
        pub fn new() -> Self {
            let (model, license_key) = load_test_model().unwrap();
            let processor = Processor::new(&model, &license_key)
                .unwrap()
                .with_config(&ProcessorConfig::optimal(&model))
                .unwrap();
            MyModel {
                _model: model,
                _processor: processor,
            }
        }
    }

    #[test]
    fn can_create_self_referential_structs_with_statics() {
        let _model = MyModel::new();
    }
}

#[doc(hidden)]
mod _compile_fail_tests {
    //! Compile-fail regression: a `Processor`'s model buffer must not be dropped before the processor.
    //!
    //! ```rust,compile_fail
    //! use aic_sdk::{Model, Processor, ProcessorConfig};
    //!
    //! fn main() {
    //!     let buffer = vec![0u8; 64];
    //!     let model = Model::from_buffer(&buffer).unwrap();
    //!     let config = ProcessorConfig::optimal(&model);
    //!
    //!     let mut processor = Processor::new(&model, "license")
    //!         .unwrap()
    //!         .with_config(&config)
    //!         .unwrap();
    //!
    //!     drop(model); // Model can be dropped without issues
    //!
    //!     drop(buffer); // This should fail to compile
    //!
    //!     let mut audio = vec![0.0f32; config.block_size];
    //!     processor.process(&mut audio).unwrap();
    //! }
    //! ```
}