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
use crate::{
    config::{XSynthRenderAudioFormat, XSynthRenderConfig},
    XSynthRender,
};

use std::sync::Arc;

use xsynth_core::{
    channel::{ChannelAudioEvent, ChannelConfigEvent, ControlEvent},
    channel_group::SynthEvent,
    soundfont::{LoadSfError, SoundfontBase},
};

use thiserror::Error;

use midi_toolkit::{
    events::{Event, MIDIEventEnum},
    io::{MIDIFile, MIDILoadError},
    pipe,
    sequence::{
        event::{cancel_tempo_events, scale_event_time},
        unwrap_items, TimeCaster,
    },
};

pub use xsynth_core::channel_group::ParallelismOptions;

/// Statistics of an XSynthRender object.
pub struct XSynthRenderStats {
    /// The progress of the render in seconds.
    /// For example, if two seconds of the MIDI are rendered the value will be `2.0`.
    pub progress: f64,

    /// The active voice count of the synthesizer.
    pub voice_count: u64,
    // pub render_time: f64,
}

/// Errors that can be generated when rendering a MIDI.
#[derive(Debug, Error)]
pub enum XSynthRenderError {
    #[error("SF loading failed")]
    SfLoadingFailed(#[from] LoadSfError),

    #[error("MIDI loading failed")]
    MidiLoadingFailed(MIDILoadError),
}

impl From<MIDILoadError> for XSynthRenderError {
    fn from(e: MIDILoadError) -> Self {
        XSynthRenderError::MidiLoadingFailed(e)
    }
}

/// Helper struct to create an XSynthRender object and render a MIDI file.
///
/// Initialize using the `xsynth_renderer` function.
pub struct XSynthRenderBuilder<'a, StatsCallback: FnMut(XSynthRenderStats)> {
    config: XSynthRenderConfig,
    midi_path: &'a str,
    soundfonts: Vec<Arc<dyn SoundfontBase>>,
    layer_count: Option<usize>,
    out_path: &'a str,
    stats_callback: StatsCallback,
}

/// Initializes an XSynthRenderBuilder object.
pub fn xsynth_renderer<'a>(
    config: XSynthRenderConfig,
    midi_path: &'a str,
    out_path: &'a str,
) -> XSynthRenderBuilder<'a, impl FnMut(XSynthRenderStats)> {
    XSynthRenderBuilder {
        config,
        midi_path,
        soundfonts: vec![],
        layer_count: Some(4),
        out_path,
        stats_callback: |_| {},
    }
}

impl<'a, ProgressCallback: FnMut(XSynthRenderStats)> XSynthRenderBuilder<'a, ProgressCallback> {
    pub fn with_config(mut self, config: XSynthRenderConfig) -> Self {
        self.config = config;
        self
    }

    pub fn with_channel_count(mut self, channels: u32) -> Self {
        self.config.group_options.channel_count = channels;
        self
    }

    pub fn with_parallelism(mut self, options: ParallelismOptions) -> Self {
        self.config.group_options.parallelism = options;
        self
    }

    pub fn use_limiter(mut self, use_limiter: bool) -> Self {
        self.config.use_limiter = use_limiter;
        self
    }

    pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
        self.config.group_options.audio_params.sample_rate = sample_rate;
        self
    }

    pub fn with_audio_channels(mut self, audio_channels: u16) -> Self {
        self.config.group_options.audio_params.channels = audio_channels.into();
        self
    }

    /// Unused because only WAV is supported
    pub fn _with_audio_format(mut self, audio_format: XSynthRenderAudioFormat) -> Self {
        self.config.audio_format = audio_format;
        self
    }

    pub fn with_layer_count(mut self, layers: Option<usize>) -> Self {
        self.layer_count = layers;
        self
    }

    // Set up functions
    pub fn add_soundfonts(mut self, soundfonts: Vec<Arc<dyn SoundfontBase>>) -> Self {
        self.soundfonts.extend(soundfonts);
        self
    }

    /// Sets a callback function to be used to update the render statistics.
    pub fn with_progress_callback<F: FnMut(XSynthRenderStats)>(
        self,
        stats_callback: F,
    ) -> XSynthRenderBuilder<'a, F> {
        XSynthRenderBuilder {
            config: self.config,
            midi_path: self.midi_path,
            soundfonts: self.soundfonts,
            layer_count: self.layer_count,
            out_path: self.out_path,
            stats_callback,
        }
    }

    pub fn run(mut self) -> Result<(), XSynthRenderError> {
        let mut synth = XSynthRender::new(self.config.clone(), self.out_path.into());

        synth.send_event(SynthEvent::ChannelConfig(
            ChannelConfigEvent::SetSoundfonts(
                self.soundfonts
                    .drain(..)
                    .collect::<Vec<Arc<dyn SoundfontBase>>>(),
            ),
        ));

        synth.send_event(SynthEvent::ChannelConfig(
            ChannelConfigEvent::SetLayerCount(self.layer_count),
        ));

        let midi = MIDIFile::open(self.midi_path, None)?;

        let ppq = midi.ppq();
        let merged = pipe!(
            midi.iter_all_track_events_merged_batches()
            |>TimeCaster::<f64>::cast_event_delta()
            |>cancel_tempo_events(250000)
            |>scale_event_time(1.0 / ppq as f64)
            |>unwrap_items()
        );

        let mut pos: f64 = 0.0;

        for batch in merged {
            if batch.delta > 0.0 {
                synth.render_batch(batch.delta);
                pos += batch.delta;
            }
            for e in batch.iter_events() {
                (self.stats_callback)(XSynthRenderStats {
                    progress: pos,
                    voice_count: synth.voice_count(),
                });
                match e.as_event() {
                    Event::NoteOn(e) => {
                        synth.send_event(SynthEvent::Channel(
                            e.channel as u32,
                            ChannelAudioEvent::NoteOn {
                                key: e.key,
                                vel: e.velocity,
                            },
                        ));
                    }
                    Event::NoteOff(e) => {
                        synth.send_event(SynthEvent::Channel(
                            e.channel as u32,
                            ChannelAudioEvent::NoteOff { key: e.key },
                        ));
                    }
                    Event::ControlChange(e) => {
                        synth.send_event(SynthEvent::Channel(
                            e.channel as u32,
                            ChannelAudioEvent::Control(ControlEvent::Raw(e.controller, e.value)),
                        ));
                    }
                    Event::PitchWheelChange(e) => {
                        synth.send_event(SynthEvent::Channel(
                            e.channel as u32,
                            ChannelAudioEvent::Control(ControlEvent::PitchBendValue(
                                e.pitch as f32 / 8192.0,
                            )),
                        ));
                    }
                    Event::ProgramChange(e) => {
                        synth.send_event(SynthEvent::Channel(
                            e.channel as u32,
                            ChannelAudioEvent::ProgramChange(e.program),
                        ));
                    }
                    _ => {}
                }
            }
        }
        synth.send_event(SynthEvent::AllChannels(ChannelAudioEvent::AllNotesOff));
        synth.send_event(SynthEvent::AllChannels(ChannelAudioEvent::ResetControl));
        synth.finalize();

        Ok(())
    }
}