rvoip-codec-core 0.3.8

G.711 and optional G.729/Opus/AMR audio codec implementations for RVOIP
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
//! Input validation utilities for codec operations

use crate::error::{CodecError, Result};
use crate::types::{CodecType, SampleRate};

/// Validate audio samples for codec processing
///
/// # Errors
///
/// Returns an error when `samples` is empty.
pub fn validate_samples(samples: &[i16]) -> Result<()> {
    if samples.is_empty() {
        return Err(CodecError::invalid_format("Input samples cannot be empty"));
    }
    // Per-sample range check removed: every `i16` is by definition
    // within [-32768, 32767], and `i16::MIN.abs()` would overflow.
    Ok(())
}

/// Validate encoded data for codec processing
///
/// # Errors
///
/// Returns an error when `data` is empty or exceeds the supported size limit.
pub fn validate_encoded_data(data: &[u8]) -> Result<()> {
    if data.is_empty() {
        return Err(CodecError::invalid_format("Encoded data cannot be empty"));
    }

    // Check for reasonable data size (not too large)
    if data.len() > 1024 * 1024 {
        return Err(CodecError::invalid_format(format!(
            "Encoded data too large: {} bytes",
            data.len()
        )));
    }

    Ok(())
}

/// Validate frame size for a specific codec
///
/// # Errors
///
/// Returns an error when `frame_size` is unsupported by `codec_type`.
pub fn validate_frame_size(codec_type: CodecType, frame_size: usize) -> Result<()> {
    let expected_sizes = match codec_type {
        CodecType::G711Pcmu | CodecType::G711Pcma => {
            // G.711 commonly uses 10ms or 20ms frames at 8kHz
            vec![80, 160, 240, 320]
        }

        CodecType::G729 | CodecType::G729A | CodecType::G729BA => {
            // G.729/G.729A/G.729BA use fixed 10ms frames at 8kHz
            vec![80]
        }
        CodecType::Opus => {
            // Opus supports various frame sizes
            vec![120, 240, 480, 960, 1920, 2880]
        }
        // AMR is fixed at 20 ms: 160 samples at 8 kHz, 320 at 16 kHz.
        CodecType::AmrNb => vec![160],
        CodecType::AmrWb => vec![320],
    };

    if !expected_sizes.contains(&frame_size) {
        return Err(CodecError::InvalidFrameSize {
            expected: expected_sizes[0],
            actual: frame_size,
        });
    }

    Ok(())
}

/// Validate sample rate for a specific codec
///
/// # Errors
///
/// Returns an error when `sample_rate` is unsupported by `codec_type`.
pub fn validate_sample_rate(codec_type: CodecType, sample_rate: SampleRate) -> Result<()> {
    let supported_rates = codec_type.supported_sample_rates();
    let rate_hz = sample_rate.hz();

    if !supported_rates.contains(&rate_hz) {
        return Err(CodecError::InvalidSampleRate {
            rate: rate_hz,
            supported: supported_rates.to_vec(),
        });
    }

    Ok(())
}

/// Validate channel count for a specific codec
///
/// # Errors
///
/// Returns an error when `channels` is unsupported by `codec_type`.
pub fn validate_channels(codec_type: CodecType, channels: u8) -> Result<()> {
    let supported_channels = codec_type.supported_channels();

    if !supported_channels.contains(&channels) {
        return Err(CodecError::InvalidChannelCount {
            channels,
            supported: supported_channels.to_vec(),
        });
    }

    Ok(())
}

/// Validate bitrate for a specific codec
///
/// # Errors
///
/// Returns an error when `bitrate` is outside the codec's supported range.
pub const fn validate_bitrate(codec_type: CodecType, bitrate: u32) -> Result<()> {
    let (min_bitrate, max_bitrate) = codec_type.bitrate_range();

    if bitrate < min_bitrate || bitrate > max_bitrate {
        return Err(CodecError::InvalidBitrate {
            bitrate,
            min: min_bitrate,
            max: max_bitrate,
        });
    }

    Ok(())
}

/// Validate buffer sizes for encoding/decoding operations
///
/// # Errors
///
/// Returns an error when `output_size` is smaller than the size implied by
/// `input_size` and `expected_ratio`.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]
pub fn validate_buffer_sizes(
    input_size: usize,
    output_size: usize,
    expected_ratio: f32,
) -> Result<()> {
    let expected_output_size = (input_size as f32 * expected_ratio) as usize;

    if output_size < expected_output_size {
        return Err(CodecError::BufferTooSmall {
            needed: expected_output_size,
            actual: output_size,
        });
    }

    Ok(())
}

