| 1 | // Copyright 2025 LiveKit, Inc. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | use cxx::UniquePtr; |
| 16 | use webrtc_sys::audio_resampler as sys_ar; |
| 17 | |
| 18 | pub struct AudioResampler { |
| 19 | sys_handle: UniquePtr<sys_ar::ffi::AudioResampler>, |
| 20 | } |
| 21 | |
| 22 | impl Default for AudioResampler { |
| 23 | fn default() -> Self { |
| 24 | Self { sys_handle: sys_ar::ffi::create_audio_resampler() } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl AudioResampler { |
| 29 | pub fn remix_and_resample<'a>( |
| 30 | &'a mut self, |
| 31 | src: &[i16], |
| 32 | samples_per_channel: u32, |
| 33 | num_channels: u32, |
| 34 | sample_rate: u32, |
| 35 | dst_num_channels: u32, |
| 36 | dst_sample_rate: u32, |
| 37 | ) -> &'a [i16] { |
| 38 | assert!(src.len() >= (samples_per_channel * num_channels) as usize, "src buffer too small"); |
| 39 | |
| 40 | unsafe { |
| 41 | let len = self.sys_handle.pin_mut().remix_and_resample( |
| 42 | src.as_ptr(), |
| 43 | samples_per_channel as usize, |
| 44 | num_channels as usize, |
| 45 | sample_rate as i32, |
| 46 | dst_num_channels as usize, |
| 47 | dst_sample_rate as i32, |
| 48 | ); |
| 49 | |
| 50 | std::slice::from_raw_parts(self.sys_handle.data(), len / 2) |
| 51 | } |
| 52 | } |
| 53 | } |