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
};
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
;
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
};
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
>>>,
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(
39 kiss_out_rx
: Arc
::new(Mutex
::new(kiss_out_rx
)),
40 partial_kiss_out
: Arc
::new(Mutex
::new(None
)),
45 struct PartialKissOut
{
50 impl Read
for Soundmodem
{
51 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
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());
58 .copy_from_slice(&partial
.output
[partial
.idx
..(partial
.idx
+ to_write
)]);
59 if to_write
== remaining
{
60 *partial_kiss_out
= None
;
62 partial
.idx
+= to_write
;
68 let rx
= self.kiss_out_rx
.lock().unwrap
();
70 .map_err(|s
| io
::Error
::new(ErrorKind
::Other
, format
!("{:?}", s
)))?
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
{
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
()));
90 fn flush(&mut self) -> std
::io
::Result
<()> {
95 impl Tnc
for Soundmodem
{
96 fn try_clone(&mut self) -> Result
<Self, TncError
> {
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(),
104 fn start(&mut self) -> Result
<(), TncError
> {
105 let _
= self.event_tx
.send(SoundmodemEvent
::Start
);
109 fn close(&mut self) -> Result
<(), TncError
> {
110 let _
= self.event_tx
.send(SoundmodemEvent
::Close
);
115 pub enum SoundmodemEvent
{
117 BasebandInput(Arc
<[i16]>),
120 DidReadFromOutputBuffer
{ len
: usize, timestamp
: Instant
},
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
>,
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();
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
);
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
153 SoundmodemEvent
::BasebandInput(b
) => {
155 if let Some(frame
) = demodulator
.demod(*sample
) {
156 tnc
.handle_frame(frame
);
158 let n
= tnc
.read_kiss(&mut buf
);
160 let _
= kiss_out_tx
.try_send(buf
[0..n
].into
());
167 tnc
.set_data_carrier_detect(demodulator
.data_carrier_detect());
169 SoundmodemEvent
::Start
=> {
170 input
.start(event_tx
.clone());
171 output
.start(event_tx
.clone(), out_buffer
.clone());
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
)
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
_o
utp
ut
_b
uffer
(
185 internal_latency
+ dynamic_latency
,
188 SoundmodemEvent
::OutputUnderrun
=> {
189 // TODO: cancel transmission, send empty data frame to host
194 let new_ptt
= tnc
.ptt();
204 // Let the modulator do what it wants
205 while let Some(action
) = modulator
.run() {
207 ModulatorAction
::SetIdle(idling
) => {
208 out_buffer
.write().unwrap
().idl
ing
= idling
;
210 ModulatorAction
::GetNextFrame
=> {
211 modulator
.provide_next_frame(tnc
.read_tx_frame());
213 ModulatorAction
::ReadOutput
=> loop {
214 let n
= modulator
.read_output_samples(&mut out_samples
);
218 let mut out_buffer
= out_buffer
.write().unwrap
();
219 for s
in &out_samples
[0..n
] {
220 out_buffer
.samples
.push_back(*s
);
223 ModulatorAction
::TransmissionWillEnd(in_samples
) => {
224 tnc
.set_tx_end_time(in_samples
);
232 pub trait InputSource
: Send
+ Sync
+ '
static {
233 fn start(&self, samples
: SyncSender
<SoundmodemEvent
>);
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
<()>>>,
243 impl InputSoundcard
{
244 pub fn new() -> Self {
247 end_tx
: Mutex
::new(None
),
251 pub fn new_with_card(card_name
: String
) -> Self {
253 cpal_name
: Some(card_name
),
254 end_tx
: Mutex
::new(None
),
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() {
268 .find
(|d
| d
.name().unwrap
() == name
)
271 host
.default_input_device().unwrap
()
273 let mut configs
= device
.supported_input_configs().unwrap
();
275 .find
(|c
| c
.channels() == 1 && c
.sample_format() == SampleFormat
::I16
)
277 .with_sample_rate(SampleRate(48000));
281 move |data
: &[i16], _info
: &cpal
::InputCallbackInfo
| {
282 let out
: Vec
<i16> = data
.iter
().map(|s
| *s
).collect();
283 let _
= samples
.try_send(SoundmodemEvent
::BasebandInput(out
.into
()));
287 debug
!("error occurred in soundcard input: {e:?}");
292 stream
.play().unwrap
();
293 let _
= end_rx
.recv();
295 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
299 let _
= self.end_tx
.lock().unwrap
().take();
303 pub struct InputRrcFile
{
305 end_tx
: Mutex
<Option
<Sender
<()>>>,
309 pub fn new(path
: PathBuf
) -> Self {
312 end_tx
: Mutex
::new(None
),
317 impl InputSource
for InputRrcFile
{
318 fn start(&self, samples
: SyncSender
<SoundmodemEvent
>) {
319 let (end_tx
, end_rx
) = channel();
320 let path
= self.path
.clone();
321 std
::thread
::spawn(move || {
322 // TODO: error handling
323 let mut file
= File
::open(path
).unwrap
();
324 let mut baseband
= vec
![];
325 file
.read_to_end(&mut baseband
).unwrap
();
327 // assuming 48 kHz for now
328 const TICK
: Duration
= Duration
::from_millis(25);
329 const SAMPLES_PER_TICK
: usize = 1200;
331 let mut next_tick
= Instant
::now() + TICK
;
332 let mut buf
= [0i16; SAMPLES_PER_TICK
];
335 for sample
in baseband
337 .map(|pair
| i16::from_le_bytes([pair
[0], pair
[1]]))
341 if idx
== SAMPLES_PER_TICK
{
342 if let Err(e
) = samples
.try_send(SoundmodemEvent
::BasebandInput(buf
.into
())) {
343 debug
!("overflow feeding soundmodem: {e:?}");
345 next_tick
= next_tick
+ TICK
;
347 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
349 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
354 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
358 let _
= self.end_tx
.lock().unwrap
().take();
362 pub struct NullInputSource
{
363 end_tx
: Mutex
<Option
<Sender
<()>>>,
366 impl NullInputSource
{
367 pub fn new() -> Self {
369 end_tx
: Mutex
::new(None
),
374 impl InputSource
for NullInputSource
{
375 fn start(&self, samples
: SyncSender
<SoundmodemEvent
>) {
376 let (end_tx
, end_rx
) = channel();
377 std
::thread
::spawn(move || {
378 // assuming 48 kHz for now
379 const TICK
: Duration
= Duration
::from_millis(25);
380 const SAMPLES_PER_TICK
: usize = 1200;
381 let mut next_tick
= Instant
::now() + TICK
;
384 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
385 next_tick
= next_tick
+ TICK
;
386 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
389 if let Err(e
) = samples
.try_send(SoundmodemEvent
::BasebandInput(
390 [0i16; SAMPLES_PER_TICK
].into
(),
392 debug
!("overflow feeding soundmodem: {e:?}");
396 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
400 let _
= self.end_tx
.lock().unwrap
().take();
404 pub struct OutputBuffer
{
406 // TODO: something more efficient
407 samples
: VecDeque
<i16>,
412 pub fn new() -> Self {
415 samples
: VecDeque
::new(),
416 latency
: Duration
::ZERO
,
421 pub trait OutputSink
: Send
+ Sync
+ '
static {
422 fn start(&self, event_tx
: SyncSender
<SoundmodemEvent
>, buffer
: Arc
<RwLock
<OutputBuffer
>>);
426 pub struct OutputRrcFile
{
428 end_tx
: Mutex
<Option
<Sender
<()>>>,
432 pub fn new(path
: PathBuf
) -> Self {
435 end_tx
: Mutex
::new(None
),
440 impl OutputSink
for OutputRrcFile
{
441 fn start(&self, event_tx
: SyncSender
<SoundmodemEvent
>, buffer
: Arc
<RwLock
<OutputBuffer
>>) {
442 let (end_tx
, end_rx
) = channel();
443 let path
= self.path
.clone();
444 std
::thread
::spawn(move || {
445 // TODO: error handling
446 let mut file
= File
::create(path
).unwrap
();
448 // assuming 48 kHz for now
449 const TICK
: Duration
= Duration
::from_millis(25);
450 const SAMPLES_PER_TICK
: usize = 1200;
452 // flattened BE i16s for writing
453 let mut buf
= [0u8; SAMPLES_PER_TICK
* 2];
454 let mut next_tick
= Instant
::now() + TICK
;
457 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
458 next_tick
= next_tick
+ TICK
;
459 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
462 // For now only write deliberately modulated (non-idling) samples
463 // Multiple transmissions will get smooshed together
464 let mut buf_used
= 0;
466 let mut buffer
= buffer
.write().unwrap
();
467 for out
in buf
.chunks_mut(2) {
468 if let Some(s
) = buffer
.samples
.pop_front() {
469 let be
= s
.to_le_bytes();
470 out
.copy_from_slice(&[be
[0], be
[1]]);
472 } else if !buffer
.idl
ing
{
473 debug
!("output rrc file had underrun");
474 let _
= event_tx
.send(SoundmodemEvent
::OutputUnderrun
);
478 if let Err(e
) = file
.write_all(&buf
[0..buf_used
]) {
479 debug
!("failed to write to rrc file: {e:?}");
482 let _
= event_tx
.send(SoundmodemEvent
::DidReadFromOutputBuffer
{
484 timestamp
: Instant
::now(),
488 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
492 let _
= self.end_tx
.lock().unwrap
().take();
496 pub struct NullOutputSink
{
497 end_tx
: Mutex
<Option
<Sender
<()>>>,
500 impl NullOutputSink
{
501 pub fn new() -> Self {
503 end_tx
: Mutex
::new(None
),
508 impl OutputSink
for NullOutputSink
{
509 fn start(&self, event_tx
: SyncSender
<SoundmodemEvent
>, buffer
: Arc
<RwLock
<OutputBuffer
>>) {
510 let (end_tx
, end_rx
) = channel();
511 std
::thread
::spawn(move || {
512 // assuming 48 kHz for now
513 const TICK
: Duration
= Duration
::from_millis(25);
514 const SAMPLES_PER_TICK
: usize = 1200;
515 let mut next_tick
= Instant
::now() + TICK
;
518 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
519 next_tick
= next_tick
+ TICK
;
520 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
524 let mut buffer
= buffer
.write().unwrap
();
526 for _
in 0..SAMPLES_PER_TICK
{
527 if !buffer
.samples
.pop_front().is
_some
() {
529 debug
!("null output had underrun");
530 let _
= event_tx
.send(SoundmodemEvent
::OutputUnderrun
);
537 let _
= event_tx
.send(SoundmodemEvent
::DidReadFromOutputBuffer
{
539 timestamp
: Instant
::now(),
543 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
547 let _
= self.end_tx
.lock().unwrap
().take();