summaryrefslogtreecommitdiff
path: root/muse/synti/zynaddsubfx/Misc/Microtonal.C
blob: 30a3a71e74931e073ddacfb90787f94e6876ab2d (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
  ZynAddSubFX - a software synthesizer
 
  Microtonal.C - Tuning settings and microtonal capabilities
  Copyright (C) 2002-2005 Nasca Octavian Paul
  Author: Nasca Octavian Paul

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License 
  as published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License (version 2) for more details.

  You should have received a copy of the GNU General Public License (version 2)
  along with this program; if not, write to the Free Software Foundation,
  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

*/

#include <math.h>
#include <string.h>
#include "Microtonal.h"

#define MAX_LINE_SIZE 80

Microtonal::Microtonal(){
    Pname=new unsigned char[MICROTONAL_MAX_NAME_LEN];
    Pcomment=new unsigned char[MICROTONAL_MAX_NAME_LEN];
    defaults();
};

void Microtonal::defaults(){
    Pinvertupdown=0;
    Pinvertupdowncenter=60;
    octavesize=12;
    Penabled=0;
    PAnote=69;
    PAfreq=440.0;
    Pscaleshift=64;
    
    Pfirstkey=0;Plastkey=127;
    Pmiddlenote=60;Pmapsize=12;
    Pmappingenabled=0;
    
    for (int i=0;i<128;i++) Pmapping[i]=i;
    
    for (int i=0;i<MAX_OCTAVE_SIZE;i++){
	octave[i].tuning=tmpoctave[i].tuning=pow(2,(i%octavesize+1)/12.0);
	octave[i].type=tmpoctave[i].type=1;
	octave[i].x1=tmpoctave[i].x1=(i%octavesize+1)*100;
	octave[i].x2=tmpoctave[i].x2=0;
    };
    octave[11].type=2;octave[11].x1=2;octave[11].x2=1;
    for (int i=0;i<MICROTONAL_MAX_NAME_LEN;i++){
	Pname[i]='\0';
	Pcomment[i]='\0';
    };
    snprintf((char *) Pname,MICROTONAL_MAX_NAME_LEN,"12tET");
    snprintf((char *) Pcomment,MICROTONAL_MAX_NAME_LEN,"Equal Temperament 12 notes per octave");    
    Pglobalfinedetune=64;
};

Microtonal::~Microtonal(){
    delete (Pname);
    delete (Pcomment);
};

/*
 * Get the size of the octave
 */
unsigned char Microtonal::getoctavesize(){
    if (Penabled!=0) return(octavesize);
	else return(12);
};

/*
 * Get the frequency according the note number
 */
REALTYPE Microtonal::getnotefreq(int note,int keyshift){
    // in this function will appears many times things like this:
    // var=(a+b*100)%b 
    // I had written this way because if I use var=a%b gives unwanted results when a<0
    // This is the same with divisions.
    
    if ((Pinvertupdown!=0)&&((Pmappingenabled==0)||(Penabled==0))) note=(int) Pinvertupdowncenter*2-note;

    //compute global fine detune
    REALTYPE globalfinedetunerap=pow(2.0,(Pglobalfinedetune-64.0)/1200.0);//-64.0 .. 63.0 cents
        
    if (Penabled==0) return(pow(2.0,(note-PAnote+keyshift)/12.0)*PAfreq*globalfinedetunerap);//12tET
    
    int scaleshift=((int)Pscaleshift-64+(int) octavesize*100)%octavesize;

    //compute the keyshift
    REALTYPE rap_keyshift=1.0;
    if (keyshift!=0){
	int kskey=(keyshift+(int)octavesize*100)%octavesize;
	int ksoct=(keyshift+(int)octavesize*100)/octavesize-100;
	rap_keyshift=(kskey==0) ? (1.0):(octave[kskey-1].tuning);
	rap_keyshift*=pow(octave[octavesize-1].tuning,ksoct);
    };

    //if the mapping is enabled
    if (Pmappingenabled!=0){
	if ((note<Pfirstkey)||(note>Plastkey)) return (-1.0);
	//Compute how many mapped keys are from middle note to reference note
	//and find out the proportion between the freq. of middle note and "A" note
	int tmp=PAnote-Pmiddlenote,minus=0;
	if (tmp<0) { tmp=-tmp; minus=1; };
	int deltanote=0;
	for (int i=0;i<tmp;i++) if (Pmapping[i%Pmapsize]>=0) deltanote++;
	REALTYPE rap_anote_middlenote=(deltanote==0) ? (1.0) : (octave[(deltanote-1)%octavesize].tuning);
	if (deltanote!=0) rap_anote_middlenote*=pow(octave[octavesize-1].tuning,(deltanote-1)/octavesize);
	if (minus!=0) rap_anote_middlenote=1.0/rap_anote_middlenote;
	
	//Convert from note (midi) to degree (note from the tunning)
	int degoct=(note-(int)Pmiddlenote+(int) Pmapsize*200)/(int)Pmapsize-200;
	int degkey=(note-Pmiddlenote+(int)Pmapsize*100)%Pmapsize;
	degkey=Pmapping[degkey];
	if (degkey<0) return(-1.0);//this key is not mapped
	
	//invert the keyboard upside-down if it is asked for
	//TODO: do the right way by using Pinvertupdowncenter
	if (Pinvertupdown!=0){
	    degkey=octavesize-degkey-1;
	    degoct=-degoct;
	};
	//compute the frequency of the note
	degkey=degkey+scaleshift;
	degoct+=degkey/octavesize;
	degkey%=octavesize;

	REALTYPE freq=(degkey==0) ? (1.0):octave[degkey-1].tuning;
	freq*=pow(octave[octavesize-1].tuning,degoct);
	freq*=PAfreq/rap_anote_middlenote;
	freq*=globalfinedetunerap;
	if (scaleshift!=0) freq/=octave[scaleshift-1].tuning;
	return(freq*rap_keyshift);
    } else {//if the mapping is disabled
	int nt=note-PAnote+scaleshift;
	int ntkey=(nt+(int)octavesize*100)%octavesize;
	int ntoct=(nt-ntkey)/octavesize;    
    
	REALTYPE oct=octave[octavesize-1].tuning;
	REALTYPE freq=octave[(ntkey+octavesize-1)%octavesize].tuning*pow(oct,ntoct)*PAfreq;
	if (ntkey==0) freq/=oct;
        if (scaleshift!=0) freq/=octave[scaleshift-1].tuning;
//	fprintf(stderr,"note=%d freq=%.3f cents=%d\n",note,freq,(int)floor(log(freq/PAfreq)/log(2.0)*1200.0+0.5));
	freq*=globalfinedetunerap;
    	return(freq*rap_keyshift);
    };
};


/*
 * Convert a line to tunings; returns -1 if it ok
 */
int Microtonal::linetotunings(unsigned int nline,const char *line){
    int x1=-1,x2=-1,type=-1;
    REALTYPE x=-1.0,tmp,tuning=1.0;
    if (strstr(line,"/")==NULL){
	if (strstr(line,".")==NULL){// M case (M=M/1)
	    sscanf(line,"%d",&x1);
	    x2=1;
	    type=2;//division
	} else {// float number case
    	    sscanf(line,"%f",&x);
	    if (x<0.000001) return(1);
	    type=1;//float type(cents)
	};
    } else {// M/N case
	sscanf(line,"%d/%d",&x1,&x2);
	if ((x1<0)||(x2<0)) return(1);
	if (x2==0) x2=1;
	type=2;//division
    };
    
    if (x1<=0) x1=1;//not allow zero frequency sounds (consider 0 as 1)
    
    //convert to float if the number are too big
    if ((type==2)&&((x1>(128*128*128-1))||(x2>(128*128*128-1)))){
	type=1;
	x=((REALTYPE) x1)/x2;
    };
    switch (type){
	case 1:	x1=(int) floor(x);
		tmp=fmod(x,1.0);
		x2=(int) (floor (tmp*1e6));
		tuning=pow(2.0,x/1200.0);
		break;
	case 2:	x=((REALTYPE)x1)/x2;
		tuning=x;
		break;
    };
    
    tmpoctave[nline].tuning=tuning;
    tmpoctave[nline].type=type;
    tmpoctave[nline].x1=x1;
    tmpoctave[nline].x2=x2;
    
    return(-1);//ok
};

/*
 * Convert the text to tunnings
 */
int Microtonal::texttotunings(const char *text){
    unsigned int i,k=0,nl=0;
    char *lin;
    lin=new char[MAX_LINE_SIZE+1];
    while (k<strlen(text)){
	for (i=0;i<MAX_LINE_SIZE;i++){
	    lin[i]=text[k++];
	    if (lin[i]<0x20) break;
	};
	lin[i]='\0';
	if (strlen(lin)==0) continue;
	int err=linetotunings(nl,lin);
	if (err!=-1) {
	    delete [] lin;
	    return(nl);//Parse error
	};
	nl++;
    };
    delete [] lin;
    if (nl>MAX_OCTAVE_SIZE) nl=MAX_OCTAVE_SIZE;
    if (nl==0) return(-2);//the input is empty
    octavesize=nl;
    for (i=0;i<octavesize;i++){
	octave[i].tuning=tmpoctave[i].tuning;
	octave[i].type=tmpoctave[i].type;
	octave[i].x1=tmpoctave[i].x1;
	octave[i].x2=tmpoctave[i].x2;
    };
    return(-1);//ok
};

/*
 * Convert the text to mapping
 */
void Microtonal::texttomapping(const char *text){
    unsigned int i,k=0;
    char *lin;
    lin=new char[MAX_LINE_SIZE+1];
    for (i=0;i<128;i++) Pmapping[i]=-1;
    int tx=0;
    while (k<strlen(text)){
	for (i=0;i<MAX_LINE_SIZE;i++){
	    lin[i]=text[k++];
	    if (lin[i]<0x20) break;
	};
	lin[i]='\0';
	if (strlen(lin)==0) continue;

	int tmp=0;
	if (sscanf(lin,"%d",&tmp)==0) tmp=-1;
	if (tmp<-1) tmp=-1;
	Pmapping[tx]=tmp;
	
	if ((tx++)>127) break;
    };
    delete [] lin;
    
    if (tx==0) tx=1;
    Pmapsize=tx;
};

/*
 * Convert tunning to text line
 */
void Microtonal::tuningtoline(int n,char *line,int maxn){
    if ((n>octavesize) || (n>MAX_OCTAVE_SIZE)) {
	line[0]='\0';
	return;
    };
    if (octave[n].type==1) snprintf(line,maxn,"%d.%d",octave[n].x1,octave[n].x2);
    if (octave[n].type==2) snprintf(line,maxn,"%d/%d",octave[n].x1,octave[n].x2);
};

 
int Microtonal::loadline(FILE *file,char *line){
    do {
    if (fgets(line,500,file)==0) return(1);
    } while (line[0]=='!');
    return(0);
};
/*
 * Loads the tunnings from a scl file
 */
int Microtonal::loadscl(const char *filename){
    FILE *file=fopen(filename, "r");
    char tmp[500];
    fseek(file,0,SEEK_SET);
    //loads the short description
    if (loadline(file,&tmp[0])!=0) return(2);
    for (int i=0;i<500;i++) if (tmp[i]<32) tmp[i]=0;
    snprintf((char *) Pname,MICROTONAL_MAX_NAME_LEN,"%s",tmp);
    snprintf((char *) Pcomment,MICROTONAL_MAX_NAME_LEN,"%s",tmp);
    //loads the number of the notes
    if (loadline(file,&tmp[0])!=0) return(2);
    int nnotes=MAX_OCTAVE_SIZE;
    sscanf(&tmp[0],"%d",&nnotes);
    if (nnotes>MAX_OCTAVE_SIZE) return (2);
    //load the tunnings
    for (int nline=0;nline<nnotes;nline++){
	if (loadline(file,&tmp[0])!=0) return(2);
	linetotunings(nline,&tmp[0]);
    };
    fclose(file);

    octavesize=nnotes;
    for (int i=0;i<octavesize;i++){
	octave[i].tuning=tmpoctave[i].tuning;
	octave[i].type=tmpoctave[i].type;
	octave[i].x1=tmpoctave[i].x1;
	octave[i].x2=tmpoctave[i].x2;
    };

    return(0);
};

/*
 * Loads the mapping from a kbm file
 */
int Microtonal::loadkbm(const char *filename){
    FILE *file=fopen(filename, "r");
    int x;
    char tmp[500];

    fseek(file,0,SEEK_SET);
    //loads the mapsize
    if (loadline(file,&tmp[0])!=0) return(2);
    if (sscanf(&tmp[0],"%d",&x)==0) return(2);
    if (x<1) x=0;if (x>127) x=127;//just in case...
    Pmapsize=x;
    //loads first MIDI note to retune
    if (loadline(file,&tmp[0])!=0) return(2);
    if (sscanf(&tmp[0],"%d",&x)==0) return(2);
    if (x<1) x=0;if (x>127) x=127;//just in case...
    Pfirstkey=x;
    //loads last MIDI note to retune
    if (loadline(file,&tmp[0])!=0) return(2);
    if (sscanf(&tmp[0],"%d",&x)==0) return(2);
    if (x<1) x=0;if (x>127) x=127;//just in case...
    Plastkey=x;
    //loads last the middle note where scale fro scale degree=0
    if (loadline(file,&tmp[0])!=0) return(2);
    if (sscanf(&tmp[0],"%d",&x)==0) return(2);
    if (x<1) x=0;if (x>127) x=127;//just in case...
    Pmiddlenote=x;
    //loads the reference note
    if (loadline(file,&tmp[0])!=0) return(2);
    if (sscanf(&tmp[0],"%d",&x)==0) return(2);
    if (x<1) x=0;if (x>127) x=127;//just in case...
    PAnote=x;
    //loads the reference freq.
    if (loadline(file,&tmp[0])!=0) return(2);
    REALTYPE tmpPAfreq=440.0;
    if (sscanf(&tmp[0],"%f",&tmpPAfreq)==0) return(2);
    PAfreq=tmpPAfreq;

    //the scale degree(which is the octave) is not loaded, it is obtained by the tunnings with getoctavesize() method
    if (loadline(file,&tmp[0])!=0) return(2);

    //load the mappings
    if (Pmapsize!=0){
	for (int nline=0;nline<Pmapsize;nline++){
	    if (loadline(file,&tmp[0])!=0) return(2);
	    if (sscanf(&tmp[0],"%d",&x)==0) x=-1;
	    Pmapping[nline]=x;
	};
	Pmappingenabled=1;
    } else {
	Pmappingenabled=0;
	Pmapping[0]=0;
	Pmapsize=1;
    };
    fclose(file);

    return(0);
};



void Microtonal::add2XML(XMLwrapper *xml){
    xml->addparstr("name",(char *) Pname);
    xml->addparstr("comment",(char *) Pcomment);

    xml->addparbool("invert_up_down",Pinvertupdown);
    xml->addparbool("invert_up_down_center",Pinvertupdowncenter);

    xml->addparbool("enabled",Penabled);
    xml->addpar("global_fine_detune",Pglobalfinedetune);

    xml->addpar("a_note",PAnote);
    xml->addparreal("a_freq",PAfreq);

    if ((Penabled==0)&&(xml->minimal)) return;

    xml->beginbranch("SCALE");
        xml->addpar("scale_shift",Pscaleshift);
	xml->addpar("first_key",Pfirstkey);
	xml->addpar("last_key",Plastkey);
	xml->addpar("middle_note",Pmiddlenote);

	xml->beginbranch("OCTAVE");
	    xml->addpar("octave_size",octavesize);
	    for (int i=0;i<octavesize;i++){
		xml->beginbranch("DEGREE",i);
		    if (octave[i].type==1){			
			xml->addparreal("cents",octave[i].tuning);
		    };
		    if (octave[i].type==2){			
			xml->addpar("numerator",octave[i].x1);
			xml->addpar("denominator",octave[i].x2);
		    };
		xml->endbranch();
	    };
	xml->endbranch();

	xml->beginbranch("KEYBOARD_MAPPING");
	    xml->addpar("map_size",Pmapsize);
	    xml->addpar("mapping_enabled",Pmappingenabled);
		for (int i=0;i<Pmapsize;i++){
		    xml->beginbranch("KEYMAP",i);
			xml->addpar("degree",Pmapping[i]);
		    xml->endbranch();
		};
	xml->endbranch();
    xml->endbranch();
};

void Microtonal::getfromXML(XMLwrapper *xml){
    xml->getparstr("name",(char *) Pname,MICROTONAL_MAX_NAME_LEN);
    xml->getparstr("comment",(char *) Pcomment,MICROTONAL_MAX_NAME_LEN);

    Pinvertupdown=xml->getparbool("invert_up_down",Pinvertupdown);
    Pinvertupdowncenter=xml->getparbool("invert_up_down_center",Pinvertupdowncenter);

    Penabled=xml->getparbool("enabled",Penabled);
    Pglobalfinedetune=xml->getpar127("global_fine_detune",Pglobalfinedetune);

    PAnote=xml->getpar127("a_note",PAnote);
    PAfreq=xml->getparreal("a_freq",PAfreq,1.0,10000.0);

    if (xml->enterbranch("SCALE")){
	Pscaleshift=xml->getpar127("scale_shift",Pscaleshift);
	Pfirstkey=xml->getpar127("first_key",Pfirstkey);
	Plastkey=xml->getpar127("last_key",Plastkey);
	Pmiddlenote=xml->getpar127("middle_note",Pmiddlenote);

	if (xml->enterbranch("OCTAVE")){
	    octavesize=xml->getpar127("octave_size",octavesize);
	    for (int i=0;i<octavesize;i++){
		if (xml->enterbranch("DEGREE",i)==0) continue;
		    octave[i].x2=0;
		    octave[i].tuning=xml->getparreal("cents",octave[i].tuning);
		    octave[i].x1=xml->getpar127("numerator",octave[i].x1);
		    octave[i].x2=xml->getpar127("denominator",octave[i].x2);
		    
		    if (octave[i].x2!=0) octave[i].type=2; 
			else octave[i].type=1;
		    
		xml->exitbranch();
	    };
	    xml->exitbranch();
	};

	if (xml->enterbranch("KEYBOARD_MAPPING")){
	    Pmapsize=xml->getpar127("map_size",Pmapsize);
	    Pmappingenabled=xml->getpar127("mapping_enabled",Pmappingenabled);
		for (int i=0;i<Pmapsize;i++){
		    if (xml->enterbranch("KEYMAP",i)==0) continue;
			Pmapping[i]=xml->getpar127("degree",Pmapping[i]);
		    xml->exitbranch();
		};
	    xml->exitbranch();
	};
	xml->exitbranch();
    };
};


int Microtonal::saveXML(char *filename){
    XMLwrapper *xml=new XMLwrapper();

    xml->beginbranch("MICROTONAL");
    add2XML(xml);
    xml->endbranch();

    int result=xml->saveXMLfile(filename);
    delete (xml);
    return(result);
};

int Microtonal::loadXML(char *filename){
    XMLwrapper *xml=new XMLwrapper();
    if (xml->loadXMLfile(filename)<0) {
	delete(xml);
	return(-1);
    };
    
    if (xml->enterbranch("MICROTONAL")==0) return(-10);
	getfromXML(xml);
    xml->exitbranch();
    
    delete(xml);
    return(0);
};