summaryrefslogtreecommitdiff
path: root/lib/SampOsc.ck
blob: 398e087c64a74384249803486d8758b28fe7f697 (plain)
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
/*
 * Sample based oscillator
 */
public class SampOsc extends Chubgraph {
	static string @__sourceDir; /* pseudo-private */

	inlet => blackhole;
	inlet.last() => float __last_in; /* pseudo-private */
	1 => float __freq; /* pseudo-private */
	SndBuf __buf => outlet; /* pseudo-private */

	fun float
	freq(float f)
	{
		return f => __freq;
	}
	fun float
	freq()
	{
		if (inlet.last() != __last_in)
			inlet.last() => __last_in => __freq;
		return __freq;
	}

	/*
	 * __buf shortcuts
	 */
	fun void
	read(string file)
	{
		file => __buf.read;
	}
	fun float
	rate(float v)
	{
		return v => __buf.rate;
	}
	fun float
	rate()
	{
		return __buf.rate();
	}

	/*
	 * Wait till next loop point but no longer than `max_latency',
	 * so frequency changes get applied with a maximum of 100::ms latency.
	 * NOTE: Due to a ChucK bug (?), simply killing and restarting the shred
	 * does not work very well.
	 */
	100::ms => dur max_latency;

	fun void
	__loop() /* pseudo-private */
	{
		now => time last_trigger;

		while (second/freq() => dur interval) {
			if (last_trigger+interval - now > max_latency) {
				max_latency => now;
			} else {
				interval +=> last_trigger;
				if (last_trigger > now)
					last_trigger => now;
				0 => __buf.pos;
			}
		}

		/* never reached */
	}
	spork ~ __loop();

	__sourceDir+"/pulse.wav" => read;
	1 => rate;
}
/* static initialization */
me.sourceDir() => SampOsc.__sourceDir;
/* BUG WORKAROUND: me.sourceDir() == "" if VM is started with --loop */
if (SampOsc.__sourceDir == "")
	"lib" => SampOsc.__sourceDir;