rustradio 0.18.0

Software defined radio library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! This module contains wasm versions of various code.
//!
//! It must fail gracefully when used in a web worker.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;

use wasm_bindgen::prelude::*;

use crate::stream::{Tag, TagPos};
use crate::{Error, Result};

pub mod wasm_graph;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
    #[wasm_bindgen(js_namespace = performance)]
    fn now() -> f64;
}

impl From<Error> for JsValue {
    fn from(e: Error) -> Self {
        JsValue::from_str(&format!("RustRadio: {e}"))
    }
}

pub fn initialize_rustradio() {
    log(&format!(
        "Initializing RustRadio {} rustc version {} git version {}",
        env!("CARGO_PKG_VERSION"),
        env!("RUSTC_VERSION"),
        env!("GIT_VERSION")
    ));
}

#[must_use]
pub(crate) fn get_cpu_time() -> std::time::Duration {
    // This is not available in WASM.
    // We could try using `performance.now()`, but that's wallclock time.
    std::time::Duration::from_secs(0)
}

pub(crate) fn sleep(_d: std::time::Duration) {}

/// Fake std::time::Instant.
pub(crate) struct Instant {
    ts: f64,
}
impl Instant {
    pub(crate) fn now() -> Self {
        Self { ts: Self::now2() }
    }
    fn now2() -> f64 {
        web_sys::window()
            .and_then(|v| v.performance())
            .map(|v| v.now())
            .unwrap_or_default()
    }
    pub(crate) fn elapsed(&self) -> std::time::Duration {
        std::time::Duration::from_millis((Self::now2() - self.ts) as u64)
    }
}

// The stream in BufferState is not actually shared. Producing initializes
// values in it, and consuming drops those values and marks the slots free by
// advancing rpos/used.
//
// This is not as performant as the circular buffer for non-WASM, but it does
// work.
//
// Originally this used `Vec<Option<T>>`, but that uses twice the buffer space
// and was marginally slower. (an AX.25 decode test went from ~60% CPU to ~55%).
//
// It should be possible to not copy to and from the readers and writers, but it
// requires more careful lifetime and pointer handling.
//
// The main requirement making this complex is that the users of these buffers
// need linear `&[T]` to work with, and a block needing to write two elements can
// get stuck if we keep giving it just one elements of space.
//
// We can't do `VecDeque` because it doesn't give us a linear buffer.
//
// We can't "just" rotate the buffer when needed. Well, we can, but:
// 1. We need to make sure there are no readers or writers outstanding, and
// 2. every rotation means copying all the elements, which is what we wanted to
//    avoid in the first place. Though to be fair, one less copy.
#[derive(Debug)]
struct BufferState<T> {
    rpos: usize,
    wpos: usize,
    used: usize,
    // Only the range described by rpos/used is initialized.
    stream: Vec<T>,
    tags: BTreeMap<TagPos, Vec<Tag>>,

    // Extra accounting to ensure that we never read uninitialized content.
    #[cfg(debug_assertions)]
    initialized: Vec<bool>,
}

impl<T: Default> BufferState<T> {
    const _CHECK_NOT_ZERO: () = assert!(
        std::mem::size_of::<T>() != 0,
        "Zero sized stream members are not supported"
    );

    /// Size in bytes.
    fn new(byte_size: usize) -> Result<Self> {
        let member_size = std::mem::size_of::<T>();
        let size = byte_size / member_size;
        if !byte_size.is_multiple_of(member_size) {
            return Err(Error::msg(format!(
                "Buffer size ({byte_size}) must be multiple of element size ({member_size})"
            )));
        }
        let stream = std::iter::repeat_with(T::default).take(size).collect();
        Ok(Self {
            rpos: 0,
            wpos: 0,
            used: 0,
            stream,
            tags: BTreeMap::default(),

            #[cfg(debug_assertions)]
            initialized: vec![false; size],
        })
    }
}

impl<T> BufferState<T> {
    // Return write range, in samples.
    #[must_use]
    fn write_range(&self) -> (usize, usize) {
        //eprintln!("Write range: {} {}", self.rpos, self.wpos);
        (self.wpos, self.wpos + self.free())
    }
    // Read range, in samples
    #[must_use]
    fn read_range(&self) -> (usize, usize) {
        (self.rpos, self.rpos + self.used)
    }

