synth.rs 9.84 KB
Newer Older
Aske Simon Christensen's avatar
Aske Simon Christensen committed
1
2
3

use std::collections::{HashMap, VecDeque};
use std::marker::PhantomData;
4
5
use std::ops::Deref;
use std::sync::{Arc, RwLock};
Aske Simon Christensen's avatar
Aske Simon Christensen committed
6

7
8
9
10
use vst::api::{Events, Supported};
use vst::buffer::AudioBuffer;
use vst::event::{Event, MidiEvent};
use vst::host::Host;
11
use vst::plugin::{CanDo, Category, HostCallback, Info, Plugin, PluginParameters};
Aske Simon Christensen's avatar
Aske Simon Christensen committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

use cache::SoundCache;
use generate::{Sample, SoundGenerator, SoundParameters};


#[allow(dead_code)]
pub enum MidiCommand {
	NoteOn      { channel: u8, key: u8, velocity: u8 },
	NoteOff     { channel: u8, key: u8, velocity: u8 },
	AllNotesOff { channel: u8,          velocity: u8 },
	AllSoundOff { channel: u8,          velocity: u8 },
	Unknown
}

impl MidiCommand {
27
	fn from_data(data: &[u8; 3]) -> MidiCommand {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
28
29
30
31
32
33
34
35
36
37
38
39
40
		match data[0] & 0xF0 {
			0x80 => MidiCommand::NoteOff { channel: data[0] & 0x0F, key: data[1], velocity: data[2] },
			0x90 => MidiCommand::NoteOn  { channel: data[0] & 0x0F, key: data[1], velocity: data[2] },
			0xB0 => match data[1] {
				120 => MidiCommand::AllSoundOff { channel: data[0] & 0x0F, velocity: data[2] },
				123 => MidiCommand::AllNotesOff { channel: data[0] & 0x0F, velocity: data[2] },
				_   => MidiCommand::Unknown
			},
			_    => MidiCommand::Unknown
		}
	}
}

41
pub struct TimedMidiCommand {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
42
43
44
45
46
47
	time: usize,
	command: MidiCommand,
}

struct Note {
	time: usize,
48
49
	dead_time: usize,
	max_dead_time: Option<usize>,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
50
51
52
53
54
55
56
57
58
	tone: u8,
	velocity: u8,
	attack: f32,
	release: f32,

	release_time: Option<usize>
}

impl Note {
59
	fn new(tone: u8, velocity: u8, attack: f32, release: f32, max_dead_time: Option<usize>) -> Note {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
60
61
		Note {
			time: 0,
62
63
			dead_time: 0,
			max_dead_time: max_dead_time,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
64
65
66
67
68
69
70
71
72
73
			tone: tone,
			velocity: velocity,
			attack: attack,
			release: release,

			release_time: None
		}
	}

	fn produce_sample<G: SoundGenerator>(&mut self, cache: &mut Vec<SoundCache<G>>, param: &G::Parameters, global: &G::Global) -> Sample {
74
		let wave = cache[self.tone as usize].get_sample(self.time, param, global);
75
		let amp = self.attack_amp().min(self.release_amp()) * (self.velocity as f32 / 127.0);
76
		let sample = wave * amp;
Aske Simon Christensen's avatar
Aske Simon Christensen committed
77
78
		self.time += 1;

79
80
81
82
83
84
85
		if sample.left.abs() < 0.001 && sample.right.abs() < 0.001 {
			self.dead_time += 1;
		} else {
			self.dead_time = 0;
		}

		sample
Aske Simon Christensen's avatar
Aske Simon Christensen committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
	}

	fn attack_amp(&self) -> f32 {
		(self.time as f32 * self.attack).min(1.0)
	}

	fn release_amp(&self) -> f32 {
		match self.release_time {
			None => 1.0,
			Some(t) => (1.0 - (self.time - t) as f32 * self.release).max(0.0)
		}
	}

	fn release(&mut self, _velocity: u8) {
		self.release_time = Some(self.time);
	}

103
	fn is_released(&self) -> bool {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
104
105
106
		self.release_time.is_some()
	}

107
	fn is_alive(&self) -> bool {
108
109
110
111
112
		if let Some(max_dead_time) = self.max_dead_time {
			if self.dead_time > max_dead_time {
				return false;
			}
		}
Aske Simon Christensen's avatar
Aske Simon Christensen committed
113
114
115
116
117
118
119
120
121
		self.release_amp() > 0.0
	}
}


pub trait SynthInfo {
	fn get_info() -> Info;
}

122
pub struct SynthPlugin<G: SoundGenerator + 'static, S: SynthInfo> {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
123
124
125
	sample_rate: f32,
	time: usize,
	notes: Vec<Note>,
126
	events: VecDeque<TimedMidiCommand>,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
127

128
	cache: Vec<SoundCache<G>>,
129
	cached_sound_params: G::Parameters,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
130
131
	global: G::Global,

