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