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
// The MIT License (MIT)

// Copyright (c) 2016 RustAudio Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::{buffer::Buffer, node::Input, node::Node, BoxedNode};
use hashbrown::HashMap;
use petgraph::data::{DataMap, DataMapMut};
use petgraph::visit::{
    Data,
    DfsPostOrder,
    GraphBase,
    IntoNeighborsDirected,
    Reversed, //NodeCount, NodeIndexable,
    Visitable,
};
use petgraph::Incoming;

pub struct Processor<G, const N: usize>
where
    G: Visitable,
{
    // State related to the traversal of the audio graph starting from the output node.
    dfs_post_order: DfsPostOrder<G::NodeId, G::Map>,
    // Solely for collecting the inputs of a node in order to apply its `Node::process` method.
    inputs: HashMap<usize, Input<N>>,
    // pub processed: Vec<G::NodeId>
}

/// For use as the node weight within a dasp graph. Contains the node and its buffers.
///
/// For a graph to be compatible with a graph **Processor**, its node weights must be of type
/// `NodeData<T>`, where `T` is some type that implements the `Node` trait.
pub struct NodeData<T: ?Sized, const N: usize> {
    pub buffers: Vec<Buffer<N>>,
    pub node: T,
}

impl<G, const N: usize> Processor<G, N>
where
    G: Visitable + petgraph::visit::NodeIndexable,
{
    pub fn with_capacity(max_nodes: usize) -> Self
    where
        G::Map: Default,
    {
        let dfs_post_order = DfsPostOrder {
            stack: Vec::with_capacity(max_nodes),
            ..Default::default()
        };
        let inputs = HashMap::new(); //Vec::with_capacity(max_nodes);
        Self {
            dfs_post_order,
            inputs,
        }
    }
    pub fn process<T>(&mut self, graph: &mut G, node: G::NodeId)
    where
        G: Data<NodeWeight = NodeData<T, N>> + DataMapMut,
        for<'a> &'a G: GraphBase<NodeId = G::NodeId> + IntoNeighborsDirected,
        T: Node<N>,
    {
        process(self, graph, node)
    }
}

impl<T, const N: usize> NodeData<T, N> {
    /// Construct a new **NodeData** from an instance of its node type and buffers.
    pub fn new(node: T, buffers: Vec<Buffer<N>>) -> Self {
        NodeData { node, buffers }
    }

    /// Creates a new **NodeData** with a single buffer.
    pub fn new1(node: T) -> Self {
        Self::new(node, vec![Buffer::SILENT])
    }

    /// Creates a new **NodeData** with two buffers.
    pub fn new2(node: T) -> Self {
        Self::new(node, vec![Buffer::SILENT; 2])
    }

    /// Creates a new **NodeData** with 8 buffers.
    pub fn multi_chan_node(chan: usize, node: T) -> Self {
        Self::new(node, vec![Buffer::SILENT; chan])
    }
}

#[cfg(feature = "node-boxed")]
impl<const N: usize> NodeData<BoxedNode<N>, N> {
    /// The same as **new**, but boxes the given node data before storing it.
    pub fn boxed<T>(node: T, buffers: Vec<Buffer<N>>) -> Self
    where
        T: 'static + Node<N>,
    {
        NodeData::new(BoxedNode(Box::new(node)), buffers)
    }

    /// The same as **new1**, but boxes the given node data before storing it.
    pub fn boxed1<T>(node: T) -> Self
    where
        T: 'static + Node<N>,
    {
        Self::boxed(node, vec![Buffer::SILENT])
    }

    /// The same as **new2**, but boxes the given node data before storing it.
    pub fn boxed2<T>(node: T) -> Self
    where
        T: 'static + Node<N>,
    {
        Self::boxed(node, vec![Buffer::SILENT, Buffer::SILENT])
    }
}

pub fn process<G, T, const N: usize>(
    processor: &mut Processor<G, N>,
    graph: &mut G,
    node: G::NodeId,
) where
    G: Data<NodeWeight = NodeData<T, N>> + DataMapMut + Visitable + petgraph::visit::NodeIndexable,
    for<'a> &'a G: GraphBase<NodeId = G::NodeId> + IntoNeighborsDirected,
    T: Node<N>,
{
    const NO_NODE: &str = "no node exists for the given index";
    processor.dfs_post_order.reset(Reversed(&*graph));
    processor.dfs_post_order.move_to(node);
    while let Some(n) = processor.dfs_post_order.next(Reversed(&*graph)) {
        processor.inputs.clear();
        for in_n in (&*graph).neighbors_directed(n, Incoming) {
            // Skip edges that connect the node to itself to avoid aliasing `node`.
            if n == in_n {
                continue;
            }
            // println!("{:?}", (&*graph).to_index(in_n));

            let input_container = graph.node_weight(in_n).expect(NO_NODE);
            let input = Input::new(&input_container.buffers, (*graph).to_index(in_n));
            processor.inputs.insert((*graph).to_index(in_n), input);
        }

        // Here we used to dereference a raw pointer to the `NodeData`. The only references to the
        // graph at this point in time are the input references and the node itself. We know that
        // the input references do not alias out node's mutable reference as we explicitly check
        // for it while looping through the inputs above.
        let data = graph.node_weight_mut(n).expect(NO_NODE);
        data
            .node
            .process(&mut processor.inputs, &mut data.buffers);
    }
}