132
133
	params: Arc<RwLockWrapper<SynthPluginParameters<G>>>,

Aske Simon Christensen's avatar
Aske Simon Christensen committed
134
135
136
	phantom: PhantomData<S>
}

137
struct SynthPluginParameters<G: SoundGenerator> {
138
139
	host: Option<HostCallback>,
	values: Vec<f32>,
140
141
	map: HashMap<&'static str, f32>,
	sound_params: G::Parameters,
142
143
144
145
146
147
148
149
150
151
152
153
154
155
	sample_rate: f32,
}

// Work around orphan rule
struct RwLockWrapper<T> {
	inner: RwLock<T>
}

impl<T> Deref for RwLockWrapper<T> {
	type Target = RwLock<T>;

	fn deref(&self) -> &RwLock<T> {
		&self.inner
	}
156
157
}

158
159
160
161
162
163
164
165
fn make_param_map(param_names: &[&'static str], param_values: &[f32]) -> HashMap<&'static str, f32> {
	let mut param_map = HashMap::new();
	for (s, v) in param_names.iter().zip(param_values) {
		param_map.insert(*s, *v);
	}
	param_map
}

Aske Simon Christensen's avatar
Aske Simon Christensen committed
166
167
impl<G: SoundGenerator, S: SynthInfo> Default for SynthPlugin<G, S> {
	fn default() -> Self {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
168
169
		let param_values: Vec<f32> = G::Parameters::names().iter().map(|s| G::Parameters::default_value(s)).collect();
		let param_map = make_param_map(G::Parameters::names(), &param_values);
170
171

		let cache = (0..128).map(|tone| SoundCache::new(tone)).collect();
Aske Simon Christensen's avatar
Aske Simon Christensen committed
172
173
174

		let sample_rate = 44100.0;

175
176
177
		let sound_params = G::Parameters::build(&param_map, sample_rate);

		let params = SynthPluginParameters {
178
179
			host: None,
			values: param_values,
180
			map: param_map,
181
182
			sound_params: sound_params.clone(),
			sample_rate: sample_rate,
183
184
		};

Aske Simon Christensen's avatar
Aske Simon Christensen committed
185
186
187
188
189
		SynthPlugin {
			sample_rate: sample_rate,
			time: 0,
			notes: Vec::new(),
			events: VecDeque::new(),
190
			cache: cache,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
191

192
			cached_sound_params: sound_params,
193
			params: Arc::new(RwLockWrapper { inner: RwLock::new(params) }),
Aske Simon Christensen's avatar
Aske Simon Christensen committed
194
195
196
197
198
199
200
201
202

			global: G::Global::default(),

			phantom: PhantomData
		}
	}
}

impl<G: SoundGenerator, S: SynthInfo> Plugin for SynthPlugin<G, S> {
203
	fn new(host: HostCallback) -> SynthPlugin<G, S> {
204
205
		let plugin = SynthPlugin::default();
		plugin.params.write().unwrap().host = Some(host);
206

207
		plugin
208
209
	}

Aske Simon Christensen's avatar
Aske Simon Christensen committed
210
211
212
	fn get_info(&self) -> Info {
		Info {
			presets: 0,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
213
			parameters: G::Parameters::names().len() as i32,
Aske Simon Christensen's avatar
Aske Simon Christensen committed
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
			inputs: 0,
			outputs: 2,
			category: Category::Synth,
			f64_precision: false,

			.. S::get_info()
		}
	}

	fn can_do(&self, can_do: CanDo) -> Supported {
		match can_do {
			CanDo::ReceiveMidiEvent => Supported::Yes,
			_                       => Supported::No
		}
	}

230
231
232
233
234
	fn process_events(&mut self, events: &Events) {
		for e in events.events() {
			match e {
				Event::Midi(MidiEvent { delta_frames, ref data, .. }) => {
					self.events.push_back(TimedMidiCommand {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
235
						time: self.time + (delta_frames as usize),
236
						command: MidiCommand::from_data(data)
Aske Simon Christensen's avatar
Aske Simon Christensen committed
237
238
239
240
241
242
243
					});
				}
				_ => {}
			}
		}
	}

244
	fn process(&mut self, buffer: &mut AudioBuffer<f32>) {
245
		self.update_cache();
246

Aske Simon Christensen's avatar
Aske Simon Christensen committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
		let mut outputs = buffer.split().1;
		for i in 0..outputs[0].len() {
			while !self.events.is_empty() && self.events.front().unwrap().time == self.time {
				let event = self.events.pop_front().unwrap();
				self.handle_event(event);
			}
			let sample = self.produce_sample();
			outputs[0][i] = sample.left;
			outputs[1][i] = sample.right;
			self.time += 1;
		}
	}

	fn set_sample_rate(&mut self, rate: f32) {
		self.sample_rate = rate;
262
263
264
		let params: &mut SynthPluginParameters<G> = &mut self.params.write().unwrap();
		params.sample_rate = rate;
		params.build_sound_params();
Aske Simon Christensen's avatar
Aske Simon Christensen committed
265
266
	}

267
268
269
270
271
272
	fn get_parameter_object(&mut self) -> Arc<PluginParameters> {
		Arc::clone(&self.params) as Arc<PluginParameters>
	}
}

impl<G: SoundGenerator> PluginParameters for RwLockWrapper<SynthPluginParameters<G>> {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
273
	fn get_parameter_name(&self, index: i32) -> String {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
274
		G::Parameters::names()[index as usize].to_string()
Aske Simon Christensen's avatar
Aske Simon Christensen committed
275
276
277
	}

	fn get_parameter_text(&self, index: i32) -> String {
278
		let params: &SynthPluginParameters<G> = &self.read().unwrap();
279
		params.sound_params.display(G::Parameters::names()[index as usize], &params.map).0
Aske Simon Christensen's avatar
Aske Simon Christensen committed
280
281
282
	}

	fn get_parameter_label(&self, index: i32) -> String {
283
		let params: &SynthPluginParameters<G> = &self.read().unwrap();
284
		params.sound_params.display(G::Parameters::names()[index as usize], &params.map).1
Aske Simon Christensen's avatar
Aske Simon Christensen committed
285
286
287
	}

	fn get_parameter(&self, index: i32) -> f32 {
288
		let params: &SynthPluginParameters<G> = &self.read().unwrap();
289
		params.values[index as usize]
Aske Simon Christensen's avatar
Aske Simon Christensen committed
290
291
	}

292
293
294
	fn set_parameter(&self, index: i32, value: f32) {
		let params: &mut SynthPluginParameters<G> = &mut self.write().unwrap();
		params.values[index as usize] = value;
295

296
297
298
299
300
		if let Some(ref mut host) = params.host {
			for name in G::Parameters::influence(G::Parameters::names()[index as usize]) {
				if let Some(p) = G::Parameters::names().iter().position(|n| *n == name) {
					params.values[p] = infinitesimal_change(params.values[p]).min(1.0);
					host.automate(p as i32, params.values[p]);
301
302
303
304
				}
			}
		}

305
		params.build_sound_params();
Aske Simon Christensen's avatar
Aske Simon Christensen committed
306
307
308
309
	}
}

impl<G: SoundGenerator, S: SynthInfo> SynthPlugin<G, S> {
310
	fn handle_event(&mut self, event: TimedMidiCommand) {
311
		let params: &SynthPluginParameters<G> = &self.params.read().unwrap();
Aske Simon Christensen's avatar
Aske Simon Christensen committed
312
313
		match event.command {
			MidiCommand::NoteOn { key, velocity, .. } => {
314
315
				let attack = G::Parameters::attack(&params.map, self.sample_rate);
				let release = G::Parameters::release(&params.map, self.sample_rate);
316
				let note = Note::new(key, velocity, attack, release, Some(self.sample_rate as usize));
Aske Simon Christensen's avatar
Aske Simon Christensen committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
				self.notes.push(note);
			},
			MidiCommand::NoteOff { key, velocity, .. } => {
				for note in &mut self.notes {
					if note.tone == key && !note.is_released() {
						note.release(velocity);
						break;
					}
				}
			},
			MidiCommand::AllNotesOff { velocity, .. } => {
				for note in &mut self.notes {
					if !note.is_released() {
						note.release(velocity);
					}
				}
			},
			MidiCommand::AllSoundOff { .. } => {
				self.notes.clear();
			},
			MidiCommand::Unknown => {}
		}
	}

	fn produce_sample(&mut self) -> Sample {
		let mut sample: Sample = Sample::from(0.0);
		for i in (0..self.notes.len()).rev() {
			if self.notes[i].is_alive() {
345
				sample += self.notes[i].produce_sample(&mut self.cache, &self.cached_sound_params, &self.global);
Aske Simon Christensen's avatar
Aske Simon Christensen committed
346
347
348
349
350
351
352
			} else {
				self.notes.remove(i);
			}
		}
		sample
	}

353
354
355
356
357
358
359
360
361
362
363
364
	fn update_cache(&mut self) {
		let params: &SynthPluginParameters<G> = &self.params.read().unwrap();
		if params.sound_params != self.cached_sound_params {
			self.cached_sound_params = params.sound_params.clone();
			for c in &mut self.cache {
				c.invalidate();
			}
		}
	}
}

impl<G: SoundGenerator> SynthPluginParameters<G> {
Aske Simon Christensen's avatar
Aske Simon Christensen committed
365
	fn build_sound_params(&mut self) {
366
367
		self.map = make_param_map(G::Parameters::names(), &self.values);
		self.sound_params = G::Parameters::build(&self.map, self.sample_rate);
Aske Simon Christensen's avatar
Aske Simon Christensen committed
368
369
	}
}
370
371

fn infinitesimal_change(value: f32) -> f32 {
372
	let mut bits = value.to_bits();
373
	bits += 1;
374
	f32::from_bits(bits)
375
}