1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2004 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     instrum.c
21 
22     Code to load and unload GUS-compatible instrument patches.
23 */
24 
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif /* HAVE_CONFIG_H */
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <math.h>
31 
32 #ifndef NO_STRING_H
33 #include <string.h>
34 #else
35 #include <strings.h>
36 #endif
37 
38 #include "timidity.h"
39 #include "common.h"
40 #include "instrum.h"
41 #include "playmidi.h"
42 #include "readmidi.h"
43 #include "output.h"
44 #include "controls.h"
45 #include "resample.h"
46 #include "tables.h"
47 #include "filter.h"
48 #include "quantity.h"
49 #include "freq.h"
50 
51 #define INSTRUMENT_HASH_SIZE 128
52 struct InstrumentCache
53 {
54     char *name;
55     int panning, amp, note_to_use, strip_loop, strip_envelope, strip_tail;
56     Instrument *ip;
57     struct InstrumentCache *next;
58 };
59 static struct InstrumentCache *instrument_cache[INSTRUMENT_HASH_SIZE];
60 
61 /* Some functions get aggravated if not even the standard banks are
62    available. */
63 static ToneBank standard_tonebank, standard_drumset;
64 ToneBank
65   *tonebank[128 + MAP_BANK_COUNT] = {&standard_tonebank},
66   *drumset[128 + MAP_BANK_COUNT] = {&standard_drumset};
67 
68 /* bank mapping (mapped bank) */
69 struct bank_map_elem {
70 	int16 used, mapid;
71 	int bankno;
72 };
73 static struct bank_map_elem map_bank[MAP_BANK_COUNT], map_drumset[MAP_BANK_COUNT];
74 static int map_bank_counter;
75 
76 /* This is a special instrument, used for all melodic programs */
77 Instrument *default_instrument=0;
78 SpecialPatch *special_patch[NSPECIAL_PATCH];
79 int progbase = 0;
80 struct inst_map_elem
81 {
82     int set, elem, mapped;
83 };
84 
85 static struct inst_map_elem *inst_map_table[NUM_INST_MAP][128];
86 
87 /* This is only used for tracks that don't specify a program */
88 int default_program[MAX_CHANNELS];
89 
90 char *default_instrument_name = NULL;
91 
92 int antialiasing_allowed=0;
93 #ifdef FAST_DECAY
94 int fast_decay=1;
95 #else
96 int fast_decay=0;
97 #endif
98 
99 /*Pseudo Reverb*/
100 int32 modify_release;
101 
102 /** below three functinos are imported from sndfont.c **/
103 
104 /* convert from 8bit value to fractional offset (15.15) */
to_offset(int offset)105 static int32 to_offset(int offset)
106 {
107 	return (int32)offset << (7+15);
108 }
109 
110 /* calculate ramp rate in fractional unit;
111  * diff = 8bit, time = msec
112  */
calc_rate(int diff,double msec)113 static int32 calc_rate(int diff, double msec)
114 {
115     double rate;
116 
117     if(msec < 6)
118 	msec = 6;
119     if(diff == 0)
120 	diff = 255;
121     diff <<= (7+15);
122     rate = ((double)diff / play_mode->rate) * control_ratio * 1000.0 / msec;
123     if(fast_decay)
124 	rate *= 2;
125     return (int32)rate;
126 }
127 /*End of Pseudo Reverb*/
128 
free_instrument(Instrument * ip)129 void free_instrument(Instrument *ip)
130 {
131   Sample *sp;
132   int i;
133   if (!ip) return;
134 
135   for (i=0; i<ip->samples; i++)
136     {
137       sp=&(ip->sample[i]);
138       if(sp->data_alloced)
139 	  free(sp->data);
140     }
141   free(ip->sample);
142   free(ip);
143 }
144 
clear_magic_instruments(void)145 void clear_magic_instruments(void)
146 {
147     int i, j;
148 
149     for(j = 0; j < 128 + map_bank_counter; j++)
150     {
151 	if(tonebank[j])
152 	{
153 	    ToneBank *bank = tonebank[j];
154 	    for(i = 0; i < 128; i++)
155 		if(IS_MAGIC_INSTRUMENT(bank->tone[i].instrument))
156 		    bank->tone[i].instrument = NULL;
157 	}
158 	if(drumset[j])
159 	{
160 	    ToneBank *bank = drumset[j];
161 	    for(i = 0; i < 128; i++)
162 		if(IS_MAGIC_INSTRUMENT(bank->tone[i].instrument))
163 		    bank->tone[i].instrument = NULL;
164 	}
165     }
166 }
167 
168 #define GUS_ENVRATE_MAX (int32)(0x3FFFFFFF >> 9)
169 
convert_envelope_rate(uint8 rate)170 static int32 convert_envelope_rate(uint8 rate)
171 {
172   int32 r;
173 
174   r=3-((rate>>6) & 0x3);
175   r*=3;
176   r = (int32)(rate & 0x3f) << r; /* 6.9 fixed point */
177 
178   /* 15.15 fixed point. */
179   r = r * 44100 / play_mode->rate * control_ratio * (1 << fast_decay);
180   if(r > GUS_ENVRATE_MAX) {r = GUS_ENVRATE_MAX;}
181   return (r << 9);
182 }
183 
convert_envelope_offset(uint8 offset)184 static int32 convert_envelope_offset(uint8 offset)
185 {
186   /* This is not too good... Can anyone tell me what these values mean?
187      Are they GUS-style "exponential" volumes? And what does that mean? */
188 
189   /* 15.15 fixed point */
190   return offset << (7+15);
191 }
192 
convert_tremolo_sweep(uint8 sweep)193 static int32 convert_tremolo_sweep(uint8 sweep)
194 {
195   if (!sweep)
196     return 0;
197 
198   return
199     ((control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
200       (play_mode->rate * sweep);
201 }
202 
convert_vibrato_sweep(uint8 sweep,int32 vib_control_ratio)203 static int32 convert_vibrato_sweep(uint8 sweep, int32 vib_control_ratio)
204 {
205   if (!sweep)
206     return 0;
207 
208   return (int32)(TIM_FSCALE((double) (vib_control_ratio)
209 			    * SWEEP_TUNING, SWEEP_SHIFT)
210 		 / (double)(play_mode->rate * sweep));
211 
212   /* this was overflowing with seashore.pat
213 
214       ((vib_control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
215       (play_mode->rate * sweep); */
216 }
217 
convert_tremolo_rate(uint8 rate)218 static int32 convert_tremolo_rate(uint8 rate)
219 {
220   return
221     ((SINE_CYCLE_LENGTH * control_ratio * rate) << RATE_SHIFT) /
222       (TREMOLO_RATE_TUNING * play_mode->rate);
223 }
224 
convert_vibrato_rate(uint8 rate)225 static int32 convert_vibrato_rate(uint8 rate)
226 {
227   /* Return a suitable vibrato_control_ratio value */
228   return
229     (VIBRATO_RATE_TUNING * play_mode->rate) /
230       (rate * 2 * VIBRATO_SAMPLE_INCREMENTS);
231 }
232 
reverse_data(int16 * sp,int32 ls,int32 le)233 static void reverse_data(int16 *sp, int32 ls, int32 le)
234 {
235   int16 s, *ep=sp+le;
236   int32 i;
237   sp+=ls;
238   le-=ls;
239   le/=2;
240   for(i = 0; i < le; i++)
241   {
242       s=*sp;
243       *sp++=*ep;
244       *ep--=s;
245   }
246 }
247 
name_hash(char * name)248 static int name_hash(char *name)
249 {
250     unsigned int addr = 0;
251 
252     while(*name)
253 	addr += *name++;
254     return addr % INSTRUMENT_HASH_SIZE;
255 }
256 
search_instrument_cache(char * name,int panning,int amp,int note_to_use,int strip_loop,int strip_envelope,int strip_tail)257 static Instrument *search_instrument_cache(char *name,
258 				int panning, int amp, int note_to_use,
259 				int strip_loop, int strip_envelope,
260 				int strip_tail)
261 {
262     struct InstrumentCache *p;
263 
264     for(p = instrument_cache[name_hash(name)]; p != NULL; p = p->next)
265     {
266 	if(strcmp(p->name, name) != 0)
267 	    return NULL;
268 	if(p->panning == panning &&
269 	   p->amp == amp &&
270 	   p->note_to_use == note_to_use &&
271 	   p->strip_loop == strip_loop &&
272 	   p->strip_envelope == strip_envelope &&
273 	   p->strip_tail == strip_tail)
274 	    return p->ip;
275     }
276     return NULL;
277 }
278 
store_instrument_cache(Instrument * ip,char * name,int panning,int amp,int note_to_use,int strip_loop,int strip_envelope,int strip_tail)279 static void store_instrument_cache(Instrument *ip,
280 				   char *name,
281 				   int panning, int amp, int note_to_use,
282 				   int strip_loop, int strip_envelope,
283 				   int strip_tail)
284 {
285     struct InstrumentCache *p;
286     int addr;
287 
288     addr = name_hash(name);
289     p = (struct InstrumentCache *)safe_malloc(sizeof(struct InstrumentCache));
290     p->next = instrument_cache[addr];
291     instrument_cache[addr] = p;
292     p->name = name;
293     p->panning = panning;
294     p->amp = amp;
295     p->note_to_use = note_to_use;
296     p->strip_loop = strip_loop;
297     p->strip_envelope = strip_envelope;
298     p->strip_tail = strip_tail;
299     p->ip = ip;
300 }
301 
adjust_tune_freq(int32 val,float tune)302 static int32 adjust_tune_freq(int32 val, float tune)
303 {
304 	if (! tune)
305 		return val;
306 	return val / pow(2.0, tune / 12.0);
307 }
308 
adjust_scale_tune(int16 val)309 static int16 adjust_scale_tune(int16 val)
310 {
311 	return 1024 * (double) val / 100 + 0.5;
312 }
313 
adjust_fc(int16 val)314 static int16 adjust_fc(int16 val)
315 {
316 	if (val < 0 || val > play_mode->rate / 2) {
317 		return 0;
318 	} else {
319 		return val;
320 	}
321 }
322 
adjust_reso(int16 val)323 static int16 adjust_reso(int16 val)
324 {
325 	if (val < 0 || val > 960) {
326 		return 0;
327 	} else {
328 		return val;
329 	}
330 }
331 
to_rate(int rate)332 static int32 to_rate(int rate)
333 {
334 	return (rate) ? (int32) (0x200 * pow(2.0, rate / 17.0)
335 			* 44100 / play_mode->rate * control_ratio) << fast_decay : 0;
336 }
337 
338 #if 0
339 static int32 to_control(int control)
340 {
341 	return (int32) (0x2000 / pow(2.0, control / 31.0));
342 }
343 #endif
344 
apply_bank_parameter(Instrument * ip,ToneBankElement * tone)345 static void apply_bank_parameter(Instrument *ip, ToneBankElement *tone)
346 {
347 	int i, j;
348 	Sample *sp;
349 
350 	if (tone->tunenum)
351 		for (i = 0; i < ip->samples; i++) {
352 			sp = &ip->sample[i];
353 			if (tone->tunenum == 1) {
354 				sp->low_freq = adjust_tune_freq(sp->low_freq, tone->tune[0]);
355 				sp->high_freq = adjust_tune_freq(sp->high_freq, tone->tune[0]);
356 				sp->root_freq = adjust_tune_freq(sp->root_freq, tone->tune[0]);
357 			} else if (i < tone->tunenum) {
358 				sp->low_freq = adjust_tune_freq(sp->low_freq, tone->tune[i]);
359 				sp->high_freq = adjust_tune_freq(sp->high_freq, tone->tune[i]);
360 				sp->root_freq = adjust_tune_freq(sp->root_freq, tone->tune[i]);
361 			}
362 		}
363 	if (tone->envratenum)
364 		for (i = 0; i < ip->samples; i++) {
365 			sp = &ip->sample[i];
366 			if (tone->envratenum == 1) {
367 				for (j = 0; j < 6; j++)
368 					if (tone->envrate[0][j] >= 0)
369 						sp->envelope_rate[j] = to_rate(tone->envrate[0][j]);
370 			} else if (i < tone->envratenum) {
371 				for (j = 0; j < 6; j++)
372 					if (tone->envrate[i][j] >= 0)
373 						sp->envelope_rate[j] = to_rate(tone->envrate[i][j]);
374 			}
375 		}
376 	if (tone->envofsnum)
377 		for (i = 0; i < ip->samples; i++) {
378 			sp = &ip->sample[i];
379 			if (tone->envofsnum == 1) {
380 				for (j = 0; j < 6; j++)
381 					if (tone->envofs[0][j] >= 0)
382 						sp->envelope_offset[j] = to_offset(tone->envofs[0][j]);
383 			} else if (i < tone->envofsnum) {
384 				for (j = 0; j < 6; j++)
385 					if (tone->envofs[i][j] >= 0)
386 						sp->envelope_offset[j] = to_offset(tone->envofs[i][j]);
387 			}
388 		}
389 	if (tone->tremnum)
390 		for (i = 0; i < ip->samples; i++) {
391 			sp = &ip->sample[i];
392 			if (tone->tremnum == 1) {
393 				if (IS_QUANTITY_DEFINED(tone->trem[0][0]))
394 					sp->tremolo_sweep_increment =
395 							quantity_to_int(&tone->trem[0][0], 0);
396 				if (IS_QUANTITY_DEFINED(tone->trem[0][1]))
397 					sp->tremolo_phase_increment =
398 							quantity_to_int(&tone->trem[0][1], 0);
399 				if (IS_QUANTITY_DEFINED(tone->trem[0][2]))
400 					sp->tremolo_depth =
401 							quantity_to_int(&tone->trem[0][2], 0) << 1;
402 			} else if (i < tone->tremnum) {
403 				if (IS_QUANTITY_DEFINED(tone->trem[i][0]))
404 					sp->tremolo_sweep_increment =
405 							quantity_to_int(&tone->trem[i][0], 0);
406 				if (IS_QUANTITY_DEFINED(tone->trem[i][1]))
407 					sp->tremolo_phase_increment =
408 							quantity_to_int(&tone->trem[i][1], 0);
409 				if (IS_QUANTITY_DEFINED(tone->trem[i][2]))
410 					sp->tremolo_depth =
411 							quantity_to_int(&tone->trem[i][2], 0) << 1;
412 			}
413 		}
414 	if (tone->vibnum)
415 		for (i = 0; i < ip->samples; i++) {
416 			sp = &ip->sample[i];
417 			if (tone->vibnum == 1) {
418 				if (IS_QUANTITY_DEFINED(tone->vib[0][1]))
419 					sp->vibrato_control_ratio =
420 							quantity_to_int(&tone->vib[0][1], 0);
421 				if (IS_QUANTITY_DEFINED(tone->vib[0][0]))
422 					sp->vibrato_sweep_increment =
423 							quantity_to_int(&tone->vib[0][0],
424 							sp->vibrato_control_ratio);
425 				if (IS_QUANTITY_DEFINED(tone->vib[0][2]))
426 					sp->vibrato_depth = quantity_to_int(&tone->vib[0][2], 0);
427 			} else if (i < tone->vibnum) {
428 				if (IS_QUANTITY_DEFINED(tone->vib[i][1]))
429 					sp->vibrato_control_ratio =
430 							quantity_to_int(&tone->vib[i][1], 0);
431 				if (IS_QUANTITY_DEFINED(tone->vib[i][0]))
432 					sp->vibrato_sweep_increment =
433 							quantity_to_int(&tone->vib[i][0],
434 							sp->vibrato_control_ratio);
435 				if (IS_QUANTITY_DEFINED(tone->vib[i][2]))
436 					sp->vibrato_depth = quantity_to_int(&tone->vib[i][2], 0);
437 			}
438 		}
439 	if (tone->sclnotenum)
440 		for (i = 0; i < ip->samples; i++) {
441 			sp = &ip->sample[i];
442 			if (tone->sclnotenum == 1)
443 				sp->scale_freq = tone->sclnote[0];
444 			else if (i < tone->sclnotenum)
445 				sp->scale_freq = tone->sclnote[i];
446 		}
447 	if (tone->scltunenum)
448 		for (i = 0; i < ip->samples; i++) {
449 			sp = &ip->sample[i];
450 			if (tone->scltunenum == 1)
451 				sp->scale_factor = adjust_scale_tune(tone->scltune[0]);
452 			else if (i < tone->scltunenum)
453 				sp->scale_factor = adjust_scale_tune(tone->scltune[i]);
454 		}
455 	if (tone->modenvratenum)
456 		for (i = 0; i < ip->samples; i++) {
457 			sp = &ip->sample[i];
458 			if (tone->modenvratenum == 1) {
459 				for (j = 0; j < 6; j++)
460 					if (tone->modenvrate[0][j] >= 0)
461 						sp->modenv_rate[j] = to_rate(tone->modenvrate[0][j]);
462 			} else if (i < tone->modenvratenum) {
463 				for (j = 0; j < 6; j++)
464 					if (tone->modenvrate[i][j] >= 0)
465 						sp->modenv_rate[j] = to_rate(tone->modenvrate[i][j]);
466 			}
467 		}
468 	if (tone->modenvofsnum)
469 		for (i = 0; i < ip->samples; i++) {
470 			sp = &ip->sample[i];
471 			if (tone->modenvofsnum == 1) {
472 				for (j = 0; j < 6; j++)
473 					if (tone->modenvofs[0][j] >= 0)
474 						sp->modenv_offset[j] =
475 								to_offset(tone->modenvofs[0][j]);
476 			} else if (i < tone->modenvofsnum) {
477 				for (j = 0; j < 6; j++)
478 					if (tone->modenvofs[i][j] >= 0)
479 						sp->modenv_offset[j] =
480 								to_offset(tone->modenvofs[i][j]);
481 			}
482 		}
483 	if (tone->envkeyfnum)
484 		for (i = 0; i < ip->samples; i++) {
485 			sp = &ip->sample[i];
486 			if (tone->envkeyfnum == 1) {
487 				for (j = 0; j < 6; j++)
488 					if (tone->envkeyf[0][j] != -1)
489 						sp->envelope_keyf[j] = tone->envkeyf[0][j];
490 			} else if (i < tone->envkeyfnum) {
491 				for (j = 0; j < 6; j++)
492 					if (tone->envkeyf[i][j] != -1)
493 						sp->envelope_keyf[j] = tone->envkeyf[i][j];
494 			}
495 		}
496 	if (tone->envvelfnum)
497 		for (i = 0; i < ip->samples; i++) {
498 			sp = &ip->sample[i];
499 			if (tone->envvelfnum == 1) {
500 				for (j = 0; j < 6; j++)
501 					if (tone->envvelf[0][j] != -1)
502 						sp->envelope_velf[j] = tone->envvelf[0][j];
503 			} else if (i < tone->envvelfnum) {
504 				for (j = 0; j < 6; j++)
505 					if (tone->envvelf[i][j] != -1)
506 						sp->envelope_velf[j] = tone->envvelf[i][j];
507 			}
508 		}
509 	if (tone->modenvkeyfnum)
510 		for (i = 0; i < ip->samples; i++) {
511 			sp = &ip->sample[i];
512 			if (tone->modenvkeyfnum == 1) {
513 				for (j = 0; j < 6; j++)
514 					if (tone->modenvkeyf[0][j] != -1)
515 						sp->modenv_keyf[j] = tone->modenvkeyf[0][j];
516 			} else if (i < tone->modenvkeyfnum) {
517 				for (j = 0; j < 6; j++)
518 					if (tone->modenvkeyf[i][j] != -1)
519 						sp->modenv_keyf[j] = tone->modenvkeyf[i][j];
520 			}
521 		}
522 	if (tone->modenvvelfnum)
523 		for (i = 0; i < ip->samples; i++) {
524 			sp = &ip->sample[i];
525 			if (tone->modenvvelfnum == 1) {
526 				for (j = 0; j < 6; j++)
527 					if (tone->modenvvelf[0][j] != -1)
528 						sp->modenv_velf[j] = tone->modenvvelf[0][j];
529 			} else if (i < tone->modenvvelfnum) {
530 				for (j = 0; j < 6; j++)
531 					if (tone->modenvvelf[i][j] != -1)
532 						sp->modenv_velf[j] = tone->modenvvelf[i][j];
533 			}
534 		}
535 	if (tone->trempitchnum)
536 		for (i = 0; i < ip->samples; i++) {
537 			sp = &ip->sample[i];
538 			if (tone->trempitchnum == 1)
539 				sp->tremolo_to_pitch = tone->trempitch[0];
540 			else if (i < tone->trempitchnum)
541 				sp->tremolo_to_pitch = tone->trempitch[i];
542 		}
543 	if (tone->tremfcnum)
544 		for (i = 0; i < ip->samples; i++) {
545 			sp = &ip->sample[i];
546 			if (tone->tremfcnum == 1)
547 				sp->tremolo_to_fc = tone->tremfc[0];
548 			else if (i < tone->tremfcnum)
549 				sp->tremolo_to_fc = tone->tremfc[i];
550 		}
551 	if (tone->modpitchnum)
552 		for (i = 0; i < ip->samples; i++) {
553 			sp = &ip->sample[i];
554 			if (tone->modpitchnum == 1)
555 				sp->modenv_to_pitch = tone->modpitch[0];
556 			else if (i < tone->modpitchnum)
557 				sp->modenv_to_pitch = tone->modpitch[i];
558 		}
559 	if (tone->modfcnum)
560 		for (i = 0; i < ip->samples; i++) {
561 			sp = &ip->sample[i];
562 			if (tone->modfcnum == 1)
563 				sp->modenv_to_fc = tone->modfc[0];
564 			else if (i < tone->modfcnum)
565 				sp->modenv_to_fc = tone->modfc[i];
566 		}
567 	if (tone->fcnum)
568 		for (i = 0; i < ip->samples; i++) {
569 			sp = &ip->sample[i];
570 			if (tone->fcnum == 1)
571 				sp->cutoff_freq = adjust_fc(tone->fc[0]);
572 			else if (i < tone->fcnum)
573 				sp->cutoff_freq = adjust_fc(tone->fc[i]);
574 		}
575 	if (tone->resonum)
576 		for (i = 0; i < ip->samples; i++) {
577 			sp = &ip->sample[i];
578 			if (tone->resonum == 1)
579 				sp->resonance = adjust_reso(tone->reso[0]);
580 			else if (i < tone->resonum)
581 				sp->resonance = adjust_reso(tone->reso[i]);
582 		}
583 }
584 
585 #define READ_CHAR(thing) { \
586 		uint8 tmpchar; \
587 		\
588 		if (tf_read(&tmpchar, 1, 1, tf) != 1) \
589 			goto fail; \
590 		thing = tmpchar; \
591 }
592 #define READ_SHORT(thing) { \
593 		uint16 tmpshort; \
594 		\
595 		if (tf_read(&tmpshort, 2, 1, tf) != 1) \
596 			goto fail; \
597 		thing = LE_SHORT(tmpshort); \
598 }
599 #define READ_LONG(thing) { \
600 		int32 tmplong; \
601 		\
602 		if (tf_read(&tmplong, 4, 1, tf) != 1) \
603 			goto fail; \
604 		thing = LE_LONG(tmplong); \
605 }
606 
607 /* If panning or note_to_use != -1, it will be used for all samples,
608  * instead of the sample-specific values in the instrument file.
609  *
610  * For note_to_use, any value < 0 or > 127 will be forced to 0.
611  *
612  * For other parameters, 1 means yes, 0 means no, other values are
613  * undefined.
614  *
615  * TODO: do reverse loops right
616  */
load_gus_instrument(char * name,ToneBank * bank,int dr,int prog,char * infomsg)617 static Instrument *load_gus_instrument(char *name,
618 		ToneBank *bank, int dr, int prog, char *infomsg)
619 {
620 	ToneBankElement *tone;
621 	int amp, note_to_use, panning, strip_envelope, strip_loop, strip_tail;
622 	Instrument *ip;
623 	struct timidity_file *tf;
624 	uint8 tmp[1024], fractions;
625 	Sample *sp;
626 	int i, j, noluck = 0;
627 
628 	if (! name)
629 		return 0;
630 	if (infomsg != NULL)
631 		ctl->cmsg(CMSG_INFO, VERB_NOISY, "%s: %s", infomsg, name);
632 	else
633 		ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", name);
634 	if (bank) {
635 		tone = &bank->tone[prog];
636 		amp = tone->amp;
637 		note_to_use = (tone->note != -1) ? tone->note : ((dr) ? prog : -1);
638 		panning = tone->pan;
639 		strip_envelope = (tone->strip_envelope != -1)
640 				? tone->strip_envelope : ((dr) ? 1 : -1);
641 		strip_loop = (tone->strip_loop != -1)
642 				? tone->strip_loop : ((dr) ? 1 : -1);
643 		strip_tail = tone->strip_tail;
644 	} else {
645 		tone = NULL;
646 		amp = note_to_use = panning = -1;
647 		strip_envelope = strip_loop = strip_tail = 0;
648 	}
649 	if (tone && tone->tunenum == 0
650 			&& tone->envratenum == 0 && tone->envofsnum == 0
651 			&& tone->tremnum == 0 && tone->vibnum == 0
652 			&& tone->sclnotenum == 0 && tone->scltunenum == 0
653 			&& tone->modenvratenum == 0 && tone->modenvofsnum == 0
654 			&& tone->envkeyfnum == 0 && tone->envvelfnum == 0
655 			&& tone->modenvkeyfnum == 0 && tone->modenvvelfnum == 0
656 			&& tone->trempitchnum == 0 && tone->tremfcnum == 0
657 			&& tone->modpitchnum == 0 && tone->modfcnum == 0
658 			&& tone->fcnum == 0 && tone->resonum == 0)
659 		if ((ip = search_instrument_cache(name, panning, amp, note_to_use,
660 				strip_loop, strip_envelope, strip_tail)) != NULL) {
661 			ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * Cached");
662 			return ip;
663 		}
664 	/* Open patch file */
665 	if (! (tf = open_file_r(name, 2, OF_NORMAL))) {
666 #ifdef PATCH_EXT_LIST
667 		int name_len, ext_len;
668 		static char *patch_ext[] = PATCH_EXT_LIST;
669 #endif
670 
671 		noluck = 1;
672 #ifdef PATCH_EXT_LIST
673 		name_len = strlen(name);
674 		/* Try with various extensions */
675 		for (i = 0; patch_ext[i]; i++) {
676 			ext_len = strlen(patch_ext[i]);
677 			if (name_len + ext_len < 1024) {
678 				if (name_len >= ext_len && strcmp(name + name_len - ext_len,
679 						patch_ext[i]) == 0)
680 					continue;	/* duplicated ext. */
681 				strcpy((char *) tmp, name);
682 				strcat((char *) tmp, patch_ext[i]);
683 				if ((tf = open_file_r((char *) tmp, 1, OF_NORMAL))) {
684 					noluck = 0;
685 					break;
686 				}
687 			}
688 		}
689 #endif
690 	}
691 	if (noluck) {
692 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
693 				"Instrument `%s' can't be found.", name);
694 		return 0;
695 	}
696 	/* Read some headers and do cursory sanity checks. There are loads
697 	 * of magic offsets.  This could be rewritten...
698 	 */
699 	tmp[0] = tf_getc(tf);
700 	if (tmp[0] == '\0') {
701 		/* for Mac binary */
702 		skip(tf, 127);
703 		tmp[0] = tf_getc(tf);
704 	}
705 	if ((tf_read(tmp + 1, 1, 238, tf) != 238)
706 			|| (memcmp(tmp, "GF1PATCH110\0ID#000002", 22)
707 			&& memcmp(tmp, "GF1PATCH100\0ID#000002", 22))) {
708 			/* don't know what the differences are */
709 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
710 		close_file(tf);
711 		return 0;
712 	}
713 	/* instruments.  To some patch makers, 0 means 1 */
714 	if (tmp[82] != 1 && tmp[82] != 0) {
715 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
716 				"Can't handle patches with %d instruments", tmp[82]);
717 		close_file(tf);
718 		return 0;
719 	}
720 	if (tmp[151] != 1 && tmp[151] != 0) {	/* layers.  What's a layer? */
721 		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
722 				"Can't handle instruments with %d layers", tmp[151]);
723 		close_file(tf);
724 		return 0;
725 	}
726 	ip = (Instrument *) safe_malloc(sizeof(Instrument));
727 	ip->type = INST_GUS;
728 	ip->samples = tmp[198];
729 	ip->sample = (Sample *) safe_malloc(sizeof(Sample) * ip->samples);
730 	memset(ip->sample, 0, sizeof(Sample) * ip->samples);
731 	for (i = 0; i < ip->samples; i++) {
732 		skip(tf, 7);	/* Skip the wave name */
733 		if (tf_read(&fractions, 1, 1, tf) != 1) {
734 fail:
735 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
736 			for (j = 0; j < i; j++)
737 				free(ip->sample[j].data);
738 			free(ip->sample);
739 			free(ip);
740 			close_file(tf);
741 			return 0;
742 		}
743 		sp = &(ip->sample[i]);
744 		sp->low_vel = 0;
745 		sp->high_vel = 127;
746 		sp->cutoff_freq = sp->resonance = 0;
747 		sp->tremolo_to_pitch = sp->tremolo_to_fc = 0;
748 		sp->modenv_to_pitch = sp->modenv_to_fc = 0;
749 		sp->vel_to_fc = sp->key_to_fc = sp->vel_to_resonance = 0;
750 		sp->envelope_velf_bpo = sp->modenv_velf_bpo = 64;
751 		sp->vel_to_fc_threshold = 64;
752 		sp->key_to_fc_bpo = 60;
753 		sp->envelope_delay = sp->modenv_delay = 0;
754 		sp->tremolo_delay = sp->vibrato_delay = 0;
755 		sp->inst_type = INST_GUS;
756 		sp->sample_type = SF_SAMPLETYPE_MONO;
757 		sp->sf_sample_link = -1;
758 		sp->sf_sample_index = 0;
759 		memset(sp->envelope_velf, 0, sizeof(sp->envelope_velf));
760 		memset(sp->envelope_keyf, 0, sizeof(sp->envelope_keyf));
761 		memset(sp->modenv_velf, 0, sizeof(sp->modenv_velf));
762 		memset(sp->modenv_keyf, 0, sizeof(sp->modenv_keyf));
763 		memset(sp->modenv_rate, 0, sizeof(sp->modenv_rate));
764 		memset(sp->modenv_offset, 0, sizeof(sp->modenv_offset));
765 		READ_LONG(sp->data_length);
766 		READ_LONG(sp->loop_start);
767 		READ_LONG(sp->loop_end);
768 		READ_SHORT(sp->sample_rate);
769 		READ_LONG(sp->low_freq);
770 		READ_LONG(sp->high_freq);
771 		READ_LONG(sp->root_freq);
772 		skip(tf, 2);	/* Why have a "root frequency" and then "tuning"?? */
773 		READ_CHAR(tmp[0]);
774 		ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Rate/Low/Hi/Root = %d/%d/%d/%d",
775 				sp->sample_rate, sp->low_freq, sp->high_freq, sp->root_freq);
776 		if (panning == -1)
777 			/* 0x07 and 0x08 are both center panning */
778 			sp->panning = ((tmp[0] - ((tmp[0] < 8) ? 7 : 8)) * 63) / 7 + 64;
779 		else
780 			sp->panning = (uint8) (panning & 0x7f);
781 		/* envelope, tremolo, and vibrato */
782 		if (tf_read(tmp, 1, 18, tf) != 18)
783 			goto fail;
784 		if (! tmp[13] || ! tmp[14]) {
785 			sp->tremolo_sweep_increment = sp->tremolo_phase_increment = 0;
786 			sp->tremolo_depth = 0;
787 			ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
788 		} else {
789 			sp->tremolo_sweep_increment = convert_tremolo_sweep(tmp[12]);
790 			sp->tremolo_phase_increment = convert_tremolo_rate(tmp[13]);
791 			sp->tremolo_depth = tmp[14];
792 			ctl->cmsg(CMSG_INFO, VERB_DEBUG,
793 					" * tremolo: sweep %d, phase %d, depth %d",
794 					sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
795 					sp->tremolo_depth);
796 		}
797 		if (! tmp[16] || ! tmp[17]) {
798 			sp->vibrato_sweep_increment = sp->vibrato_control_ratio = 0;
799 			sp->vibrato_depth = 0;
800 			ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
801 		} else {
802 			sp->vibrato_control_ratio = convert_vibrato_rate(tmp[16]);
803 			sp->vibrato_sweep_increment = convert_vibrato_sweep(tmp[15],
804 					sp->vibrato_control_ratio);
805 			sp->vibrato_depth = tmp[17];
806 			ctl->cmsg(CMSG_INFO, VERB_DEBUG,
807 					" * vibrato: sweep %d, ctl %d, depth %d",
808 					sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
809 					sp->vibrato_depth);
810 		}
811 		READ_CHAR(sp->modes);
812 		ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * mode: 0x%02x", sp->modes);
813 		READ_SHORT(sp->scale_freq);
814 		READ_SHORT(sp->scale_factor);
815 		skip(tf, 36);	/* skip reserved space */
816 		/* Mark this as a fixed-pitch instrument if such a deed is desired. */
817 		sp->note_to_use = (note_to_use != -1) ? (uint8) note_to_use : 0;
818 		/* seashore.pat in the Midia patch set has no Sustain.  I don't
819 		 * understand why, and fixing it by adding the Sustain flag to
820 		 * all looped patches probably breaks something else.  We do it
821 		 * anyway.
822 		 */
823 		if (sp->modes & MODES_LOOPING)
824 			sp->modes |= MODES_SUSTAIN;
825 		/* Strip any loops and envelopes we're permitted to */
826 		if ((strip_loop == 1) && (sp->modes & (MODES_SUSTAIN | MODES_LOOPING
827 				| MODES_PINGPONG | MODES_REVERSE))) {
828 			sp->modes &= ~(MODES_SUSTAIN | MODES_LOOPING
829 					| MODES_PINGPONG | MODES_REVERSE);
830 			ctl->cmsg(CMSG_INFO, VERB_DEBUG,
831 					" - Removing loop and/or sustain");
832 		}
833 		if (strip_envelope == 1) {
834 			if (sp->modes & MODES_ENVELOPE)
835 				ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
836 			sp->modes &= ~MODES_ENVELOPE;
837 		} else if (strip_envelope != 0) {
838 			/* Have to make a guess. */
839 			if (! (sp->modes & (MODES_LOOPING
840 					| MODES_PINGPONG | MODES_REVERSE))) {
841 				/* No loop? Then what's there to sustain?
842 				 * No envelope needed either...
843 				 */
844 				sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
845 				ctl->cmsg(CMSG_INFO, VERB_DEBUG,
846 						" - No loop, removing sustain and envelope");
847 			} else if (! memcmp(tmp, "??????", 6) || tmp[11] >= 100) {
848 				/* Envelope rates all maxed out?
849 				 * Envelope end at a high "offset"?
850 				 * That's a weird envelope.  Take it out.
851 				 */
852 				sp->modes &= ~MODES_ENVELOPE;
853 				ctl->cmsg(CMSG_INFO, VERB_DEBUG,
854 						" - Weirdness, removing envelope");
855 			} else if (! (sp->modes & MODES_SUSTAIN)) {
856 				/* No sustain? Then no envelope.  I don't know if this is
857 				 * justified, but patches without sustain usually don't need
858 				 * the envelope either... at least the Gravis ones.  They're
859 				 * mostly drums.  I think.
860 				 */
861 				sp->modes &= ~MODES_ENVELOPE;
862 				ctl->cmsg(CMSG_INFO, VERB_DEBUG,
863 						" - No sustain, removing envelope");
864 			}
865 		}
866 		for (j = 0; j < 6; j++) {
867 			sp->envelope_rate[j]= convert_envelope_rate(tmp[j]);
868 			sp->envelope_offset[j] = convert_envelope_offset(tmp[j + 6]);
869 		}
870 		/* this envelope seems to give reverb like effects to most patches
871 		 * use the same method as soundfont
872 		 */
873 		if (modify_release) {
874 			sp->envelope_offset[3] = to_offset(5);
875 			sp->envelope_rate[3] = calc_rate(255, modify_release);
876 			sp->envelope_offset[4] = to_offset(4);
877 			sp->envelope_rate[4] = to_offset(200);
878 			sp->envelope_offset[5] = to_offset(4);
879 			sp->envelope_rate[5] = to_offset(200);
880 		}
881 		/* Then read the sample data */
882 		sp->data = (sample_t *) safe_malloc(sp->data_length + 4);
883 		sp->data_alloced = 1;
884 		if ((j = tf_read(sp->data, 1, sp->data_length, tf))
885 				!= sp->data_length) {
886 			ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
887 					"Too small this patch length: %d < %d",
888 					j, sp->data_length);
889 			goto fail;
890 		}
891 		if (! (sp->modes & MODES_16BIT)) {	/* convert to 16-bit data */
892 			int32 i;
893 			uint16 *tmp;
894 			uint8 *cp = (uint8 *) sp->data;
895 
896 			tmp = (uint16 *) safe_malloc(sp->data_length * 2 + 4);
897 			for (i = 0; i < sp->data_length; i++)
898 				tmp[i] = (uint16) cp[i] << 8;
899 			sp->data = (sample_t *) tmp;
900 			free(cp);
901 			sp->data_length *= 2;
902 			sp->loop_start *= 2;
903 			sp->loop_end *= 2;
904 		}
905 #ifndef LITTLE_ENDIAN
906 		else {	/* convert to machine byte order */
907 			int32 i;
908 			int16 *tmp = (int16 *) sp->data, s;
909 
910 			for (i = 0; i < sp->data_length / 2; i++)
911 				s = LE_SHORT(tmp[i]), tmp[i] = s;
912 		}
913 #endif
914 		if (sp->modes & MODES_UNSIGNED) {	/* convert to signed data */
915 			int32 i = sp->data_length / 2;
916 			int16 *tmp = (int16 *) sp->data;
917 
918 			while (i--)
919 				*tmp++ ^= 0x8000;
920 		}
921 		/* Reverse loops and pass them off as normal loops */
922 		if (sp->modes & MODES_REVERSE) {
923 			/* The GUS apparently plays reverse loops by reversing the
924 			 * whole sample.  We do the same because the GUS does not SUCK.
925 			 */
926 			int32 t;
927 
928 			reverse_data((int16 *) sp->data, 0, sp->data_length / 2);
929 			t = sp->loop_start;
930 			sp->loop_start = sp->data_length - sp->loop_end;
931 			sp->loop_end = sp->data_length - t;
932 			sp->modes &= ~MODES_REVERSE;
933 			sp->modes |= MODES_LOOPING;	/* just in case */
934 			ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s", name);
935 		}
936 		/* If necessary do some anti-aliasing filtering */
937 		if (antialiasing_allowed)
938 			antialiasing((int16 *) sp->data, sp->data_length / 2,
939 					sp->sample_rate, play_mode->rate);
940 #ifdef ADJUST_SAMPLE_VOLUMES
941 		if (amp != -1)
942 			sp->volume = (double) amp / 100;
943 		else {
944 			/* Try to determine a volume scaling factor for the sample.
945 			 * This is a very crude adjustment, but things sound more
946 			 * balanced with it.  Still, this should be a runtime option.
947 			 */
948 			int32 i, a, maxamp = 0;
949 			int16 *tmp = (int16 *) sp->data;
950 
951 			for (i = 0; i < sp->data_length / 2; i++)
952 				if ((a = abs(tmp[i])) > maxamp)
953 					maxamp = a;
954 			sp->volume = 32768 / (double) maxamp;
955 			ctl->cmsg(CMSG_INFO, VERB_DEBUG,
956 					" * volume comp: %f", sp->volume);
957 		}
958 #else
959 		sp->volume = (amp != -1) ? (double) amp / 100 : 1.0;
960 #endif
961 		/* These are in bytes.  Convert into samples. */
962 		sp->data_length /= 2;
963 		sp->loop_start /= 2;
964 		sp->loop_end /= 2;
965 		/* The sample must be padded out by 2 extra sample, so that
966 		 * round off errors in the offsets used in interpolation will not
967 		 * cause a "pop" by reading random data beyond data_length
968 		 */
969 		sp->data[sp->data_length] = sp->data[sp->data_length + 1] = 0;
970 		/* Remove abnormal loops which cause pop noise
971 		 * in long sustain stage
972 		 */
973 		if (! (sp->modes & MODES_LOOPING)) {
974 			sp->loop_start = sp->data_length - 1;
975 			sp->loop_end = sp->data_length;
976 			sp->data[sp->data_length - 1] = 0;
977 		}
978 		/* Then fractional samples */
979 		sp->data_length <<= FRACTION_BITS;
980 		sp->loop_start <<= FRACTION_BITS;
981 		sp->loop_end <<= FRACTION_BITS;
982 		/* Adjust for fractional loop points. This is a guess.  Does anyone
983 		 * know what "fractions" really stands for?
984 		 */
985 		sp->loop_start |= (fractions & 0x0f) << (FRACTION_BITS - 4);
986 		sp->loop_end |= ((fractions >> 4) & 0x0f) << (FRACTION_BITS - 4);
987 		/* If this instrument will always be played on the same note,
988 		 * and it's not looped, we can resample it now.
989 		 */
990 		if (sp->note_to_use && ! (sp->modes & MODES_LOOPING))
991 			pre_resample(sp);
992 
993 		/* do pitch detection on drums if surround chorus is used */
994 		if (dr && opt_surround_chorus)
995 		{
996 		    sp->chord = -1;
997 		    sp->root_freq_detected = freq_fourier(sp, &(sp->chord));
998 		    sp->transpose_detected =
999 			assign_pitch_to_freq(sp->root_freq_detected) -
1000 			assign_pitch_to_freq(sp->root_freq / 1024.0);
1001 		}
1002 
1003 #ifdef LOOKUP_HACK
1004 		squash_sample_16to8(sp);
1005 #endif
1006 		if (strip_tail == 1) {
1007 			/* Let's not really, just say we did. */
1008 			sp->data_length = sp->loop_end;
1009 			ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail");
1010 		}
1011 	}
1012 	close_file(tf);
1013 	store_instrument_cache(ip, name, panning, amp, note_to_use,
1014 			strip_loop, strip_envelope, strip_tail);
1015 	return ip;
1016 }
1017 
1018 #ifdef LOOKUP_HACK
1019 /*! Squash the 16-bit data into 8 bits. */
squash_sample_16to8(Sample * sp)1020 void squash_sample_16to8(Sample *sp)
1021 {
1022 	uint8 *gulp, *ulp;
1023 	int16 *swp;
1024 	int l = sp->data_length >> FRACTION_BITS;
1025 
1026 	gulp = ulp = (uint8 *)safe_malloc(l + 1);
1027 	swp = (int16 *)sp->data;
1028 	while (l--)
1029 		*ulp++ = (*swp++ >> 8) & 0xff;
1030 	free(sp->data);
1031 	sp->data = (sample_t *)gulp;
1032 }
1033 #endif
1034 
load_instrument(int dr,int b,int prog)1035 Instrument *load_instrument(int dr, int b, int prog)
1036 {
1037 	ToneBank *bank = ((dr) ? drumset[b] : tonebank[b]);
1038 	Instrument *ip;
1039 	int i, font_bank, font_preset, font_keynote;
1040 	extern Instrument *extract_sample_file(char *);
1041 	FLOAT_T volume_max;
1042 	int pan, panning;
1043 	char infomsg[256];
1044 
1045 #ifndef CFG_FOR_SF
1046 	if (play_system_mode == GS_SYSTEM_MODE && (b == 64 || b == 65)) {
1047 		if (! dr)	/* User Instrument */
1048 			recompute_userinst(b, prog);
1049 		else {		/* User Drumset */
1050 			ip = recompute_userdrum(b, prog);
1051 			if (ip != NULL) {
1052 				return ip;
1053 			}
1054 		}
1055         }
1056 #endif
1057 	if (bank->tone[prog].instype == 1 || bank->tone[prog].instype == 2) {
1058 		if (bank->tone[prog].instype == 1) {	/* Font extention */
1059 			font_bank = bank->tone[prog].font_bank;
1060 			font_preset = bank->tone[prog].font_preset;
1061 			font_keynote = bank->tone[prog].font_keynote;
1062 			ip = extract_soundfont(bank->tone[prog].name,
1063 					font_bank, font_preset, font_keynote);
1064 		} else	/* Sample extension */
1065 			ip = extract_sample_file(bank->tone[prog].name);
1066 		/* amp tuning */
1067 		if (ip != NULL && bank->tone[prog].amp != -1) {
1068 			for (i = 0, volume_max = 0; i < ip->samples; i++)
1069 				if (volume_max < ip->sample[i].volume)
1070 					volume_max = ip->sample[i].volume;
1071 			if (volume_max != 0)
1072 				for (i = 0; i < ip->samples; i++)
1073 					ip->sample[i].volume *= bank->tone[prog].amp
1074 							/ 100.0 / volume_max;
1075 		}
1076 		/* panning */
1077 		if (ip != NULL && bank->tone[prog].pan != -1) {
1078 			pan = ((int) bank->tone[prog].pan & 0x7f) - 64;
1079 			for (i = 0; i < ip->samples; i++) {
1080 				panning = (int) ip->sample[i].panning + pan;
1081 				panning = (panning < 0) ? 0
1082 						: ((panning > 127) ? 127 : panning);
1083 				ip->sample[i].panning = panning;
1084 			}
1085 		}
1086 		/* note to use */
1087 		if (ip != NULL && bank->tone[prog].note != -1)
1088 			for (i = 0; i < ip->samples; i++)
1089 				ip->sample[i].root_freq =
1090 						freq_table[bank->tone[prog].note & 0x7f];
1091 		/* filter key-follow */
1092 		if (ip != NULL && bank->tone[prog].key_to_fc != 0)
1093 			for (i = 0; i < ip->samples; i++)
1094 				ip->sample[i].key_to_fc = bank->tone[prog].key_to_fc;
1095 		/* filter velocity-follow */
1096 		if (ip != NULL && bank->tone[prog].vel_to_fc != 0)
1097 			for (i = 0; i < ip->samples; i++)
1098 				ip->sample[i].key_to_fc = bank->tone[prog].vel_to_fc;
1099 		/* resonance velocity-follow */
1100 		if (ip != NULL && bank->tone[prog].vel_to_resonance != 0)
1101 			for (i = 0; i < ip->samples; i++)
1102 				ip->sample[i].vel_to_resonance =
1103 						bank->tone[prog].vel_to_resonance;
1104 		/* strip tail */
1105 		if (ip != NULL && bank->tone[prog].strip_tail == 1)
1106 			for (i = 0; i < ip->samples; i++)
1107 				ip->sample[i].data_length = ip->sample[i].loop_end;
1108 		if (ip != NULL) {
1109 			i = (dr) ? 0 : prog;
1110 			if (bank->tone[i].comment)
1111 				free(bank->tone[i].comment);
1112 			bank->tone[i].comment = safe_strdup(ip->instname);
1113 			apply_bank_parameter(ip, &bank->tone[prog]);
1114 		}
1115 		return ip;
1116 	}
1117 	if (! dr) {
1118 		font_bank = b;
1119 		font_preset = prog;
1120 		font_keynote = -1;
1121 	} else {
1122 		font_bank = 128;
1123 		font_preset = b;
1124 		font_keynote = prog;
1125 	}
1126 	/* preload soundfont */
1127 	ip = load_soundfont_inst(0, font_bank, font_preset, font_keynote);
1128 	if (ip != NULL) {
1129 		if (bank->tone[prog].name == NULL) /* this should not be NULL to play the instrument */
1130 			bank->tone[prog].name = safe_strdup(DYNAMIC_INSTRUMENT_NAME);
1131 		if (bank->tone[prog].comment)
1132 			free(bank->tone[prog].comment);
1133 		bank->tone[prog].comment = safe_strdup(ip->instname);
1134 	}
1135 	if (ip == NULL) {	/* load GUS/patch file */
1136 		if (! dr)
1137 			sprintf(infomsg, "Tonebank %d %d", b, prog + progbase);
1138 		else
1139 			sprintf(infomsg, "Drumset %d %d(%s)",
1140 					b + progbase, prog, note_name[prog % 12]);
1141 		ip = load_gus_instrument(bank->tone[prog].name,
1142 				bank, dr, prog, infomsg);
1143 		if (ip == NULL) {	/* no patch; search soundfont again */
1144 			ip = load_soundfont_inst(1, font_bank, font_preset, font_keynote);
1145 			if (ip != NULL) {
1146 				if (bank->tone[0].comment)
1147 					free(bank->tone[0].comment);
1148 				bank->tone[0].comment = safe_strdup(ip->instname);
1149 			}
1150 		}
1151 	}
1152 	if (ip != NULL)
1153 		apply_bank_parameter(ip, &bank->tone[prog]);
1154 	return ip;
1155 }
1156 
fill_bank(int dr,int b,int * rc)1157 static int fill_bank(int dr, int b, int *rc)
1158 {
1159     int i, errors = 0;
1160     ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
1161 
1162     if(rc != NULL)
1163 	*rc = RC_NONE;
1164 
1165     for(i = 0; i < 128; i++)
1166     {
1167 	if(bank->tone[i].instrument == MAGIC_LOAD_INSTRUMENT)
1168 	{
1169 	    if(!(bank->tone[i].name))
1170 	    {
1171 		bank->tone[i].instrument = load_instrument(dr, b, i);
1172 		if(bank->tone[i].instrument == NULL)
1173 		{
1174 		    ctl->cmsg(CMSG_WARNING,
1175 			      (b != 0) ? VERB_VERBOSE : VERB_NORMAL,
1176 			      "No instrument mapped to %s %d, program %d%s",
1177 			      dr ? "drum set" : "tone bank",
1178 			      dr ? b+progbase : b,
1179 			      dr ? i : i+progbase,
1180 			      (b != 0) ? "" :
1181 			      " - this instrument will not be heard");
1182 		    if(b != 0)
1183 		    {
1184 			/* Mark the corresponding instrument in the default
1185 			   bank / drumset for loading (if it isn't already) */
1186 			if(!dr)
1187 			{
1188 			    if(!(standard_tonebank.tone[i].instrument))
1189 				standard_tonebank.tone[i].instrument =
1190 				    MAGIC_LOAD_INSTRUMENT;
1191 			}
1192 			else
1193 			{
1194 			    if(!(standard_drumset.tone[i].instrument))
1195 				standard_drumset.tone[i].instrument =
1196 				    MAGIC_LOAD_INSTRUMENT;
1197 			}
1198 			bank->tone[i].instrument = 0;
1199 		    }
1200 		    else
1201 			bank->tone[i].instrument = MAGIC_ERROR_INSTRUMENT;
1202 		    errors++;
1203 		}
1204 	    }
1205 	    else
1206 	    {
1207 		if(rc != NULL)
1208 		{
1209 		    *rc = check_apply_control();
1210 		    if(RC_IS_SKIP_FILE(*rc))
1211 			return errors;
1212 		}
1213 
1214 		bank->tone[i].instrument = load_instrument(dr, b, i);
1215 		if(!bank->tone[i].instrument)
1216 		{
1217 		    ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
1218 			      "Couldn't load instrument %s "
1219 			      "(%s %d, program %d)", bank->tone[i].name,
1220 			      dr ? "drum set" : "tone bank",
1221 			      dr ? b+progbase : b,
1222 			      dr ? i : i+progbase);
1223 		    errors++;
1224 		}
1225 	    }
1226 	}
1227     }
1228     return errors;
1229 }
1230 
load_missing_instruments(int * rc)1231 int load_missing_instruments(int *rc)
1232 {
1233   int i = 128 + map_bank_counter, errors = 0;
1234   if(rc != NULL)
1235       *rc = RC_NONE;
1236   while (i--)
1237     {
1238       if (tonebank[i])
1239 	errors+=fill_bank(0,i,rc);
1240       if(rc != NULL && RC_IS_SKIP_FILE(*rc))
1241 	  return errors;
1242       if (drumset[i])
1243 	errors+=fill_bank(1,i,rc);
1244       if(rc != NULL && RC_IS_SKIP_FILE(*rc))
1245 	  return errors;
1246     }
1247   return errors;
1248 }
1249 
safe_memdup(void * s,size_t size)1250 static void *safe_memdup(void *s, size_t size)
1251 {
1252 	return memcpy(safe_malloc(size), s, size);
1253 }
1254 
1255 /*! Copy ToneBankElement src to elm. The original elm is released. */
copy_tone_bank_element(ToneBankElement * elm,const ToneBankElement * src)1256 void copy_tone_bank_element(ToneBankElement *elm, const ToneBankElement *src)
1257 {
1258 	int i;
1259 
1260 	free_tone_bank_element(elm);
1261 	memcpy(elm, src, sizeof(ToneBankElement));
1262 	if (elm->name)
1263 		elm->name = safe_strdup(elm->name);
1264 	if (elm->tunenum)
1265 		elm->tune = (float *) safe_memdup(elm->tune,
1266 				elm->tunenum * sizeof(float));
1267 	if (elm->envratenum) {
1268 		elm->envrate = (int **) safe_memdup(elm->envrate,
1269 				elm->envratenum * sizeof(int *));
1270 		for (i = 0; i < elm->envratenum; i++)
1271 			elm->envrate[i] = (int *) safe_memdup(elm->envrate[i],
1272 					6 * sizeof(int));
1273 	}
1274 	if (elm->envofsnum) {
1275 		elm->envofs = (int **) safe_memdup(elm->envofs,
1276 				elm->envofsnum * sizeof(int *));
1277 		for (i = 0; i < elm->envofsnum; i++)
1278 			elm->envofs[i] = (int *) safe_memdup(elm->envofs[i],
1279 					6 * sizeof(int));
1280 	}
1281 	if (elm->tremnum) {
1282 		elm->trem = (Quantity **) safe_memdup(elm->trem,
1283 				elm->tremnum * sizeof(Quantity *));
1284 		for (i = 0; i < elm->tremnum; i++)
1285 			elm->trem[i] = (Quantity *) safe_memdup(elm->trem[i],
1286 					3 * sizeof(Quantity));
1287 	}
1288 	if (elm->vibnum) {
1289 		elm->vib = (Quantity **) safe_memdup(elm->vib,
1290 				elm->vibnum * sizeof(Quantity *));
1291 		for (i = 0; i < elm->vibnum; i++)
1292 			elm->vib[i] = (Quantity *) safe_memdup(elm->vib[i],
1293 					3 * sizeof(Quantity));
1294 	}
1295 	if (elm->sclnotenum)
1296 		elm->sclnote = (int16 *) safe_memdup(elm->sclnote,
1297 				elm->sclnotenum * sizeof(int16));
1298 	if (elm->scltunenum)
1299 		elm->scltune = (int16 *) safe_memdup(elm->scltune,
1300 				elm->scltunenum * sizeof(int16));
1301 	if (elm->comment)
1302 		elm->comment = safe_strdup(elm->comment);
1303 	if (elm->modenvratenum) {
1304 		elm->modenvrate = (int **) safe_memdup(elm->modenvrate,
1305 				elm->modenvratenum * sizeof(int *));
1306 		for (i = 0; i < elm->modenvratenum; i++)
1307 			elm->modenvrate[i] = (int *) safe_memdup(elm->modenvrate[i],
1308 					6 * sizeof(int));
1309 	}
1310 	if (elm->modenvofsnum) {
1311 		elm->modenvofs = (int **) safe_memdup(elm->modenvofs,
1312 				elm->modenvofsnum * sizeof(int *));
1313 		for (i = 0; i < elm->modenvofsnum; i++)
1314 			elm->modenvofs[i] = (int *) safe_memdup(elm->modenvofs[i],
1315 					6 * sizeof(int));
1316 	}
1317 	if (elm->envkeyfnum) {
1318 		elm->envkeyf = (int **) safe_memdup(elm->envkeyf,
1319 				elm->envkeyfnum * sizeof(int *));
1320 		for (i = 0; i < elm->envkeyfnum; i++)
1321 			elm->envkeyf[i] = (int *) safe_memdup(elm->envkeyf[i],
1322 					6 * sizeof(int));
1323 	}
1324 	if (elm->envvelfnum) {
1325 		elm->envvelf = (int **) safe_memdup(elm->envvelf,
1326 				elm->envvelfnum * sizeof(int *));
1327 		for (i = 0; i < elm->envvelfnum; i++)
1328 			elm->envvelf[i] = (int *) safe_memdup(elm->envvelf[i],
1329 					6 * sizeof(int));
1330 	}
1331 	if (elm->modenvkeyfnum) {
1332 		elm->modenvkeyf = (int **) safe_memdup(elm->modenvkeyf,
1333 				elm->modenvkeyfnum * sizeof(int *));
1334 		for (i = 0; i < elm->modenvkeyfnum; i++)
1335 			elm->modenvkeyf[i] = (int *) safe_memdup(elm->modenvkeyf[i],
1336 					6 * sizeof(int));
1337 	}
1338 	if (elm->modenvvelfnum) {
1339 		elm->modenvvelf = (int **) safe_memdup(elm->modenvvelf,
1340 				elm->modenvvelfnum * sizeof(int *));
1341 		for (i = 0; i < elm->modenvvelfnum; i++)
1342 			elm->modenvvelf[i] = (int *) safe_memdup(elm->modenvvelf[i],
1343 					6 * sizeof(int));
1344 	}
1345 	if (elm->trempitchnum)
1346 		elm->trempitch = (int16 *) safe_memdup(elm->trempitch,
1347 				elm->trempitchnum * sizeof(int16));
1348 	if (elm->tremfcnum)
1349 		elm->tremfc = (int16 *) safe_memdup(elm->tremfc,
1350 				elm->tremfcnum * sizeof(int16));
1351 	if (elm->modpitchnum)
1352 		elm->modpitch = (int16 *) safe_memdup(elm->modpitch,
1353 				elm->modpitchnum * sizeof(int16));
1354 	if (elm->modfcnum)
1355 		elm->modfc = (int16 *) safe_memdup(elm->modfc,
1356 				elm->modfcnum * sizeof(int16));
1357 	if (elm->fcnum)
1358 		elm->fc = (int16 *) safe_memdup(elm->fc,
1359 				elm->fcnum * sizeof(int16));
1360 	if (elm->resonum)
1361 		elm->reso = (int16 *) safe_memdup(elm->reso,
1362 				elm->resonum * sizeof(int16));
1363 
1364 }
1365 
1366 /*! Release ToneBank[128 + MAP_BANK_COUNT] */
free_tone_bank_list(ToneBank * tb[])1367 static void free_tone_bank_list(ToneBank *tb[])
1368 {
1369 	int i, j;
1370 	ToneBank *bank;
1371 
1372 	for (i = 0; i < 128 + map_bank_counter; i++)
1373 	{
1374 		bank = tb[i];
1375 		if (!bank)
1376 			continue;
1377 		for (j = 0; j < 128; j++)
1378 			free_tone_bank_element(&bank->tone[j]);
1379 		if (i > 0)
1380 		{
1381 			free(bank);
1382 			tb[i] = NULL;
1383 		}
1384 	}
1385 }
1386 
1387 /*! Release tonebank and drumset */
free_tone_bank(void)1388 void free_tone_bank(void)
1389 {
1390 	free_tone_bank_list(tonebank);
1391 	free_tone_bank_list(drumset);
1392 }
1393 
1394 /*! Release ToneBankElement. */
free_tone_bank_element(ToneBankElement * elm)1395 void free_tone_bank_element(ToneBankElement *elm)
1396 {
1397 	elm->instype = 0;
1398 	if (elm->name)
1399 		free(elm->name);
1400 	elm->name = NULL;
1401 	if (elm->tune)
1402 		free(elm->tune);
1403 	elm->tune = NULL, elm->tunenum = 0;
1404 	if (elm->envratenum)
1405 		free_ptr_list(elm->envrate, elm->envratenum);
1406 	elm->envrate = NULL, elm->envratenum = 0;
1407 	if (elm->envofsnum)
1408 		free_ptr_list(elm->envofs, elm->envofsnum);
1409 	elm->envofs = NULL, elm->envofsnum = 0;
1410 	if (elm->tremnum)
1411 		free_ptr_list(elm->trem, elm->tremnum);
1412 	elm->trem = NULL, elm->tremnum = 0;
1413 	if (elm->vibnum)
1414 		free_ptr_list(elm->vib, elm->vibnum);
1415 	elm->vib = NULL, elm->vibnum = 0;
1416 	if (elm->sclnote)
1417 		free(elm->sclnote);
1418 	elm->sclnote = NULL, elm->sclnotenum = 0;
1419 	if (elm->scltune)
1420 		free(elm->scltune);
1421 	elm->scltune = NULL, elm->scltunenum = 0;
1422 	if (elm->comment)
1423 		free(elm->comment);
1424 	elm->comment = NULL;
1425 	if (elm->modenvratenum)
1426 		free_ptr_list(elm->modenvrate, elm->modenvratenum);
1427 	elm->modenvrate = NULL, elm->modenvratenum = 0;
1428 	if (elm->modenvofsnum)
1429 		free_ptr_list(elm->modenvofs, elm->modenvofsnum);
1430 	elm->modenvofs = NULL, elm->modenvofsnum = 0;
1431 	if (elm->envkeyfnum)
1432 		free_ptr_list(elm->envkeyf, elm->envkeyfnum);
1433 	elm->envkeyf = NULL, elm->envkeyfnum = 0;
1434 	if (elm->envvelfnum)
1435 		free_ptr_list(elm->envvelf, elm->envvelfnum);
1436 	elm->envvelf = NULL, elm->envvelfnum = 0;
1437 	if (elm->modenvkeyfnum)
1438 		free_ptr_list(elm->modenvkeyf, elm->modenvkeyfnum);
1439 	elm->modenvkeyf = NULL, elm->modenvkeyfnum = 0;
1440 	if (elm->modenvvelfnum)
1441 		free_ptr_list(elm->modenvvelf, elm->modenvvelfnum);
1442 	elm->modenvvelf = NULL, elm->modenvvelfnum = 0;
1443 	if (elm->trempitch)
1444 		free(elm->trempitch);
1445 	elm->trempitch = NULL, elm->trempitchnum = 0;
1446 	if (elm->tremfc)
1447 		free(elm->tremfc);
1448 	elm->tremfc = NULL, elm->tremfcnum = 0;
1449 	if (elm->modpitch)
1450 		free(elm->modpitch);
1451 	elm->modpitch = NULL, elm->modpitchnum = 0;
1452 	if (elm->modfc)
1453 		free(elm->modfc);
1454 	elm->modfc = NULL, elm->modfcnum = 0;
1455 	if (elm->fc)
1456 		free(elm->fc);
1457 	elm->fc = NULL, elm->fcnum = 0;
1458 	if (elm->reso)
1459 		free(elm->reso);
1460 	elm->reso = NULL, elm->resonum = 0;
1461 }
1462 
free_instruments(int reload_default_inst)1463 void free_instruments(int reload_default_inst)
1464 {
1465     int i = 128 + map_bank_counter, j;
1466     struct InstrumentCache *p;
1467     ToneBank *bank;
1468     Instrument *ip;
1469     struct InstrumentCache *default_entry;
1470     int default_entry_addr;
1471 
1472     clear_magic_instruments();
1473 
1474     /* Free soundfont instruments */
1475     while(i--)
1476     {
1477 	/* Note that bank[*]->tone[j].instrument may pointer to
1478 	   bank[0]->tone[j].instrument. See play_midi_load_instrument()
1479 	   at playmidi.c for the implementation */
1480 
1481 	if((bank = tonebank[i]) != NULL)
1482 	    for(j = 127; j >= 0; j--)
1483 	    {
1484 		ip = bank->tone[j].instrument;
1485 		if(ip != NULL && ip->type == INST_SF2 &&
1486 		   (i == 0 || ip != tonebank[0]->tone[j].instrument))
1487 		    free_instrument(ip);
1488 		bank->tone[j].instrument = NULL;
1489 		if(bank->tone[j].name && !bank->tone[j].name[0]) /* DYNAMIC_INSTRUMENT_NAME */
1490 		{
1491 			free(bank->tone[j].name);
1492 			bank->tone[j].name = NULL;
1493 		}
1494 	    }
1495 	if((bank = drumset[i]) != NULL)
1496 	    for(j = 127; j >= 0; j--)
1497 	    {
1498 		ip = bank->tone[j].instrument;
1499 		if(ip != NULL && ip->type == INST_SF2 &&
1500 		   (i == 0 || ip != drumset[0]->tone[j].instrument))
1501 		    free_instrument(ip);
1502 		bank->tone[j].instrument = NULL;
1503 		if(bank->tone[j].name && !bank->tone[j].name[0]) /* DYNAMIC_INSTRUMENT_NAME */
1504 		{
1505 			free(bank->tone[j].name);
1506 			bank->tone[j].name = NULL;
1507 		}
1508 	    }
1509 #if 0
1510 		if ((drumset[i] != NULL) && (drumset[i]->alt != NULL)) {
1511 			free(drumset[i]->alt);
1512 			drumset[i]->alt = NULL;
1513 		}
1514 #endif
1515     }
1516 
1517     /* Free GUS/patch instruments */
1518     default_entry = NULL;
1519     default_entry_addr = 0;
1520     for(i = 0; i < INSTRUMENT_HASH_SIZE; i++)
1521     {
1522 	p = instrument_cache[i];
1523 	while(p != NULL)
1524 	{
1525 	    if(!reload_default_inst && p->ip == default_instrument)
1526 	    {
1527 		default_entry = p;
1528 		default_entry_addr = i;
1529 		p = p->next;
1530 	    }
1531 	    else
1532 	    {
1533 		struct InstrumentCache *tmp;
1534 
1535 		tmp = p;
1536 		p = p->next;
1537 		free_instrument(tmp->ip);
1538 		free(tmp);
1539 	    }
1540 	}
1541 	instrument_cache[i] = NULL;
1542     }
1543 
1544     if(reload_default_inst)
1545 	set_default_instrument(NULL);
1546     else if(default_entry)
1547     {
1548 	default_entry->next = NULL;
1549 	instrument_cache[default_entry_addr] = default_entry;
1550     }
1551 }
1552 
free_special_patch(int id)1553 void free_special_patch(int id)
1554 {
1555     int i, j, start, end;
1556 
1557     if(id >= 0)
1558 	start = end = id;
1559     else
1560     {
1561 	start = 0;
1562 	end = NSPECIAL_PATCH - 1;
1563     }
1564 
1565     for(i = start; i <= end; i++)
1566 	if(special_patch[i] != NULL)
1567 	{
1568 	    Sample *sp;
1569 	    int n;
1570 
1571 	    if(special_patch[i]->name != NULL)
1572 		free(special_patch[i]->name);
1573 			special_patch[i]->name = NULL;
1574 	    n = special_patch[i]->samples;
1575 	    sp = special_patch[i]->sample;
1576 	    if(sp)
1577 	    {
1578 		for(j = 0; j < n; j++)
1579 		    if(sp[j].data_alloced && sp[j].data)
1580 			free(sp[j].data);
1581 		free(sp);
1582 	    }
1583 	    free(special_patch[i]);
1584 	    special_patch[i] = NULL;
1585 	}
1586 }
1587 
set_default_instrument(char * name)1588 int set_default_instrument(char *name)
1589 {
1590     Instrument *ip;
1591     int i;
1592     static char *last_name;
1593 
1594     if(name == NULL)
1595     {
1596 	name = last_name;
1597 	if(name == NULL)
1598 	    return 0;
1599     }
1600 
1601     if(!(ip = load_gus_instrument(name, NULL, 0, 0, NULL)))
1602 	return -1;
1603     if(default_instrument)
1604 	free_instrument(default_instrument);
1605     default_instrument = ip;
1606     for(i = 0; i < MAX_CHANNELS; i++)
1607 	default_program[i] = SPECIAL_PROGRAM;
1608     last_name = name;
1609 
1610     return 0;
1611 }
1612 
1613 /*! search mapped bank.
1614     returns negative value indicating free bank if not found,
1615     0 if no free bank was available */
find_instrument_map_bank(int dr,int map,int bk)1616 int find_instrument_map_bank(int dr, int map, int bk)
1617 {
1618 	struct bank_map_elem *bm;
1619 	int i;
1620 
1621 	if (map == INST_NO_MAP)
1622 		return 0;
1623 	bm = dr ? map_drumset : map_bank;
1624 	for(i = 0; i < MAP_BANK_COUNT; i++)
1625 	{
1626 		if (!bm[i].used)
1627 			return -(128 + i);
1628 		else if (bm[i].mapid == map && bm[i].bankno == bk)
1629 			return 128 + i;
1630 	}
1631 	return 0;
1632 }
1633 
1634 /*! allocate mapped bank if needed. returns -1 if allocation failed. */
alloc_instrument_map_bank(int dr,int map,int bk)1635 int alloc_instrument_map_bank(int dr, int map, int bk)
1636 {
1637 	struct bank_map_elem *bm;
1638 	int i;
1639 
1640 	if (map == INST_NO_MAP)
1641 	{
1642 		alloc_instrument_bank(dr, bk);
1643 		return bk;
1644 	}
1645 	i = find_instrument_map_bank(dr, map, bk);
1646 	if (i == 0)
1647 		return -1;
1648 	if (i < 0)
1649 	{
1650 		i = -i - 128;
1651 		bm = dr ? map_drumset : map_bank;
1652 		bm[i].used = 1;
1653 		bm[i].mapid = map;
1654 		bm[i].bankno = bk;
1655 		if (map_bank_counter < i + 1)
1656 			map_bank_counter = i + 1;
1657 		i += 128;
1658 		alloc_instrument_bank(dr, i);
1659 	}
1660 	return i;
1661 }
1662 
alloc_instrument_bank(int dr,int bk)1663 void alloc_instrument_bank(int dr, int bk)
1664 {
1665     ToneBank *b;
1666 
1667     if(dr)
1668     {
1669 	if((b = drumset[bk]) == NULL)
1670 	{
1671 	    b = drumset[bk] = (ToneBank *)safe_malloc(sizeof(ToneBank));
1672 	    memset(b, 0, sizeof(ToneBank));
1673 	}
1674     }
1675     else
1676     {
1677 	if((b = tonebank[bk]) == NULL)
1678 	{
1679 	    b = tonebank[bk] = (ToneBank *)safe_malloc(sizeof(ToneBank));
1680 	    memset(b, 0, sizeof(ToneBank));
1681 	}
1682     }
1683 }
1684 
1685 
1686 /* Instrument alias map - Written by Masanao Izumo */
1687 
instrument_map(int mapID,int * set,int * elem)1688 int instrument_map(int mapID, int *set, int *elem)
1689 {
1690     int s, e;
1691     struct inst_map_elem *p;
1692 
1693     if(mapID == INST_NO_MAP)
1694 	return 0; /* No map */
1695 
1696     s = *set;
1697     e = *elem;
1698     p = inst_map_table[mapID][s];
1699     if(p != NULL && p[e].mapped)
1700     {
1701 	*set = p[e].set;
1702 	*elem = p[e].elem;
1703 	return 1;
1704     }
1705 
1706     if(s != 0)
1707     {
1708 	p = inst_map_table[mapID][0];
1709 	if(p != NULL && p[e].mapped)
1710 	{
1711 	    *set = p[e].set;
1712 	    *elem = p[e].elem;
1713 	}
1714 	return 2;
1715     }
1716     return 0;
1717 }
1718 
set_instrument_map(int mapID,int set_from,int elem_from,int set_to,int elem_to)1719 void set_instrument_map(int mapID,
1720 			int set_from, int elem_from,
1721 			int set_to, int elem_to)
1722 {
1723     struct inst_map_elem *p;
1724 
1725     p = inst_map_table[mapID][set_from];
1726     if(p == NULL)
1727     {
1728 		p = (struct inst_map_elem *)
1729 	    safe_malloc(128 * sizeof(struct inst_map_elem));
1730 	    memset(p, 0, 128 * sizeof(struct inst_map_elem));
1731 		inst_map_table[mapID][set_from] = p;
1732     }
1733     p[elem_from].set = set_to;
1734     p[elem_from].elem = elem_to;
1735 	p[elem_from].mapped = 1;
1736 }
1737 
free_instrument_map(void)1738 void free_instrument_map(void)
1739 {
1740   int i, j;
1741 
1742   for(i = 0; i < map_bank_counter; i++)
1743     map_bank[i].used = map_drumset[i].used = 0;
1744   /* map_bank_counter = 0; never shrinks rather than assuming tonebank was already freed */
1745   for (i = 0; i < NUM_INST_MAP; i++) {
1746     for (j = 0; j < 128; j++) {
1747       struct inst_map_elem *map;
1748       map = inst_map_table[i][j];
1749       if (map) {
1750 	free(map);
1751 	inst_map_table[i][j] = NULL;
1752       }
1753     }
1754   }
1755 }
1756 
1757 /* Alternate assign - Written by Masanao Izumo */
1758 
add_altassign_string(AlternateAssign * old,char ** params,int n)1759 AlternateAssign *add_altassign_string(AlternateAssign *old,
1760 				      char **params, int n)
1761 {
1762     int i, j;
1763     char *p;
1764     int beg, end;
1765     AlternateAssign *alt;
1766 
1767     if(n == 0)
1768 	return old;
1769     if(!strcmp(*params, "clear")) {
1770 	while(old) {
1771 	    AlternateAssign *next;
1772 	    next = old->next;
1773 	    free(old);
1774 	    old = next;
1775 	}
1776 	params++;
1777 	n--;
1778 	if(n == 0)
1779 	    return NULL;
1780     }
1781 
1782     alt = (AlternateAssign *)safe_malloc(sizeof(AlternateAssign));
1783     memset(alt, 0, sizeof(AlternateAssign));
1784     for(i = 0; i < n; i++) {
1785 	p = params[i];
1786 	if(*p == '-') {
1787 	    beg = 0;
1788 	    p++;
1789 	} else
1790 	    beg = atoi(p);
1791 	if((p = strchr(p, '-')) != NULL) {
1792 	    if(p[1] == '\0')
1793 		end = 127;
1794 	    else
1795 		end = atoi(p + 1);
1796 	} else
1797 	    end = beg;
1798 	if(beg > end) {
1799 	    int t;
1800 	    t = beg;
1801 	    beg = end;
1802 	    end = t;
1803 	}
1804 	if(beg < 0)
1805 	    beg = 0;
1806 	if(end > 127)
1807 	    end = 127;
1808 	for(j = beg; j <= end; j++)
1809 	    alt->bits[(j >> 5) & 0x3] |= 1 << (j & 0x1F);
1810     }
1811     alt->next = old;
1812     return alt;
1813 }
1814 
find_altassign(AlternateAssign * altassign,int note)1815 AlternateAssign *find_altassign(AlternateAssign *altassign, int note)
1816 {
1817     AlternateAssign *p;
1818     uint32 mask;
1819     int idx;
1820 
1821     mask = 1 << (note & 0x1F);
1822     idx = (note >> 5) & 0x3;
1823     for(p = altassign; p != NULL; p = p->next)
1824 	if(p->bits[idx] & mask)
1825 	    return p;
1826     return NULL;
1827 }
1828