/// Validate that frame samples are properly aligned for multi-channel audio
///
/// # Errors
///
/// Returns an error when the sample count is not divisible by `channels`.
#[allow(clippy::manual_is_multiple_of)]
pub fn validate_channel_alignment(samples: &[i16], channels: u8) -> Result<()> {
    if samples.len() % usize::from(channels) != 0 {
        return Err(CodecError::invalid_format(format!(
            "Sample count {} not divisible by channel count {}",
            samples.len(),
            channels
        )));
    }

    Ok(())
}

/// Validate G.711 specific parameters
///
/// # Errors
///
/// Returns an error when the frame is empty or has the wrong sample count.
pub fn validate_g711_frame(samples: &[i16], expected_frame_size: usize) -> Result<()> {
    validate_samples(samples)?;

    if samples.len() != expected_frame_size {
        return Err(CodecError::InvalidFrameSize {
            expected: expected_frame_size,
            actual: samples.len(),
        });
    }

    Ok(())
}

/// Validate G.722 specific parameters
///
/// # Errors
///
/// Returns an error when the frame is empty, has the wrong sample count, or
/// contains an odd number of samples.
pub fn validate_g722_frame(samples: &[i16], expected_frame_size: usize) -> Result<()> {
    validate_samples(samples)?;

    if samples.len() != expected_frame_size {
        return Err(CodecError::InvalidFrameSize {
            expected: expected_frame_size,
            actual: samples.len(),
        });
    }

    // G.722 requires even number of samples for QMF processing
    if !samples.len().is_multiple_of(2) {
        return Err(CodecError::invalid_format(
            "G.722 requires even number of samples for QMF processing",
        ));
    }

    Ok(())
}

/// Validate G.729 specific parameters
///
/// # Errors
///
/// Returns an error when the frame is empty or does not contain 80 samples.
pub fn validate_g729_frame(samples: &[i16]) -> Result<()> {
    validate_samples(samples)?;

    // G.729 uses fixed 80-sample frames (10ms at 8kHz)
    if samples.len() != 80 {
        return Err(CodecError::InvalidFrameSize {
            expected: 80,
            actual: samples.len(),
        });
    }

    Ok(())
}

/// Validate Opus specific parameters
///
/// # Errors
///
/// Returns an error when the frame is empty, its sample rate is unsupported,
/// or its sample count is invalid for the selected rate.
pub fn validate_opus_frame(samples: &[i16], sample_rate: SampleRate) -> Result<()> {
    validate_samples(samples)?;

    let rate_hz = sample_rate.hz();
    let frame_size = samples.len();

    // Opus supports specific frame sizes based on sample rate
    let valid_frame_sizes = match rate_hz {
        8000 => vec![20, 40, 80, 160, 320, 480],
        12000 => vec![30, 60, 120, 240, 480, 720],
        16000 => vec![40, 80, 160, 320, 640, 960],
        24000 => vec![60, 120, 240, 480, 960, 1440],
        48000 => vec![120, 240, 480, 960, 1920, 2880],
        _ => {
            return Err(CodecError::InvalidSampleRate {
                rate: rate_hz,
                supported: vec![8000, 12000, 16000, 24000, 48000],
            });
        }
    };

    if !valid_frame_sizes.contains(&frame_size) {
        return Err(CodecError::InvalidFrameSize {
            expected: valid_frame_sizes[0],
            actual: frame_size,
        });
    }

    Ok(())
}

/// Validate that two buffers have compatible sizes for processing
///
/// # Errors
///
/// Returns an error when `output` is smaller than the size implied by the
/// input length and `compression_ratio`.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]
pub fn validate_buffer_compatibility(
    input: &[i16],
    output: &[u8],
    compression_ratio: f32,
) -> Result<()> {
    let expected_output_size = (input.len() as f32 * compression_ratio) as usize;

    if output.len() < expected_output_size {
        return Err(CodecError::BufferTooSmall {
            needed: expected_output_size,
            actual: output.len(),
        });
    }

    Ok(())
}

