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