Debian Codegraph @

examples/deep/dither.ck

raw
1 // dither.ck
2 // demo of dithering
3 //
4 // can use any UGen as source in play_with_dither()
5 // qbits : number of bits to quantize to
6 // do_dither : whether to dither
7 //
8 // gewang
9
10 // patch
11 Impulse imp => dac;
12
13 // sine wave generator
14 SinOsc s => blackhole;
15 220 => s.freq;
16
17 // go
18 play_with_dither( s, 2::second, 6, false );
19 play_with_dither( s, 2::second, 6, true );
20 .5::second => now;
21
22 play_with_dither( s, 2::second, 5, false );
23 play_with_dither( s, 2::second, 5, true );
24 .5::second => now;
25
26 play_with_dither( s, 2::second, 4, false );
27 play_with_dither( s, 2::second, 4, true );
28 .5::second => now;
29
30 // dither
31 fun void play_with_dither( UGen src, dur T, int qbits, int do_dither )
32 {
33 // sanity check
34 if( qbits <= 0 || qbits > 24 )
35 {
36 <<< "quantization bits out of range (1-24)", "" >>>;
37 return;
38 }
39
40 // loop
41 float sample;
42 int quantized;
43 (1 << 24) => int max;
44 while( T > 0::second )
45 {
46 // get the last sample
47 src.last() => sample;
48 // quantize it
49 if( do_dither ) // dither
50 ((sample + Math.random2f(0,Math.pow(2,-qbits))) * max) $ int => quantized;
51 else // no dither
52 (sample * max) $ int => quantized;
53
54 // throw away extra resolution
55 quantized >> (24-qbits) << (24-qbits) => quantized;
56 // cast it back for playback
57 (quantized $ float) / max => imp.next;
58 // advance time
59 1::samp => now;
60 // decrement
61 1::samp -=> T;
62 }
63 }
64