/// Validate memory alignment for SIMD operations
///
/// # Errors
///
/// This check currently reports misalignment through tracing and always
/// succeeds; the result type is retained for API compatibility.
pub fn validate_simd_alignment(data: &[i16]) -> Result<()> {
    let ptr = data.as_ptr() as usize;

    // Check for 16-byte alignment (required for SSE)
    if !ptr.is_multiple_of(16) {
        tracing::debug!("Data not aligned for SIMD operations, falling back to scalar");
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::SampleRate;

    #[test]
    fn test_validate_samples() {
        let valid_samples = vec![0, 1000, -1000, 16000, -16000];
        assert!(validate_samples(&valid_samples).is_ok());

        let empty_samples: Vec<i16> = vec![];
        assert!(validate_samples(&empty_samples).is_err());
    }

    #[test]
    fn test_validate_encoded_data() {
        let valid_data = vec![0u8, 127, 255, 64, 192];
        assert!(validate_encoded_data(&valid_data).is_ok());

        let empty_data: Vec<u8> = vec![];
        assert!(validate_encoded_data(&empty_data).is_err());

        let too_large_data = vec![0u8; 2 * 1024 * 1024]; // 2MB
        assert!(validate_encoded_data(&too_large_data).is_err());
    }

    #[test]
    fn test_validate_frame_size() {
        // G.711 valid frame sizes
        assert!(validate_frame_size(CodecType::G711Pcmu, 160).is_ok());
        assert!(validate_frame_size(CodecType::G711Pcmu, 123).is_err());

        // G.729 fixed frame size
        assert!(validate_frame_size(CodecType::G729, 80).is_ok());
        assert!(validate_frame_size(CodecType::G729, 160).is_err());
    }

    #[test]
    fn test_validate_sample_rate() {
        // G.711 supports only 8kHz
        assert!(validate_sample_rate(CodecType::G711Pcmu, SampleRate::Rate8000).is_ok());
        assert!(validate_sample_rate(CodecType::G711Pcmu, SampleRate::Rate48000).is_err());

        // Opus supports multiple rates
        assert!(validate_sample_rate(CodecType::Opus, SampleRate::Rate8000).is_ok());
        assert!(validate_sample_rate(CodecType::Opus, SampleRate::Rate48000).is_ok());
    }

    #[test]
    fn test_validate_channels() {
        // G.711 supports only mono
        assert!(validate_channels(CodecType::G711Pcmu, 1).is_ok());
        assert!(validate_channels(CodecType::G711Pcmu, 2).is_err());

        // Opus supports mono and stereo
        assert!(validate_channels(CodecType::Opus, 1).is_ok());
        assert!(validate_channels(CodecType::Opus, 2).is_ok());
        assert!(validate_channels(CodecType::Opus, 3).is_err());
    }

    #[test]
    fn test_validate_bitrate() {
        // G.711 has fixed bitrate
        assert!(validate_bitrate(CodecType::G711Pcmu, 64_000).is_ok());
        assert!(validate_bitrate(CodecType::G711Pcmu, 128_000).is_err());

        // Opus has variable bitrate
        assert!(validate_bitrate(CodecType::Opus, 32_000).is_ok());
        assert!(validate_bitrate(CodecType::Opus, 600_000).is_err());
    }

    #[test]
    fn test_validate_buffer_sizes() {
        // G.711 has 1:1 compression ratio (16-bit to 8-bit)
        assert!(validate_buffer_sizes(160, 80, 0.5).is_ok());
        assert!(validate_buffer_sizes(160, 40, 0.5).is_err());
    }

    #[test]
    fn test_validate_channel_alignment() {
        let mono_samples = vec![0, 1, 2, 3, 4]; // 5 samples
        assert!(validate_channel_alignment(&mono_samples, 1).is_ok());
        assert!(validate_channel_alignment(&mono_samples, 2).is_err());

        let stereo_samples = vec![0, 1, 2, 3]; // 4 samples = 2 stereo pairs
        assert!(validate_channel_alignment(&stereo_samples, 2).is_ok());
    }

    #[test]
    fn test_codec_specific_validation() {
        // G.711 frame validation
        let g711_frame = vec![0i16; 160];
        assert!(validate_g711_frame(&g711_frame, 160).is_ok());
        assert!(validate_g711_frame(&g711_frame, 80).is_err());

        // G.729 frame validation
        let g729_frame = vec![0i16; 80];
        assert!(validate_g729_frame(&g729_frame).is_ok());

        let wrong_g729_frame = vec![0i16; 160];
        assert!(validate_g729_frame(&wrong_g729_frame).is_err());
    }

    #[test]
    fn test_buffer_compatibility() {
        let input = vec![0i16; 160];
        let output = vec![0u8; 80];

        // G.711 compression ratio: 0.5 (16-bit to 8-bit)
        assert!(validate_buffer_compatibility(&input, &output, 0.5).is_ok());

        let small_output = vec![0u8; 40];
        assert!(validate_buffer_compatibility(&input, &small_output, 0.5).is_err());
    }
}