softmixer.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use std::sync::atomic::{AtomicUsize, Ordering};
  2. use std::sync::Arc;
  3. use super::AudioFilter;
  4. use super::{Mixer, MixerConfig};
  5. #[derive(Clone)]
  6. pub struct SoftMixer {
  7. volume: Arc<AtomicUsize>,
  8. }
  9. impl Mixer for SoftMixer {
  10. fn open(_: Option<MixerConfig>) -> SoftMixer {
  11. SoftMixer {
  12. volume: Arc::new(AtomicUsize::new(0xFFFF)),
  13. }
  14. }
  15. fn start(&self) {}
  16. fn stop(&self) {}
  17. fn volume(&self) -> u16 {
  18. self.volume.load(Ordering::Relaxed) as u16
  19. }
  20. fn set_volume(&self, volume: u16) {
  21. self.volume.store(volume as usize, Ordering::Relaxed);
  22. }
  23. fn get_audio_filter(&self) -> Option<Box<dyn AudioFilter + Send>> {
  24. Some(Box::new(SoftVolumeApplier {
  25. volume: self.volume.clone(),
  26. }))
  27. }
  28. }
  29. struct SoftVolumeApplier {
  30. volume: Arc<AtomicUsize>,
  31. }
  32. impl AudioFilter for SoftVolumeApplier {
  33. fn modify_stream(&self, data: &mut [i16]) {
  34. let volume = self.volume.load(Ordering::Relaxed) as u16;
  35. if volume != 0xFFFF {
  36. for x in data.iter_mut() {
  37. *x = (*x as i32 * volume as i32 / 0xFFFF) as i16;
  38. }
  39. }
  40. }
  41. }