Browse Source

SoftMixer: Change volume to AtomicUsize and pass AtomicUsize to SoftVolumeApplier

Daniel Romero 8 năm trước cách đây
mục cha
commit
2de5d10a2f
1 tập tin đã thay đổi với 9 bổ sung10 xóa
  1. 9 10
      src/mixer/softmixer.rs

+ 9 - 10
src/mixer/softmixer.rs

@@ -1,5 +1,6 @@
 use std::borrow::Cow;
-use std::sync::{Arc, RwLock};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
 
 use spirc::UpdateMessageSender;
 use spirc::UpdateMessage;
@@ -8,14 +9,14 @@ use super::Mixer;
 use super::AudioFilter;
 
 pub struct SoftMixer {
-  volume: Arc<RwLock<u16>>,
+  volume: Arc<AtomicUsize>,
   tx: Option<UpdateMessageSender>
 }
 
 impl SoftMixer {
     pub fn new() -> SoftMixer {
         SoftMixer {
-            volume: Arc::new(RwLock::new(0xFFFF)),
+            volume: Arc::new(AtomicUsize::new(0xFFFF)),
             tx: None
         }
     }
@@ -30,27 +31,25 @@ impl Mixer for SoftMixer {
     fn stop(&self) {
     }
     fn volume(&self) -> u16 {
-        *self.volume.read().unwrap()
+        self.volume.load(Ordering::Relaxed) as u16
     }
     fn set_volume(&self, volume: u16) {
-        *self.volume.write().unwrap() = volume;
+        self.volume.store(volume as usize, Ordering::Relaxed);
         let tx = self.tx.as_ref().expect("SoftMixer not initialized");
         tx.send(UpdateMessage).unwrap();
     }
     fn get_audio_filter(&self) -> Option<Box<AudioFilter + Send>> {
-        let vol = self.volume.clone();
-        let get_volume = Box::new(move || *vol.read().unwrap());
-        Some(Box::new(SoftVolumeApplier { get_volume: get_volume }))
+        Some(Box::new(SoftVolumeApplier { volume: self.volume.clone() }))
     }
 }
 
 struct SoftVolumeApplier {
-  get_volume: Box<Fn() -> u16 + Send>
+  volume: Arc<AtomicUsize>
 }
 
 impl AudioFilter for SoftVolumeApplier {
     fn modify_stream<'a>(&self, data: &'a [i16]) -> Cow<'a, [i16]> {
-        let volume = (self.get_volume)();
+        let volume = self.volume.load(Ordering::Relaxed) as u16;
         if volume == 0xFFFF {
             Cow::Borrowed(data)
         } else {