alsamixer.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. use super::AudioFilter;
  2. use super::{Mixer, MixerConfig};
  3. use std::error::Error;
  4. use alsa;
  5. #[derive(Clone)]
  6. pub struct AlsaMixer {
  7. config: MixerConfig,
  8. }
  9. impl AlsaMixer {
  10. fn map_volume(&self, set_volume: Option<u16>) -> Result<(u16), Box<dyn Error>> {
  11. let mixer = alsa::mixer::Mixer::new(&self.config.card, false)?;
  12. let sid = alsa::mixer::SelemId::new(&*self.config.mixer, self.config.index);
  13. let selem = mixer.find_selem(&sid).expect(
  14. format!(
  15. "Couldn't find simple mixer control for {}",
  16. self.config.mixer
  17. )
  18. .as_str(),
  19. );
  20. let (min, max) = selem.get_playback_volume_range();
  21. let range = (max - min) as f64;
  22. let new_vol: u16;
  23. if let Some(vol) = set_volume {
  24. let alsa_volume: i64 = ((vol as f64 / 0xFFFF as f64) * range) as i64 + min;
  25. debug!("Mapping volume {:?} ->> alsa {:?}", vol, alsa_volume);
  26. selem
  27. .set_playback_volume_all(alsa_volume)
  28. .expect("Couldn't set alsa volume");
  29. new_vol = vol;
  30. } else {
  31. let cur_vol = selem
  32. .get_playback_volume(alsa::mixer::SelemChannelId::mono())
  33. .expect("Couldn't get current volume");
  34. new_vol = (((cur_vol - min) as f64 / range) * 0xFFFF as f64) as u16;
  35. debug!("Mapping volume {:?} <<- alsa {:?}", new_vol, cur_vol);
  36. }
  37. Ok(new_vol)
  38. }
  39. }
  40. impl Mixer for AlsaMixer {
  41. fn open(config: Option<MixerConfig>) -> AlsaMixer {
  42. let config = config.unwrap_or_default();
  43. info!(
  44. "Setting up new mixer: card:{} mixer:{} index:{}",
  45. config.card, config.mixer, config.index
  46. );
  47. AlsaMixer { config: config }
  48. }
  49. fn start(&self) {}
  50. fn stop(&self) {}
  51. fn volume(&self) -> u16 {
  52. match self.map_volume(None) {
  53. Ok(vol) => vol,
  54. Err(e) => {
  55. error!("Error getting volume for <{}>, {:?}", self.config.card, e);
  56. 0
  57. }
  58. }
  59. }
  60. fn set_volume(&self, volume: u16) {
  61. match self.map_volume(Some(volume)) {
  62. Ok(_) => (),
  63. Err(e) => error!("Error setting volume for <{}>, {:?}", self.config.card, e),
  64. }
  65. }
  66. fn get_audio_filter(&self) -> Option<Box<dyn AudioFilter + Send>> {
  67. None
  68. }
  69. }