1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2005 Masanao Izumo <iz@onicos.co.jp>
4     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
5 
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10 
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15 
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 
20     This code from awesfx
21     Modified by Masanao Izumo <mo@goice.co.jp>
22 
23     ================================================================
24     parsesf.c
25          parse SoundFont layers and convert it to AWE driver patch
26 
27     Copyright (C) 1996,1997 Takashi Iwai
28     ================================================================
29 */
30 
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <math.h>
35 
36 #include "timidity.h"
37 #include "common.h"
38 #include "tables.h"
39 #include "instrum.h"
40 #include "playmidi.h"
41 #include "filter.h"
42 #include "freq.h"
43 #include "resample.h"
44 
45 namespace TimidityPlus
46 {
47 
48 #define SFMalloc(rec, count)      new_segment(&(rec)->pool, count)
49 #define SFStrdup(rec, s)          strdup_mblock(&(rec)->pool, s)
50 
51 /*----------------------------------------------------------------
52  * compile flags
53  *----------------------------------------------------------------*/
54 
55 
56 /* return value */
57 #define AWE_RET_OK		0	/* successfully loaded */
58 #define AWE_RET_ERR		1	/* some fatal error occurs */
59 #define AWE_RET_SKIP		2	/* some fonts are skipped */
60 #define AWE_RET_NOMEM		3	/* out or memory; not all fonts loaded */
61 #define AWE_RET_NOT_FOUND	4	/* the file is not found */
62 
63 /*----------------------------------------------------------------
64  * local parameters
65  *----------------------------------------------------------------*/
66 
67 struct SFPatchRec
68 {
69 	int preset, bank, keynote; /* -1 = matches all */
70 };
71 
72 struct SampleList
73 {
74 	Sample v;
75 	SampleList *next;
76 	int32_t start;
77 	int32_t len;
78 	int32_t cutoff_freq;
79 	int16_t resonance;
80 	int16_t root, tune;
81 	char low, high;		/* key note range */
82 	int8_t reverb_send, chorus_send;
83 
84 	/* Depend on playback_rate */
85 	int32_t vibrato_freq;
86 	int32_t attack;
87 	int32_t hold;
88 	int32_t sustain;
89 	int32_t decay;
90 	int32_t release;
91 
92 	int32_t modattack;
93 	int32_t modhold;
94 	int32_t modsustain;
95 	int32_t moddecay;
96 	int32_t modrelease;
97 
98 	int bank, keynote;	/* for drum instruments */
99 };
100 
101 struct InstList {
102 	SFPatchRec pat;
103 	int pr_idx;
104 	int samples;
105 	int order;
106 	SampleList *slist;
107 	InstList *next;
108 };
109 
110 struct SFExclude {
111 	SFPatchRec pat;
112 	SFExclude *next;
113 };
114 
115 struct SFOrder {
116 	SFPatchRec pat;
117 	int order;
118 	SFOrder *next;
119 };
120 
121 #define INSTHASHSIZE 127
122 #define INSTHASH(bank, preset, keynote) \
123 	((int)(((unsigned)bank ^ (unsigned)preset ^ (unsigned)keynote) % INSTHASHSIZE))
124 
125 struct SFInsts {
126 	timidity_file *tf;
127 	char *fname;
128 	int8_t def_order, def_cutoff_allowed, def_resonance_allowed;
129 	uint16_t version, minorversion;
130 	int32_t samplepos, samplesize;
131 	InstList *instlist[INSTHASHSIZE];
132 	char **inst_namebuf;
133 	SFExclude *sfexclude;
134 	SFOrder *sforder;
135 	SFInsts *next;
136 	double amptune;
137 	MBlockList pool;
138 };
139 
140 /*----------------------------------------------------------------*/
141 
142 /* prototypes */
143 
144 #define P_GLOBAL	1
145 #define P_LAYER		2
146 #define def_drum_inst 0
147 
148 
149 /*----------------------------------------------------------------*/
150 
151 
find_soundfont(char * sf_file)152 SFInsts *Instruments::find_soundfont(char *sf_file)
153 {
154     SFInsts *sf;
155 
156     for(sf = sfrecs; sf != NULL; sf = sf->next)
157 	if(sf->fname != NULL && strcmp(sf->fname, sf_file) == 0)
158 	    return sf;
159     return NULL;
160 }
161 
new_soundfont(char * sf_file)162 SFInsts *Instruments::new_soundfont(char *sf_file)
163 {
164 	SFInsts *sf, *prev;
165 
166 	for(sf = sfrecs, prev = NULL; sf != NULL; prev = sf, sf = sf->next)
167 	{
168 		if(sf->fname == NULL)
169 		{
170 			/* remove the record from the chain to reuse */
171 			if (prev != NULL)
172 				prev->next = sf->next;
173 			else if (sfrecs == sf)
174 				sfrecs = sf->next;
175 			break;
176 		}
177 	}
178 	if(sf == NULL)
179 		sf = (SFInsts *)safe_malloc(sizeof(SFInsts));
180 	memset(sf, 0, sizeof(SFInsts));
181 	init_mblock(&sf->pool);
182 	sf->fname = SFStrdup(sf, sf_file);
183 	sf->def_order = DEFAULT_SOUNDFONT_ORDER;
184 	sf->amptune = 1.0;
185 	return sf;
186 }
187 
add_soundfont(char * sf_file,int sf_order,int sf_cutoff,int sf_resonance,int amp)188 void Instruments::add_soundfont(char *sf_file, int sf_order, int sf_cutoff, int sf_resonance, int amp)
189 {
190     SFInsts *sf;
191 
192     if((sf = find_soundfont(sf_file)) == NULL)
193     {
194         sf = new_soundfont(sf_file);
195         sf->next = sfrecs;
196         sfrecs = sf;
197     }
198 
199     if(sf_order >= 0)
200         sf->def_order = sf_order;
201     if(sf_cutoff >= 0)
202         sf->def_cutoff_allowed = sf_cutoff;
203     if(sf_resonance >= 0)
204         sf->def_resonance_allowed = sf_resonance;
205     if(amp >= 0)
206         sf->amptune = (double)amp * 0.01;
207     current_sfrec = sf;
208 }
209 
remove_soundfont(char * sf_file)210 void Instruments::remove_soundfont(char *sf_file)
211 {
212     SFInsts *sf;
213 
214     if((sf = find_soundfont(sf_file)) != NULL)
215 	end_soundfont(sf);
216 }
217 
free_soundfonts()218 void Instruments::free_soundfonts()
219 {
220 	SFInsts *sf, *next;
221 
222 	for (sf = sfrecs; sf != NULL; sf = next) {
223 		if (sf->tf != nullptr) tf_close(sf->tf);
224 		sf->tf = nullptr;
225 		reuse_mblock(&sf->pool);
226 		next = sf->next;
227 		free(sf);
228 	}
229 }
230 
soundfont_preset_name(int bank,int preset,int keynote,char ** sndfile)231 char *Instruments::soundfont_preset_name(int bank, int preset, int keynote,
232 			    char **sndfile)
233 {
234     SFInsts *rec;
235     if(sndfile != NULL)
236 	*sndfile = NULL;
237     for(rec = sfrecs; rec != NULL; rec = rec->next)
238 	if(rec->fname != NULL)
239 	{
240 	    int addr;
241 	    InstList *ip;
242 
243 	    addr = INSTHASH(bank, preset, keynote);
244 	    for(ip = rec->instlist[addr]; ip; ip = ip->next)
245 		if(ip->pat.bank == bank && ip->pat.preset == preset &&
246 		   (keynote < 0 || keynote == ip->pat.keynote))
247 		    break;
248 	    if(ip != NULL)
249 	    {
250 		if(sndfile != NULL)
251 		    *sndfile = rec->fname;
252 		return rec->inst_namebuf[ip->pr_idx];
253 	    }
254 	}
255     return NULL;
256 }
257 
init_sf(SFInsts * rec)258 void Instruments::init_sf(SFInsts *rec)
259 {
260 	SFInfo sfinfo;
261 	int i;
262 
263 	if ((rec->tf = open_file(rec->fname, sfreader)) == NULL) {
264 		printMessage(CMSG_ERROR, VERB_NORMAL,
265 			  "Can't open soundfont file %s", rec->fname);
266 		end_soundfont(rec);
267 		return;
268 	}
269 
270 	// SoundFont spec, 7.2: ... contains a minimum of two records, one record for each preset and one for a terminal record
271 	if(load_soundfont(&sfinfo, rec->tf) || sfinfo.npresets < 2)
272 	{
273 	    end_soundfont(rec);
274 	    return;
275 	}
276 
277 	correct_samples(&sfinfo);
278 	current_sfrec = rec;
279 	for (i = 0; i < sfinfo.npresets - 1; i++) {
280 		int bank = sfinfo.preset[i].bank;
281 		int preset = sfinfo.preset[i].preset;
282 
283 		if (bank == 128)
284 		    /* FIXME: why not allow exclusion of drumsets? */
285 		    alloc_instrument_bank(1, preset);
286 		else {
287 			if (is_excluded(rec, bank, preset, -1))
288 				continue;
289 			alloc_instrument_bank(0, bank);
290 		}
291 		load_font(&sfinfo, i);
292 	}
293 
294 	/* copy header info */
295 	rec->version = sfinfo.version;
296 	rec->minorversion = sfinfo.minorversion;
297 	rec->samplepos = sfinfo.samplepos;
298 	rec->samplesize = sfinfo.samplesize;
299 	rec->inst_namebuf =
300 	    (char **)SFMalloc(rec, sfinfo.npresets * sizeof(char *));
301 	for(i = 0; i < sfinfo.npresets; i++)
302 	    rec->inst_namebuf[i] =
303 		(char *)SFStrdup(rec, sfinfo.preset[i].hdr.name);
304 	free_soundfont(&sfinfo);
305 
306 	if (opt_sf_close_each_file) {
307 		tf_close(rec->tf);
308 		rec->tf = NULL;
309 	}
310 }
311 
init_load_soundfont(void)312 void Instruments::init_load_soundfont(void)
313 {
314     SFInsts *rec;
315     for(rec = sfrecs; rec != NULL; rec = rec->next)
316 	if(rec->fname != NULL)
317 	    init_sf(rec);
318 }
319 
end_soundfont(SFInsts * rec)320 void Instruments::end_soundfont(SFInsts *rec)
321 {
322 	if (rec->tf) {
323 		tf_close(rec->tf);
324 		rec->tf = NULL;
325 	}
326 
327 	rec->fname = NULL;
328 	rec->inst_namebuf = NULL;
329 	rec->sfexclude = NULL;
330 	rec->sforder = NULL;
331 	reuse_mblock(&rec->pool);
332 }
333 
extract_soundfont(char * sf_file,int bank,int preset,int keynote)334 Instrument *Instruments::extract_soundfont(char *sf_file, int bank, int preset,int keynote)
335 {
336     SFInsts *sf;
337 
338     if((sf = find_soundfont(sf_file)) != NULL)
339 	return try_load_soundfont(sf, -1, bank, preset, keynote);
340     sf = new_soundfont(sf_file);
341     sf->next = sfrecs;
342     sf->def_order = 2;
343     sfrecs = sf;
344     init_sf(sf);
345     return try_load_soundfont(sf, -1, bank, preset, keynote);
346 }
347 
348 /*----------------------------------------------------------------
349  * get converted instrument info and load the wave data from file
350  *----------------------------------------------------------------*/
351 
try_load_soundfont(SFInsts * rec,int order,int bank,int preset,int keynote)352 Instrument *Instruments::try_load_soundfont(SFInsts *rec, int order, int bank,int preset, int keynote)
353 {
354 	InstList *ip;
355 	Instrument *inst = NULL;
356 	int addr;
357 
358 	if (rec->tf == NULL) {
359 		if (rec->fname == NULL)
360 			return NULL;
361 		if ((rec->tf = open_file(rec->fname, sfreader)) == NULL)
362 		{
363 			printMessage(CMSG_ERROR, VERB_NORMAL,
364 				  "Can't open soundfont file %s", rec->fname);
365 			end_soundfont(rec);
366 			return NULL;
367 		}
368 	}
369 
370 	addr = INSTHASH(bank, preset, keynote);
371 	for (ip = rec->instlist[addr]; ip; ip = ip->next) {
372 		if (ip->pat.bank == bank && ip->pat.preset == preset &&
373 		    (keynote < 0 || ip->pat.keynote == keynote) &&
374 		    (order < 0 || ip->order == order))
375 			break;
376 	}
377 
378 	if (ip && ip->samples)
379 		inst = load_from_file(rec, ip);
380 
381 	if (opt_sf_close_each_file) {
382 		tf_close(rec->tf);
383 		rec->tf = NULL;
384 	}
385 
386 	return inst;
387 }
388 
load_soundfont_inst(int order,int bank,int preset,int keynote)389 Instrument *Instruments::load_soundfont_inst(int order, int bank, int preset, int keynote)
390 {
391     SFInsts *rec;
392     Instrument *ip;
393     /*
394      * Search through all ordered soundfonts
395      */
396     int o = order;
397 
398     for(rec = sfrecs; rec != NULL; rec = rec->next)
399     {
400 	if(rec->fname != NULL)
401 	{
402 	    ip = try_load_soundfont(rec, o, bank, preset, keynote);
403 	    if(ip != NULL)
404 		return ip;
405 	    if (o > 0) o++;
406 	}
407     }
408     return NULL;
409 }
410 
411 /*----------------------------------------------------------------*/
412 #define TO_MHZ(abscents) (int32_t)(8176.0 * pow(2.0,(double)(abscents)/1200.0))
413 #define TO_VOLUME(level)  (uint8_t)(255.0 - (level) * (255.0/1000.0))
414 
calc_volume(LayerTable * tbl)415 double Instruments::calc_volume(LayerTable *tbl)
416 {
417     int v;
418 
419     if(!tbl->set[SF_initAtten] || (int)tbl->val[SF_initAtten] == 0)
420 	return (double)1.0;
421 
422 	v = (int)tbl->val[SF_initAtten];
423     if(v < 0) {v = 0;}
424     else if(v > 960) {v = 960;}
425 	return cb_to_amp_table[v];
426 }
427 
428 /* convert from 16bit value to fractional offset (15.15) */
to_offset(int32_t offset)429 int32_t Instruments::to_offset(int32_t offset)
430 {
431 	return offset << 14;
432 }
433 
434 #define SF_ENVRATE_MAX (0x3FFFFFFFL)
435 #define SF_ENVRATE_MIN (1L)
436 
437 /* calculate ramp rate in fractional unit;
438  * diff = 16bit, time = msec
439  */
calc_rate(int32_t diff,double msec)440 int32_t Instruments::calc_rate(int32_t diff, double msec)
441 {
442     double rate;
443 
444     if(msec == 0) {return (int32_t)SF_ENVRATE_MAX + 1;}
445     if(diff <= 0) {diff = 1;}
446     diff <<= 14;
447     rate = ((double)diff / playback_rate) * control_ratio * 1000.0 / msec;
448     if(fast_decay) {rate *= 2;}
449 	if(rate > SF_ENVRATE_MAX) {rate = SF_ENVRATE_MAX;}
450 	else if(rate < SF_ENVRATE_MIN) {rate = SF_ENVRATE_MIN;}
451     return (int32_t)rate;
452 }
453 
454 /* calculate ramp rate in fractional unit;
455  * diff = 16bit, timecent
456  */
to_rate(int32_t diff,int timecent)457 int32_t Instruments::to_rate(int32_t diff, int timecent)
458 {
459     double rate;
460 
461     if(timecent == -12000)	/* instantaneous attack */
462 	{return (int32_t)SF_ENVRATE_MAX + 1;}
463     if(diff <= 0) {diff = 1;}
464     diff <<= 14;
465     rate = (double)diff * control_ratio / playback_rate / pow(2.0, (double)timecent / 1200.0);
466     if(fast_decay) {rate *= 2;}
467 	if(rate > SF_ENVRATE_MAX) {rate = SF_ENVRATE_MAX;}
468 	else if(rate < SF_ENVRATE_MIN) {rate = SF_ENVRATE_MIN;}
469     return (int32_t)rate;
470 }
471 
472 /*
473  * convert timecents to sec
474  */
to_msec(int timecent)475 double Instruments::to_msec(int timecent)
476 {
477     return timecent == -12000 ? 0 : 1000.0 * pow(2.0, (double)timecent / 1200.0);
478 }
479 
480 /*
481  * Sustain level
482  * sf: centibels
483  * parm: 0x7f - sustain_level(dB) * 0.75
484  */
calc_sustain(int sust_cB)485 int32_t Instruments::calc_sustain(int sust_cB)
486 {
487 	if(sust_cB <= 0) {return 65533;}
488 	else if(sust_cB >= 1000) {return 0;}
489 	else {return (1000 - sust_cB) * 65533 / 1000;}
490 }
491 
load_from_file(SFInsts * rec,InstList * ip)492 Instrument *Instruments::load_from_file(SFInsts *rec, InstList *ip)
493 {
494 	SampleList *sp;
495 	Instrument *inst;
496 	int i;
497 	int32_t len;
498 
499 	inst = (Instrument *)safe_malloc(sizeof(Instrument));
500 	inst->instname = rec->inst_namebuf[ip->pr_idx];
501 	inst->type = INST_SF2;
502 	inst->samples = ip->samples;
503 	inst->sample = (Sample *)safe_malloc(sizeof(Sample) * ip->samples);
504 	memset(inst->sample, 0, sizeof(Sample) * ip->samples);
505 	for (i = 0, sp = ip->slist; i < ip->samples && sp; i++, sp = sp->next) {
506 		Sample *sample = inst->sample + i;
507 		int32_t j;
508 #ifdef _BIG_ENDIAN_
509 		int32_t k;
510 		int16_t *tmp, s;
511 #endif
512 		memcpy(sample, &sp->v, sizeof(Sample));
513 		sample->data = NULL;
514 		sample->data_alloced = 0;
515 
516 		if(i > 0 && (!sample->note_to_use ||
517 			     (sample->modes & MODES_LOOPING)))
518 		{
519 		    SampleList *sps;
520 		    Sample *found, *s;
521 
522 		    found = NULL;
523 		    for(j = 0, sps = ip->slist, s = inst->sample; j < i && sps;
524 			j++, sps = sps->next, s++)
525 		    {
526 			if(s->data == NULL)
527 			    break;
528 			if(sp->start == sps->start)
529 			{
530 			    if(antialiasing_allowed)
531 			    {
532 				 if(sample->data_length != s->data_length ||
533 				    sample->sample_rate != s->sample_rate)
534 				     continue;
535 			    }
536 			    if(s->note_to_use && !(s->modes & MODES_LOOPING))
537 				continue;
538 			    found = s;
539 			    break;
540 			}
541 		    }
542 		    if(found)
543 		    {
544 			sample->data = found->data;
545 			sample->data_alloced = 0;
546 			continue;
547 		    }
548 		}
549 
550 		sample->data = (sample_t *)safe_large_malloc(sp->len + 2 * 3);
551 		sample->data_alloced = 1;
552 
553 		tf_seek(rec->tf, sp->start, SEEK_SET);
554 		tf_read(sample->data, sp->len, rec->tf);
555 
556 #ifdef _BIG_ENDIAN_
557 		tmp = (int16_t*)sample->data;
558 		k = sp->len / 2;
559 		for (j = 0; j < k; j++) {
560 			s = LE_SHORT(*tmp);
561 			*tmp++ = s;
562 		}
563 #endif
564 		/* set a small blank loop at the tail for avoiding abnormal loop. */
565 		len = sp->len / 2;
566 		sample->data[len] = sample->data[len + 1] = sample->data[len + 2] = 0;
567 
568 		if (antialiasing_allowed)
569 		    antialiasing((int16_t *)sample->data,
570 				 sample->data_length >> FRACTION_BITS,
571 				 sample->sample_rate,
572 				 playback_rate);
573 
574 		/* resample it if possible */
575 		if (sample->note_to_use && !(sample->modes & MODES_LOOPING))
576 			pre_resample(sample);
577 
578 		/* do pitch detection on drums if surround chorus is used */
579 		if (ip->pat.bank == 128 && timidity_surround_chorus)
580 		{
581 			Freq freq;
582 		    sample->chord = -1;
583 		    sample->root_freq_detected =
584 		    	freq.freq_fourier(sample, &(sample->chord));
585 		    sample->transpose_detected =
586 			assign_pitch_to_freq(sample->root_freq_detected) -
587 			assign_pitch_to_freq(sample->root_freq / 1024.0);
588 		}
589 	}
590 
591 	return inst;
592 }
593 
594 
595 /*----------------------------------------------------------------
596  * excluded samples
597  *----------------------------------------------------------------*/
598 
exclude_soundfont(int bank,int preset,int keynote)599 int Instruments::exclude_soundfont(int bank, int preset, int keynote)
600 {
601 	SFExclude *exc;
602 	if(current_sfrec == NULL)
603 	    return 1;
604 	exc = (SFExclude*)SFMalloc(current_sfrec , sizeof(SFExclude));
605 	exc->pat.bank = bank;
606 	exc->pat.preset = preset;
607 	exc->pat.keynote = keynote;
608 	exc->next = current_sfrec->sfexclude;
609 	current_sfrec->sfexclude = exc;
610 	return 0;
611 }
612 
613 /* check the instrument is specified to be excluded */
is_excluded(SFInsts * rec,int bank,int preset,int keynote)614 int Instruments::is_excluded(SFInsts *rec, int bank, int preset, int keynote)
615 {
616 	SFExclude *p;
617 	for (p = rec->sfexclude; p; p = p->next) {
618 		if (p->pat.bank == bank &&
619 		    (p->pat.preset < 0 || p->pat.preset == preset) &&
620 		    (p->pat.keynote < 0 || p->pat.keynote == keynote))
621 			return 1;
622 	}
623 	return 0;
624 }
625 
626 
627 /*----------------------------------------------------------------
628  * ordered samples
629  *----------------------------------------------------------------*/
630 
order_soundfont(int bank,int preset,int keynote,int order)631 int Instruments::order_soundfont(int bank, int preset, int keynote, int order)
632 {
633 	SFOrder *p;
634 	if(current_sfrec == NULL)
635 	    return 1;
636 	p = (SFOrder*)SFMalloc(current_sfrec, sizeof(SFOrder));
637 	p->pat.bank = bank;
638 	p->pat.preset = preset;
639 	p->pat.keynote = keynote;
640 	p->order = order;
641 	p->next = current_sfrec->sforder;
642 	current_sfrec->sforder = p;
643 	return 0;
644 }
645 
646 /* check the instrument is specified to be ordered */
is_ordered(SFInsts * rec,int bank,int preset,int keynote)647 int Instruments::is_ordered(SFInsts *rec, int bank, int preset, int keynote)
648 {
649 	SFOrder *p;
650 	for (p = rec->sforder; p; p = p->next) {
651 		if (p->pat.bank == bank &&
652 		    (p->pat.preset < 0 || p->pat.preset == preset) &&
653 		    (p->pat.keynote < 0 || p->pat.keynote == keynote))
654 			return p->order;
655 	}
656 	return -1;
657 }
658 
659 
660 /*----------------------------------------------------------------*/
661 
load_font(SFInfo * sf,int pridx)662 int Instruments::load_font(SFInfo *sf, int pridx)
663 {
664 	SFPresetHdr *preset = &sf->preset[pridx];
665 	int rc, j, nlayers;
666 	SFGenLayer *layp, *globalp;
667 
668 	/* if layer is empty, skip it */
669 	if ((nlayers = preset->hdr.nlayers) <= 0 ||
670 	    (layp = preset->hdr.layer) == NULL)
671 		return AWE_RET_SKIP;
672 	/* check global layer */
673 	globalp = NULL;
674 	if (is_global(layp)) {
675 		globalp = layp;
676 		layp++;
677 		nlayers--;
678 	}
679 	/* parse for each preset layer */
680 	for (j = 0; j < nlayers; j++, layp++) {
681 		LayerTable tbl;
682 
683 		/* set up table */
684 		clear_table(&tbl);
685 		if (globalp)
686 			set_to_table(sf, &tbl, globalp, P_GLOBAL);
687 		set_to_table(sf, &tbl, layp, P_LAYER);
688 
689 		/* parse the instrument */
690 		rc = parse_layer(sf, pridx, &tbl, 0);
691 		if(rc == AWE_RET_ERR || rc == AWE_RET_NOMEM)
692 			return rc;
693 	}
694 
695 	return AWE_RET_OK;
696 }
697 
698 
699 /*----------------------------------------------------------------*/
700 
701 /* parse a preset layer and convert it to the patch structure */
parse_layer(SFInfo * sf,int pridx,LayerTable * tbl,int level)702 int Instruments::parse_layer(SFInfo *sf, int pridx, LayerTable *tbl, int level)
703 {
704 	SFInstHdr *inst;
705 	int rc, i, nlayers;
706 	SFGenLayer *lay, *globalp;
707 
708 	if (level >= 2) {
709 		fprintf(stderr, "parse_layer: too deep instrument level\n");
710 		return AWE_RET_ERR;
711 	}
712 
713 	/* instrument must be defined */
714 	if (!tbl->set[SF_instrument])
715 		return AWE_RET_SKIP;
716 
717 	inst = &sf->inst[tbl->val[SF_instrument]];
718 
719 	/* if layer is empty, skip it */
720 	if ((nlayers = inst->hdr.nlayers) <= 0 ||
721 	    (lay = inst->hdr.layer) == NULL)
722 		return AWE_RET_SKIP;
723 
724 	reset_last_sample_info();
725 
726 	/* check global layer */
727 	globalp = NULL;
728 	if (is_global(lay)) {
729 		globalp = lay;
730 		lay++;
731 		nlayers--;
732 	}
733 
734 	/* parse for each layer */
735 	for (i = 0; i < nlayers; i++, lay++) {
736 		LayerTable ctbl;
737 		clear_table(&ctbl);
738 		if (globalp)
739 			set_to_table(sf, &ctbl, globalp, P_GLOBAL);
740 		set_to_table(sf, &ctbl, lay, P_LAYER);
741 
742 		if (!ctbl.set[SF_sampleId]) {
743 			/* recursive loading */
744 			merge_table(sf, &ctbl, tbl);
745 			if (! sanity_range(&ctbl))
746 				continue;
747 			rc = parse_layer(sf, pridx, &ctbl, level+1);
748 			if (rc != AWE_RET_OK && rc != AWE_RET_SKIP)
749 				return rc;
750 
751 			reset_last_sample_info();
752 		} else {
753 			init_and_merge_table(sf, &ctbl, tbl);
754 			if (! sanity_range(&ctbl))
755 				continue;
756 
757 			/* load the info data */
758 			if ((rc = make_patch(sf, pridx, &ctbl)) == AWE_RET_ERR)
759 				return rc;
760 		}
761 	}
762 	return AWE_RET_OK;
763 }
764 
765 
is_global(SFGenLayer * layer)766 int Instruments::is_global(SFGenLayer *layer)
767 {
768 	int i;
769 	for (i = 0; i < layer->nlists; i++) {
770 		if (layer->list[i].oper == SF_instrument ||
771 		    layer->list[i].oper == SF_sampleId)
772 			return 0;
773 	}
774 	return 1;
775 }
776 
777 
778 /*----------------------------------------------------------------
779  * layer table handlers
780  *----------------------------------------------------------------*/
781 
782 /* initialize layer table */
clear_table(LayerTable * tbl)783 void Instruments::clear_table(LayerTable *tbl)
784 {
785 	memset(tbl->val, 0, sizeof(tbl->val));
786 	memset(tbl->set, 0, sizeof(tbl->set));
787 }
788 
789 /* set items in a layer to the table */
set_to_table(SFInfo * sf,LayerTable * tbl,SFGenLayer * lay,int level)790 void Instruments::set_to_table(SFInfo *sf, LayerTable *tbl, SFGenLayer *lay, int level)
791 {
792 	int i;
793 	for (i = 0; i < lay->nlists; i++) {
794 		SFGenRec *gen = &lay->list[i];
795 		/* copy the value regardless of its copy policy */
796 		tbl->val[gen->oper] = gen->amount;
797 		tbl->set[gen->oper] = level;
798 	}
799 }
800 
801 /* add an item to the table */
add_item_to_table(LayerTable * tbl,int oper,int amount,int level)802 void Instruments::add_item_to_table(LayerTable *tbl, int oper, int amount, int level)
803 {
804 	LayerItem *item = &layer_items[oper];
805 	int o_lo, o_hi, lo, hi;
806 
807 	switch (item->copy) {
808 	case L_INHRT:
809 		tbl->val[oper] += amount;
810 		break;
811 	case L_OVWRT:
812 		tbl->val[oper] = amount;
813 		break;
814 	case L_PRSET:
815 	case L_INSTR:
816 		/* do not overwrite */
817 		if (!tbl->set[oper])
818 			tbl->val[oper] = amount;
819 		break;
820 	case L_RANGE:
821 		if (!tbl->set[oper]) {
822 			tbl->val[oper] = amount;
823 		} else {
824 			o_lo = LOWNUM(tbl->val[oper]);
825 			o_hi = HIGHNUM(tbl->val[oper]);
826 			lo = LOWNUM(amount);
827 			hi = HIGHNUM(amount);
828 			if (lo < o_lo) lo = o_lo;
829 			if (hi > o_hi) hi = o_hi;
830 			tbl->val[oper] = RANGE(lo, hi);
831 		}
832 		break;
833 	}
834 }
835 
836 /* merge two tables */
merge_table(SFInfo * sf,LayerTable * dst,LayerTable * src)837 void Instruments::merge_table(SFInfo *sf, LayerTable *dst, LayerTable *src)
838 {
839 	int i;
840 	for (i = 0; i < SF_EOF; i++) {
841 		if (src->set[i]) {
842 			if (sf->version == 1) {
843 				if (!dst->set[i] ||
844 				    i == SF_keyRange || i == SF_velRange)
845 					/* just copy it */
846 					dst->val[i] = src->val[i];
847 			}
848 			else
849 				add_item_to_table(dst, i, src->val[i], P_GLOBAL);
850 			dst->set[i] = P_GLOBAL;
851 		}
852 	}
853 }
854 
855 /* merge and set default values */
init_and_merge_table(SFInfo * sf,LayerTable * dst,LayerTable * src)856 void Instruments::init_and_merge_table(SFInfo *sf, LayerTable *dst, LayerTable *src)
857 {
858 	int i;
859 
860 	/* default value is not zero */
861 	if (sf->version == 1) {
862 		layer_items[SF_sustainEnv1].defv = 1000;
863 		layer_items[SF_sustainEnv2].defv = 1000;
864 		layer_items[SF_freqLfo1].defv = -725;
865 		layer_items[SF_freqLfo2].defv = -15600;
866 	} else {
867 		layer_items[SF_sustainEnv1].defv = 0;
868 		layer_items[SF_sustainEnv2].defv = 0;
869 		layer_items[SF_freqLfo1].defv = 0;
870 		layer_items[SF_freqLfo2].defv = 0;
871 	}
872 
873 	/* set default */
874 	for (i = 0; i < SF_EOF; i++) {
875 		if (!dst->set[i])
876 			dst->val[i] = layer_items[i].defv;
877 	}
878 	merge_table(sf, dst, src);
879 	/* convert from SBK to SF2 */
880 	if (sf->version == 1) {
881 		for (i = 0; i < SF_EOF; i++) {
882 			if (dst->set[i])
883 				dst->val[i] = sbk_to_sf2(i, dst->val[i], layer_items);
884 		}
885 	}
886 }
887 
888 
889 /*----------------------------------------------------------------
890  * check key and velocity range
891  *----------------------------------------------------------------*/
892 
sanity_range(LayerTable * tbl)893 int Instruments::sanity_range(LayerTable *tbl)
894 {
895 	int lo, hi;
896 
897 	lo = LOWNUM(tbl->val[SF_keyRange]);
898 	hi = HIGHNUM(tbl->val[SF_keyRange]);
899 	if (lo < 0 || lo > 127 || hi < 0 || hi > 127 || hi < lo)
900 		return 0;
901 
902 	lo = LOWNUM(tbl->val[SF_velRange]);
903 	hi = HIGHNUM(tbl->val[SF_velRange]);
904 	if (lo < 0 || lo > 127 || hi < 0 || hi > 127 || hi < lo)
905 		return 0;
906 
907 	return 1;
908 }
909 
910 
911 /*----------------------------------------------------------------
912  * create patch record from the stored data table
913  *----------------------------------------------------------------*/
914 
make_patch(SFInfo * sf,int pridx,LayerTable * tbl)915 int Instruments::make_patch(SFInfo *sf, int pridx, LayerTable *tbl)
916 {
917     int bank, preset, keynote;
918     int keynote_from, keynote_to, done;
919     int addr, order;
920     InstList *ip;
921     SFSampleInfo *sample;
922     SampleList *sp;
923 
924     sample = &sf->sample[tbl->val[SF_sampleId]];
925 
926 	if(sample->sampletype & SF_SAMPLETYPE_ROM) /* is ROM sample? */
927     {
928 	printMessage(CMSG_INFO, VERB_DEBUG, "preset %d is ROM sample: 0x%x",
929 		  pridx, sample->sampletype);
930 	return AWE_RET_SKIP;
931     }
932 
933     bank = sf->preset[pridx].bank;
934     preset = sf->preset[pridx].preset;
935     if(bank == 128){
936 		keynote_from = LOWNUM(tbl->val[SF_keyRange]);
937 		keynote_to = HIGHNUM(tbl->val[SF_keyRange]);
938     } else
939 	keynote_from = keynote_to = -1;
940 
941 	done = 0;
942 	for(keynote=keynote_from;keynote<=keynote_to;keynote++){
943 
944     if(is_excluded(current_sfrec, bank, preset, keynote))
945     {
946 	continue;
947     } else
948 	done++;
949 
950     order = is_ordered(current_sfrec, bank, preset, keynote);
951     if(order < 0)
952 	order = current_sfrec->def_order;
953 
954     addr = INSTHASH(bank, preset, keynote);
955 
956     for(ip = current_sfrec->instlist[addr]; ip; ip = ip->next)
957     {
958 	if(ip->pat.bank == bank && ip->pat.preset == preset &&
959 	   (keynote < 0 || keynote == ip->pat.keynote))
960 	    break;
961     }
962 
963     if(ip == NULL)
964     {
965 	ip = (InstList*)SFMalloc(current_sfrec, sizeof(InstList));
966 	memset(ip, 0, sizeof(InstList));
967 	ip->pr_idx = pridx;
968 	ip->pat.bank = bank;
969 	ip->pat.preset = preset;
970 	ip->pat.keynote = keynote;
971 	ip->order = order;
972 	ip->samples = 0;
973 	ip->slist = NULL;
974 	ip->next = current_sfrec->instlist[addr];
975 	current_sfrec->instlist[addr] = ip;
976     }
977 
978     /* new sample */
979     sp = (SampleList *)SFMalloc(current_sfrec, sizeof(SampleList));
980     memset(sp, 0, sizeof(SampleList));
981 
982 	sp->bank = bank;
983 	sp->keynote = keynote;
984 
985 	if(tbl->set[SF_keynum]) {
986 		sp->v.note_to_use = (int)tbl->val[SF_keynum];
987 	} else if(bank == 128) {
988 		sp->v.note_to_use = keynote;
989 	}
990     make_info(sf, sp, tbl);
991 
992     /* add a sample */
993     if(ip->slist == NULL)
994 	ip->slist = sp;
995     else
996     {
997 	SampleList *cur, *prev;
998 	int32_t start;
999 
1000 	/* Insert sample */
1001 	start = sp->start;
1002 	cur = ip->slist;
1003 	prev = NULL;
1004 	while(cur && cur->start <= start)
1005 	{
1006 	    prev = cur;
1007 	    cur = cur->next;
1008 	}
1009 	if(prev == NULL)
1010 	{
1011 	    sp->next = ip->slist;
1012 	    ip->slist = sp;
1013 	}
1014 	else
1015 	{
1016 	    prev->next = sp;
1017 	    sp->next = cur;
1018 	}
1019     }
1020     ip->samples++;
1021 
1022 	} /* for(;;) */
1023 
1024 
1025 	if(done==0)
1026 	return AWE_RET_SKIP;
1027 	else
1028 	return AWE_RET_OK;
1029 }
1030 
1031 /*----------------------------------------------------------------
1032  *
1033  * Modified for TiMidity
1034  */
1035 
1036 /* conver to Sample parameter */
make_info(SFInfo * sf,SampleList * vp,LayerTable * tbl)1037 void Instruments::make_info(SFInfo *sf, SampleList *vp, LayerTable *tbl)
1038 {
1039 	set_sample_info(sf, vp, tbl);
1040 	set_init_info(sf, vp, tbl);
1041 	set_rootkey(sf, vp, tbl);
1042 	set_rootfreq(vp);
1043 
1044 	/* tremolo & vibrato */
1045 	convert_tremolo(vp, tbl);
1046 	convert_vibrato(vp, tbl);
1047 }
1048 
set_envelope_parameters(SampleList * vp)1049 void Instruments::set_envelope_parameters(SampleList *vp)
1050 {
1051 		/* convert envelope parameters */
1052 		vp->v.envelope_offset[0] = to_offset(65535);
1053 		vp->v.envelope_rate[0] = vp->attack;
1054 
1055 		vp->v.envelope_offset[1] = to_offset(65534);
1056 		vp->v.envelope_rate[1] = vp->hold;
1057 
1058 		vp->v.envelope_offset[2] = to_offset(vp->sustain);
1059 		vp->v.envelope_rate[2] = vp->decay;
1060 
1061 		vp->v.envelope_offset[3] = 0;
1062 		vp->v.envelope_rate[3] = vp->release;
1063 
1064 		vp->v.envelope_offset[4] = 0;
1065 		vp->v.envelope_rate[4] = vp->release;
1066 
1067 		vp->v.envelope_offset[5] = 0;
1068 		vp->v.envelope_rate[5] = vp->release;
1069 
1070 		/* convert modulation envelope parameters */
1071 		vp->v.modenv_offset[0] = to_offset(65535);
1072 		vp->v.modenv_rate[0] = vp->modattack;
1073 
1074 		vp->v.modenv_offset[1] = to_offset(65534);
1075 		vp->v.modenv_rate[1] = vp->modhold;
1076 
1077 		vp->v.modenv_offset[2] = to_offset(vp->modsustain);
1078 		vp->v.modenv_rate[2] = vp->moddecay;
1079 
1080 		vp->v.modenv_offset[3] = 0;
1081 		vp->v.modenv_rate[3] = vp->modrelease;
1082 
1083 		vp->v.modenv_offset[4] = 0;
1084 		vp->v.modenv_rate[4] = vp->modrelease;
1085 
1086 		vp->v.modenv_offset[5] = 0;
1087 		vp->v.modenv_rate[5] = vp->modrelease;
1088 }
1089 
1090 /* set sample address */
set_sample_info(SFInfo * sf,SampleList * vp,LayerTable * tbl)1091 void Instruments::set_sample_info(SFInfo *sf, SampleList *vp, LayerTable *tbl)
1092 {
1093     SFSampleInfo *sp = &sf->sample[tbl->val[SF_sampleId]];
1094 
1095     /* set sample position */
1096     vp->start = (tbl->val[SF_startAddrsHi] << 15)
1097 	+ tbl->val[SF_startAddrs]
1098 	+ sp->startsample;
1099     vp->len = (tbl->val[SF_endAddrsHi] << 15)
1100 	+ tbl->val[SF_endAddrs]
1101 	+ sp->endsample - vp->start;
1102 
1103 	vp->start = abs(vp->start);
1104 	vp->len = abs(vp->len);
1105 
1106     /* set loop position */
1107     vp->v.loop_start = (tbl->val[SF_startloopAddrsHi] << 15)
1108 	+ tbl->val[SF_startloopAddrs]
1109 	+ sp->startloop - vp->start;
1110     vp->v.loop_end = (tbl->val[SF_endloopAddrsHi] << 15)
1111 	+ tbl->val[SF_endloopAddrs]
1112 	+ sp->endloop - vp->start;
1113 
1114     /* set data length */
1115     vp->v.data_length = vp->len + 1;
1116 
1117 	/* fix loop position */
1118 	if (vp->v.loop_end > (splen_t)vp->len + 1)
1119 		vp->v.loop_end = vp->len + 1;
1120 	if (vp->v.loop_start > (splen_t)vp->len)
1121 		vp->v.loop_start = vp->len;
1122 	if (vp->v.loop_start >= vp->v.loop_end)
1123 	{
1124 		vp->v.loop_start = vp->len;
1125 		vp->v.loop_end = vp->len + 1;
1126 	}
1127 
1128     /* Sample rate */
1129 	if(sp->samplerate > 50000) {sp->samplerate = 50000;}
1130 	else if(sp->samplerate < 400) {sp->samplerate = 400;}
1131     vp->v.sample_rate = sp->samplerate;
1132 
1133     /* sample mode */
1134     vp->v.modes = MODES_16BIT;
1135 
1136     /* volume envelope & total volume */
1137     vp->v.volume = calc_volume(tbl) * current_sfrec->amptune;
1138 
1139 	convert_volume_envelope(vp, tbl);
1140 	set_envelope_parameters(vp);
1141 
1142     if(tbl->val[SF_sampleFlags] == 1 || tbl->val[SF_sampleFlags] == 3)
1143     {
1144 		/* looping */
1145 		vp->v.modes |= MODES_LOOPING | MODES_SUSTAIN;
1146 		if(tbl->val[SF_sampleFlags] == 3)
1147 			vp->v.data_length = vp->v.loop_end; /* strip the tail */
1148 	}
1149     else
1150     {
1151 		/* set a small blank loop at the tail for avoiding abnormal loop. */
1152 		vp->v.loop_start = vp->len;
1153 		vp->v.loop_end = vp->len + 1;
1154     }
1155 
1156     /* convert to fractional samples */
1157     vp->v.data_length <<= FRACTION_BITS;
1158     vp->v.loop_start <<= FRACTION_BITS;
1159     vp->v.loop_end <<= FRACTION_BITS;
1160 
1161     /* point to the file position */
1162     vp->start = vp->start * 2 + sf->samplepos;
1163     vp->len *= 2;
1164 
1165 	vp->v.vel_to_fc = -2400;	/* SF2 default value */
1166 	vp->v.key_to_fc = vp->v.vel_to_resonance = 0;
1167 	vp->v.envelope_velf_bpo = vp->v.modenv_velf_bpo =
1168 		vp->v.vel_to_fc_threshold = 64;
1169 	vp->v.key_to_fc_bpo = 60;
1170 	memset(vp->v.envelope_velf, 0, sizeof(vp->v.envelope_velf));
1171 	memset(vp->v.modenv_velf, 0, sizeof(vp->v.modenv_velf));
1172 
1173 	vp->v.inst_type = INST_SF2;
1174 }
1175 
1176 /*----------------------------------------------------------------*/
1177 
1178 /* set global information */
1179 
set_init_info(SFInfo * sf,SampleList * vp,LayerTable * tbl)1180 void Instruments::set_init_info(SFInfo *sf, SampleList *vp, LayerTable *tbl)
1181 {
1182     int val;
1183     SFSampleInfo *sample;
1184     sample = &sf->sample[tbl->val[SF_sampleId]];
1185 
1186     /* key range */
1187     if(tbl->set[SF_keyRange])
1188     {
1189 	vp->low = LOWNUM(tbl->val[SF_keyRange]);
1190 	vp->high = HIGHNUM(tbl->val[SF_keyRange]);
1191     }
1192     else
1193     {
1194 	vp->low = 0;
1195 	vp->high = 127;
1196     }
1197     vp->v.low_freq = freq_table[(int)vp->low];
1198     vp->v.high_freq = freq_table[(int)vp->high];
1199 
1200     /* velocity range */
1201     if(tbl->set[SF_velRange]) {
1202 		vp->v.low_vel = LOWNUM(tbl->val[SF_velRange]);
1203 		vp->v.high_vel = HIGHNUM(tbl->val[SF_velRange]);
1204     } else {
1205 		vp->v.low_vel = 0;
1206 		vp->v.high_vel = 127;
1207 	}
1208 
1209     /* fixed key & velocity */
1210     if(tbl->set[SF_keynum])
1211 		vp->v.note_to_use = (int)tbl->val[SF_keynum];
1212 	if(tbl->set[SF_velocity] && (int)tbl->val[SF_velocity] != 0) {
1213 		printMessage(CMSG_INFO,VERB_DEBUG,"error: fixed-velocity is not supported.");
1214 	}
1215 
1216 	vp->v.sample_type = sample->sampletype;
1217 	vp->v.sf_sample_index = tbl->val[SF_sampleId];
1218 	vp->v.sf_sample_link = sample->samplelink;
1219 
1220 	/* Some sf2 files don't contain valid sample links, so see if the
1221 	   previous sample was a matching Left / Right sample with the
1222 	   link missing and add it */
1223 	switch (sample->sampletype) {
1224 	case SF_SAMPLETYPE_LEFT:
1225 		if (vp->v.sf_sample_link == 0 &&
1226 		    last_sample_type == SF_SAMPLETYPE_RIGHT &&
1227 		    last_sample_instrument == tbl->val[SF_instrument] &&
1228 		    last_sample_keyrange == tbl->val[SF_keyRange]) {
1229 		    	/* The previous sample was a matching right sample
1230 		    	   set the link */
1231 		    	vp->v.sf_sample_link = last_sample_list->v.sf_sample_index;
1232 		}
1233 		break;
1234 	case SF_SAMPLETYPE_RIGHT:
1235 		if (last_sample_list &&
1236 		    last_sample_list->v.sf_sample_link == 0 &&
1237 		    last_sample_type == SF_SAMPLETYPE_LEFT &&
1238 		    last_sample_instrument == tbl->val[SF_instrument] &&
1239 		    last_sample_keyrange == tbl->val[SF_keyRange]) {
1240 		    	/* The previous sample was a matching left sample
1241 		    	   set the link on the previous sample*/
1242 		    	last_sample_list->v.sf_sample_link = tbl->val[SF_sampleId];
1243 		}
1244 		break;
1245 	}
1246 
1247 	/* Remember this sample in case the next one is a match */
1248 	last_sample_type = sample->sampletype;;
1249 	last_sample_instrument = tbl->val[SF_instrument];
1250 	last_sample_keyrange = tbl->val[SF_keyRange];
1251 	last_sample_list = vp;
1252 
1253 	/* panning position: 0 to 127 */
1254 	val = (int)tbl->val[SF_panEffectsSend];
1255     if(sample->sampletype == SF_SAMPLETYPE_MONO || val != 0) {	/* monoSample = 1 */
1256 		if(val < -500)
1257 		vp->v.panning = 0;
1258 		else if(val > 500)
1259 		vp->v.panning = 127;
1260 		else
1261 		vp->v.panning = (int8_t)((val + 500) * 127 / 1000);
1262 	} else if(sample->sampletype == SF_SAMPLETYPE_RIGHT) {	/* rightSample = 2 */
1263 		vp->v.panning = 127;
1264 	} else if(sample->sampletype == SF_SAMPLETYPE_LEFT) {	/* leftSample = 4 */
1265 		vp->v.panning = 0;
1266 	} else if(sample->sampletype == SF_SAMPLETYPE_LINKED) {	/* linkedSample = 8 */
1267 		printMessage(CMSG_ERROR,VERB_NOISY,"error: linkedSample is not supported.");
1268 	}
1269 
1270 	memset(vp->v.envelope_keyf, 0, sizeof(vp->v.envelope_keyf));
1271 	memset(vp->v.modenv_keyf, 0, sizeof(vp->v.modenv_keyf));
1272 	if(tbl->set[SF_autoHoldEnv2]) {
1273 		vp->v.envelope_keyf[1] = (int16_t)tbl->val[SF_autoHoldEnv2];
1274 	}
1275 	if(tbl->set[SF_autoDecayEnv2]) {
1276 		vp->v.envelope_keyf[2] = (int16_t)tbl->val[SF_autoDecayEnv2];
1277 	}
1278 	if(tbl->set[SF_autoHoldEnv1]) {
1279 		vp->v.modenv_keyf[1] = (int16_t)tbl->val[SF_autoHoldEnv1];
1280 	}
1281 	if(tbl->set[SF_autoDecayEnv1]) {
1282 		vp->v.modenv_keyf[2] = (int16_t)tbl->val[SF_autoDecayEnv1];
1283 	}
1284 
1285 	current_sfrec->def_cutoff_allowed = 1;
1286 	current_sfrec->def_resonance_allowed = 1;
1287 
1288     /* initial cutoff & resonance */
1289     vp->cutoff_freq = 0;
1290     if((int)tbl->val[SF_initialFilterFc] < 0)
1291 	tbl->set[SF_initialFilterFc] = tbl->val[SF_initialFilterFc] = 0;
1292     if(current_sfrec->def_cutoff_allowed && tbl->set[SF_initialFilterFc]
1293 		&& (int)tbl->val[SF_initialFilterFc] >= 1500 && (int)tbl->val[SF_initialFilterFc] <= 13500)
1294     {
1295     val = (int)tbl->val[SF_initialFilterFc];
1296 	val = abscent_to_Hz(val);
1297 
1298 	if(!timidity_modulation_envelope) {
1299 		if(tbl->set[SF_env1ToFilterFc] && (int)tbl->val[SF_env1ToFilterFc] > 0)
1300 		{
1301 			val = int( val * pow(2.0,(double)tbl->val[SF_env1ToFilterFc] / 1200.0f));
1302 			if(val > 20000) {val = 20000;}
1303 		}
1304 	}
1305 
1306 	vp->cutoff_freq = val;
1307     }
1308 	vp->v.cutoff_freq = vp->cutoff_freq;
1309 
1310 	vp->resonance = 0;
1311     if(current_sfrec->def_resonance_allowed && tbl->set[SF_initialFilterQ])
1312     {
1313 	val = (int)tbl->val[SF_initialFilterQ];
1314 	vp->resonance = val;
1315 	}
1316 	vp->v.resonance = vp->resonance;
1317 }
1318 
reset_last_sample_info(void)1319 void Instruments::reset_last_sample_info(void)
1320 {
1321     last_sample_list = NULL;
1322     last_sample_type = 0;
1323     /* Set last instrument and keyrange to a value which cannot be represented
1324        by LayerTable.val (which is a short) */
1325     last_sample_instrument = 0x80000000;
1326     last_sample_keyrange   = 0x80000000;
1327 }
1328 
abscent_to_Hz(int abscents)1329 int Instruments::abscent_to_Hz(int abscents)
1330 {
1331 	return (int)(8.176 * pow(2.0, (double)abscents / 1200.0));
1332 }
1333 
1334 /*----------------------------------------------------------------*/
1335 
1336 #define SF_MODENV_CENT_MAX 1200	/* Live! allows only +-1200cents. */
1337 
1338 /* calculate root key & fine tune */
set_rootkey(SFInfo * sf,SampleList * vp,LayerTable * tbl)1339 void Instruments::set_rootkey(SFInfo *sf, SampleList *vp, LayerTable *tbl)
1340 {
1341 	SFSampleInfo *sp = &sf->sample[tbl->val[SF_sampleId]];
1342 	int temp;
1343 
1344 	/* scale factor */
1345 	vp->v.scale_factor = 1024 * (double) tbl->val[SF_scaleTuning] / 100 + 0.5;
1346 	/* set initial root key & fine tune */
1347 	if (sf->version == 1 && tbl->set[SF_samplePitch]) {
1348 		/* set from sample pitch */
1349 		vp->root = tbl->val[SF_samplePitch] / 100;
1350 		vp->tune = -tbl->val[SF_samplePitch] % 100;
1351 		if (vp->tune <= -50)
1352 			vp->root++, vp->tune += 100;
1353 	} else {
1354 		/* from sample info */
1355 		vp->root = sp->originalPitch;
1356 		vp->tune = (int8_t) sp->pitchCorrection;
1357 	}
1358 	/* orverride root key */
1359 	if (tbl->set[SF_rootKey])
1360 		vp->root = tbl->val[SF_rootKey];
1361 	else if (vp->bank == 128 && vp->v.scale_factor != 0)
1362 		vp->tune += int16_t((vp->keynote - sp->originalPitch) * 100 * (double) vp->v.scale_factor / 1024);
1363 	vp->tune += tbl->val[SF_coarseTune] * 100 + tbl->val[SF_fineTune];
1364 	/* correct too high pitch */
1365 	if (vp->root >= vp->high + 60)
1366 		vp->root -= 60;
1367 	vp->v.tremolo_to_pitch =
1368 			(tbl->set[SF_lfo1ToPitch]) ? tbl->val[SF_lfo1ToPitch] : 0;
1369 	vp->v.tremolo_to_fc =
1370 			(tbl->set[SF_lfo1ToFilterFc]) ? tbl->val[SF_lfo1ToFilterFc] : 0;
1371 	vp->v.modenv_to_pitch =
1372 			(tbl->set[SF_env1ToPitch]) ? tbl->val[SF_env1ToPitch] : 0;
1373 	/* correct tune with the sustain level of modulation envelope */
1374 	temp = vp->v.modenv_to_pitch
1375 			* (double) (1000 - tbl->val[SF_sustainEnv1]) / 1000 + 0.5;
1376 	vp->tune += temp, vp->v.modenv_to_pitch -= temp;
1377 	vp->v.modenv_to_fc =
1378 			(tbl->set[SF_env1ToFilterFc]) ? tbl->val[SF_env1ToFilterFc] : 0;
1379 }
1380 
set_rootfreq(SampleList * vp)1381 void Instruments::set_rootfreq(SampleList *vp)
1382 {
1383 	int root = vp->root;
1384 	int tune = 0.5 - 256 * (double) vp->tune / 100;
1385 
1386 	/* 0 <= tune < 255 */
1387 	while (tune < 0)
1388 		root--, tune += 256;
1389 	while (tune > 255)
1390 		root++, tune -= 256;
1391 	if (root < 0) {
1392 		vp->v.root_freq = freq_table[0] * (double) bend_fine[tune]
1393 				/ bend_coarse[-root] + 0.5;
1394 		vp->v.scale_freq = 0;		/* scale freq */
1395 	} else if (root > 127) {
1396 		vp->v.root_freq = freq_table[127] * (double) bend_fine[tune]
1397 				* bend_coarse[root - 127] + 0.5;
1398 		vp->v.scale_freq = 127;		/* scale freq */
1399 	} else {
1400 		vp->v.root_freq = freq_table[root] * (double) bend_fine[tune] + 0.5;
1401 		vp->v.scale_freq = root;	/* scale freq */
1402 	}
1403 }
1404 
1405 /*----------------------------------------------------------------*/
1406 
1407 
1408 /*Pseudo Reverb*/
1409 extern int32_t modify_release;
1410 
1411 
1412 /* volume envelope parameters */
convert_volume_envelope(SampleList * vp,LayerTable * tbl)1413 void Instruments::convert_volume_envelope(SampleList *vp, LayerTable *tbl)
1414 {
1415     vp->attack  = to_rate(65535, tbl->val[SF_attackEnv2]);
1416     vp->hold    = to_rate(1, tbl->val[SF_holdEnv2]);
1417     vp->sustain = calc_sustain(tbl->val[SF_sustainEnv2]);
1418     vp->decay   = to_rate(65533 - vp->sustain, tbl->val[SF_decayEnv2]);
1419     if(modify_release) /* Pseudo Reverb */
1420 	vp->release = calc_rate(65535, modify_release);
1421     else
1422 	vp->release = to_rate(65535, tbl->val[SF_releaseEnv2]);
1423 	vp->v.envelope_delay = playback_rate *
1424 		to_msec(tbl->val[SF_delayEnv2]) * 0.001;
1425 
1426 	/* convert modulation envelope */
1427     vp->modattack  = to_rate(65535, tbl->val[SF_attackEnv1]);
1428     vp->modhold    = to_rate(1, tbl->val[SF_holdEnv1]);
1429     vp->modsustain = calc_sustain(tbl->val[SF_sustainEnv1]);
1430     vp->moddecay   = to_rate(65533 - vp->modsustain, tbl->val[SF_decayEnv1]);
1431     if(modify_release) /* Pseudo Reverb */
1432 	vp->modrelease = calc_rate(65535, modify_release);
1433     else
1434 	vp->modrelease = to_rate(65535, tbl->val[SF_releaseEnv1]);
1435 	vp->v.modenv_delay = playback_rate *
1436 		to_msec(tbl->val[SF_delayEnv1]) * 0.001;
1437 
1438     vp->v.modes |= MODES_ENVELOPE;
1439 }
1440 
1441 
1442 /*----------------------------------------------------------------
1443  * tremolo (LFO1) conversion
1444  *----------------------------------------------------------------*/
1445 
convert_tremolo(SampleList * vp,LayerTable * tbl)1446 void Instruments::convert_tremolo(SampleList *vp, LayerTable *tbl)
1447 {
1448 	int32_t freq;
1449 	double level;
1450 
1451 	if (!tbl->set[SF_lfo1ToVolume])
1452 		return;
1453 
1454 	level = pow(10.0, (double)abs(tbl->val[SF_lfo1ToVolume]) / -200.0);
1455 	vp->v.tremolo_depth = 256 * (1.0 - level);
1456 	if ((int)tbl->val[SF_lfo1ToVolume] < 0) { vp->v.tremolo_depth = -vp->v.tremolo_depth; }
1457 
1458 	/* frequency in mHz */
1459 	if (!tbl->set[SF_freqLfo1])
1460 		freq = 0;
1461 	else
1462 	{
1463 		freq = (int)tbl->val[SF_freqLfo1];
1464 		freq = TO_MHZ(freq);
1465 	}
1466 
1467 	/* convert mHz to sine table increment; 1024<<rate_shift=1wave */
1468 	vp->v.tremolo_phase_increment = ((playback_rate / 1000 * freq) >> RATE_SHIFT) / control_ratio;
1469 	vp->v.tremolo_delay = playback_rate *
1470 		to_msec(tbl->val[SF_delayLfo1]) * 0.001;
1471 }
1472 
1473 /*----------------------------------------------------------------
1474  * vibrato (LFO2) conversion
1475  *----------------------------------------------------------------*/
1476 
convert_vibrato(SampleList * vp,LayerTable * tbl)1477 void Instruments::convert_vibrato(SampleList *vp, LayerTable *tbl)
1478 {
1479 	int32_t shift, freq;
1480 
1481 	if (!tbl->set[SF_lfo2ToPitch]) {
1482 		vp->v.vibrato_control_ratio = 0;
1483 		return;
1484 	}
1485 
1486 	shift = (int)tbl->val[SF_lfo2ToPitch];
1487 
1488 	/* cents to linear; 400cents = 256 */
1489 	shift = shift * 256 / 400;
1490 	if (shift > 255) { shift = 255; }
1491 	else if (shift < -255) { shift = -255; }
1492 	vp->v.vibrato_depth = (int16_t)shift;
1493 
1494 	/* frequency in mHz */
1495 	if (!tbl->set[SF_freqLfo2])
1496 		freq = 0;
1497 	else
1498 	{
1499 		freq = (int)tbl->val[SF_freqLfo2];
1500 		freq = TO_MHZ(freq);
1501 		if (freq == 0) { freq = 1; }
1502 		/* convert mHz to control ratio */
1503 		vp->v.vibrato_control_ratio = (1000 * playback_rate) /
1504 			(freq * 2 * VIBRATO_SAMPLE_INCREMENTS);
1505 	}
1506 
1507 	vp->v.vibrato_delay = playback_rate *
1508 		to_msec(tbl->val[SF_delayLfo2]) * 0.001;
1509 }
1510 
1511 }
1512