fixed ticket [f9c074e766ade1bd] (pickups should not be infinitely tall) (i hope ;-)
[k8vavoom.git] / libs / timidity / instrum.cpp
blobdf777377f03b0a672cca24afceffde8e28114d10
1 /*
3 TiMidity -- Experimental MIDI to WAVE converter
4 Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
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.
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.
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.
20 instrum.c
22 Code to load and unload GUS-compatible instrument patches.
26 #include <string.h>
27 #include <stdlib.h>
29 #include "timidity.h"
31 namespace LibTimidity
33 #include "gf1.h"
35 #ifdef FAST_DECAY
36 int fast_decay=1;
37 #else
38 int fast_decay=0;
39 #endif
41 static void free_instrument(Instrument* ip)
43 if (!ip)
45 return;
48 for (int i = 0; i < ip->samples; i++)
50 Sample* sp = &(ip->sample[i]);
52 if (sp->data)
54 free(sp->data);
55 sp->data = NULL;
58 free(ip->sample);
59 ip->sample = NULL;
60 free(ip);
61 ip = NULL;
64 static void free_bank(MidiSong* song, int dr, int b)
66 ToneBank* bank = ((dr) ? song->drumset[b] : song->tonebank[b]);
68 for (int i = 0; i < 128; i++)
70 if (bank->instrument[i])
72 /* Not that this could ever happen, of course */
73 if (bank->instrument[i] != MAGIC_LOAD_INSTRUMENT)
75 free_instrument(bank->instrument[i]);
76 bank->instrument[i] = NULL;
80 if (bank->tone[i].name)
82 free(bank->tone[i].name);
83 bank->tone[i].name = NULL;
89 static int32 convert_envelope_rate(MidiSong* song, uint8 rate)
91 int32 r = 3 - ((rate >> 6) & 0x3);
92 r *= 3;
93 r = (int32)(rate & 0x3f) << r; /* 6.9 fixed point */
95 /* 15.15 fixed point. */
96 return ((r * 44100) / song->control_ratio) << ((fast_decay) ? 10 : 9);
99 static int32 convert_envelope_offset(uint8 offset)
101 /* This is not too good... Can anyone tell me what these values mean?
102 Are they GUS-style "exponential" volumes? And what does that mean? */
104 /* 15.15 fixed point */
105 return offset << (7 + 15);
108 static int32 convert_tremolo_sweep(MidiSong* song, uint8 sweep)
110 if (!sweep)
112 return 0;
115 return (SWEEP_TUNING << SWEEP_SHIFT) / (song->control_ratio * sweep);
118 static int32 convert_vibrato_sweep(uint8 sweep, int32 vib_control_ratio)
120 if (!sweep)
122 return 0;
125 return (int32) (VTIM_FSCALE((double) (vib_control_ratio) * SWEEP_TUNING, SWEEP_SHIFT) /
126 (double)(OUTPUT_RATE * sweep));
128 /* this was overflowing with seashore.pat
130 ((vib_control_ratio * SWEEP_TUNING) << SWEEP_SHIFT) /
131 (play_mode->rate * sweep); */
134 static int32 convert_tremolo_rate(MidiSong* song, uint8 rate)
136 return ((SINE_CYCLE_LENGTH * rate) << RATE_SHIFT) /
137 (TREMOLO_RATE_TUNING * song->control_ratio);
140 static int32 convert_vibrato_rate(uint8 rate)
142 /* Return a suitable vibrato_control_ratio value */
143 return (VIBRATO_RATE_TUNING * OUTPUT_RATE) /
144 (rate * 2 * VIBRATO_SAMPLE_INCREMENTS);
147 static void reverse_data(int16* sp, int32 ls, int32 le)
149 int16* ep = sp + le;
150 sp += ls;
151 le -= ls;
152 le /= 2;
154 while (le--)
156 int16 s = *sp;
157 *sp++ = *ep;
158 *ep-- = s;
163 If panning or note_to_use != -1, it will be used for all samples,
164 instead of the sample-specific values in the instrument file.
166 For note_to_use, any value <0 or >127 will be forced to 0.
168 For other parameters, 1 means yes, 0 means no, other values are
169 undefined.
171 TODO: do reverse loops right */
172 static Instrument* load_instrument(MidiSong* song, const char *name, int /*percussion*/,
173 int panning, int amp, int note_to_use,
174 int strip_loop, int strip_envelope,
175 int strip_tail)
177 Instrument *ip;
178 FILE *fp;
179 int i,j,noluck=0;
181 if (!name)
183 return 0;
186 /* Open patch file */
187 if ((fp=open_file(name, 1, OF_NORMAL)) == NULL)
189 noluck = 1;
191 if (strlen(name) + strlen(".pat") < 1024)
193 char path[1024];
194 strcpy(path, name);
195 strcat(path, ".pat");
196 if ((fp = open_file(path, 1, OF_NORMAL)) != NULL)
198 noluck = 0;
203 if (noluck)
205 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Instrument `%s' can't be found.", name);
206 return 0;
209 /*ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", current_filename);*/
211 /* Read some headers and do cursory sanity checks. */
212 GF1PatchHeader PatchHdr;
213 GF1InstrumentHeader InstrHdr;
214 GF1LayerHeader LayerHdr;
215 if (1 != fread(&PatchHdr, sizeof(PatchHdr), 1, fp) ||
216 1 != fread(&InstrHdr, sizeof(InstrHdr), 1, fp) ||
217 1 != fread(&LayerHdr, sizeof(LayerHdr), 1, fp))
219 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: Failed to read headers", name);
220 return 0;
223 if ((memcmp(PatchHdr.Magic, GF1_MAGIC1, 12) &&
224 memcmp(PatchHdr.Magic, GF1_MAGIC2, 12)) ||
225 memcmp(PatchHdr.Id, GF1_PATCH_ID, 10))
227 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
228 return 0;
231 // instruments. To some patch makers, 0 means 1
232 if (PatchHdr.NumInstruments != 1 && PatchHdr.NumInstruments != 0)
234 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
235 "Can't handle patches with %d instruments", PatchHdr.NumInstruments);
236 return 0;
239 // layers. What's a layer?
240 if (InstrHdr.NumLayers != 1 && InstrHdr.NumLayers != 0)
242 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
243 "Can't handle instruments with %d layers", InstrHdr.NumLayers);
244 return 0;
247 if (LayerHdr.NumSamples == 0)
249 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Instrument has 0 samples");
250 return 0;
253 ip = (Instrument *)safe_malloc(sizeof(Instrument));
254 ip->type = INST_GUS;
255 ip->samples = LayerHdr.NumSamples;
256 ip->sample = (Sample*)safe_malloc(sizeof(Sample) * ip->samples);
257 memset(ip->sample, 0, sizeof(Sample) * ip->samples);
258 for (i = 0; i < ip->samples; i++)
260 GF1SampleHeader SmplHdr;
262 if (1 != fread(&SmplHdr, sizeof(GF1SampleHeader), 1, fp))
264 fail:
265 ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
266 free_instrument(ip);
267 return 0;
269 Sample* sp = &ip->sample[i];
271 sp->data_length = LE_LONG(SmplHdr.DataLength);
272 sp->loop_start = LE_LONG(SmplHdr.LoopStart);
273 sp->loop_end = LE_LONG(SmplHdr.LoopEnd);
274 sp->sample_rate = LE_SHORT(SmplHdr.SampleRate);
275 sp->low_freq = LE_LONG(SmplHdr.LowFreq);
276 sp->high_freq = LE_LONG(SmplHdr.HighFreq);
277 sp->root_freq = LE_LONG(SmplHdr.RootFreq);
278 sp->low_vel = 0;
279 sp->high_vel = 127;
281 if (panning == -1)
283 sp->panning = (SmplHdr.Panning * 8 + 4) & 0x7F;
285 else
287 sp->panning = (uint8)(panning & 0x7F);
290 if (!SmplHdr.TremoloRate || !SmplHdr.TremoloDepth)
292 sp->tremolo_sweep_increment =
293 sp->tremolo_phase_increment = sp->tremolo_depth = 0;
294 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
296 else
298 sp->tremolo_sweep_increment =
299 convert_tremolo_sweep(song, SmplHdr.TremoloSweep);
300 sp->tremolo_phase_increment =
301 convert_tremolo_rate(song, SmplHdr.TremoloRate);
302 sp->tremolo_depth = SmplHdr.TremoloDepth;
303 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
304 " * tremolo: sweep %d, phase %d, depth %d",
305 sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
306 sp->tremolo_depth);
309 if (!SmplHdr.VibratoRate || !SmplHdr.VibratoDepth)
311 sp->vibrato_sweep_increment =
312 sp->vibrato_control_ratio = sp->vibrato_depth = 0;
313 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
315 else
317 sp->vibrato_control_ratio =
318 convert_vibrato_rate(SmplHdr.VibratoRate);
319 sp->vibrato_sweep_increment =
320 convert_vibrato_sweep(SmplHdr.VibratoSweep,
321 sp->vibrato_control_ratio);
322 sp->vibrato_depth = SmplHdr.VibratoDepth;
323 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
324 " * vibrato: sweep %d, ctl %d, depth %d",
325 sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
326 sp->vibrato_depth);
328 sp->modes = SmplHdr.Modes;
330 /* Mark this as a fixed-pitch instrument if such a deed is desired. */
331 if (note_to_use != -1)
333 sp->note_to_use = (uint8)(note_to_use);
335 else
337 sp->note_to_use = 0;
340 /* seashore.pat in the Midia patch set has no Sustain. I don't
341 understand why, and fixing it by adding the Sustain flag to
342 all looped patches probably breaks something else. We do it
343 anyway. */
345 if (sp->modes & MODES_LOOPING)
347 sp->modes |= MODES_SUSTAIN;
350 /* Strip any loops and envelopes we're permitted to */
351 if ((strip_loop==1) &&
352 (sp->modes & (MODES_SUSTAIN | MODES_LOOPING |
353 MODES_PINGPONG | MODES_REVERSE)))
355 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
356 sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING |
357 MODES_PINGPONG | MODES_REVERSE);
360 if (strip_envelope==1)
362 if (sp->modes & MODES_ENVELOPE)
363 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
364 sp->modes &= ~MODES_ENVELOPE;
366 else if (strip_envelope != 0)
368 /* Have to make a guess. */
369 if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
371 /* No loop? Then what's there to sustain? No envelope needed
372 either... */
373 sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
374 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
375 " - No loop, removing sustain and envelope");
377 else if (!memcmp(SmplHdr.EnvelopeRate, "??????", 6) ||
378 SmplHdr.EnvelopeOffset[5] >= 100)
380 /* Envelope rates all maxed out? Envelope end at a high "offset"?
381 That's a weird envelope. Take it out. */
382 sp->modes &= ~MODES_ENVELOPE;
383 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
384 " - Weirdness, removing envelope");
386 else if (!(sp->modes & MODES_SUSTAIN))
388 /* No sustain? Then no envelope. I don't know if this is
389 justified, but patches without sustain usually don't need the
390 envelope either... at least the Gravis ones. They're mostly
391 drums. I think. */
392 sp->modes &= ~MODES_ENVELOPE;
393 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
394 " - No sustain, removing envelope");
398 for (j = 0; j < 6; j++)
400 sp->envelope_rate[j] =
401 convert_envelope_rate(song, SmplHdr.EnvelopeRate[j]);
402 sp->envelope_offset[j] =
403 convert_envelope_offset(SmplHdr.EnvelopeOffset[j]);
405 /* Then read the sample data */
406 sp->data = (sample_t*)safe_malloc(sp->data_length);
408 if (1 != fread(sp->data, sp->data_length, 1, fp))
410 goto fail;
413 if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
415 int32 k = sp->data_length;
416 uint8 *cp = (uint8*)(sp->data);
417 uint16 *tmp,*newdta;
418 tmp = newdta = (uint16*)safe_malloc(sp->data_length * 2);
419 while (k--)
421 *tmp++ = (uint16)(*cp++) << 8;
423 cp = (uint8*)(sp->data);
424 sp->data = (sample_t*)newdta;
425 free(cp);
426 cp = NULL;
427 sp->data_length *= 2;
428 sp->loop_start *= 2;
429 sp->loop_end *= 2;
431 #ifndef LITTLE_ENDIAN
432 else
433 /* convert to machine byte order */
435 int32 i = sp->data_length / 2;
436 int16 *tmp = (int16*)sp->data, s;
437 while (i--)
439 s = LE_SHORT(*tmp);
440 *tmp++ = s;
443 #endif
445 if (sp->modes & MODES_UNSIGNED) /* convert to signed data */
447 int32 k = sp->data_length / 2;
448 int16* tmp = (int16*)sp->data;
449 while (k--)
450 *tmp++ ^= 0x8000;
453 /* Reverse reverse loops and pass them off as normal loops */
454 if (sp->modes & MODES_REVERSE)
456 int32 t;
458 /* The GUS apparently plays reverse loops by reversing the
459 whole sample. We do the same because the GUS does not SUCK. */
460 ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s", name);
461 reverse_data((int16*)sp->data, 0, sp->data_length / 2);
463 t=sp->loop_start;
464 sp->loop_start = sp->data_length - sp->loop_end;
465 sp->loop_end = sp->data_length - t;
467 sp->modes &= ~MODES_REVERSE;
468 sp->modes |= MODES_LOOPING; /* just in case */
471 if (amp != -1)
473 sp->volume = (float)((amp) / 100.0);
475 else
477 #ifdef ADJUST_SAMPLE_VOLUMES
478 /* Try to determine a volume scaling factor for the sample.
479 This is a very crude adjustment, but things sound more
480 balanced with it. Still, this should be a runtime option. */
481 int32 k = sp->data_length / 2;
482 int16 maxamp = 0, a;
483 int16* tmp = (int16*)sp->data;
485 while (k--)
487 a = *tmp++;
488 if (a < 0)
490 a = -a;
492 if (a > maxamp)
494 maxamp = a;
497 sp->volume=(float)(32768.0 / maxamp);
498 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f", sp->volume);
499 #else
500 sp->volume = 1.0;
501 #endif
503 sp->data_length /= 2; /* These are in bytes. Convert into samples. */
505 sp->loop_start /= 2;
506 sp->loop_end /= 2;
508 /* Then fractional samples */
509 sp->data_length <<= FRACTION_BITS;
510 sp->loop_start <<= FRACTION_BITS;
511 sp->loop_end <<= FRACTION_BITS;
513 /* Adjust for fractional loop points. This is a guess. Does anyone
514 know what "fractions" really stands for? */
515 sp->loop_start |=
516 (SmplHdr.Fractions & 0x0F) << (FRACTION_BITS - 4);
517 sp->loop_end |=
518 ((SmplHdr.Fractions >> 4) & 0x0F) << (FRACTION_BITS - 4);
520 /* If this instrument will always be played on the same note,
521 and it's not looped, we can resample it now. */
522 if (sp->note_to_use && !(sp->modes & MODES_LOOPING))
524 pre_resample(sp);
527 if (strip_tail == 1)
529 /* Let's not really, just say we did. */
530 ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail");
531 sp->data_length = sp->loop_end;
534 close_file(fp);
536 return ip;
539 static int fill_bank(MidiSong* song, int dr, int b)
541 int i, errors = 0;
542 ToneBank* bank = ((dr) ? song->drumset[b] : song->tonebank[b]);
544 if (!bank)
546 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
547 "Huh. Tried to load instruments in non-existent %s %d",
548 (dr) ? "drumset" : "tone bank", b);
549 return 0;
551 for (i = 0; i < 128; i++)
553 if (bank->instrument[i] == MAGIC_LOAD_INSTRUMENT)
555 bank->instrument[i] = load_instrument_sf2(song, b, i, dr ? true : false);
557 if (bank->instrument[i])
559 continue;
561 bank->instrument[i] = load_instrument_dls(song, dr, b, i);
563 if (bank->instrument[i])
565 continue;
568 if (!(bank->tone[i].name))
570 ctl->cmsg(CMSG_WARNING, (b != 0) ? VERB_VERBOSE : VERB_NORMAL,
571 "No instrument mapped to %s %d, program %d%s",
572 (dr)? "drum set" : "tone bank", b, i,
573 (b != 0) ? "" : " - this instrument will not be heard");
575 if (b != 0)
577 /* Mark the corresponding instrument in the default
578 bank / drumset for loading (if it isn't already) */
579 if (!dr)
581 if (!(song->tonebank[0]->instrument[i]))
583 song->tonebank[0]->instrument[i] = MAGIC_LOAD_INSTRUMENT;
586 else
588 if (!(song->drumset[0]->instrument[i]))
590 song->drumset[0]->instrument[i] = MAGIC_LOAD_INSTRUMENT;
594 bank->instrument[i] = 0;
595 errors++;
597 else if (!(bank->instrument[i] =
598 load_instrument(song, bank->tone[i].name,
599 (dr) ? 1 : 0,
600 bank->tone[i].pan,
601 bank->tone[i].amp,
602 (bank->tone[i].note!=-1) ?
603 bank->tone[i].note :
604 ((dr) ? i : -1),
605 (bank->tone[i].strip_loop!=-1) ?
606 bank->tone[i].strip_loop :
607 ((dr) ? 1 : -1),
608 (bank->tone[i].strip_envelope != -1) ?
609 bank->tone[i].strip_envelope :
610 ((dr) ? 1 : -1),
611 bank->tone[i].strip_tail)))
613 ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
614 "Couldn't load instrument %s (%s %d, program %d)",
615 bank->tone[i].name,
616 (dr)? "drum set" : "tone bank", b, i);
617 errors++;
622 return errors;
625 int load_missing_instruments(MidiSong* song)
627 int i = 128, errors = 0;
629 while (i--)
631 if (song->tonebank[i])
633 errors += fill_bank(song, 0, i);
636 if (song->drumset[i])
638 errors += fill_bank(song, 1, i);
642 return errors;
645 void free_instruments(MidiSong* song)
647 int i = 128;
649 while(i--)
651 if (song->tonebank[i])
653 free_bank(song, 0, i);
655 if (song->drumset[i])
657 free_bank(song, 1, i);
662 int set_default_instrument(MidiSong* song, const char* name)
664 Instrument* ip;
666 if (!(ip = load_instrument(song, name, 0, -1, -1, -1, 0, 0, 0)))
668 return -1;
670 song->default_instrument = ip;
671 song->default_program = SPECIAL_PROGRAM;
673 return 0;