1use crate::audio_hardware_interface::{AudioPlayError, HardwareParameters, Streams, WritePlayFunction};
2
3pub struct Device {
4 pcm: alsa::pcm::PCM,
5 parameters: HardwareParameters,
6}
7
8impl crate::audio_hardware_interface::AudioHardwareInterface for Device {
9 fn new(params: HardwareParameters) -> Result<Self, String> {
10 let name = std::ffi::CString::new("default").unwrap();
11 let pcm = alsa::pcm::PCM::open(&name, alsa::Direction::Playback, false)
12 .map_err(|e| format!("Failed to open PCM device: {}", e))?;
13
14 {
15 let hwp = alsa::pcm::HwParams::any(&pcm).map_err(|e| format!("Failed to get hardware parameters: {}", e))?;
16 hwp.set_channels(params.channels)
17 .map_err(|e| format!("Failed to set channels: {}", e))?;
18 hwp.set_rate(params.sample_rate, alsa::ValueOr::Nearest)
19 .map_err(|e| format!("Failed to set sample rate: {}", e))?;
20 hwp.set_format(match params.bit_depth {
21 8 => alsa::pcm::Format::S8,
22 16 => alsa::pcm::Format::S16LE,
23 24 => return Err("24-bit audio is not supported by this implementation".to_string()),
24 32 => alsa::pcm::Format::FloatLE,
25 _ => return Err(format!("Unsupported bit depth: {}", params.bit_depth)),
26 })
27 .map_err(|e| format!("Failed to set format: {}", e))?;
28 hwp.set_access(alsa::pcm::Access::MMapInterleaved)
29 .map_err(|e| format!("Failed to set access type: {}", e))?;
30 let effective_period_size = hwp
31 .set_period_size_near(1024, alsa::ValueOr::Nearest)
32 .map_err(|e| format!("Failed to set period size: {}", e))?;
33 let _ = hwp.set_buffer_size_near(effective_period_size * 2);
34
35 pcm.hw_params(&hwp)
36 .map_err(|e| format!("Failed to apply hardware parameters: {}", e))?;
37 }
38
39 {
40 let hwp = pcm
41 .hw_params_current()
42 .map_err(|e| format!("Failed to get current hardware parameters: {}", e))?;
43 let swp = pcm
44 .sw_params_current()
45 .map_err(|e| format!("Failed to get current software parameters: {}", e))?;
46 let period_size = hwp
47 .get_period_size()
48 .map_err(|e| format!("Failed to get period size: {}", e))?;
49 swp.set_start_threshold(period_size)
50 .map_err(|e| format!("Failed to set start threshold: {}", e))?;
51 swp.set_avail_min(period_size)
52 .map_err(|e| format!("Failed to set minimum available frames: {}", e))?;
53 pcm.sw_params(&swp)
54 .map_err(|e| format!("Failed to set software parameters: {}", e))?;
55 }
56
57 Ok(Device { pcm, parameters: params })
58 }
59
60 fn get_period_size(&self) -> usize {
61 let pcm = &self.pcm;
62 let hwp = pcm.hw_params_current().ok().unwrap();
63 hwp.get_period_size().ok().unwrap() as usize
64 }
65
66 fn play(&self, wpf: impl WritePlayFunction) -> Result<usize, AudioPlayError> {
67 let pcm = &self.pcm;
68
69 let available_frames = match pcm.avail_update() {
70 Ok(frames) if frames > 0 => frames as usize,
71 Ok(_) => return Ok(0),
72 Err(error) => {
73 return if pcm.try_recover(error, true).is_ok() {
74 Ok(0)
75 } else {
76 Err(AudioPlayError::RecoveryFailed)
77 };
78 }
79 };
80
81 let hw_params = pcm.hw_params_current().unwrap();
82 let access = hw_params.get_access().unwrap();
83 let period_size = self.get_period_size().min(available_frames);
84
85 if period_size == 0 {
86 return Ok(0);
87 }
88
89 match self.parameters.bit_depth {
90 16 => {
91 let io = pcm.io_i16().map_err(|_| AudioPlayError::UnsupportedFormat)?;
92
93 let frames = match access {
94 alsa::pcm::Access::MMapInterleaved => {
95 let mmap_result = io.mmap(period_size, |b| match self.parameters.channels {
96 1 => {
97 let frames = b.len();
98 wpf(Streams::Mono16Bit(b));
99 frames
100 }
101 2 => {
102 if b.len() % 2 != 0 {
103 return 0;
104 }
105
106 let frames = b.len() / 2;
107 let buffer =
108 unsafe { std::slice::from_raw_parts_mut(b.as_mut_ptr() as *mut (i16, i16), frames) };
109
110 wpf(Streams::Stereo16Bit(buffer));
111 frames
112 }
113 _ => panic!(),
114 });
115
116 match mmap_result {
117 Ok(frames) => frames,
118 Err(error) => {
119 return if pcm.try_recover(error, true).is_ok() {
120 Ok(0)
121 } else {
122 Err(AudioPlayError::RecoveryFailed)
123 };
124 }
125 }
126 }
127 _ => return Err(AudioPlayError::UnsupportedFormat),
128 };
129
130 if frames > 0 && pcm.state() == alsa::pcm::State::Prepared {
131 pcm.start().map_err(|_| AudioPlayError::StartFailed)?;
132 }
133
134 Ok(frames)
135 }
136 32 => {
137 let io = pcm.io_f32().map_err(|_| AudioPlayError::UnsupportedFormat)?;
138
139 let frames = match access {
140 alsa::pcm::Access::MMapInterleaved => {
141 let mmap_result = io.mmap(period_size, |b| match self.parameters.channels {
142 1 => {
143 let frames = b.len();
144 wpf(Streams::MonoFloat32(b));
145 frames
146 }
147 2 => {
148 if b.len() % 2 != 0 {
149 return 0;
150 }
151
152 let frames = b.len() / 2;
153 let buffer =
154 unsafe { std::slice::from_raw_parts_mut(b.as_mut_ptr() as *mut (f32, f32), frames) };
155
156 wpf(Streams::StereoFloat32(buffer));
157 frames
158 }
159 _ => panic!(),
160 });
161
162 match mmap_result {
163 Ok(frames) => frames,
164 Err(error) => {
165 return if pcm.try_recover(error, true).is_ok() {
166 Ok(0)
167 } else {
168 Err(AudioPlayError::RecoveryFailed)
169 };
170 }
171 }
172 }
173 _ => return Err(AudioPlayError::UnsupportedFormat),
174 };
175
176 if frames > 0 && pcm.state() == alsa::pcm::State::Prepared {
177 pcm.start().map_err(|_| AudioPlayError::StartFailed)?;
178 }
179
180 Ok(frames)
181 }
182 _ => Err(AudioPlayError::UnsupportedFormat),
183 }
184 }
185
186 fn pause(&self) {
187 let pcm = &self.pcm;
188
189 pcm.pause(true).unwrap();
190 }
191}