softmixer.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use super::Mixer;
  2. use super::StreamEditor;
  3. use std::borrow::Cow;
  4. use std::sync::{Arc, RwLock};
  5. pub struct SoftMixer {
  6. volume: Arc<RwLock<u16>>
  7. }
  8. impl SoftMixer {
  9. pub fn new() -> SoftMixer {
  10. SoftMixer {
  11. volume: Arc::new(RwLock::new(0xFFFF))
  12. }
  13. }
  14. }
  15. impl Mixer for SoftMixer {
  16. fn init(&self) {
  17. }
  18. fn start(&self) {
  19. }
  20. fn stop(&self) {
  21. }
  22. fn volume(&self) -> u16 {
  23. *self.volume.read().unwrap()
  24. }
  25. fn set_volume(&self, volume: u16) {
  26. *self.volume.write().unwrap() = volume;
  27. }
  28. fn get_stream_editor(&self) -> Option<Box<StreamEditor + Send>> {
  29. let vol = self.volume.clone();
  30. Some(Box::new(SoftVolumeApplier { get_volume: Box::new(move || *vol.read().unwrap() ) }))
  31. }
  32. }
  33. struct SoftVolumeApplier {
  34. get_volume: Box<Fn() -> u16 + Send>
  35. }
  36. impl StreamEditor for SoftVolumeApplier {
  37. fn modify_stream<'a>(&self, data: &'a [i16]) -> Cow<'a, [i16]> {
  38. let volume = (self.get_volume)();
  39. if volume == 0xFFFF {
  40. Cow::Borrowed(data)
  41. } else {
  42. Cow::Owned(data.iter()
  43. .map(|&x| {
  44. (x as i32
  45. * volume as i32
  46. / 0xFFFF) as i16
  47. })
  48. .collect())
  49. }
  50. }
  51. }