gemini_genai_rs/buffer/convert.rs
1//! Zero-copy audio sample format conversion.
2//!
3//! Provides utilities for converting between i16 PCM sample slices and raw byte
4//! slices using [`bytemuck`] (zero-copy reinterpret casts), and for wrapping
5//! owned byte vectors as shared [`Bytes`] handles for zero-copy fan-out.
6
7use bytes::Bytes;
8
9/// Convert a slice of i16 PCM samples to raw bytes (zero-copy via bytemuck).
10pub fn i16_to_bytes(samples: &[i16]) -> &[u8] {
11 bytemuck::cast_slice(samples)
12}
13
14/// Convert raw bytes to i16 PCM samples (zero-copy via bytemuck).
15///
16/// Returns `None` if the byte slice length is not a multiple of 2 or the
17/// slice is not 2-byte aligned. Both are normal for a slice cut from a
18/// network frame, and the cast uses the machine's byte order; for bytes that
19/// arrive off the wire use [`pcm16_le_samples`], which has none of these
20/// conditions.
21pub fn bytes_to_i16(data: &[u8]) -> Option<&[i16]> {
22 bytemuck::try_cast_slice(data).ok()
23}
24
25/// Decode little-endian PCM16 bytes (the Live wire format) to samples.
26///
27/// Works on any slice: alignment does not matter, the byte order is always
28/// little-endian, and a trailing odd byte is ignored.
29///
30/// ```
31/// # use gemini_genai_rs::buffer::convert::pcm16_le_samples;
32/// assert_eq!(pcm16_le_samples(&[1, 0, 0xff, 0xff, 9]).collect::<Vec<_>>(), [1, -1]);
33/// ```
34pub fn pcm16_le_samples(data: &[u8]) -> impl ExactSizeIterator<Item = i16> + '_ {
35 data.as_chunks::<2>()
36 .0
37 .iter()
38 .map(|pair| i16::from_le_bytes(*pair))
39}
40
41/// Encode samples as little-endian PCM16 bytes (the Live wire format).
42///
43/// ```
44/// # use gemini_genai_rs::buffer::convert::i16_to_pcm16_le;
45/// assert_eq!(i16_to_pcm16_le(&[1, -1]), [1, 0, 0xff, 0xff]);
46/// ```
47pub fn i16_to_pcm16_le(samples: &[i16]) -> Vec<u8> {
48 samples.iter().flat_map(|s| s.to_le_bytes()).collect()
49}
50
51/// Wrap raw bytes as a shared `Bytes` handle for zero-copy fan-out.
52///
53/// `Bytes::clone()` is O(1) — it bumps an internal `Arc` refcount instead of
54/// copying the data. Use this when the same audio chunk must be broadcast to
55/// multiple subscribers.
56pub fn into_shared(data: Vec<u8>) -> Bytes {
57 Bytes::from(data)
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_i16_to_bytes_round_trip() {
66 let samples: Vec<i16> = vec![0, 1, -1, i16::MAX, i16::MIN, 12345];
67 let raw = i16_to_bytes(&samples);
68 assert_eq!(raw.len(), samples.len() * 2);
69
70 let back = bytes_to_i16(raw).expect("round-trip should succeed");
71 assert_eq!(back, &samples[..]);
72 }
73
74 #[test]
75 fn test_bytes_to_i16_invalid_length() {
76 // Odd-length byte slice cannot be reinterpreted as &[i16]
77 let odd = vec![1u8, 2, 3];
78 assert!(bytes_to_i16(&odd).is_none());
79 }
80
81 #[test]
82 fn pcm16_le_round_trips_and_ignores_a_trailing_odd_byte() {
83 let samples = [0i16, 1, -1, i16::MAX, i16::MIN, 12345];
84 let bytes = i16_to_pcm16_le(&samples);
85 assert_eq!(bytes.len(), samples.len() * 2);
86 assert_eq!(&bytes[..4], &[0, 0, 1, 0]);
87 assert_eq!(pcm16_le_samples(&bytes).collect::<Vec<_>>(), samples);
88
89 let mut odd = bytes;
90 odd.push(7);
91 assert_eq!(pcm16_le_samples(&odd).len(), samples.len());
92 assert_eq!(pcm16_le_samples(&[]).len(), 0);
93 }
94
95 #[test]
96 fn pcm16_le_decodes_a_misaligned_slice_the_zero_copy_cast_refuses() {
97 // Two samples (1, -1), copied to whichever start is odd-addressed.
98 let mut backing = [0u8; 8];
99 let odd_start = usize::from((backing.as_ptr() as usize).is_multiple_of(2));
100 backing[odd_start..odd_start + 4].copy_from_slice(&[1, 0, 0xff, 0xff]);
101 let misaligned = &backing[odd_start..odd_start + 4];
102 assert!(bytes_to_i16(misaligned).is_none());
103 assert_eq!(pcm16_le_samples(misaligned).collect::<Vec<_>>(), [1, -1]);
104 }
105
106 #[test]
107 fn test_shared_bytes_clone_is_cheap() {
108 let original = vec![42u8; 4096];
109 let ptr = original.as_ptr();
110 let shared = into_shared(original);
111
112 // Clone should share the same backing allocation
113 let cloned = shared.clone();
114 assert_eq!(shared.as_ptr(), cloned.as_ptr());
115 // The data pointer may differ from the original Vec (Bytes may reallocate
116 // during From<Vec<u8>>), but the two Bytes handles must share the same
117 // underlying memory.
118 let _ = ptr; // original vec was consumed
119 assert_eq!(&shared[..], &cloned[..]);
120 assert_eq!(shared.len(), 4096);
121 }
122}