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
use futuresdr::prelude::*;
/// Apply a function to each N input samples, producing M output samples.
///
/// Applies a function on N samples in the input stream,
/// and creates M samples in the output stream.
/// Handy for interleaved samples for example.
/// See examples/audio/play_stereo.rs
///
/// # Inputs
///
/// `in`: Input
///
/// # Outputs
///
/// `out`: Output after function applied
///
/// # Usage
/// ```
/// use futuresdr::blocks::ApplyNM;
/// use futuresdr::runtime::Flowgraph;
/// use num_complex::Complex;
///
/// let mut fg = Flowgraph::new();
///
/// // Convert mono stream to stereo interleaved stream
/// let mono_to_stereo = fg.add_block(ApplyNM::<_, _, _, 1, 2>::new(move |v: &[f32], d: &mut [f32]| {
/// d[0] = v[0] * 0.5; // gain left
/// d[1] = v[0] * 0.9; // gain right
/// }));
/// // Note that the closure can also hold state
/// // Additionally, the closure can change the type of the sample
/// ```
#[allow(clippy::type_complexity)]
#[derive(Block)]
pub struct ApplyNM<
F,
A,
B,
const N: usize,
const M: usize,
I = DefaultCpuReader<A>,
O = DefaultCpuWriter<B>,
> where
F: FnMut(&[A], &mut [B]) + Send + 'static,
A: Send + 'static,
B: Send + 'static,
I: CpuBufferReader<Item = A>,
O: CpuBufferWriter<Item = B>,
{
f: F,
#[input]
input: I,
#[output]
output: O,
}
impl<F, A, B, const N: usize, const M: usize, I, O> ApplyNM<F, A, B, N, M, I, O>
where
F: FnMut(&[A], &mut [B]) + Send + 'static,
A: Send + 'static,
B: Send + 'static,
I: CpuBufferReader<Item = A>,
O: CpuBufferWriter<Item = B>,
{
/// Create [`ApplyNM`] block
pub fn new(f: F) -> Self {
Self {
f,
input: I::default(),
output: O::default(),
}
}
}
#[doc(hidden)]
impl<F, A, B, const N: usize, const M: usize, I, O> Kernel for ApplyNM<F, A, B, N, M, I, O>
where
F: FnMut(&[A], &mut [B]) + Send + 'static,
A: Send + 'static,
B: Send + 'static,
I: CpuBufferReader<Item = A>,
O: CpuBufferWriter<Item = B>,
{
async fn work(
&mut self,
io: &mut WorkIo,
_mio: &mut MessageOutputs,
_meta: &mut BlockMeta,
) -> Result<()> {
let i = self.input.slice();
let o = self.output.slice();
let i_len = i.len();
// See https://www.nickwilcox.com/blog/autovec/ for a discussion
// on auto-vectorization of these types of functions.
let m = std::cmp::min(i.len() / N, o.len() / M);
if m > 0 {
for (v, r) in i.chunks_exact(N).zip(o.chunks_exact_mut(M)) {
(self.f)(v, r);
}
self.input.consume(N * m);
self.output.produce(M * m);
}
if self.input.finished() && (i_len - N * m) < N {
io.finished = true;
}
Ok(())
}
}