1use glint_sys::*;
4use std::slice;
5
6pub struct Encoder {
8 handle: glint_t,
9 samples_per_frame: usize,
10 channels: usize,
11}
12
13unsafe impl Send for Encoder {}
16
17impl Encoder {
18 pub fn new(sample_rate: u32, channels: u32, bitrate: u32) -> Result<Self, &'static str> {
23 unsafe {
24 let rc = glint_check_config(sample_rate as i32, bitrate as i32);
25 if rc != 0 {
26 return Err("unsupported sample rate or bitrate");
27 }
28
29 let mode = if channels == 1 { 0 } else { 2 }; let cfg = glint_config {
31 sample_rate: sample_rate as i32,
32 num_channels: channels as i32,
33 mode,
34 bitrate: bitrate as i32,
35 path: 0, simd: 0, quality: 1, vbr: 0,
39 vbr_quality: 0,
40 };
41
42 let handle = glint_create(&cfg);
43 if handle.is_null() {
44 return Err("glint_create returned null");
45 }
46
47 let spf = glint_samples_per_frame(handle) as usize;
48
49 Ok(Encoder {
50 handle,
51 samples_per_frame: spf,
52 channels: channels as usize,
53 })
54 }
55 }
56
57 pub fn with_options(sample_rate: u32, channels: u32, bitrate: u32,
61 mode: u32, quality: u32, path: u32, vbr_quality: Option<u32>)
62 -> Result<Self, &'static str> {
63 unsafe {
64 let cfg = glint_config {
65 sample_rate: sample_rate as i32,
66 num_channels: channels as i32,
67 mode: mode as i32,
68 bitrate: bitrate as i32,
69 path: path as i32,
70 simd: 0,
71 quality: quality as i32,
72 vbr: if vbr_quality.is_some() { 1 } else { 0 },
73 vbr_quality: vbr_quality.unwrap_or(0) as i32,
74 };
75 let handle = glint_create(&cfg);
76 if handle.is_null() {
77 return Err("glint_create returned null");
78 }
79 let spf = glint_samples_per_frame(handle) as usize;
80 Ok(Encoder { handle, samples_per_frame: spf,
81 channels: channels as usize })
82 }
83 }
84
85 pub fn samples_per_frame(&self) -> usize {
87 self.samples_per_frame
88 }
89
90 pub fn channels(&self) -> usize {
92 self.channels
93 }
94
95 pub fn encode(&mut self, pcm: &[i16]) -> Vec<u8> {
101 let spf = self.samples_per_frame;
102 let ch = self.channels;
103
104 let mut channel_bufs: Vec<Vec<i16>> = (0..ch).map(|_| vec![0i16; spf]).collect();
106 for (i, &sample) in pcm.iter().enumerate() {
107 let c = i % ch;
108 let s = i / ch;
109 if s < spf {
110 channel_bufs[c][s] = sample;
111 }
112 }
113
114 let ptrs: Vec<*const i16> = channel_bufs.iter().map(|b| b.as_ptr()).collect();
115 let mut out_size: i32 = 0;
116
117 unsafe {
118 let data = glint_encode(self.handle, ptrs.as_ptr(), &mut out_size);
119 if data.is_null() || out_size <= 0 {
120 return Vec::new();
121 }
122 slice::from_raw_parts(data, out_size as usize).to_vec()
123 }
124 }
125
126 pub fn encode_float(&mut self, pcm: &[f32]) -> Vec<u8> {
131 let spf = self.samples_per_frame;
132 let ch = self.channels;
133
134 let mut channel_bufs: Vec<Vec<f32>> = (0..ch).map(|_| vec![0.0f32; spf]).collect();
135 for (i, &sample) in pcm.iter().enumerate() {
136 let c = i % ch;
137 let s = i / ch;
138 if s < spf {
139 channel_bufs[c][s] = sample;
140 }
141 }
142
143 let ptrs: Vec<*const f32> = channel_bufs.iter().map(|b| b.as_ptr()).collect();
144 let mut out_size: i32 = 0;
145
146 unsafe {
147 let data = glint_encode_float(self.handle, ptrs.as_ptr(), &mut out_size);
148 if data.is_null() || out_size <= 0 {
149 return Vec::new();
150 }
151 slice::from_raw_parts(data, out_size as usize).to_vec()
152 }
153 }
154
155 pub fn flush(&mut self) -> Vec<u8> {
157 let mut out_size: i32 = 0;
158 unsafe {
159 let data = glint_flush(self.handle, &mut out_size);
160 if data.is_null() || out_size <= 0 {
161 return Vec::new();
162 }
163 slice::from_raw_parts(data, out_size as usize).to_vec()
164 }
165 }
166}
167
168impl Drop for Encoder {
169 fn drop(&mut self) {
170 unsafe {
171 glint_destroy(self.handle);
172 }
173 }
174}
175
176pub struct AacEncoder {
182 handle: glint_t,
183 samples_per_frame: usize,
184 channels: usize,
185}
186
187unsafe impl Send for AacEncoder {}
188
189impl AacEncoder {
190 pub fn new(
192 sample_rate: u32,
193 channels: u32,
194 bitrate: u32,
195 quality: u32,
196 ) -> Result<Self, &'static str> {
197 unsafe {
198 let cfg = glint_aac_config {
199 sample_rate: sample_rate as i32,
200 num_channels: channels as i32,
201 bitrate: bitrate as i32,
202 quality: quality as i32,
203 vbr: 0,
204 vbr_quality: 0,
205 reserved: [0; 4],
206 };
207 let handle = glint_aac_create(&cfg);
208 if handle.is_null() {
209 return Err("glint_aac_create returned null");
210 }
211 let spf = glint_aac_samples_per_frame(handle) as usize;
212 Ok(AacEncoder { handle, samples_per_frame: spf, channels: channels as usize })
213 }
214 }
215
216 pub fn with_options(sample_rate: u32, channels: u32, bitrate: u32,
219 quality: u32, vbr_quality: Option<u32>) -> Result<Self, &'static str> {
220 unsafe {
221 let cfg = glint_aac_config {
222 sample_rate: sample_rate as i32,
223 num_channels: channels as i32,
224 bitrate: bitrate as i32,
225 quality: quality as i32,
226 vbr: if vbr_quality.is_some() { 1 } else { 0 },
227 vbr_quality: vbr_quality.unwrap_or(0) as i32,
228 reserved: [0; 4],
229 };
230 let handle = glint_aac_create(&cfg);
231 if handle.is_null() {
232 return Err("glint_aac_create returned null");
233 }
234 let spf = glint_aac_samples_per_frame(handle) as usize;
235 Ok(AacEncoder { handle, samples_per_frame: spf, channels: channels as usize })
236 }
237 }
238
239 pub fn samples_per_frame(&self) -> usize {
240 self.samples_per_frame
241 }
242
243 pub fn channels(&self) -> usize {
244 self.channels
245 }
246
247 pub fn encode(&mut self, pcm: &[i16]) -> Vec<u8> {
249 let spf = self.samples_per_frame;
250 let ch = self.channels;
251 let mut channel_bufs: Vec<Vec<i16>> = (0..ch).map(|_| vec![0i16; spf]).collect();
252 for (i, &sample) in pcm.iter().enumerate() {
253 let c = i % ch;
254 let s = i / ch;
255 if s < spf {
256 channel_bufs[c][s] = sample;
257 }
258 }
259 let ptrs: Vec<*const i16> = channel_bufs.iter().map(|b| b.as_ptr()).collect();
260 let mut out_size: i32 = 0;
261 unsafe {
262 let data = glint_aac_encode(self.handle, ptrs.as_ptr(), &mut out_size);
263 if data.is_null() || out_size <= 0 {
264 return Vec::new();
265 }
266 slice::from_raw_parts(data, out_size as usize).to_vec()
267 }
268 }
269
270 pub fn flush(&mut self) -> Vec<u8> {
272 let mut out_size: i32 = 0;
273 unsafe {
274 let data = glint_aac_flush(self.handle, &mut out_size);
275 if data.is_null() || out_size <= 0 {
276 return Vec::new();
277 }
278 slice::from_raw_parts(data, out_size as usize).to_vec()
279 }
280 }
281}
282
283impl Drop for AacEncoder {
284 fn drop(&mut self) {
285 unsafe {
286 glint_aac_destroy(self.handle);
287 }
288 }
289}
290
291pub fn encode_pcm_aac(
294 pcm: &[i16],
295 sample_rate: u32,
296 channels: u32,
297 bitrate: u32,
298 quality: u32,
299) -> Vec<u8> {
300 let mut enc = match AacEncoder::new(sample_rate, channels, bitrate, quality) {
301 Ok(e) => e,
302 Err(_) => return Vec::new(),
303 };
304 let frame_len = enc.samples_per_frame() * enc.channels();
305 let mut aac = Vec::new();
306 for chunk in pcm.chunks(frame_len) {
307 aac.extend(enc.encode(chunk));
308 }
309 aac.extend(enc.flush());
310 aac
311}
312
313pub fn encode_pcm(pcm: &[i16], sample_rate: u32, channels: u32, bitrate: u32) -> Vec<u8> {
316 let mut enc = match Encoder::new(sample_rate, channels, bitrate) {
317 Ok(e) => e,
318 Err(_) => return Vec::new(),
319 };
320
321 let frame_len = enc.samples_per_frame() * enc.channels();
322 let mut mp3 = Vec::new();
323
324 for chunk in pcm.chunks(frame_len) {
325 mp3.extend(enc.encode(chunk));
326 }
327 mp3.extend(enc.flush());
328 mp3
329}
330
331
332pub struct OpusEncoder {
335 handle: glint_sys::glint_t,
336 channels: usize,
337}
338
339unsafe impl Send for OpusEncoder {}
340
341impl OpusEncoder {
342 pub fn new(channels: u32, bitrate: u32, vbr: bool) -> Result<Self, &'static str> {
343 let handle = unsafe {
344 glint_sys::glint_opus_enc_create(channels as i32, bitrate as i32, vbr as i32)
345 };
346 if handle.is_null() {
347 return Err("invalid Opus encoder config");
348 }
349 Ok(OpusEncoder { handle, channels: channels as usize })
350 }
351
352 pub fn encode(&mut self, pcm: &[f32]) -> Result<Vec<u8>, &'static str> {
355 let frame = pcm.len() / self.channels;
356 let mut out = vec![0u8; 1500];
357 let n = unsafe {
358 glint_sys::glint_opus_encode(
359 self.handle, pcm.as_ptr(), frame as i32, out.as_mut_ptr(), out.len() as i32)
360 };
361 if n < 0 {
362 return Err("opus encode failed (frame must be 120/240/480/960)");
363 }
364 out.truncate(n as usize);
365 Ok(out)
366 }
367
368 pub fn final_range(&self) -> u32 {
369 unsafe { glint_sys::glint_opus_enc_final_range(self.handle) }
370 }
371}
372
373impl Drop for OpusEncoder {
374 fn drop(&mut self) {
375 unsafe { glint_sys::glint_opus_enc_destroy(self.handle) };
376 }
377}
378
379pub struct OpusDecoder {
382 handle: glint_sys::glint_t,
383 channels: usize,
384}
385
386unsafe impl Send for OpusDecoder {}
387
388impl OpusDecoder {
389 pub fn new(channels: u32, sample_rate: u32) -> Result<Self, &'static str> {
390 let handle = unsafe {
391 glint_sys::glint_opus_dec_create(channels as i32, sample_rate as i32)
392 };
393 if handle.is_null() {
394 return Err("invalid Opus decoder config");
395 }
396 Ok(OpusDecoder { handle, channels: channels as usize })
397 }
398
399 pub fn decode(&mut self, packet: &[u8]) -> Result<Vec<f32>, &'static str> {
401 let mut pcm = vec![0f32; 2 * 5760];
402 let n = unsafe {
403 glint_sys::glint_opus_decode(
404 self.handle, packet.as_ptr(), packet.len() as i32, pcm.as_mut_ptr(), 5760)
405 };
406 if n < 0 {
407 return Err("opus decode failed");
408 }
409 pcm.truncate(n as usize * self.channels);
410 Ok(pcm)
411 }
412
413 pub fn decode_lost(
417 &mut self,
418 frame_size: usize,
419 next_packet: Option<&[u8]>,
420 ) -> Result<Vec<f32>, &'static str> {
421 let mut pcm = vec![0f32; 2 * 5760];
422 let n = unsafe {
423 match next_packet {
424 Some(p) => glint_sys::glint_opus_decode_fec(
425 self.handle, p.as_ptr(), p.len() as i32, pcm.as_mut_ptr(),
426 frame_size as i32),
427 None => glint_sys::glint_opus_decode_fec(
428 self.handle, std::ptr::null(), 0, pcm.as_mut_ptr(),
429 frame_size as i32),
430 }
431 };
432 if n < 0 {
433 return Err("opus concealment failed");
434 }
435 pcm.truncate(n as usize * self.channels);
436 Ok(pcm)
437 }
438
439 pub fn final_range(&self) -> u32 {
440 unsafe { glint_sys::glint_opus_dec_final_range(self.handle) }
441 }
442}
443
444impl Drop for OpusDecoder {
445 fn drop(&mut self) {
446 unsafe { glint_sys::glint_opus_dec_destroy(self.handle) };
447 }
448}
449
450#[cfg(test)]
451mod opus_tests {
452 use super::*;
453
454 #[test]
455 fn opus_roundtrip_final_range() {
456 let mut enc = OpusEncoder::new(2, 96000, false).unwrap();
457 let mut dec = OpusDecoder::new(2, 48000).unwrap();
458 for f in 0..5 {
459 let mut pcm = vec![0f32; 960 * 2];
460 for i in 0..960 {
461 let t = (f * 960 + i) as f32 / 48000.0;
462 pcm[i * 2] = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
463 pcm[i * 2 + 1] = 0.3 * (2.0 * std::f32::consts::PI * 660.0 * t).sin();
464 }
465 let pkt = enc.encode(&pcm).unwrap();
466 let out = dec.decode(&pkt).unwrap();
467 assert_eq!(out.len(), 960 * 2);
468 assert_eq!(enc.final_range(), dec.final_range());
469 }
470 let lost = dec.decode_lost(960, None).unwrap();
471 assert_eq!(lost.len(), 960 * 2);
472 }
473}
474
475
476#[derive(Debug, Clone, Copy)]
478pub struct DecFrameInfo {
479 pub sample_rate: u32,
480 pub channels: u32,
481 pub samples: u32,
482 pub frame_bytes: u32,
483}
484
485macro_rules! frame_decoder {
486 ($name:ident, $create:ident, $decode:ident, $info:ident,
487 $destroy:ident, $doc:literal) => {
488 #[doc = $doc]
489 pub struct $name {
490 handle: glint_sys::glint_t,
491 }
492 unsafe impl Send for $name {}
493 impl $name {
494 pub fn new() -> Result<Self, &'static str> {
495 let handle = unsafe { glint_sys::$create() };
496 if handle.is_null() {
497 return Err("decoder create failed");
498 }
499 Ok($name { handle })
500 }
501
502 pub fn frame_info(&self, data: &[u8]) -> Option<DecFrameInfo> {
505 let mut fi = glint_sys::GlintDecFrameInfo::default();
506 let ok = unsafe {
507 glint_sys::$info(data.as_ptr(), data.len() as i32, &mut fi)
508 };
509 if ok < 0 {
510 return None;
511 }
512 Some(DecFrameInfo {
513 sample_rate: fi.sample_rate as u32,
514 channels: fi.channels as u32,
515 samples: fi.samples as u32,
516 frame_bytes: fi.frame_bytes as u32,
517 })
518 }
519
520 pub fn decode_frame(
523 &mut self,
524 data: &[u8],
525 ) -> Result<(Vec<f32>, DecFrameInfo), &'static str> {
526 let mut pcm = vec![0f32; 2 * 1152];
527 let mut fi = glint_sys::GlintDecFrameInfo::default();
528 let n = unsafe {
529 glint_sys::$decode(self.handle, data.as_ptr(),
530 data.len() as i32, pcm.as_mut_ptr(), &mut fi)
531 };
532 if n < 0 {
533 return Err("decode failed");
534 }
535 let ch = fi.channels.max(1) as usize;
536 pcm.truncate(n as usize * ch);
537 Ok((pcm, DecFrameInfo {
538 sample_rate: fi.sample_rate as u32,
539 channels: fi.channels as u32,
540 samples: n as u32,
541 frame_bytes: fi.frame_bytes as u32,
542 }))
543 }
544
545 pub fn decode(&mut self, data: &[u8]) -> Vec<f32> {
548 let mut off = 0usize;
549 if data.len() > 10 && &data[..3] == b"ID3" {
550 let sz = ((data[6] as usize & 0x7f) << 21)
551 | ((data[7] as usize & 0x7f) << 14)
552 | ((data[8] as usize & 0x7f) << 7)
553 | (data[9] as usize & 0x7f);
554 off = 10 + sz;
555 }
556 let mut out = Vec::new();
557 while off + 7 <= data.len() {
558 let info = match self.frame_info(&data[off..]) {
559 Some(i) => i,
560 None => {
561 off += 1;
562 continue;
563 }
564 };
565 let fb = info.frame_bytes as usize;
566 if fb == 0 || off + fb > data.len() {
567 break;
568 }
569 if let Ok((pcm, _)) = self.decode_frame(&data[off..off + fb]) {
570 out.extend_from_slice(&pcm);
571 }
572 off += fb;
573 }
574 out
575 }
576 }
577 impl Drop for $name {
578 fn drop(&mut self) {
579 unsafe { glint_sys::$destroy(self.handle) };
580 }
581 }
582 };
583}
584
585frame_decoder!(Mp3Decoder, glint_mp3_dec_create, glint_mp3_decode,
586 glint_mp3_frame_info, glint_mp3_dec_destroy,
587 "MPEG-1/2 Layer III decoder (keeps a bit reservoir across frames).");
588frame_decoder!(AacDecoder, glint_aac_dec_create, glint_aac_decode,
589 glint_aac_frame_info, glint_aac_dec_destroy,
590 "ADTS AAC-LC decoder.");
591
592#[cfg(test)]
593mod decoder_tests {
594 use super::*;
595
596 #[test]
597 fn mp3_encode_decode_roundtrip() {
598 let mut enc = Encoder::new(44100, 2, 128).unwrap();
599 let spf = enc.samples_per_frame();
600 let mut stream = Vec::new();
601 let mut phase = 0.0f64;
602 for _ in 0..40 {
603 let mut pcm = vec![0i16; spf * 2];
604 for i in 0..spf {
605 let s = 0.4 * (2.0 * std::f64::consts::PI * 440.0 * phase
606 / 44100.0).sin();
607 phase += 1.0;
608 pcm[i * 2] = (s * 20000.0) as i16;
609 pcm[i * 2 + 1] = (s * 15000.0) as i16;
610 }
611 stream.extend_from_slice(&enc.encode(&pcm));
612 }
613 stream.extend_from_slice(&enc.flush());
614 let mut dec = Mp3Decoder::new().unwrap();
615 let out = dec.decode(&stream);
616 assert!(out.len() > 40000, "decoded {} samples", out.len());
617 }
618}
619
620
621pub fn resample(pcm: &[f32], channels: u32, sr_in: u32, sr_out: u32) -> Vec<f32> {
630 if channels == 0 || pcm.is_empty() {
631 return Vec::new();
632 }
633 let ch = channels as i32;
634 let in_frames = pcm.len() as i32 / ch;
635 let mut out_frames: core::ffi::c_int = 0;
636 let ptr = unsafe {
637 glint_sys::glint_resample(pcm.as_ptr(), in_frames, ch,
638 sr_in as i32, sr_out as i32, &mut out_frames)
639 };
640 if ptr.is_null() {
641 return Vec::new();
642 }
643 let total = out_frames as usize * channels as usize;
644 let out = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
645 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
646 out
647}
648
649#[derive(Debug, Clone)]
651pub struct DecodedAudio {
652 pub pcm: Vec<f32>,
653 pub sample_rate: u32,
654 pub channels: u32,
655}
656
657pub fn decode_audio(data: &[u8]) -> Option<DecodedAudio> {
661 if data.is_empty() {
662 return None;
663 }
664 let mut sr: core::ffi::c_int = 0;
665 let mut ch: core::ffi::c_int = 0;
666 let mut frames: core::ffi::c_int = 0;
667 let ptr = unsafe {
668 glint_sys::glint_decode_audio(data.as_ptr(), data.len() as i32,
669 &mut sr, &mut ch, &mut frames)
670 };
671 if ptr.is_null() || ch <= 0 {
672 return None;
673 }
674 let total = frames as usize * ch as usize;
675 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
676 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
677 Some(DecodedAudio { pcm, sample_rate: sr as u32, channels: ch as u32 })
678}
679
680pub fn decode_vorbis(ogg: &[u8]) -> Option<DecodedAudio> {
686 if ogg.is_empty() {
687 return None;
688 }
689 let mut sr: core::ffi::c_int = 0;
690 let mut ch: core::ffi::c_int = 0;
691 let mut frames: core::ffi::c_int = 0;
692 let ptr = unsafe {
693 glint_sys::glint_vorbis_decode(ogg.as_ptr(), ogg.len() as i32,
694 &mut sr, &mut ch, &mut frames)
695 };
696 if ptr.is_null() || ch <= 0 {
697 return None;
698 }
699 let total = frames as usize * ch as usize;
700 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
701 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
702 Some(DecodedAudio { pcm, sample_rate: sr as u32, channels: ch as u32 })
703}
704
705pub fn decode_flac(flac: &[u8]) -> Option<DecodedAudio> {
708 if flac.is_empty() {
709 return None;
710 }
711 let mut sr: core::ffi::c_int = 0;
712 let mut ch: core::ffi::c_int = 0;
713 let mut frames: core::ffi::c_int = 0;
714 let ptr = unsafe {
715 glint_sys::glint_flac_decode(flac.as_ptr(), flac.len() as i32,
716 &mut sr, &mut ch, &mut frames)
717 };
718 if ptr.is_null() || ch <= 0 {
719 return None;
720 }
721 let total = frames as usize * ch as usize;
722 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
723 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
724 Some(DecodedAudio { pcm, sample_rate: sr as u32, channels: ch as u32 })
725}
726
727pub fn encode_opus_file(pcm: &[f32], channels: u32, bitrate_bps: u32,
732 vbr: bool) -> Option<Vec<u8>> {
733 if channels == 0 || channels > 2 || pcm.is_empty() {
734 return None;
735 }
736 let frames = pcm.len() as i32 / channels as i32;
737 let mut out_size: core::ffi::c_int = 0;
738 let ptr = unsafe {
739 glint_sys::glint_opus_encode_file(pcm.as_ptr(), frames,
740 channels as i32, bitrate_bps as i32, vbr as i32, &mut out_size)
741 };
742 if ptr.is_null() || out_size <= 0 {
743 return None;
744 }
745 let data = unsafe { std::slice::from_raw_parts(ptr, out_size as usize) }
746 .to_vec();
747 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
748 Some(data)
749}
750
751pub fn decode_audio_rate(data: &[u8], out_rate: u32) -> Option<DecodedAudio> {
755 if data.is_empty() {
756 return None;
757 }
758 let (mut sr, mut ch, mut fr) = (0i32, 0i32, 0i32);
759 let ptr = unsafe {
760 glint_sys::glint_decode_audio_ex(data.as_ptr(), data.len() as i32,
761 out_rate as i32, 0, &mut sr, &mut ch, &mut fr)
762 } as *mut f32;
763 if ptr.is_null() || ch <= 0 {
764 return None;
765 }
766 let total = fr as usize * ch as usize;
767 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
768 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
769 Some(DecodedAudio { pcm, sample_rate: sr as u32, channels: ch as u32 })
770}
771
772pub fn decode_audio_i16(data: &[u8], out_rate: u32)
775 -> Option<(Vec<i16>, u32, u32)> {
776 if data.is_empty() {
777 return None;
778 }
779 let (mut sr, mut ch, mut fr) = (0i32, 0i32, 0i32);
780 let ptr = unsafe {
781 glint_sys::glint_decode_audio_ex(data.as_ptr(), data.len() as i32,
782 out_rate as i32, 1, &mut sr, &mut ch, &mut fr)
783 } as *mut i16;
784 if ptr.is_null() || ch <= 0 {
785 return None;
786 }
787 let total = fr as usize * ch as usize;
788 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
789 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
790 Some((pcm, sr as u32, ch as u32))
791}
792
793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
795pub enum Codec {
796 Mp3 = 0,
797 Aac = 1,
798 Opus = 2,
799}
800
801pub fn encode_audio(pcm: &[f32], channels: u32, sample_rate: u32,
807 codec: Codec, bitrate_kbps: u32, vbr_quality: Option<u32>,
808 quality: u32) -> Option<Vec<u8>> {
809 if channels == 0 || channels > 2 || pcm.is_empty() {
810 return None;
811 }
812 let frames = pcm.len() as i32 / channels as i32;
813 let mut out_size: core::ffi::c_int = 0;
814 let ptr = unsafe {
815 glint_sys::glint_encode_audio(pcm.as_ptr(), frames, channels as i32,
816 sample_rate as i32, codec as i32, bitrate_kbps as i32,
817 vbr_quality.map(|q| q as i32).unwrap_or(-1), quality as i32,
818 &mut out_size)
819 };
820 if ptr.is_null() || out_size <= 0 {
821 return None;
822 }
823 let data = unsafe { std::slice::from_raw_parts(ptr, out_size as usize) }
824 .to_vec();
825 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
826 Some(data)
827}
828
829pub fn read_wav(data: &[u8]) -> Option<DecodedAudio> {
833 if data.is_empty() {
834 return None;
835 }
836 let mut sr: core::ffi::c_int = 0;
837 let mut ch: core::ffi::c_int = 0;
838 let mut frames: core::ffi::c_int = 0;
839 let ptr = unsafe {
840 glint_sys::glint_wav_read(data.as_ptr(), data.len() as i32,
841 &mut sr, &mut ch, &mut frames)
842 };
843 if ptr.is_null() || ch <= 0 {
844 return None;
845 }
846 let total = frames as usize * ch as usize;
847 let pcm = unsafe { std::slice::from_raw_parts(ptr, total) }.to_vec();
848 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
849 Some(DecodedAudio { pcm, sample_rate: sr as u32, channels: ch as u32 })
850}
851
852pub fn write_wav(pcm: &[f32], channels: u32, sample_rate: u32, bits: u32,
856 float_fmt: bool) -> Option<Vec<u8>> {
857 if channels == 0 {
858 return None;
859 }
860 let frames = pcm.len() as i32 / channels as i32;
861 let mut out_size: core::ffi::c_int = 0;
862 let ptr = unsafe {
863 glint_sys::glint_wav_write(pcm.as_ptr(), frames, channels as i32,
864 sample_rate as i32, bits as i32, float_fmt as i32, &mut out_size)
865 };
866 if ptr.is_null() || out_size <= 0 {
867 return None;
868 }
869 let data = unsafe { std::slice::from_raw_parts(ptr, out_size as usize) }
870 .to_vec();
871 unsafe { glint_sys::glint_free(ptr as *mut core::ffi::c_void) };
872 Some(data)
873}
874
875#[cfg(test)]
876mod buckets_ab_tests {
877 use super::*;
878
879 #[test]
880 fn resample_length_and_passthrough() {
881 let n = 4410usize;
882 let pcm: Vec<f32> = (0..n)
883 .map(|i| (2.0 * std::f32::consts::PI * 200.0 * i as f32 / 44100.0).sin())
884 .collect();
885 let up = resample(&pcm, 1, 44100, 48000);
886 let expect = (n as f64 * 48000.0 / 44100.0).round() as usize;
887 assert!((up.len() as i64 - expect as i64).abs() <= 2,
888 "got {} want ~{}", up.len(), expect);
889 let same = resample(&pcm, 1, 44100, 44100);
890 assert_eq!(same.len(), n);
891 }
892
893 #[test]
894 fn resample_preserves_amplitude() {
895 let n = 8820usize;
896 let pcm: Vec<f32> = (0..n)
897 .map(|i| 0.5 * (2.0 * std::f32::consts::PI * 300.0 * i as f32 / 44100.0).sin())
898 .collect();
899 let out = resample(&pcm, 1, 44100, 22050);
900 let peak = out[100..out.len() - 100].iter().fold(0f32, |m, &x| m.max(x.abs()));
901 assert!(peak > 0.45 && peak < 0.55, "peak {}", peak);
902 }
903
904 #[test]
905 fn decode_audio_mp3_and_aac() {
906 let spf = 1152usize;
908 let mut mp3enc = Encoder::new(44100, 2, 128).unwrap();
909 let mut mp3 = Vec::new();
910 let mut aacenc = AacEncoder::new(44100, 2, 128, 1).unwrap();
911 let mut aac = Vec::new();
912 let mut phase = 0.0f64;
913 for _ in 0..50 {
914 let mut pcm = vec![0i16; spf * 2];
915 for i in 0..spf {
916 let s = (0.4 * (2.0 * std::f64::consts::PI * 440.0 * phase / 44100.0).sin()
917 * 20000.0) as i16;
918 phase += 1.0;
919 pcm[i * 2] = s;
920 pcm[i * 2 + 1] = s;
921 }
922 mp3.extend_from_slice(&mp3enc.encode(&pcm));
923 let mut af = vec![0i16; 1024 * 2];
925 af.copy_from_slice(&pcm[..1024 * 2]);
926 aac.extend_from_slice(&aacenc.encode(&af));
927 }
928 mp3.extend_from_slice(&mp3enc.flush());
929 aac.extend_from_slice(&aacenc.flush());
930
931 let d1 = decode_audio(&mp3).expect("mp3 decodes");
932 assert_eq!(d1.channels, 2);
933 assert!(d1.pcm.len() > 40000, "mp3 {} samples", d1.pcm.len());
934
935 let d2 = decode_audio(&aac).expect("aac decodes");
936 assert_eq!(d2.channels, 2);
937 assert!(d2.pcm.len() > 40000, "aac {} samples", d2.pcm.len());
938 }
939
940 #[test]
941 fn encoder_knobs() {
942 let spf = 1152usize;
944 let mut enc = Encoder::with_options(44100, 2, 192, 3, 2, 0, Some(3))
945 .expect("mp3 opts");
946 let mut mp3 = Vec::new();
947 let mut aac_enc = AacEncoder::with_options(44100, 2, 128, 1, Some(2))
948 .expect("aac opts");
949 let mut aac = Vec::new();
950 let mut phase = 0.0f64;
951 for _ in 0..50 {
952 let mut pcm = vec![0i16; spf * 2];
953 for i in 0..spf {
954 let s = (0.4 * (2.0 * std::f64::consts::PI * 440.0 * phase / 44100.0).sin()
955 * 20000.0) as i16;
956 phase += 1.0;
957 pcm[i * 2] = s;
958 pcm[i * 2 + 1] = s;
959 }
960 mp3.extend_from_slice(&enc.encode(&pcm));
961 let mut af = vec![0i16; 1024 * 2];
962 af.copy_from_slice(&pcm[..1024 * 2]);
963 aac.extend_from_slice(&aac_enc.encode(&af));
964 }
965 mp3.extend_from_slice(&enc.flush());
966 aac.extend_from_slice(&aac_enc.flush());
967 assert_eq!(decode_audio(&mp3).unwrap().channels, 2);
968 assert_eq!(decode_audio(&aac).unwrap().channels, 2);
969 }
970
971 #[test]
972 fn decode_dtype_and_rate() {
973 let (sr, ch, n) = (44100u32, 2usize, 44100usize);
974 let mut pcm = vec![0f32; n * ch];
975 for i in 0..n {
976 let v = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / sr as f32).sin();
977 pcm[i * 2] = v;
978 pcm[i * 2 + 1] = v;
979 }
980 let mp3 = encode_audio(&pcm, ch as u32, sr, Codec::Mp3, 128, None, 1)
981 .expect("encode");
982 let f = decode_audio_rate(&mp3, 0).expect("float");
983 assert_eq!((f.sample_rate, f.channels), (44100, 2));
984 let (i16pcm, isr, ich) = decode_audio_i16(&mp3, 0).expect("i16");
985 assert_eq!((isr, ich), (44100, 2));
986 assert_eq!(i16pcm.len(), f.pcm.len());
987 let r = decode_audio_rate(&mp3, 24000).expect("resampled");
988 assert_eq!(r.sample_rate, 24000);
989 }
990
991 #[test]
992 fn encode_audio_all_codecs_odd_rate() {
993 let (sr, ch, n) = (37000u32, 2usize, 37000usize);
995 let mut pcm = vec![0f32; n * ch];
996 for i in 0..n {
997 let v = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / sr as f32).sin();
998 pcm[i * 2] = v;
999 pcm[i * 2 + 1] = v;
1000 }
1001 for (codec, want) in [(Codec::Mp3, 32000u32), (Codec::Aac, 32000),
1002 (Codec::Opus, 48000)] {
1003 let data = encode_audio(&pcm, ch as u32, sr, codec, 128, None, 1)
1004 .expect("encode");
1005 assert!(data.len() > 1000, "{:?} {}", codec, data.len());
1006 let d = decode_audio(&data).expect("decode");
1007 assert_eq!(d.sample_rate, want, "{:?} rate", codec);
1008 assert_eq!(d.channels, 2, "{:?} ch", codec);
1009 }
1010 }
1011
1012 #[test]
1013 fn wav_bit_depths_roundtrip() {
1014 let n = 4096usize;
1015 let pcm: Vec<f32> = (0..n)
1016 .map(|i| 0.5 * (2.0 * std::f32::consts::PI * 300.0 * i as f32 / 44100.0).sin())
1017 .collect();
1018 for &(bits, flt, tol) in &[(8u32, false, 0.02f32), (16, false, 2e-4),
1019 (24, false, 1e-5), (32, false, 1e-6), (32, true, 1e-6)] {
1020 let wav = write_wav(&pcm, 1, 44100, bits, flt).expect("write");
1021 let a = read_wav(&wav).expect("read");
1022 assert_eq!((a.sample_rate, a.channels), (44100, 1));
1023 let err = pcm.iter().zip(a.pcm.iter())
1024 .map(|(x, y)| (x - y).abs()).fold(0f32, f32::max);
1025 assert!(err < tol, "{}-bit err {}", bits, err);
1026 }
1027 }
1028
1029 #[test]
1030 fn opus_file_encode_decode() {
1031 let n = 48000usize;
1033 let mut pcm = vec![0f32; n * 2];
1034 for i in 0..n {
1035 let v = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * i as f32 / 48000.0).sin();
1036 pcm[i * 2] = v;
1037 pcm[i * 2 + 1] = v;
1038 }
1039 let opus = encode_opus_file(&pcm, 2, 96000, false).expect("opus encodes");
1040 assert_eq!(&opus[..4], b"OggS");
1041 let dec = decode_audio(&opus).expect("opus decodes");
1042 assert_eq!((dec.sample_rate, dec.channels), (48000, 2));
1043 assert!(dec.pcm.len() > 40000 * 2, "opus {} samples", dec.pcm.len());
1044 }
1045}