2 parse_lsf
, parse_packet
, parse_stream
, sync_burst_correlation
, SyncBurst
, SYNC_THRESHOLD
,
5 encode_lsf
, encode_packet
, encode_stream
, generate_end_of_transmission
, generate_preamble
,
7 use crate::protocol
::{Frame
, LsfFrame
, PacketFrame
, StreamFrame
};
8 use crate::shaping
::RRC_48K
;
11 pub trait Demodulator
{
12 fn demod(&mut self, sample
: i16) -> Option
<Frame
>;
13 fn data_carrier_detect(&self) -> bool
;
16 /// Converts a sequence of samples into frames.
17 pub struct SoftDemodulator
{
18 /// Circular buffer of incoming samples for calculating the RRC filtered value
19 filter_win
: [i16; 81],
20 /// Current position in filter_win
22 /// Circular buffer of shaped samples for performing decodes based on the last 192 symbols
24 /// Current position in rx_cursor
26 /// A position that we are considering decoding due to decent sync
27 candidate
: Option
<DecodeCandidate
>,
28 /// How many samples have we received?
30 /// Remaining samples to read in before attempting to decode the current candidate
31 samples_until_decode
: Option
<u16>,
32 /// Do we think there is a data carrier, i.e., channel in use? If so, at what sample does it expire?
36 impl SoftDemodulator
{
37 pub fn new() -> Self {
39 filter_win
: [0i16; 81],
45 samples_until_decode
: None
,
51 impl SoftDemodulator
{
52 fn dcd_until(&mut self, end_sample
: u64) {
53 if self.dcd
.is
_none
() {
54 debug
!("SoftDemodulator DCD on");
56 self.dcd
= Some(end_sample
);
59 fn check_dcd(&mut self) {
60 if let Some(end_sample
) = self.dcd
{
61 if self.sample
> end_sample
{
63 debug
!("SoftDemodulator DCD off");
69 impl Demodulator
for SoftDemodulator
{
70 fn demod(&mut self, sample
: i16) -> Option
<Frame
> {
71 self.filter
_w
in
[self.filter
_c
ursor
] = sample
;
72 self.filter
_c
ursor
= (self.filter
_c
ursor
+ 1) % 81;
73 let mut out
: f32 = 0.0;
75 let filter_idx
= (self.filter
_c
ursor
+ i
) % 81;
76 out
+= RRC_48K
[i
] * self.filter
_w
in
[filter_idx
] as f32;
79 self.rx_win
[self.rx_cursor
] = out
;
80 self.rx_cursor
= (self.rx_cursor
+ 1) % 1920;
85 if let Some(samples_until_decode
) = self.samples_until_decode
{
86 let sud
= samples_until_decode
- 1;
88 self.samples_until_decode
= Some(sud
);
91 self.samples_until_decode
= None
;
93 if let Some(c
) = self.candidate
.take() {
94 // we have capacity for 192 symbols * 10 upsamples
95 // we have calculated that the ideal sample point for 192nd symbol is right on the edge
96 // so take samples from the 10th slot all the way through.
97 let start_idx
= self.rx_cursor
+ 1920 + 9;
98 let mut pkt_samples
= [0f32; 192];
100 let rx_idx
= (start_idx
+ i
* 10) % 1920;
101 pkt_samples
[i
] = (self.rx_win
[rx_idx
] - c
.shift
) / c
.gain
;
105 if let Some(frame
) = parse_lsf(&pkt_samples
) {
106 return Some(Frame
::Lsf(frame
));
112 SyncBurst
::Stream
=> {
113 if let Some(frame
) = parse_stream(&pkt_samples
) {
114 return Some(Frame
::Stream(frame
));
117 SyncBurst
::Packet
=> {
118 if let Some(frame
) = parse_packet(&pkt_samples
) {
119 return Some(Frame
::Packet(frame
));
122 SyncBurst
::Preamble
| SyncBurst
::EndOfTransmission
=> {
123 // should never be chosen as a candidate
129 let mut burst_window
= [0f32; 8];
131 let c
= (self.rx_cursor
+ 1920 - 1 - ((7 - i
) * 10)) % 1920;
132 burst_window
[i
] = self.rx_win
[c
];
135 for burst
in [SyncBurst
::Preamble
, SyncBurst
::EndOfTransmission
] {
136 let (diff
, _
, _
) = sync_burst_correlation(burst
.target(), &burst_window
);
137 if diff
< SYNC_THRESHOLD
{
138 // arbitrary choice, 240 samples = 5ms
139 // these bursts keep repeating so it will keep pushing out the DCD end time
140 self.dcd_until(self.sample
+ 240);
150 let (diff
, max
, shift
) = sync_burst_correlation(burst
.target(), &burst_window
);
151 if diff
< SYNC_THRESHOLD
{
152 let mut new_candidate
= true;
153 if let Some(c
) = self.candidate
.as_mut() {
156 new_candidate
= false;
160 self.candidate
= Some(DecodeCandidate
{
169 if diff
>= SYNC_THRESHOLD
173 .map(|c
| c
.burst
== burst
)
176 // wait until the rest of the frame is in the buffer
177 let c
= self.candidate
.as_ref().unwrap
();
178 self.samples_until_decode
= Some((184 * 10) - (c
.age
as u16));
180 "Found {:?} at sample {} diff {}",
182 self.sample
- c
.age
as u64,
185 // After any of these frame types you would expect to see a full EOT
186 self.dcd_until(self.sample
+ 1920 + 1920);
193 fn data_carrier_detect(&self) -> bool
{
198 impl Default
for SoftDemodulator
{
199 fn default() -> Self {
204 pub trait Modulator
{
205 /// Inform the modulator how many samples remain pending for output and latency updates.
207 /// For the buffer between `Modulator` and the process which is supplying samples to the
208 /// output sound card, `samples_to_play` is the number of bytes which the modulator has
209 /// provided that have not yet been picked up, and `capacity` is the maximum size we can
210 /// fill this particular buffer, i.e., maximum number of samples.
212 /// Furthermore we attempt to track and account for the latency between the output
213 /// soundcard callback, and when those samples will actually be on the wire. CPAL helpfully
214 /// gives us an estimate. The latest estimate of latency is converted to a duration in terms
215 /// of number of samples and provided as `output_latency`. Added to this is the current
216 /// number of samples we expect remain to be processed from the last read.
218 /// Call this whenever bytes have been read out of the buffer.
219 fn update_output_buffer(
221 samples_to_play
: usize,
223 output_latency
: usize,
226 /// Supply the next frame available from the TNC, if it was requested.
227 fn provide_next_frame(&mut self, frame
: Option
<ModulatorFrame
>);
229 /// Calculate and write out output samples for the soundcard.
231 /// Returns the number of bytes valid in `out`. Should generally be called in a loop until
233 fn read_output_samples(&mut self, out
: &mut [i16]) -> usize;
235 /// Run the modulator and receive actions to process.
237 /// Should be called in a loop until it returns `None`.
238 fn run(&mut self) -> Option
<ModulatorAction
>;
241 pub enum ModulatorAction
{
242 /// If true, once all samples have been exhausted output should revert to equilibrium.
244 /// If false, failure to pick up enough samples for output sound card is an underrun error.
247 /// Check with the TNC if there is a frame available for transmission.
249 /// Call `next_frame()` with either the next frame, or `None` if TNC has nothing more to offer.
252 /// Modulator wishes to send samples to the output buffer - call `read_output_samples`.
255 /// Advise the TNC that we will complete sending End Of Transmission after the given number of
256 /// samples has elapsed, and therefore PTT should be deasserted at this time.
257 TransmissionWillEnd(usize),
260 /// Frames for transmission, emitted by the TNC and received by the Modulator.
262 /// The TNC is responsible for all timing decisions, making sure these frames are emitted in the
263 /// correct order, breaks between transmissions, PTT and CSMA. If the modulator is given a
264 /// `ModulatorFrame` value, its job is to transmit it immediately by modulating it into the output
265 /// buffer, or otherwise directly after any previously-supplied frames.
267 /// The modulator controls the rate at which frames are drawn out of the TNC. Therefore if the send
268 /// rate is too high (or there is too much channel activity) then the effect of this backpressure is
269 /// that the TNC's internal queues will overflow and it will either discard earlier frames in the
270 /// current stream, or some packets awaiting transmission.
271 pub enum ModulatorFrame
{
273 /// TNC's configured TxDelay setting, increments of 10ms.
275 /// TNC fires PTT and it's up to modulator to apply the setting, taking advantage of whatever
276 /// buffering already exists in the sound card to reduce the artificial delay.
286 pub struct SoftModulator
{
287 // TODO: 2000 was overflowing around EOT, track down why
288 /// Next modulated frame to output - 1920 samples for 40ms frame plus 80 for ramp-down
289 next_transmission
: [i16; 4000],
290 /// How much of next_transmission should in fact be transmitted
292 /// How much of next_transmission has been read out
294 /// How many pending zero samples to emit to align start of preamble with PTT taking effect
295 tx_delay_padding
: usize,
297 /// Do we need to update idle state?
299 /// What is that idle status?
302 /// Do we need to calculate a transmission end time?
304 /// (True after we encoded an EOT.) We will wait until we get a precise timing update.
305 calculate_tx_end
: bool
,
306 /// Do we need to report a transmission end time?
308 /// This is a duration expressed in number of samples.
309 report_tx_end
: Option
<usize>,
311 /// Circular buffer of most recently output samples for calculating the RRC filtered value.
313 /// This should naturally degrade to an oldest value plus 80 zeroes after an EOT.
314 filter_win
: [f32; 81],
315 /// Current position in filter_win
316 filter_cursor
: usize,
318 /// Should we ask the TNC for another frame. True after each call to update_output_buffer.
321 /// Expected delay beyond the buffer to reach the DAC
322 output_latency
: usize,
323 /// Number of samples we have placed in the buffer for the output soundcard not yet picked up.
324 samples_in_buf
: usize,
325 /// Total size to which the output buffer is allowed to expand.
330 pub fn new() -> Self {
332 next_transmission
: [0i16; 4000],
336 // TODO: actually set this to false when we are worried about underrun
339 calculate_tx_end
: false,
341 filter_win
: [0f32; 81],
343 try_get_frame
: false,
350 fn push_sample(&mut self, dibit
: f32) {
351 // TODO: 48 kHz assumption again
353 // Right now we are encoding everything as 1.0-scaled dibit floats
354 // This is a bit silly but it will do for a minute
355 // Max possible gain from the RRC filter with upsampling is about 0.462
356 // Let's bump everything to a baseline of 16383 / 0.462 = 35461
357 // For normal signals this yields roughly 0.5 magnitude which is plenty
359 self.filter
_w
in
[self.filter
_c
ursor
] = dibit
* 35461.0;
361 self.filter
_w
in
[self.filter
_c
ursor
] = 0.0;
363 self.filter
_c
ursor
= (self.filter
_c
ursor
+ 1) % 81;
364 let mut out
: f32 = 0.0;
366 let filter_idx
= (self.filter
_c
ursor
+ i
) % 81;
367 out
+= RRC_48K
[i
] * self.filter
_w
in
[filter_idx
];
369 self.next_transmission
[self.next_len
] = out
as i16;
374 fn request_frame_if_space(&mut self) {
375 if self.buf_capacity
- self.samples_in_buf
>= 2000 {
376 self.try_get_frame
= true;
381 impl Modulator
for SoftModulator
{
382 fn update_output_buffer(
384 samples_to_play
: usize,
386 output_latency
: usize,
388 self.output_latency
= output_latency
;
389 self.buf_capacity
= capacity
;
390 self.samples_in_buf
= samples_to_play
;
392 if self.calculate_tx_end
{
393 self.calculate_tx_end
= false;
394 // next_transmission should already have been read out to the buffer by now
395 // so we don't have to consider it
396 self.report_tx_end
= Some(self.samples_in_buf
+ self.output_latency
);
399 self.request_frame_if_space();
402 fn provide_next_frame(&mut self, frame
: Option
<ModulatorFrame
>) {
403 let Some(frame
) = frame
else {
404 self.try_get_frame
= false;
412 ModulatorFrame
::Preamble
{ tx_delay
} => {
413 // TODO: Stop assuming 48 kHz everywhere. 24 kHz should be fine too.
414 let tx_delay_samples
= tx_delay
as usize * 480;
415 // Our output latency gives us a certain amount of unavoidable TxDelay
416 // So only introduce artificial delay if the requested TxDelay exceeds that
417 self.tx_delay_padding
= tx_delay_samples
.saturating_sub(self.output_latency
);
419 // We should be starting from a filter_win of zeroes
420 // Transmission is effectively smeared by 80 taps and we'll capture that in EOT
421 for dibit
in generate_preamble() {
422 self.push_sample(dibit
);
425 ModulatorFrame
::Lsf(lsf_frame
) => {
426 for dibit
in encode_lsf(&lsf_frame
) {
427 self.push_sample(dibit
);
430 ModulatorFrame
::Stream(stream_frame
) => {
431 for dibit
in encode_stream(&stream_frame
) {
432 self.push_sample(dibit
);
435 ModulatorFrame
::Packet(packet_frame
) => {
436 for dibit
in encode_packet(&packet_frame
) {
437 self.push_sample(dibit
);
440 ModulatorFrame
::EndOfTransmission
=> {
441 for dibit
in generate_end_of_transmission() {
442 self.push_sample(dibit
);
445 // This is not a real symbol value
446 // However we want to flush the filter
447 self.push_sample(0f32);
449 self.calculate_tx_end
= true;
454 fn read_output_samples(&mut self, out
: &mut [i16]) -> usize {
457 // if we have pre-TX padding to accommodate TxDelay then expend that first
458 if self.tx_delay_padding
> 0 {
459 let len
= out
.len().min(self.tx_delay_padding
);
460 self.tx_delay_padding
-= len
;
467 // then follow it with whatever might be left in next_transmission
468 let next_remaining
= self.next_len
- self.next_read
;
469 if next_remaining
> 0 {
470 let len
= (out
.len() - written
).min(next_remaining
);
471 out
[written
..(written
+ len
)]
472 .copy_from_slice(&self.next_transmission
[self.next_read
..(self.next_read
+ len
)]);
473 self.next_read
+= len
;
480 fn run(&mut self) -> Option
<ModulatorAction
> {
481 // Time-sensitive for accuracy, so handle it first
482 if let Some(end
) = self.report_tx_end
.take() {
483 return Some(ModulatorAction
::TransmissionWillEnd(end
));
486 if self.next_read
< self.next_len
{
487 return Some(ModulatorAction
::ReadOutput
);
490 if self.update
_idle
{
491 self.update
_idle
= false;
492 return Some(ModulatorAction
::SetIdle(self.idle
));
495 if self.try_get_frame
{
496 return Some(ModulatorAction
::GetNextFrame
);
503 impl Default
for SoftModulator
{
504 fn default() -> Self {
510 pub(crate) struct DecodeCandidate
{