1 /*
2
3 TiMidity -- Experimental MIDI to WAVE converter
4 Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.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., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 instrum.c
21
22 Code to load and unload GUS-compatible instrument patches.
23
24 */
25
26 #include "pent_include.h"
27
28 #ifdef USE_TIMIDITY_MIDI
29
30 #include <cstdio>
31 #include <cstring>
32 #include <cstdlib>
33
34 #include "timidity.h"
35 #include "timidity_common.h"
36 #include "timidity_instrum.h"
37 #include "timidity_playmidi.h"
38 #include "timidity_output.h"
39 #include "timidity_controls.h"
40 #include "timidity_resample.h"
41 #include "timidity_tables.h"
42 #include "timidity_filter.h"
43 #include "ignore_unused_variable_warning.h"
44
45 #ifdef NS_TIMIDITY
46 namespace NS_TIMIDITY {
47 #endif
48
49 /* Some functions get aggravated if not even the standard banks are
50 available. */
51 static ToneBank standard_tonebank, standard_drumset;
52 ToneBank
53 *tonebank[128]={&standard_tonebank},
54 *drumset[128]={&standard_drumset};
55
56 /* This is a special instrument, used for all melodic programs */
57 Instrument *default_instrument=nullptr;
58
59 /* This is only used for tracks that don't specify a program */
60 int default_program=DEFAULT_PROGRAM;
61
62 int antialiasing_allowed=0;
63 #ifdef FAST_DECAY
64 int fast_decay=1;
65 #else
66 int fast_decay=0;
67 #endif
68
free_instrument(Instrument * ip)69 static void free_instrument(Instrument *ip)
70 {
71 if (!ip) return;
72 for (int i=0; i<ip->samples; i++)
73 {
74 Sample *sp = &(ip->sample[i]);
75 free(sp->data);
76 }
77 free(ip->sample);
78 free(ip);
79 }
80
free_bank(int dr,int b)81 static void free_bank(int dr, int b)
82 {
83 ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
84 for (int i=0; i<128; i++)
85 if (bank->tone[i].instrument)
86 {
87 /* Not that this could ever happen, of course */
88 if (bank->tone[i].instrument != MAGIC_LOAD_INSTRUMENT)
89 free_instrument(bank->tone[i].instrument);
90 bank->tone[i].instrument=nullptr;
91 }
92 }
93
convert_envelope_rate(uint8 rate)94 static sint32 convert_envelope_rate(uint8 rate)
95 {
96 sint32 r=3-((rate>>6) & 0x3);
97 r*=3;
98 r = (rate & 0x3f) << r; /* 6.9 fixed point */
99
100 /* 15.15 fixed point. */
101 return (((r * 44100) / play_mode->rate) * control_ratio)
102 << ((fast_decay) ? 10 : 9);
103 }
104
convert_envelope_offset(uint8 offset)105 static sint32 convert_envelope_offset(uint8 offset)
106 {
107 /* This is not too good... Can anyone tell me what these values mean?
108 Are they GUS-style "exponential" volumes? And what does that mean? */
109
110 /* 15.15 fixed point */
111 return offset << (7+15);
112 }
113
convert_tremolo_sweep(uint8 sweep)114 static sint32 convert_tremolo_sweep(uint8 sweep)
115 {
116 if (!sweep)
117 return 0;
118
119 return
120 ((control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
121 (play_mode->rate * sweep);
122 }
123
convert_vibrato_sweep(uint8 sweep,sint32 vib_control_ratio)124 static sint32 convert_vibrato_sweep(uint8 sweep, sint32 vib_control_ratio)
125 {
126 if (!sweep)
127 return 0;
128
129 return
130 static_cast<sint32>(FSCALE(static_cast<double>(vib_control_ratio) * SWEEP_TUNING, SWEEP_SHIFT)
131 / static_cast<double>(play_mode->rate * sweep));
132
133 /* this was overflowing with seashore.pat
134
135 ((vib_control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
136 (play_mode->rate * sweep); */
137 }
138
convert_tremolo_rate(uint8 rate)139 static sint32 convert_tremolo_rate(uint8 rate)
140 {
141 return
142 ((SINE_CYCLE_LENGTH * control_ratio * rate) << RATE_SHIFT) /
143 (TREMOLO_RATE_TUNING * play_mode->rate);
144 }
145
convert_vibrato_rate(uint8 rate)146 static sint32 convert_vibrato_rate(uint8 rate)
147 {
148 /* Return a suitable vibrato_control_ratio value */
149 return
150 (VIBRATO_RATE_TUNING * play_mode->rate) /
151 (rate * 2 * VIBRATO_SAMPLE_INCREMENTS);
152 }
153
reverse_data(sint16 * sp,sint32 ls,sint32 le)154 static void reverse_data(sint16 *sp, sint32 ls, sint32 le)
155 {
156 sint16 *ep=sp+le;
157 sp+=ls;
158 le-=ls;
159 le/=2;
160 while (le--)
161 {
162 sint16 s=*sp;
163 *sp++=*ep;
164 *ep--=s;
165 }
166 }
167
168 /*
169 If panning or note_to_use != -1, it will be used for all samples,
170 instead of the sample-specific values in the instrument file.
171
172 For note_to_use, any value <0 or >127 will be forced to 0.
173
174 For other parameters, 1 means yes, 0 means no, other values are
175 undefined.
176
177 TODO: do reverse loops right */
load_instrument(char * name,int percussion,int panning,int amp,int note_to_use,int strip_loop,int strip_envelope,int strip_tail)178 static Instrument *load_instrument(char *name, int percussion,
179 int panning, int amp, int note_to_use,
180 int strip_loop, int strip_envelope,
181 int strip_tail)
182 {
183 ignore_unused_variable_warning(percussion);
184 Instrument *ip;
185 Sample *sp;
186 FILE *fp;
187 uint8 tmp[1024];
188 int i;
189 int j;
190 int noluck=0;
191 #ifdef PATCH_EXT_LIST
192 static const char *patch_ext[] = PATCH_EXT_LIST;
193 #endif
194
195 if (!name) return nullptr;
196
197 /* Open patch file */
198 if ((fp=open_file(name, 1, OF_NORMAL)) == nullptr)
199 {
200 noluck=1;
201 #ifdef PATCH_EXT_LIST
202 /* Try with various extensions */
203 for (i=0; patch_ext[i]; i++)
204 {
205 if (strlen(name)+strlen(patch_ext[i])<1024)
206 {
207 char path[1024];
208 strcpy(path, name);
209 strcat(path, patch_ext[i]);
210 if ((fp=open_file(path, 1, OF_NORMAL)) != nullptr)
211 {
212 noluck=0;
213 break;
214 }
215 }
216 }
217 #endif
218 }
219
220 if (noluck)
221 {
222 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
223 "Instrument `%s' can't be found.", name);
224 return nullptr;
225 }
226
227 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", current_filename);
228
229 /* Read some headers and do cursory sanity checks. There are loads
230 of magic offsets. This could be rewritten... */
231
232 if ((239 != fread(tmp, 1, 239, fp)) ||
233 (memcmp(tmp, "GF1PATCH110\0ID#000002", 22) != 0 &&
234 memcmp(tmp, "GF1PATCH100\0ID#000002", 22) != 0)) /* don't know what the
235 differences are */
236 {
237 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
238 close_file(fp);
239 return nullptr;
240 }
241
242 if (tmp[82] != 1 && tmp[82] != 0) /* instruments. To some patch makers,
243 0 means 1 */
244 {
245 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
246 "Can't handle patches with %d instruments", tmp[82]);
247 close_file(fp);
248 return nullptr;
249 }
250
251 if (tmp[151] != 1 && tmp[151] != 0) /* layers. What's a layer? */
252 {
253 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
254 "Can't handle instruments with %d layers", tmp[151]);
255 close_file(fp);
256 return nullptr;
257 }
258
259 ip=safe_Malloc<Instrument>();
260 ip->samples = tmp[198];
261 ip->sample = safe_Malloc<Sample>(ip->samples);
262 for (i=0; i<ip->samples; i++)
263 {
264
265 uint8 fractions;
266 sint32 tmplong;
267 uint16 tmpshort;
268 uint8 tmpchar;
269
270 #define READ_CHAR(thing) \
271 if (1 != fread(&tmpchar, 1, 1, fp)) goto fail; \
272 (thing) = tmpchar;
273 #define READ_SHORT(thing) \
274 if (1 != fread(&tmpshort, 2, 1, fp)) goto fail; \
275 (thing) = LE_SHORT(tmpshort);
276 #define READ_LONG(thing) \
277 if (1 != fread(&tmplong, 4, 1, fp)) goto fail; \
278 (thing) = LE_LONG(tmplong);
279
280 skip(fp, 7); /* Skip the wave name */
281
282 if (1 != fread(&fractions, 1, 1, fp))
283 {
284 fail:
285 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
286 for (j=0; j<i; j++)
287 free(ip->sample[j].data);
288 free(ip->sample);
289 free(ip);
290 close_file(fp);
291 return nullptr;
292 }
293
294 sp=&(ip->sample[i]);
295
296 READ_LONG(sp->data_length);
297 READ_LONG(sp->loop_start);
298 READ_LONG(sp->loop_end);
299 READ_SHORT(sp->sample_rate);
300 READ_LONG(sp->low_freq);
301 READ_LONG(sp->high_freq);
302 READ_LONG(sp->root_freq);
303 skip(fp, 2); /* Why have a "root frequency" and then "tuning"?? */
304
305 READ_CHAR(tmp[0]);
306
307 if (panning==-1)
308 sp->panning = (tmp[0] * 8 + 4) & 0x7f;
309 else
310 sp->panning=static_cast<uint8>(panning & 0x7F);
311
312 /* envelope, tremolo, and vibrato */
313 if (18 != fread(tmp, 1, 18, fp)) goto fail;
314
315 if (!tmp[13] || !tmp[14])
316 {
317 sp->tremolo_sweep_increment=
318 sp->tremolo_phase_increment=sp->tremolo_depth=0;
319 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
320 }
321 else
322 {
323 sp->tremolo_sweep_increment=convert_tremolo_sweep(tmp[12]);
324 sp->tremolo_phase_increment=convert_tremolo_rate(tmp[13]);
325 sp->tremolo_depth=tmp[14];
326 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
327 " * tremolo: sweep %d, phase %d, depth %d",
328 sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
329 sp->tremolo_depth);
330 }
331
332 if (!tmp[16] || !tmp[17])
333 {
334 sp->vibrato_sweep_increment=
335 sp->vibrato_control_ratio=sp->vibrato_depth=0;
336 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
337 }
338 else
339 {
340 sp->vibrato_control_ratio=convert_vibrato_rate(tmp[16]);
341 sp->vibrato_sweep_increment=
342 convert_vibrato_sweep(tmp[15], sp->vibrato_control_ratio);
343 sp->vibrato_depth=tmp[17];
344 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
345 " * vibrato: sweep %d, ctl %d, depth %d",
346 sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
347 sp->vibrato_depth);
348 }
349
350 READ_CHAR(sp->modes);
351
352 skip(fp, 40); /* skip the useless scale frequency, scale factor
353 (what's it mean?), and reserved space */
354
355 /* Mark this as a fixed-pitch instrument if such a deed is desired. */
356 if (note_to_use!=-1)
357 sp->note_to_use=static_cast<uint8>(note_to_use);
358 else
359 sp->note_to_use=0;
360
361 /* seashore.pat in the Midia patch set has no Sustain. I don't
362 understand why, and fixing it by adding the Sustain flag to
363 all looped patches probably breaks something else. We do it
364 anyway. */
365
366 if (sp->modes & MODES_LOOPING)
367 sp->modes |= MODES_SUSTAIN;
368
369 /* Strip any loops and envelopes we're permitted to */
370 if ((strip_loop==1) &&
371 (sp->modes & (MODES_SUSTAIN | MODES_LOOPING |
372 MODES_PINGPONG | MODES_REVERSE)))
373 {
374 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
375 sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING |
376 MODES_PINGPONG | MODES_REVERSE);
377 }
378
379 if (strip_envelope==1)
380 {
381 if (sp->modes & MODES_ENVELOPE)
382 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
383 sp->modes &= ~MODES_ENVELOPE;
384 }
385 else if (strip_envelope != 0)
386 {
387 /* Have to make a guess. */
388 if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
389 {
390 /* No loop? Then what's there to sustain? No envelope needed
391 either... */
392 sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
393 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
394 " - No loop, removing sustain and envelope");
395 }
396 else if (!memcmp(tmp, "??????", 6) || tmp[11] >= 100)
397 {
398 /* Envelope rates all maxed out? Envelope end at a high "offset"?
399 That's a weird envelope. Take it out. */
400 sp->modes &= ~MODES_ENVELOPE;
401 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
402 " - Weirdness, removing envelope");
403 }
404 else if (!(sp->modes & MODES_SUSTAIN))
405 {
406 /* No sustain? Then no envelope. I don't know if this is
407 justified, but patches without sustain usually don't need the
408 envelope either... at least the Gravis ones. They're mostly
409 drums. I think. */
410 sp->modes &= ~MODES_ENVELOPE;
411 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
412 " - No sustain, removing envelope");
413 }
414 }
415
416 for (j=0; j<6; j++)
417 {
418 sp->envelope_rate[j]=
419 convert_envelope_rate(tmp[j]);
420 sp->envelope_offset[j]=
421 convert_envelope_offset(tmp[6+j]);
422 }
423
424 /* Then read the sample data */
425 sp->data = safe_Malloc<sample_t>(sp->data_length);
426 if (1 != fread(sp->data, sp->data_length, 1, fp))
427 goto fail;
428
429 if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
430 {
431 sint32 i=sp->data_length;
432 auto *cp=reinterpret_cast<uint8 *>(sp->data);
433 uint16 *tmp;
434 uint16 *new_dat;
435 tmp=new_dat=safe_Malloc<uint16>(sp->data_length);
436 while (i--)
437 *tmp++ = static_cast<uint16>(*cp++) << 8;
438 cp=reinterpret_cast<uint8 *>(sp->data);
439 sp->data = reinterpret_cast<sample_t *>(new_dat);
440 free(cp);
441 sp->data_length *= 2;
442 sp->loop_start *= 2;
443 sp->loop_end *= 2;
444 }
445 #ifndef TIMIDITY_LITTLE_ENDIAN
446 else
447 /* convert to machine byte order */
448 {
449 sint32 i=sp->data_length/2;
450 #ifdef LOOKUP_HACK
451 sint16 *tmp=reinterpret_cast<sint16 *>(sp->data);
452 sint16 *s;
453 #else
454 sample_t *tmp=sp->data;
455 sample_t s;
456 #endif
457 while (i--)
458 {
459 s=LE_SHORT(*tmp);
460 *tmp++=s;
461 }
462 }
463 #endif
464
465 if (sp->modes & MODES_UNSIGNED) /* convert to signed data */
466 {
467 sint32 i=sp->data_length/2;
468 sint16 *tmp = sp->data;
469 while (i--)
470 *tmp++ ^= 0x8000;
471 }
472
473 /* Reverse reverse loops and pass them off as normal loops */
474 if (sp->modes & MODES_REVERSE)
475 {
476 sint32 t;
477 /* The GUS apparently plays reverse loops by reversing the
478 whole sample. We do the same because the GUS does not SUCK. */
479
480 ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s", name);
481 reverse_data(sp->data, 0, sp->data_length/2);
482
483 t=sp->loop_start;
484 sp->loop_start=sp->data_length - sp->loop_end;
485 sp->loop_end=sp->data_length - t;
486
487 sp->modes &= ~MODES_REVERSE;
488 sp->modes |= MODES_LOOPING; /* just in case */
489 }
490
491 /* If necessary do some anti-aliasing filtering */
492
493 if (antialiasing_allowed)
494 antialiasing(sp,play_mode->rate);
495
496 #ifdef ADJUST_SAMPLE_VOLUMES
497 if (amp!=-1)
498 sp->volume=static_cast<float>((amp) / 100.0);
499 else
500 {
501 /* Try to determine a volume scaling factor for the sample.
502 This is a very crude adjustment, but things sound more
503 balanced with it. Still, this should be a runtime option. */
504 sint32 i=sp->data_length/2;
505 sint16 maxamp=0;
506 sint16 *tmp = sp->data;
507 while (i--)
508 {
509 sint16 a=*tmp++;
510 if (a<0) a=-a;
511 if (a>maxamp)
512 maxamp=a;
513 }
514 sp->volume=static_cast<float>(32768.0 / maxamp);
515 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f", sp->volume);
516 }
517 #else
518 if (amp!=-1)
519 sp->volume=static_cast<double>(amp) / 100.0;
520 else
521 sp->volume=1.0;
522 #endif
523
524 sp->data_length /= 2; /* These are in bytes. Convert into samples. */
525 sp->loop_start /= 2;
526 sp->loop_end /= 2;
527
528 /* Then fractional samples */
529 sp->data_length <<= FRACTION_BITS;
530 sp->loop_start <<= FRACTION_BITS;
531 sp->loop_end <<= FRACTION_BITS;
532
533 /* Adjust for fractional loop points. This is a guess. Does anyone
534 know what "fractions" really stands for? */
535 sp->loop_start |=
536 (fractions & 0x0F) << (FRACTION_BITS-4);
537 sp->loop_end |=
538 ((fractions>>4) & 0x0F) << (FRACTION_BITS-4);
539
540 /* If this instrument will always be played on the same note,
541 and it's not looped, we can resample it now. */
542 if (sp->note_to_use && !(sp->modes & MODES_LOOPING))
543 pre_resample(sp);
544
545 #ifdef LOOKUP_HACK
546 /* Squash the 16-bit data into 8 bits. */
547 {
548 uint8 *gulp,*ulp;
549 sint16 *swp;
550 int l=sp->data_length >> FRACTION_BITS;
551 gulp=ulp=safe_Malloc<uint8>(l+1);
552 swp=(sint16 *)sp->data;
553 while(l--)
554 *ulp++ = (*swp++ >> 8) & 0xFF;
555 free(sp->data);
556 sp->data=(sample_t *)gulp;
557 }
558 #endif
559
560 if (strip_tail==1)
561 {
562 /* Let's not really, just say we did. */
563 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail");
564 sp->data_length = sp->loop_end;
565 }
566 }
567
568 close_file(fp);
569 return ip;
570 }
571
fill_bank(int dr,int b)572 static int fill_bank(int dr, int b)
573 {
574 int i;
575 int errors=0;
576 ToneBank *bank=((dr) ? drumset[b] : tonebank[b]);
577 if (!bank)
578 {
579 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
580 "Huh. Tried to load instruments in non-existent %s %d",
581 (dr) ? "drumset" : "tone bank", b);
582 return 0;
583 }
584 for (i=0; i<128; i++)
585 {
586 if (bank->tone[i].instrument==MAGIC_LOAD_INSTRUMENT)
587 {
588 if (!(bank->tone[i].name))
589 {
590 ctl->cmsg(CMSG_WARNING, (b!=0) ? VERB_VERBOSE : VERB_NORMAL,
591 "No instrument mapped to %s %d, program %d%s",
592 (dr)? "drum set" : "tone bank", b, i,
593 (b!=0) ? "" : " - this instrument will not be heard");
594 if (b!=0)
595 {
596 /* Mark the corresponding instrument in the default
597 bank / drumset for loading (if it isn't already) */
598 if (!dr)
599 {
600 if (!(standard_tonebank.tone[i].instrument))
601 standard_tonebank.tone[i].instrument=
602 MAGIC_LOAD_INSTRUMENT;
603 }
604 else
605 {
606 if (!(standard_drumset.tone[i].instrument))
607 standard_drumset.tone[i].instrument=
608 MAGIC_LOAD_INSTRUMENT;
609 }
610 }
611 bank->tone[i].instrument=nullptr;
612 errors++;
613 }
614 else if (!(bank->tone[i].instrument=
615 load_instrument(bank->tone[i].name,
616 (dr) ? 1 : 0,
617 bank->tone[i].pan,
618 bank->tone[i].amp,
619 (bank->tone[i].note!=-1) ?
620 bank->tone[i].note :
621 ((dr) ? i : -1),
622 (bank->tone[i].strip_loop!=-1) ?
623 bank->tone[i].strip_loop :
624 ((dr) ? 1 : -1),
625 (bank->tone[i].strip_envelope != -1) ?
626 bank->tone[i].strip_envelope :
627 ((dr) ? 1 : -1),
628 bank->tone[i].strip_tail )))
629 {
630 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
631 "Couldn't load instrument %s (%s %d, program %d)",
632 bank->tone[i].name,
633 (dr)? "drum set" : "tone bank", b, i);
634 errors++;
635 }
636 }
637 }
638 return errors;
639 }
640
load_missing_instruments()641 int load_missing_instruments()
642 {
643 int i=128;
644 int errors=0;
645 while (i--)
646 {
647 if (tonebank[i])
648 errors+=fill_bank(0,i);
649 if (drumset[i])
650 errors+=fill_bank(1,i);
651 }
652 return errors;
653 }
654
free_instruments()655 void free_instruments()
656 {
657 int i=128;
658 while(i--)
659 {
660 if (tonebank[i])
661 free_bank(0,i);
662 if (drumset[i])
663 free_bank(1,i);
664 }
665 }
666
set_default_instrument(char * name)667 int set_default_instrument(char *name)
668 {
669 Instrument *ip;
670 if (!(ip=load_instrument(name, 0, -1, -1, -1, 0, 0, 0)))
671 return -1;
672 if (default_instrument)
673 free_instrument(default_instrument);
674 default_instrument=ip;
675 default_program=SPECIAL_PROGRAM;
676 return 0;
677 }
678
679 #ifdef NS_TIMIDITY
680 }
681 #endif
682
683 #endif //USE_TIMIDITY_MIDI
684