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
pub use crate::{
    buffer::Buffer, node::Node, BoxedNodeSend, Message, NodeData, Pass, Processor, Sum2,
};
use hashbrown::HashMap;
use petgraph::{graph::NodeIndex, prelude::EdgeIndex};

/// The builder to build `AudioContext`
pub struct AudioContextBuilder<const N: usize> {
    sr: usize,
    channels: usize,
    // stablegraph: bool,
    max_nodes: usize,
    max_edges: usize,
}

impl<const N: usize> Default for AudioContextBuilder<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> AudioContextBuilder<N> {
    pub fn new() -> Self {
        Self {
            sr: 44100,
            channels: 2,
            // stablegraph: false,
            max_nodes: 1024,
            max_edges: 1024,
        }
    }

    pub fn sr(self, sr: usize) -> Self {
        Self { sr, ..self }
    }

    pub fn channels(self, channels: usize) -> Self {
        Self { channels, ..self }
    }

    pub fn max_nodes(self, max_nodes: usize) -> Self {
        Self { max_nodes, ..self }
    }

    pub fn max_edges(self, max_edges: usize) -> Self {
        Self { max_edges, ..self }
    }

    pub fn build(self) -> AudioContext<N> {
        AudioContext::new(AudioContextConfig {
            sr: self.sr,
            channels: self.channels,
            max_nodes: self.max_nodes,
            max_edges: self.max_edges,
        })
    }
}

/// Another option for building `AudioContext`
pub struct AudioContextConfig {
    pub sr: usize,
    pub channels: usize,
    // pub stablegraph: bool,
    pub max_nodes: usize,
    pub max_edges: usize,
}

impl std::default::Default for AudioContextConfig {
    fn default() -> Self {
        Self {
            sr: 44100,
            channels: 2,
            max_nodes: 1024,
            max_edges: 1024,
        }
    }
}

#[macro_export]
macro_rules! audiocontext {
    ($size:expr, {$($para: ident: $data:expr),*}) => {
        (
            AudioContextBuilder::<$size>::new()$(.$para($data))*.build()
        )
    }
}

pub type GlicolNodeData<const N: usize> = NodeData<BoxedNodeSend<N>, N>;
pub type GlicolGraph<const N: usize> = petgraph::stable_graph::StableGraph<GlicolNodeData<N>, ()>;
pub type GlicolProcessor<const N: usize> = Processor<GlicolGraph<N>, N>;

/// The audio context that holds a destination and the graph connection
pub struct AudioContext<const N: usize> {
    pub input: NodeIndex,
    pub destination: NodeIndex,
    pub tags: HashMap<&'static str, NodeIndex>,
    pub graph: GlicolGraph<N>,
    pub processor: GlicolProcessor<N>,
    config: AudioContextConfig,
}

impl<const N: usize> AudioContext<N> {
    pub fn new(config: AudioContextConfig) -> Self {
        let mut graph = GlicolGraph::<N>::with_capacity(config.max_nodes, config.max_edges);
        let destination = graph.add_node(NodeData::multi_chan_node(
            config.channels,
            BoxedNodeSend::<N>::new(Sum2),
        ));
        let input = graph.add_node(NodeData::multi_chan_node(
            config.channels,
            BoxedNodeSend::<N>::new(Pass),
        ));
        Self {
            graph,
            destination,
            input,
            tags: HashMap::new(),
            processor: GlicolProcessor::<N>::with_capacity(config.max_nodes),
            config,
        }
    }

    pub fn reset(&mut self) {
        // self.graph.clear_edges();
        self.graph.clear();
        self.destination = self.graph.add_node(NodeData::multi_chan_node(
            self.config.channels,
            BoxedNodeSend::<N>::new(Sum2),
        ));
        self.input = self.graph.add_node(NodeData::multi_chan_node(
            self.config.channels,
            BoxedNodeSend::<N>::new(Pass),
        ));
    }

