1
2declare name "subtractive -- saw wave filtered with resonant lowpass";
3declare author "Albert Graef";
4declare version "1.0";
5
6import("music.lib");
7
8// control variables
9
10// master volume and pan
11vol	= hslider("vol", 0.3, 0, 10, 0.01);	// %
12pan	= hslider("pan", 0.5, 0, 1, 0.01);	// %
13
14// ADSR envelop
15attack	= hslider("attack", 0.01, 0, 1, 0.001);	// sec
16decay	= hslider("decay", 0.3, 0, 1, 0.001);	// sec
17sustain = hslider("sustain", 0.5, 0, 1, 0.01);	// %
18release = hslider("release", 0.2, 0, 1, 0.001);	// sec
19
20// filter parameters
21res	= hslider("resonance (dB)", 3, 0, 20, 0.1);
22cutoff	= hslider("cutoff (harmonic)", 6, 1, 20, 0.1);
23
24// voice parameters
25freq	= nentry("freq", 440, 20, 20000, 1);	// Hz
26gain	= nentry("gain", 1, 0, 10, 0.01);	// %
27gate	= button("gate");			// 0/1
28
29// generic table-driven oscillator with phase modulation
30
31// n	= the size of the table, must be a power of 2
32// f	= the wave function, must be defined on the range [0,2*PI]
33// freq	= the desired frequency in Hz
34// mod	= the phase modulation signal, in radians
35
36tblosc(n,f,freq,mod)	= (1-d)*rdtable(n,wave,i&(n-1)) +
37			  d*rdtable(n,wave,(i+1)&(n-1))
38with {
39	wave	 	= time*(2.0*PI)/n : f;
40	phase		= freq/SR : (+ : decimal) ~ _;
41	modphase	= decimal(phase+mod/(2*PI))*n;
42	i		= int(floor(modphase));
43	d		= decimal(modphase);
44};
45
46// resonant lowpass
47
48// This is a tweaked Butterworth filter by David Werner and Patrice Tarrabia,
49// see http://www.musicdsp.org and http://www.experimentalscene.com for
50// details.
51
52// res = resonance in dB above DC gain
53// freq = cutoff frequency
54
55lowpass(res,freq)	= f : (+ ~ g) : *(a)
56with {
57	f(x)	= a0*x+a1*x'+a2*x'';
58	g(y)	= 0-b1*y-b2*y';
59	a	= 1/db2linear(0.5*res);
60
61	c	= 1.0/tan(PI*(freq/SR));
62	c2	= c*c;
63	r	= 1/db2linear(2.0*res);
64	q	= sqrt(2.0)*r;
65	a0	= 1.0/(1.0+(q*c)+(c2));
66	a1	= 2.0*a0;
67	a2	= a0;
68	b1	= 2.0*a0*(1.0-c2);
69	b2	= a0*(1.0-q*c+c2);
70};
71
72// subtractive synth (saw wave passed through resonant lowpass)
73
74saw(x)	= x/PI-1;
75
76smooth(c) = *(1-c) : +~*(c);
77
78process	= tblosc(1<<16, saw, freq, 0) : ((env,freq,_) : filter) :
79	  *(env * (gain/*:smooth(0.999)*/))
80        : vgroup("3-master", *(vol) : panner(pan))
81with {
82  env = gate : vgroup("1-adsr", adsr(attack, decay, sustain, release));
83  filter(env,freq)
84      = vgroup("2-filter", lowpass(env*res, fmax(1/cutoff, env)*freq*cutoff));
85};
86