    #[must_use]
    fn capacity(&self) -> usize {
        self.size()
    }
    #[must_use]
    fn free(&self) -> usize {
        self.size() - self.used
    }
    #[must_use]
    fn size(&self) -> usize {
        self.stream.len()
    }
}

#[derive(Debug)]
pub struct Buffer<T> {
    id: usize,
    state: Mutex<BufferState<T>>,
}
impl<T: Default> Buffer<T> {
    pub fn new(size: usize) -> Result<Self> {
        Ok(Self {
            id: crate::NEXT_STREAM_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            state: Mutex::new(BufferState::new(size)?),
        })
    }
}
impl<T> Buffer<T> {
    pub fn id(&self) -> usize {
        self.id
    }
    pub(crate) fn is_empty(&self) -> bool {
        self.state.lock().unwrap().used == 0
    }
    /// Available space to write, in bytes(?).
    pub(crate) fn free(&self) -> usize {
        self.state.lock().unwrap().free()
    }
    pub fn consume(&self, n: usize) {
        let mut l = self.state.lock().unwrap();
        assert!(
            n <= l.used,
            "trying to consume {n}, but only have {}",
            l.used
        );
        let capacity = l.capacity();
        for i in 0..n {
            let pos = (l.rpos + i) % capacity;
            #[cfg(debug_assertions)]
            {
                debug_assert!(l.initialized[pos]);
                l.initialized[pos] = false;
            }
            l.tags.remove(&pos);
        }
        l.rpos = (l.rpos + n) % capacity;
        l.used -= n;
    }
    pub fn total_size(&self) -> usize {
        self.state.lock().unwrap().capacity()
    }
    pub fn wait_for_write(&self, _need: usize) -> usize {
        // TODO
        self.free()
    }
    pub fn wait_for_read(&self, _need: usize) -> usize {
        // TODO
        self.state.lock().unwrap().used
    }
    #[cfg(feature = "async")]
    pub async fn wait_for_write_async(&self, _need: usize) -> usize {
        // TODO
        self.wait_for_write(_need)
    }
    #[cfg(feature = "async")]
    pub async fn wait_for_read_async(&self, _need: usize) -> usize {
        // TODO
        self.wait_for_read(_need)
    }
    pub fn write_buf(self: Arc<Self>) -> Result<BufferWriter<T>> {
        let l = self.state.lock().unwrap();
        let (start, end) = l.write_range();
        drop(l);
        Ok(BufferWriter::new(self, end - start))
    }
}

// Produce and creating a read buf inherently requires copying.
impl<T: Copy> Buffer<T> {
    pub fn produce(&self, samples: &[T], tags: &[Tag]) {
        if samples.is_empty() {
            debug_assert!(tags.is_empty());
            return;
        }
        let mut l = self.state.lock().unwrap();
        assert!(
            samples.len() <= l.free(),
            "tried to produce {}, but only {} is free out of {}",
            samples.len(),
            l.free(),
            l.capacity()
        );
        let capacity = l.capacity();
        let wpos = l.wpos;
        for (i, sample) in samples.iter().copied().enumerate() {
            let pos = (wpos + i) % capacity;
            l.stream[pos] = sample;
            #[cfg(debug_assertions)]
            {
                debug_assert!(!l.initialized[pos]);
                l.initialized[pos] = true;
            }
        }
        for tag in tags {
            let pos = (tag.pos() + wpos) % capacity;
            let tag = Tag::new(pos, tag.key(), tag.val().clone());
            l.tags.entry(pos).or_default().push(tag);
        }
        l.wpos = (wpos + samples.len()) % capacity;
        l.used += samples.len();
    }
    pub fn read_buf(self: Arc<Self>) -> Result<(BufferReader<T>, Vec<Tag>)> {
        let s = self.state.lock().unwrap();
        let (start, end) = s.read_range();
        let used = end - start;
        let capacity = s.capacity();
        let mut stream = Vec::with_capacity(used);
        for i in 0..used {
            let pos = (start + i) % capacity;
            #[cfg(debug_assertions)]
            {
                debug_assert!(s.initialized[pos]);
            }
            stream.push(s.stream[pos]);
        }
        let mut tags = Vec::with_capacity(s.tags.len());
        for (n, ts) in &s.tags {
            let relative_pos = (*n + capacity - start) % capacity;
            if relative_pos >= used {
                continue;
            }
            for tag in ts {
                tags.push(Tag::new(relative_pos, tag.key(), tag.val().clone()));
            }
        }
        drop(s);
        tags.sort_by_key(Tag::pos);
        Ok((BufferReader::new(self, stream), tags))
    }
}

