]> code.octet-stream.net Git - m17rt/blob - m17app/src/soundmodem.rs
99085a0f72e34d0035be3f596faeb62e2749cd33
[m17rt] / m17app / src / soundmodem.rs
1 use crate::tnc::{Tnc, TncError};
2 use cpal::traits::DeviceTrait;
3 use cpal::traits::HostTrait;
4 use cpal::traits::StreamTrait;
5 use cpal::{SampleFormat, SampleRate};
6 use log::debug;
7 use m17core::kiss::MAX_FRAME_LEN;
8 use m17core::modem::{Demodulator, Modulator, ModulatorAction, SoftDemodulator, SoftModulator};
9 use m17core::tnc::SoftTnc;
10 use std::collections::VecDeque;
11 use std::fs::File;
12 use std::io::{self, ErrorKind, Read, Write};
13 use std::path::PathBuf;
14 use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender, TryRecvError};
15 use std::sync::RwLock;
16 use std::sync::{Arc, Mutex};
17 use std::time::{Duration, Instant};
18
19 pub struct Soundmodem {
20 event_tx: SyncSender<SoundmodemEvent>,
21 kiss_out_rx: Arc<Mutex<Receiver<Arc<[u8]>>>>,
22 partial_kiss_out: Arc<Mutex<Option<PartialKissOut>>>,
23 }
24
25 impl Soundmodem {
26 pub fn new_with_input_and_output<I: InputSource, O: OutputSink>(input: I, output: O) -> Self {
27 // must create TNC here
28 let (event_tx, event_rx) = sync_channel(128);
29 let (kiss_out_tx, kiss_out_rx) = sync_channel(128);
30 spawn_soundmodem_worker(
31 event_tx.clone(),
32 event_rx,
33 kiss_out_tx,
34 Box::new(input),
35 Box::new(output),
36 );
37 Self {
38 event_tx,
39 kiss_out_rx: Arc::new(Mutex::new(kiss_out_rx)),
40 partial_kiss_out: Arc::new(Mutex::new(None)),
41 }
42 }
43 }
44
45 struct PartialKissOut {
46 output: Arc<[u8]>,
47 idx: usize,
48 }
49
50 impl Read for Soundmodem {
51 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
52 {
53 let mut partial_kiss_out = self.partial_kiss_out.lock().unwrap();
54 if let Some(partial) = partial_kiss_out.as_mut() {
55 let remaining = partial.output.len() - partial.idx;
56 let to_write = remaining.min(buf.len());
57 buf[0..to_write]
58 .copy_from_slice(&partial.output[partial.idx..(partial.idx + to_write)]);
59 if to_write == remaining {
60 *partial_kiss_out = None;
61 } else {
62 partial.idx += to_write;
63 }
64 return Ok(to_write);
65 }
66 }
67 let output = {
68 let rx = self.kiss_out_rx.lock().unwrap();
69 rx.recv()
70 .map_err(|s| io::Error::new(ErrorKind::Other, format!("{:?}", s)))?
71 };
72 let to_write = output.len().min(buf.len());
73 buf[0..to_write].copy_from_slice(&output[0..to_write]);
74 if to_write != output.len() {
75 *self.partial_kiss_out.lock().unwrap() = Some(PartialKissOut {
76 output,
77 idx: to_write,
78 })
79 }
80 Ok(to_write)
81 }
82 }
83
84 impl Write for Soundmodem {
85 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
86 let _ = self.event_tx.try_send(SoundmodemEvent::Kiss(buf.into()));
87 Ok(buf.len())
88 }
89
90 fn flush(&mut self) -> std::io::Result<()> {
91 Ok(())
92 }
93 }
94
95 impl Tnc for Soundmodem {
96 fn try_clone(&mut self) -> Result<Self, TncError> {
97 Ok(Self {
98 event_tx: self.event_tx.clone(),
99 kiss_out_rx: self.kiss_out_rx.clone(),
100 partial_kiss_out: self.partial_kiss_out.clone(),
101 })
102 }
103
104 fn start(&mut self) -> Result<(), TncError> {
105 let _ = self.event_tx.send(SoundmodemEvent::Start);
106 Ok(())
107 }
108
109 fn close(&mut self) -> Result<(), TncError> {
110 let _ = self.event_tx.send(SoundmodemEvent::Close);
111 Ok(())
112 }
113 }
114
115 pub enum SoundmodemEvent {
116 Kiss(Arc<[u8]>),
117 BasebandInput(Arc<[i16]>),
118 Start,
119 Close,
120 DidReadFromOutputBuffer { len: usize, timestamp: Instant },
121 OutputUnderrun,
122 }
123
124 fn spawn_soundmodem_worker(
125 event_tx: SyncSender<SoundmodemEvent>,
126 event_rx: Receiver<SoundmodemEvent>,
127 kiss_out_tx: SyncSender<Arc<[u8]>>,
128 input: Box<dyn InputSource>,
129 output: Box<dyn OutputSink>,
130 ) {
131 std::thread::spawn(move || {
132 // TODO: should be able to provide a custom Demodulator for a soundmodem
133 let mut demodulator = SoftDemodulator::new();
134 let mut modulator = SoftModulator::new();
135 let mut tnc = SoftTnc::new();
136 let mut buf = [0u8; MAX_FRAME_LEN];
137 let out_buffer = Arc::new(RwLock::new(OutputBuffer::new()));
138 let mut out_samples = [0i16; 1024];
139 let start = Instant::now();
140 let mut ptt = false;
141 while let Ok(ev) = event_rx.recv() {
142 // Update clock on TNC before we do anything
143 let sample_time = (start.elapsed().as_nanos() / 48000) as u64;
144 tnc.set_now(sample_time);
145
146 // Handle event
147 match ev {
148 SoundmodemEvent::Kiss(k) => {
149 let _n = tnc.write_kiss(&k);
150 // TODO: what does it mean if we fail to write it all?
151 // Probably we have to read frames for tx first - revisit this during tx
152 }
153 SoundmodemEvent::BasebandInput(b) => {
154 for sample in &*b {
155 if let Some(frame) = demodulator.demod(*sample) {
156 tnc.handle_frame(frame);
157 loop {
158 let n = tnc.read_kiss(&mut buf);
159 if n > 0 {
160 let _ = kiss_out_tx.try_send(buf[0..n].into());
161 } else {
162 break;
163 }
164 }
165 }
166 }
167 tnc.set_data_carrier_detect(demodulator.data_carrier_detect());
168 }
169 SoundmodemEvent::Start => {
170 input.start(event_tx.clone());
171 output.start(event_tx.clone(), out_buffer.clone());
172 }
173 SoundmodemEvent::Close => break,
174 SoundmodemEvent::DidReadFromOutputBuffer { len, timestamp } => {
175 let (occupied, internal_latency) = {
176 let out_buffer = out_buffer.read().unwrap();
177 (out_buffer.samples.len(), out_buffer.latency)
178 };
179 let internal_latency = (internal_latency.as_secs_f32() * 48000.0) as usize;
180 let dynamic_latency =
181 len.saturating_sub((timestamp.elapsed().as_secs_f32() * 48000.0) as usize);
182 modulator.update_output_buffer(
183 occupied,
184 48000,
185 internal_latency + dynamic_latency,
186 );
187 }
188 SoundmodemEvent::OutputUnderrun => {
189 // TODO: cancel transmission, send empty data frame to host
190 }
191 }
192
193 // Update PTT state
194 let new_ptt = tnc.ptt();
195 if new_ptt != ptt {
196 if new_ptt {
197 // turn it on
198 } else {
199 // turn it off
200 }
201 }
202 ptt = new_ptt;
203
204 // Let the modulator do what it wants
205 while let Some(action) = modulator.run() {
206 match action {
207 ModulatorAction::SetIdle(idling) => {
208 out_buffer.write().unwrap().idling = idling;
209 }
210 ModulatorAction::GetNextFrame => {
211 modulator.provide_next_frame(tnc.read_tx_frame());
212 }
213 ModulatorAction::ReadOutput => loop {
214 let n = modulator.read_output_samples(&mut out_samples);
215 if n == 0 {
216 break;
217 }
218 let mut out_buffer = out_buffer.write().unwrap();
219 for s in &out_samples[0..n] {
220 out_buffer.samples.push_back(*s);
221 }
222 },
223 ModulatorAction::TransmissionWillEnd(in_samples) => {
224 tnc.set_tx_end_time(in_samples);
225 }
226 }
227 }
228 }
229 });
230 }
231
232 pub trait InputSource: Send + Sync + 'static {
233 fn start(&self, samples: SyncSender<SoundmodemEvent>);
234 fn close(&self);
235 }
236
237 pub struct InputSoundcard {
238 // TODO: allow for inversion both here and in output
239 cpal_name: Option<String>,
240 end_tx: Mutex<Option<Sender<()>>>,
241 }
242
243 impl InputSoundcard {
244 pub fn new() -> Self {
245 Self {
246 cpal_name: None,
247 end_tx: Mutex::new(None),
248 }
249 }
250
251 pub fn new_with_card(card_name: String) -> Self {
252 Self {
253 cpal_name: Some(card_name),
254 end_tx: Mutex::new(None),
255 }
256 }
257 }
258
259 impl InputSource for InputSoundcard {
260 fn start(&self, samples: SyncSender<SoundmodemEvent>) {
261 let (end_tx, end_rx) = channel();
262 let cpal_name = self.cpal_name.clone();
263 std::thread::spawn(move || {
264 let host = cpal::default_host();
265 let device = if let Some(name) = cpal_name.as_deref() {
266 host.input_devices()
267 .unwrap()
268 .find(|d| d.name().unwrap() == name)
269 .unwrap()
270 } else {
271 host.default_input_device().unwrap()
272 };
273 let mut configs = device.supported_input_configs().unwrap();
274 let config = configs
275 .find(|c| c.channels() == 1 && c.sample_format() == SampleFormat::I16)
276 .unwrap()
277 .with_sample_rate(SampleRate(48000));
278 let stream = device
279 .build_input_stream(
280 &config.into(),
281 move |data: &[i16], _info: &cpal::InputCallbackInfo| {
282 debug!("input has given us {} samples", data.len());
283 let out: Vec<i16> = data.iter().map(|s| *s).collect();
284 let _ = samples.try_send(SoundmodemEvent::BasebandInput(out.into()));
285 },
286 |e| {
287 // TODO: abort?
288 debug!("error occurred in soundcard input: {e:?}");
289 },
290 None,
291 )
292 .unwrap();
293 stream.play().unwrap();
294 let _ = end_rx.recv();
295 });
296 *self.end_tx.lock().unwrap() = Some(end_tx);
297 }
298
299 fn close(&self) {
300 let _ = self.end_tx.lock().unwrap().take();
301 }
302 }
303
304 pub struct InputRrcFile {
305 path: PathBuf,
306 end_tx: Mutex<Option<Sender<()>>>,
307 }
308
309 impl InputRrcFile {
310 pub fn new(path: PathBuf) -> Self {
311 Self {
312 path,
313 end_tx: Mutex::new(None),
314 }
315 }
316 }
317
318 impl InputSource for InputRrcFile {
319 fn start(&self, samples: SyncSender<SoundmodemEvent>) {
320 let (end_tx, end_rx) = channel();
321 let path = self.path.clone();
322 std::thread::spawn(move || {
323 // TODO: error handling
324 let mut file = File::open(path).unwrap();
325 let mut baseband = vec![];
326 file.read_to_end(&mut baseband).unwrap();
327
328 // assuming 48 kHz for now
329 const TICK: Duration = Duration::from_millis(25);
330 const SAMPLES_PER_TICK: usize = 1200;
331
332 let mut next_tick = Instant::now() + TICK;
333 let mut buf = [0i16; SAMPLES_PER_TICK];
334 let mut idx = 0;
335
336 for sample in baseband
337 .chunks(2)
338 .map(|pair| i16::from_le_bytes([pair[0], pair[1]]))
339 {
340 buf[idx] = sample;
341 idx += 1;
342 if idx == SAMPLES_PER_TICK {
343 if let Err(e) = samples.try_send(SoundmodemEvent::BasebandInput(buf.into())) {
344 debug!("overflow feeding soundmodem: {e:?}");
345 }
346 next_tick = next_tick + TICK;
347 idx = 0;
348 std::thread::sleep(next_tick.duration_since(Instant::now()));
349 }
350 if end_rx.try_recv() != Err(TryRecvError::Empty) {
351 break;
352 }
353 }
354 });
355 *self.end_tx.lock().unwrap() = Some(end_tx);
356 }
357
358 fn close(&self) {
359 let _ = self.end_tx.lock().unwrap().take();
360 }
361 }
362
363 pub struct OutputBuffer {
364 idling: bool,
365 // TODO: something more efficient
366 samples: VecDeque<i16>,
367 latency: Duration,
368 }
369
370 impl OutputBuffer {
371 pub fn new() -> Self {
372 Self {
373 idling: true,
374 samples: VecDeque::new(),
375 latency: Duration::ZERO,
376 }
377 }
378 }
379
380 pub trait OutputSink: Send + Sync + 'static {
381 fn start(&self, event_tx: SyncSender<SoundmodemEvent>, buffer: Arc<RwLock<OutputBuffer>>);
382 fn close(&self);
383 }
384
385 pub struct OutputRrcFile {
386 path: PathBuf,
387 end_tx: Mutex<Option<Sender<()>>>,
388 }
389
390 impl OutputRrcFile {
391 pub fn new(path: PathBuf) -> Self {
392 Self {
393 path,
394 end_tx: Mutex::new(None),
395 }
396 }
397 }
398
399 impl OutputSink for OutputRrcFile {
400 fn start(&self, event_tx: SyncSender<SoundmodemEvent>, buffer: Arc<RwLock<OutputBuffer>>) {
401 let (end_tx, end_rx) = channel();
402 let path = self.path.clone();
403 std::thread::spawn(move || {
404 // TODO: error handling
405 let mut file = File::create(path).unwrap();
406
407 // assuming 48 kHz for now
408 const TICK: Duration = Duration::from_millis(25);
409 const SAMPLES_PER_TICK: usize = 1200;
410
411 // flattened BE i16s for writing
412 let mut buf = [0u8; SAMPLES_PER_TICK * 2];
413 let mut next_tick = Instant::now() + TICK;
414
415 loop {
416 std::thread::sleep(next_tick.duration_since(Instant::now()));
417 next_tick = next_tick + TICK;
418 if end_rx.try_recv() != Err(TryRecvError::Empty) {
419 break;
420 }
421
422 let mut buffer = buffer.write().unwrap();
423 for out in buf.chunks_mut(2) {
424 if let Some(s) = buffer.samples.pop_front() {
425 let be = s.to_be_bytes();
426 out.copy_from_slice(&[be[0], be[1]]);
427 } else if buffer.idling {
428 out.copy_from_slice(&[0, 0]);
429 } else {
430 debug!("output rrc file had underrun");
431 let _ = event_tx.send(SoundmodemEvent::OutputUnderrun);
432 break;
433 }
434 }
435 if let Err(e) = file.write_all(&buf) {
436 debug!("failed to write to rrc file: {e:?}");
437 break;
438 }
439 }
440 });
441 *self.end_tx.lock().unwrap() = Some(end_tx);
442 }
443
444 fn close(&self) {
445 let _ = self.end_tx.lock().unwrap().take();
446 }
447 }
448
449 pub struct NullOutputSink {
450 end_tx: Mutex<Option<Sender<()>>>,
451 }
452
453 impl NullOutputSink {
454 pub fn new() -> Self {
455 Self {
456 end_tx: Mutex::new(None),
457 }
458 }
459 }
460
461 impl OutputSink for NullOutputSink {
462 fn start(&self, event_tx: SyncSender<SoundmodemEvent>, buffer: Arc<RwLock<OutputBuffer>>) {
463 let (end_tx, end_rx) = channel();
464 std::thread::spawn(move || {
465 // assuming 48 kHz for now
466 const TICK: Duration = Duration::from_millis(25);
467 const SAMPLES_PER_TICK: usize = 1200;
468 let mut next_tick = Instant::now() + TICK;
469
470 loop {
471 std::thread::sleep(next_tick.duration_since(Instant::now()));
472 next_tick = next_tick + TICK;
473 if end_rx.try_recv() != Err(TryRecvError::Empty) {
474 break;
475 }
476
477 let mut buffer = buffer.write().unwrap();
478 for _ in 0..SAMPLES_PER_TICK {
479 if !buffer.samples.pop_front().is_some() && !buffer.idling {
480 debug!("null output had underrun");
481 let _ = event_tx.send(SoundmodemEvent::OutputUnderrun);
482 break;
483 }
484 }
485 }
486 });
487 *self.end_tx.lock().unwrap() = Some(end_tx);
488 }
489
490 fn close(&self) {
491 let _ = self.end_tx.lock().unwrap().take();
492 }
493 }