    /// an alternative to new() specify the estimated max node and edge numbers
    /// to avoid dynamic allocation
    // pub fn with_capacity(nodes: usize, edges: usize) -> Self {
    //     let mut graph = GlicolGraph::<N>::with_capacity(nodes, edges);
    //     let destination = graph.add_node( NodeData::new2( BoxedNodeSend::<N>::new( Sum)  ) );
    //     let input = graph.add_node( NodeData::multi_chan_node(config.channels, BoxedNodeSend::<N>::new(Pass) ) );
    //     Self {
    //         graph,
    //         destination,
    //         input,
    //         processor: GlicolProcessor::<N>::with_capacity(nodes),
    //     }
    // }

    pub fn add_mono_node<T>(&mut self, node: T) -> NodeIndex
    where
        T: Node<N> + Send + 'static,
    {
        self.graph.add_node(
            // channel?
            NodeData::new1(BoxedNodeSend::<N>::new(node)),
        )
    }

    pub fn add_stereo_node<T>(&mut self, node: T) -> NodeIndex
    where
        T: Node<N> + Send + 'static,
    {
        self.graph.add_node(
            // channel?
            NodeData::new2(BoxedNodeSend::<N>::new(node)),
        )
    }

    pub fn add_multi_chan_node<T>(&mut self, chan: usize, node: T) -> NodeIndex
    where
        T: Node<N> + Send + 'static,
    {
        self.graph.add_node(
            // channel?
            NodeData::multi_chan_node(chan, BoxedNodeSend::<N>::new(node)),
        )
    }

    pub fn connect(&mut self, from: NodeIndex, to: NodeIndex) -> EdgeIndex {
        let edge_index = self.graph.add_edge(from, to, ());
        self.graph[to].node.send_msg(Message::Index(from.index()));
        edge_index
    }

    pub fn connect_with_order(&mut self, from: NodeIndex, to: NodeIndex, pos: usize) -> EdgeIndex {
        let edge_index = self.graph.add_edge(from, to, ());
        self.graph[to]
            .node
            .send_msg(Message::IndexOrder(pos, from.index()));
        edge_index
    }

    pub fn chain(&mut self, chain: Vec<NodeIndex>) -> Vec<EdgeIndex> {
        chain.windows(2)
            .map(|pair| {
                let ret = self.graph.add_edge(pair[0], pair[1], ());
                self.graph[pair[1]]
                    .node
                    .send_msg(Message::Index(pair[0].index()));
                ret
            }).collect()
    }

    pub fn chain_boxed(
        &mut self,
        chain: Vec<GlicolNodeData<N>>,
    ) -> (Vec<NodeIndex>, Vec<EdgeIndex>) {
        let indices = chain.into_iter()
            .map(|node| self.graph.add_node(node))
            .collect::<Vec<_>>();

        let v = indices.windows(2)
            .map(|pair| {
                let ret = self.graph.add_edge(pair[0], pair[1], ());
                self.graph[pair[1]]
                    .node
                    .send_msg(Message::Index(pair[0].index()));
                ret
            }).collect();

        (indices, v)
    }

    pub fn add_node_chain(
        &mut self,
        chain: Vec<NodeData<BoxedNodeSend<N>, N>>,
    ) -> (Vec<NodeIndex>, Vec<EdgeIndex>) {
        let v = chain.into_iter()
            .map(|node| self.graph.add_node(node))
            .collect::<Vec<_>>();

        let j = v.windows(2)
            .map(|pair| self.graph.add_edge(pair[0], pair[1], ()))
            .collect();

        (v, j)
    }

    pub fn next_block(&mut self) -> &[Buffer<N>] {
        self.processor.process(&mut self.graph, self.destination);
        &self.graph[self.destination].buffers
    }

    pub fn send_msg(&mut self, index: NodeIndex, msg: Message) {
        self.graph[index].node.send_msg(msg);
    }

    pub fn send_msg_to_all(&mut self, msg: Message) {
        for nodedata in self.graph.node_weights_mut() {
            nodedata.node.send_msg(msg.clone());
        }
    }
}