]> code.octet-stream.net Git - m17rt/blob - m17app/src/soundmodem.rs
16bb97642900e86139c5d22aab31a681b0b53c2d
[m17rt] / m17app / src / soundmodem.rs
1 use crate::error::M17Error;
2 use crate::tnc::{Tnc, TncError};
3 use log::debug;
4 use m17core::kiss::MAX_FRAME_LEN;
5 use m17core::modem::{Demodulator, Modulator, ModulatorAction, SoftDemodulator, SoftModulator};
6 use m17core::tnc::SoftTnc;
7 use std::collections::VecDeque;
8 use std::fs::File;
9 use std::io::{self, ErrorKind, Read, Write};
10 use std::path::PathBuf;
11 use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender, TryRecvError};
12 use std::sync::RwLock;
13 use std::sync::{Arc, Mutex};
14 use std::time::{Duration, Instant};
15
16 pub struct Soundmodem {
17 event_tx: SyncSender<SoundmodemEvent>,
18 kiss_out_rx: Arc<Mutex<Receiver<Arc<[u8]>>>>,
19 partial_kiss_out: Arc<Mutex<Option<PartialKissOut>>>,
20 }
21
22 impl Soundmodem {
23 pub fn new<I: InputSource, O: OutputSink, P: Ptt>(input: I, output: O, ptt: P) -> Self {
24 // must create TNC here
25 let (event_tx, event_rx) = sync_channel(128);
26 let (kiss_out_tx, kiss_out_rx) = sync_channel(128);
27 spawn_soundmodem_worker(
28 event_tx.clone(),
29 event_rx,
30 kiss_out_tx,
31 Box::new(input),
32 Box::new(output),
33 Box::new(ptt),
34 );
35 Self {
36 event_tx,
37 kiss_out_rx: Arc::new(Mutex::new(kiss_out_rx)),
38 partial_kiss_out: Arc::new(Mutex::new(None)),
39 }
40 }
41 }
42
43 struct PartialKissOut {
44 output: Arc<[u8]>,
45 idx: usize,
46 }
47
48 impl Read for Soundmodem {
49 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
50 {
51 let mut partial_kiss_out = self.partial_kiss_out.lock().unwrap();
52 if let Some(partial) = partial_kiss_out.as_mut() {
53 let remaining = partial.output.len() - partial.idx;
54 let to_write = remaining.min(buf.len());
55 buf[0..to_write]
56 .copy_from_slice(&partial.output[partial.idx..(partial.idx + to_write)]);
57 if to_write == remaining {
58 *partial_kiss_out = None;
59 } else {
60 partial.idx += to_write;
61 }
62 return Ok(to_write);
63 }
64 }
65 let output = {
66 let rx = self.kiss_out_rx.lock().unwrap();
67 rx.recv()
68 .map_err(|s| io::Error::new(ErrorKind::Other, format!("{:?}", s)))?
69 };
70 let to_write = output.len().min(buf.len());
71 buf[0..to_write].copy_from_slice(&output[0..to_write]);
72 if to_write != output.len() {
73 *self.partial_kiss_out.lock().unwrap() = Some(PartialKissOut {
74 output,
75 idx: to_write,
76 })
77 }
78 Ok(to_write)
79 }
80 }
81
82 impl Write for Soundmodem {
83 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
84 let _ = self.event_tx.try_send(SoundmodemEvent::Kiss(buf.into()));
85 Ok(buf.len())
86 }
87
88 fn flush(&mut self) -> std::io::Result<()> {
89 Ok(())
90 }
91 }
92
93 impl Tnc for Soundmodem {
94 fn try_clone(&mut self) -> Result<Self, TncError> {
95 Ok(Self {
96 event_tx: self.event_tx.clone(),
97 kiss_out_rx: self.kiss_out_rx.clone(),
98 partial_kiss_out: self.partial_kiss_out.clone(),
99 })
100 }
101
102 fn start(&mut self) -> Result<(), TncError> {
103 let _ = self.event_tx.send(SoundmodemEvent::Start);
104 Ok(())
105 }
106
107 fn close(&mut self) -> Result<(), TncError> {
108 let _ = self.event_tx.send(SoundmodemEvent::Close);
109 Ok(())
110 }
111 }
112
113 pub enum SoundmodemEvent {
114 Kiss(Arc<[u8]>),
115 BasebandInput(Arc<[i16]>),
116 Start,
117 Close,
118 DidReadFromOutputBuffer { len: usize, timestamp: Instant },
119 OutputUnderrun,
120 }
121
122 fn spawn_soundmodem_worker(
123 event_tx: SyncSender<SoundmodemEvent>,
124 event_rx: Receiver<SoundmodemEvent>,
125 kiss_out_tx: SyncSender<Arc<[u8]>>,
126 input: Box<dyn InputSource>,
127 output: Box<dyn OutputSink>,
128 mut ptt_driver: Box<dyn Ptt>,
129 ) {
130 std::thread::spawn(move || {
131 // TODO: should be able to provide a custom Demodulator for a soundmodem
132 let mut demodulator = SoftDemodulator::new();
133 let mut modulator = SoftModulator::new();
134 let mut tnc = SoftTnc::new();
135 let mut buf = [0u8; MAX_FRAME_LEN];
136 let out_buffer = Arc::new(RwLock::new(OutputBuffer::new()));
137 let mut out_samples = [0i16; 1024];
138 let start = Instant::now();
139 let mut ptt = false;
140 while let Ok(ev) = event_rx.recv() {
141 // Update clock on TNC before we do anything
142 let sample_time = start.elapsed();
143 let secs = sample_time.as_secs();
144 let nanos = sample_time.subsec_nanos();
145 // Accurate to within approx 1 sample
146 let now_samples = 48000 * secs + (nanos as u64 / 20833);
147 tnc.set_now(now_samples);
148
149 // Handle event
150 match ev {
151 SoundmodemEvent::Kiss(k) => {
152 let _n = tnc.write_kiss(&k);
153 // TODO: what does it mean if we fail to write it all?
154 // Probably we have to read frames for tx first - revisit this during tx
155 }
156 SoundmodemEvent::BasebandInput(b) => {
157 for sample in &*b {
158 if let Some(frame) = demodulator.demod(*sample) {
159 tnc.handle_frame(frame);
160 loop {
161 let n = tnc.read_kiss(&mut buf);
162 if n > 0 {
163 let _ = kiss_out_tx.try_send(buf[0..n].into());
164 } else {
165 break;
166 }
167 }
168 }
169 }
170 tnc.set_data_carrier_detect(demodulator.data_carrier_detect());
171 }
172 SoundmodemEvent::Start => {
173 input.start(event_tx.clone());
174 output.start(event_tx.clone(), out_buffer.clone());
175 }
176 SoundmodemEvent::Close => {
177 ptt_driver.ptt_off();
178 break;
179 }
180 SoundmodemEvent::DidReadFromOutputBuffer { len, timestamp } => {
181 let (occupied, internal_latency) = {
182 let out_buffer = out_buffer.read().unwrap();
183 (out_buffer.samples.len(), out_buffer.latency)
184 };
185 let internal_latency = (internal_latency.as_secs_f32() * 48000.0) as usize;
186 let dynamic_latency =
187 len.saturating_sub((timestamp.elapsed().as_secs_f32() * 48000.0) as usize);
188 modulator.update_output_buffer(
189 occupied,
190 48000,
191 internal_latency + dynamic_latency,
192 );
193 }
194 SoundmodemEvent::OutputUnderrun => {
195 // TODO: cancel transmission, send empty data frame to host
196 }
197 }
198
199 // Update PTT state
200 let new_ptt = tnc.ptt();
201 if new_ptt != ptt {
202 if new_ptt {
203 ptt_driver.ptt_on();
204 } else {
205 ptt_driver.ptt_off();
206 }
207 }
208 ptt = new_ptt;
209
210 // Let the modulator do what it wants
211 while let Some(action) = modulator.run() {
212 match action {
213 ModulatorAction::SetIdle(idling) => {
214 out_buffer.write().unwrap().idling = idling;
215 }
216 ModulatorAction::GetNextFrame => {
217 modulator.provide_next_frame(tnc.read_tx_frame());
218 }
219 ModulatorAction::ReadOutput => loop {
220 let n = modulator.read_output_samples(&mut out_samples);
221 if n == 0 {
222 break;
223 }
224 let mut out_buffer = out_buffer.write().unwrap();
225 for s in &out_samples[0..n] {
226 out_buffer.samples.push_back(*s);
227 }
228 },
229 ModulatorAction::TransmissionWillEnd(in_samples) => {
230 tnc.set_tx_end_time(in_samples);
231 }
232 }
233 }
234 }
235 });
236 }
237
238 pub trait InputSource: Send + Sync + 'static {
239 fn start(&self, samples: SyncSender<SoundmodemEvent>);
240 fn close(&self);
241 }
242
243 pub struct InputRrcFile {
244 baseband: Arc<[u8]>,
245 end_tx: Mutex<Option<Sender<()>>>,
246 }
247
248 impl InputRrcFile {
249 pub fn new(path: PathBuf) -> Result<Self, M17Error> {
250 let mut file = File::open(&path).map_err(|_| M17Error::InvalidRrcPath(path.clone()))?;
251 let mut baseband = vec![];
252 file.read_to_end(&mut baseband)
253 .map_err(|_| M17Error::RrcReadFailed(path))?;
254 Ok(Self {
255 baseband: baseband.into(),
256 end_tx: Mutex::new(None),
257 })
258 }
259 }
260
261 impl InputSource for InputRrcFile {
262 fn start(&self, samples: SyncSender<SoundmodemEvent>) {
263 let (end_tx, end_rx) = channel();
264 let baseband = self.baseband.clone();
265 std::thread::spawn(move || {
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 }