pub struct BufferReader<T> {
    parent: Arc<Buffer<T>>,
    stream: Vec<T>,
}
impl<T> BufferReader<T> {
    #[must_use]
    fn new(parent: Arc<Buffer<T>>, stream: Vec<T>) -> Self {
        Self { parent, stream }
    }

    /// Return slice to read from.
    #[must_use]
    pub fn slice(&self) -> &[T] {
        &self.stream
    }

    /// Helper function to iterate over input instead.
    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.slice().iter()
    }

    /// We're done with the buffer. Consume `n` samples.
    pub fn consume(self, n: usize) {
        assert!(
            n <= self.stream.len(),
            "trying to consume {n}, but read buffer only has {}",
            self.stream.len()
        );
        self.parent.consume(n);
    }

    /// len convenience function.
    #[must_use]
    pub fn len(&self) -> usize {
        self.slice().len()
    }

    /// is_empty convenience function.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}
pub struct BufferWriter<T> {
    parent: Arc<Buffer<T>>,
    len: usize,
    stream: Vec<T>,
}
impl<T> BufferWriter<T> {
    #[must_use]
    fn new(parent: Arc<Buffer<T>>, len: usize) -> BufferWriter<T> {
        Self {
            parent,
            len,
            stream: Vec::new(),
        }
    }
    /// Shortcut to save typing for the common operation of copying
    /// from an iterator.
    pub fn fill_from_slice(&mut self, src: impl Into<Vec<T>>) {
        let src = src.into();
        assert!(
            src.len() <= self.len,
            "trying to write {} samples into a {} sample buffer",
            src.len(),
            self.len
        );
        self.stream = src;
    }
    /// Shortcut to save typing for the common operation of copying
    /// from an iterator.
    pub fn fill_from_iter(&mut self, src: impl IntoIterator<Item = T>) {
        self.stream = src.into_iter().take(self.len).collect();
    }

    /// len convenience function.
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// is_empty convenience function.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<T: Default> BufferWriter<T> {
    /// Return the slice to write to.
    #[must_use]
    pub fn slice(&mut self) -> &mut [T] {
        if self.stream.len() < self.len {
            self.stream.resize_with(self.len, T::default);
        }
        debug_assert_eq!(
            self.stream.len(),
            self.len(),
            "Why would the stream len ever be larger than len?"
        );
        self.stream.as_mut_slice()
    }
}

// Produce on a Writer needs Copy because the parent buffer will copy from here
// into the main buffer.
impl<T: Copy> BufferWriter<T> {
    /// Having written into the write buffer, now tell the buffer
    /// we're done. Also here are the tags, with positions relative to
    /// start of buffer.
    ///
    // Tags inherently need to be copied in, because they need to be added to
    // the underlying stream.
    pub fn produce(self, n: usize, tags: &[Tag]) {
        assert!(
            n <= self.len,
            "trying to produce {n} samples from a {} sample buffer",
            self.len
        );
        if n == 0 {
            debug_assert!(tags.is_empty(), "produced 0 samples with nonzero tags");
            return;
        }
        assert!(
            n <= self.stream.len(),
            "trying to produce {n} samples, but only {} samples were written",
            self.stream.len()
        );
        self.parent.produce(&self.stream[..n], tags);
    }
}

pub mod export {
    pub(crate) use super::Instant;
    pub(crate) use super::get_cpu_time;
    pub use super::initialize_rustradio;
    pub(crate) use super::sleep;
    pub type Buffer<T> = super::Buffer<T>;
    pub type BufferReader<T> = super::BufferReader<T>;
    pub type BufferWriter<T> = super::BufferWriter<T>;
}