]>
code.octet-stream.net Git - m17rt/blob - m17app/src/soundmodem.rs
16bb97642900e86139c5d22aab31a681b0b53c2d
1 use crate::error
::M17Error
;
2 use crate::tnc
::{Tnc
, TncError
};
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
;
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
};
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
>>>,
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(
37 kiss_out_rx
: Arc
::new(Mutex
::new(kiss_out_rx
)),
38 partial_kiss_out
: Arc
::new(Mutex
::new(None
)),
43 struct PartialKissOut
{
48 impl Read
for Soundmodem
{
49 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
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());
56 .copy_from_slice(&partial
.output
[partial
.idx
..(partial
.idx
+ to_write
)]);
57 if to_write
== remaining
{
58 *partial_kiss_out
= None
;
60 partial
.idx
+= to_write
;
66 let rx
= self.kiss_out_rx
.lock().unwrap
();
68 .map_err(|s
| io
::Error
::new(ErrorKind
::Other
, format
!("{:?}", s
)))?
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
{
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
()));
88 fn flush(&mut self) -> std
::io
::Result
<()> {
93 impl Tnc
for Soundmodem
{
94 fn try_clone(&mut self) -> Result
<Self, TncError
> {
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(),
102 fn start(&mut self) -> Result
<(), TncError
> {
103 let _
= self.event_tx
.send(SoundmodemEvent
::Start
);
107 fn close(&mut self) -> Result
<(), TncError
> {
108 let _
= self.event_tx
.send(SoundmodemEvent
::Close
);
113 pub enum SoundmodemEvent
{
115 BasebandInput(Arc
<[i16]>),
118 DidReadFromOutputBuffer
{ len
: usize, timestamp
: Instant
},
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
>,
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();
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
);
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
156 SoundmodemEvent
::BasebandInput(b
) => {
158 if let Some(frame
) = demodulator
.demod(*sample
) {
159 tnc
.handle_frame(frame
);
161 let n
= tnc
.read_kiss(&mut buf
);
163 let _
= kiss_out_tx
.try_send(buf
[0..n
].into
());
170 tnc
.set_data_carrier_detect(demodulator
.data_carrier_detect());
172 SoundmodemEvent
::Start
=> {
173 input
.start(event_tx
.clone());
174 output
.start(event_tx
.clone(), out_buffer
.clone());
176 SoundmodemEvent
::Close
=> {
177 ptt_driver
.ptt_off();
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
)
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
_o
utp
ut
_b
uffer
(
191 internal_latency
+ dynamic_latency
,
194 SoundmodemEvent
::OutputUnderrun
=> {
195 // TODO: cancel transmission, send empty data frame to host
200 let new_ptt
= tnc
.ptt();
205 ptt_driver
.ptt_off();
210 // Let the modulator do what it wants
211 while let Some(action
) = modulator
.run() {
213 ModulatorAction
::SetIdle(idling
) => {
214 out_buffer
.write().unwrap
().idl
ing
= idling
;
216 ModulatorAction
::GetNextFrame
=> {
217 modulator
.provide_next_frame(tnc
.read_tx_frame());
219 ModulatorAction
::ReadOutput
=> loop {
220 let n
= modulator
.read_output_samples(&mut out_samples
);
224 let mut out_buffer
= out_buffer
.write().unwrap
();
225 for s
in &out_samples
[0..n
] {
226 out_buffer
.samples
.push_back(*s
);
229 ModulatorAction
::TransmissionWillEnd(in_samples
) => {
230 tnc
.set_tx_end_time(in_samples
);
238 pub trait InputSource
: Send
+ Sync
+ '
static {
239 fn start(&self, samples
: SyncSender
<SoundmodemEvent
>);
243 pub struct InputRrcFile
{
245 end_tx
: Mutex
<Option
<Sender
<()>>>,
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
))?
;
255 baseband
: baseband
.into
(),
256 end_tx
: Mutex
::new(None
),
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;
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) {}