]>
code.octet-stream.net Git - m17rt/blob - m17app/src/soundmodem.rs
1 use crate::tnc
::{Tnc
, TncError
};
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
;
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
};
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
>>>,
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(
36 kiss_out_rx
: Arc
::new(Mutex
::new(kiss_out_rx
)),
37 partial_kiss_out
: Arc
::new(Mutex
::new(None
)),
42 struct PartialKissOut
{
47 impl Read
for Soundmodem
{
48 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
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());
55 .copy_from_slice(&partial
.output
[partial
.idx
..(partial
.idx
+ to_write
)]);
56 if to_write
== remaining
{
57 *partial_kiss_out
= None
;
59 partial
.idx
+= to_write
;
65 let rx
= self.kiss_out_rx
.lock().unwrap
();
67 .map_err(|s
| io
::Error
::new(ErrorKind
::Other
, format
!("{:?}", s
)))?
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
{
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
()));
87 fn flush(&mut self) -> std
::io
::Result
<()> {
92 impl Tnc
for Soundmodem
{
93 fn try_clone(&mut self) -> Result
<Self, TncError
> {
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(),
101 fn start(&mut self) -> Result
<(), TncError
> {
102 let _
= self.event_tx
.send(SoundmodemEvent
::Start
);
106 fn close(&mut self) -> Result
<(), TncError
> {
107 let _
= self.event_tx
.send(SoundmodemEvent
::Close
);
112 pub enum SoundmodemEvent
{
114 BasebandInput(Arc
<[i16]>),
117 DidReadFromOutputBuffer
{ len
: usize, timestamp
: Instant
},
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
>,
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();
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
);
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
155 SoundmodemEvent
::BasebandInput(b
) => {
157 if let Some(frame
) = demodulator
.demod(*sample
) {
158 tnc
.handle_frame(frame
);
160 let n
= tnc
.read_kiss(&mut buf
);
162 let _
= kiss_out_tx
.try_send(buf
[0..n
].into
());
169 tnc
.set_data_carrier_detect(demodulator
.data_carrier_detect());
171 SoundmodemEvent
::Start
=> {
172 input
.start(event_tx
.clone());
173 output
.start(event_tx
.clone(), out_buffer
.clone());
175 SoundmodemEvent
::Close
=> {
176 ptt_driver
.ptt_off();
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
)
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
_o
utp
ut
_b
uffer
(
190 internal_latency
+ dynamic_latency
,
193 SoundmodemEvent
::OutputUnderrun
=> {
194 // TODO: cancel transmission, send empty data frame to host
199 let new_ptt
= tnc
.ptt();
204 ptt_driver
.ptt_off();
209 // Let the modulator do what it wants
210 while let Some(action
) = modulator
.run() {
212 ModulatorAction
::SetIdle(idling
) => {
213 out_buffer
.write().unwrap
().idl
ing
= idling
;
215 ModulatorAction
::GetNextFrame
=> {
216 modulator
.provide_next_frame(tnc
.read_tx_frame());
218 ModulatorAction
::ReadOutput
=> loop {
219 let n
= modulator
.read_output_samples(&mut out_samples
);
223 let mut out_buffer
= out_buffer
.write().unwrap
();
224 for s
in &out_samples
[0..n
] {
225 out_buffer
.samples
.push_back(*s
);
228 ModulatorAction
::TransmissionWillEnd(in_samples
) => {
229 tnc
.set_tx_end_time(in_samples
);
237 pub trait InputSource
: Send
+ Sync
+ '
static {
238 fn start(&self, samples
: SyncSender
<SoundmodemEvent
>);
242 pub struct InputRrcFile
{
244 end_tx
: Mutex
<Option
<Sender
<()>>>,
248 pub fn new(path
: PathBuf
) -> Self {
251 end_tx
: Mutex
::new(None
),
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
();
266 // assuming 48 kHz for now
267 const TICK
: Duration
= Duration
::from_millis(25);
268 const SAMPLES_PER_TICK
: usize = 1200;
270 let mut next_tick
= Instant
::now() + TICK
;
271 let mut buf
= [0i16; SAMPLES_PER_TICK
];
274 for sample
in baseband
276 .map(|pair
| i16::from_le_bytes([pair
[0], pair
[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:?}");
286 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
288 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
293 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
297 let _
= self.end_tx
.lock().unwrap
().take();
301 pub struct NullInputSource
{
302 end_tx
: Mutex
<Option
<Sender
<()>>>,
305 impl NullInputSource
{
306 pub fn new() -> Self {
308 end_tx
: Mutex
::new(None
),
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
;
323 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
325 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
328 if let Err(e
) = samples
.try_send(SoundmodemEvent
::BasebandInput(
329 [0i16; SAMPLES_PER_TICK
].into
(),
331 debug
!("overflow feeding soundmodem: {e:?}");
335 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
339 let _
= self.end_tx
.lock().unwrap
().take();
343 impl Default
for NullInputSource
{
344 fn default() -> Self {
349 pub struct OutputBuffer
{
351 // TODO: something more efficient
352 pub samples
: VecDeque
<i16>,
353 pub latency
: Duration
,
357 pub fn new() -> Self {
360 samples
: VecDeque
::new(),
361 latency
: Duration
::ZERO
,
366 impl Default
for OutputBuffer
{
367 fn default() -> Self {
372 pub trait OutputSink
: Send
+ Sync
+ '
static {
373 fn start(&self, event_tx
: SyncSender
<SoundmodemEvent
>, buffer
: Arc
<RwLock
<OutputBuffer
>>);
377 pub struct OutputRrcFile
{
379 end_tx
: Mutex
<Option
<Sender
<()>>>,
383 pub fn new(path
: PathBuf
) -> Self {
386 end_tx
: Mutex
::new(None
),
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
();
399 // assuming 48 kHz for now
400 const TICK
: Duration
= Duration
::from_millis(25);
401 const SAMPLES_PER_TICK
: usize = 1200;
403 // flattened BE i16s for writing
404 let mut buf
= [0u8; SAMPLES_PER_TICK
* 2];
405 let mut next_tick
= Instant
::now() + TICK
;
408 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
410 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
413 // For now only write deliberately modulated (non-idling) samples
414 // Multiple transmissions will get smooshed together
415 let mut buf_used
= 0;
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]]);
423 } else if !buffer
.idl
ing
{
424 debug
!("output rrc file had underrun");
425 let _
= event_tx
.send(SoundmodemEvent
::OutputUnderrun
);
429 if let Err(e
) = file
.write_all(&buf
[0..buf_used
]) {
430 debug
!("failed to write to rrc file: {e:?}");
433 let _
= event_tx
.send(SoundmodemEvent
::DidReadFromOutputBuffer
{
435 timestamp
: Instant
::now(),
439 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
443 let _
= self.end_tx
.lock().unwrap
().take();
447 pub struct NullOutputSink
{
448 end_tx
: Mutex
<Option
<Sender
<()>>>,
451 impl NullOutputSink
{
452 pub fn new() -> Self {
454 end_tx
: Mutex
::new(None
),
459 impl Default
for NullOutputSink
{
460 fn default() -> Self {
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
;
475 std
::thread
::sleep(next_tick
.duration_since(Instant
::now()));
477 if end_rx
.try_recv() != Err(TryRecvError
::Empty
) {
481 let mut buffer
= buffer
.write().unwrap
();
483 for _
in 0..SAMPLES_PER_TICK
{
484 if buffer
.samples
.pop_front().is
_none
() {
486 debug
!("null output had underrun");
487 let _
= event_tx
.send(SoundmodemEvent
::OutputUnderrun
);
494 let _
= event_tx
.send(SoundmodemEvent
::DidReadFromOutputBuffer
{
496 timestamp
: Instant
::now(),
500 *self.end_tx
.lock().unwrap
() = Some(end_tx
);
504 let _
= self.end_tx
.lock().unwrap
().take();
508 pub trait Ptt
: Send
+ '
static {
509 fn ptt_on(&mut self);
510 fn ptt_off(&mut self);
513 /// There is no PTT because this TNC will never make transmissions on a real radio.
517 pub fn new() -> Self {
522 impl Default
for NullPtt
{
523 fn default() -> Self {
528 impl Ptt
for NullPtt
{
529 fn ptt_on(&mut self) {}
530 fn ptt_off(&mut self) {}