Added an uninterpolated sine table generator. Renamed default org.
[cantaveria.git] / org.c
blob6d4bf9b922f789cce8f6a6f47fc3eed718969dc1
1 /*
2 org.c
3 various software synths and samples
5 Copyright (C) 2009 Evan Rinehart
7 This software comes with no warranty.
8 1. This software can be used for any purpose, good or evil.
9 2. Modifications must retain this license, at least in spirit.
12 #include <stdlib.h>
13 #include <math.h>
15 #include <org.h>
18 heres a list of instrument ideas...
20 piano (not sure yet)
21 brass (not sure yet)
22 string (not sure yet)
23 drum (probably samples)
24 bass kick (classic analog algorithm)
25 square triangle saw (polyblep ?)
26 wind instruments (additive synth via uninterpolated table)
27 sampler (perhaps a compressed array of samples)
28 rendered ambient (PADsynth)
32 /* SINE TABLE */
33 #define TABLE_SIZE (1<<13)
34 float sine_table[TABLE_SIZE];
36 int note2tablestep(int note){
37 /* critical formula for tuning a table */
38 /* table steps for 2pif/SAMPLE_RATE radians is...*/
39 /* TABLE_SIZE/PI2 == entries per radian */
40 /* step == 2pif/SAMPLE_RATE * (TABLE_SIZE/PI2) */
41 /* == f * TABLE_SIZE / SAMPLE_RATE */
42 /* == f_0 2^(note/12) TABLE_SIZE / SAMPLE_RATE */
43 return 440*pow(2, note/12.0)*TABLE_SIZE / SAMPLE_RATE;
46 float note2wavestep(int note){
47 /* critical formula for tuning */
48 /* delta(omega*t) == wave increment */
49 /* == 2 pi f / samp_rate */
50 /* == 2pi f_0 2^(note/12) / samp_rate */
51 return 440*PI2*pow(2, note/12.0)/SAMPLE_RATE;
57 /* ORG_DEFAULT: default fallback instrument */
58 struct defstate {
59 int on;
60 int step;
61 int ptr;
64 void default_mix(void* ud, float out[], int count){
65 struct defstate* data = ud;
66 int i;
68 if(data->on == 0) return;
70 for(i=0; i<count; i++){
71 out[i] += sine_table[data->ptr];
72 data->ptr += data->step;
73 while(data->ptr >= TABLE_SIZE){
74 data->ptr -= TABLE_SIZE;
79 void default_control(void* ud, int type, int val1, int val2, int val){
80 struct defstate* data = ud;
81 switch(type){
82 case EV_NOTEON:
83 data->step = note2tablestep(val1);
84 data->on = 1;
85 break;
86 case EV_NOTEOFF:
87 if(data->step == note2tablestep(val1)){
88 data->on = 0;
90 break;
94 void default_cleanup(void* data){ free(data); }
96 instrument make_default(){
97 instrument ins;
98 struct defstate* data = malloc(sizeof(struct defstate));
99 data->on = 0;
100 data->step = 100;
101 ins.mix = default_mix;
102 ins.control = default_control;
103 ins.cleanup = default_cleanup;
104 ins.data = data;
105 return ins;
114 /*** exported methods ***/
115 instrument load_instrument(enum instrument_name name){
116 switch(name){
117 case ORG_DEFAULT: return make_default();
118 // case ORG_COOL: return make_cool();
119 default: return make_default();
124 void org_init(){
125 int i;
126 for(i=0; i<TABLE_SIZE; i++){
127 sine_table[i] = sin( (PI2*i) / TABLE_SIZE);