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
use std::{io, sync::Arc};

macro_rules! error {
    ($fmt:literal $($tt:tt)*) => {
        ::std::io::Error::new(::std::io::ErrorKind::InvalidInput, format!($fmt $($tt)*))
    };
}

pub trait Writer: Sync {
    fn is_cached(&self, hash: &Hash) -> bool;
    fn sink(&mut self, hash: &Hash) -> euphony_node::BoxProcessor;
    fn group<I: Iterator<Item = Entry>>(&mut self, name: &str, hash: &Hash, entries: I);
    fn buffer<F: FnOnce(Box<dyn BufferReader>) -> Result<Vec<ConvertedBuffer>, E>, E>(
        &self,
        path: &str,
        sample_rate: u64,
        init: F,
    ) -> Result<Vec<CachedBuffer>, E>;
}

pub trait BufferReader: io::Read + Send + Sync + 'static {}

impl<T: io::Read + Send + Sync + 'static> BufferReader for T {}

pub type ConvertedBuffer = Vec<sample::DefaultSample>;

#[derive(Clone, Debug)]
pub struct CachedBuffer {
    pub samples: Arc<[f64]>,
    pub hash: Hash,
}

#[derive(Clone, Copy, Debug)]
pub struct Entry {
    pub sample_offset: u64,
    pub hash: Hash,
}

#[path = "sample.rs"]
mod internal_sample;
pub mod sample {
    pub(crate) use super::internal_sample::*;
    pub use euphony_dsp::sample::*;
}

// TODO better error?
pub type Error = std::io::Error;
pub type Result<T = (), E = Error> = core::result::Result<T, E>;
pub type Hash = [u8; 32];

mod buffer;
mod compiler;
mod group;
mod instruction;
mod node;
mod parallel;
mod render;
mod sink;

#[derive(Debug, Default)]
pub struct Compiler {
    compiler: compiler::Compiler,
    render: render::Renderer,
}

impl Compiler {
    pub fn compile<I: io::Read, O: Writer>(&mut self, input: &mut I, output: &mut O) -> Result {
        // clear everything out first
        self.compiler.reset();
        self.render.reset();

        euphony_command::decode(input, &mut self.compiler)?;
        let buffers = self.compiler.finalize(output)?;
        self.render.set_buffers(buffers);

        for instruction in self.compiler.instructions() {
            self.render
                .push(instruction, output)
                .map_err(|err| error!("invalid instruction {:?}", err))?;
        }

        for (_id, group, entries) in self.compiler.groups() {
            output.group(&group.name, &group.hash, entries);
        }

        Ok(())
    }

    pub fn display<I: io::Read, O: io::Write>(&mut self, input: &mut I, output: &mut O) -> Result {
        // clear everything out first
        self.compiler.reset();
        self.render.reset();

        euphony_command::decode(input, &mut self.compiler)?;

        struct Output;

        impl Writer for Output {
            fn is_cached(&self, _hash: &Hash) -> bool {
                false
            }

            fn sink(&mut self, _hash: &Hash) -> euphony_node::BoxProcessor {
                unimplemented!()
            }

            fn group<I: Iterator<Item = Entry>>(&mut self, _name: &str, _hash: &Hash, _entries: I) {
            }

            fn buffer<F: FnOnce(Box<dyn BufferReader>) -> Result<Vec<ConvertedBuffer>, E>, E>(
                &self,
                _path: &str,
                _sample_rate: u64,
                _init: F,
            ) -> Result<Vec<CachedBuffer>, E> {
                unimplemented!()
            }
        }

        self.compiler.finalize(&Output)?;

        writeln!(output, "# Groups")?;
        for (_id, group, entries) in self.compiler.groups() {
            let count = entries.count();
            writeln!(output, "* {:?} ({} entries)", group.name, count)?;
        }
        writeln!(output)?;

        writeln!(output, "# Instructions")?;
        for instruction in self.compiler.instructions() {
            writeln!(output, "{}", instruction)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bolero::check;
    use std::io::Cursor;

    struct Output;

    impl Writer for Output {
        fn is_cached(&self, _hash: &Hash) -> bool {
            false
        }

        fn sink(&mut self, _hash: &Hash) -> euphony_node::BoxProcessor {
            // silence
            euphony_dsp::nodes::load(106).unwrap()
        }

        fn group<I: Iterator<Item = Entry>>(&mut self, _name: &str, _hash: &Hash, entries: I) {
            for _ in entries {}
        }

        fn buffer<F: FnOnce(Box<dyn BufferReader>) -> Result<Vec<ConvertedBuffer>, E>, E>(
            &self,
            _path: &str,
            _sample_rate: u64,
            _init: F,
        ) -> Result<Vec<CachedBuffer>, E> {
            Ok(vec![])
        }
    }

    #[test]
    fn fuzz() {
        check!().for_each(|input| {
            let mut compiler = Compiler::default();
            let mut input = Cursor::new(input);
            let _ = compiler.compile(&mut input, &mut Output);
        });
    }
}