1 /*
2 TiMidity -- Experimental MIDI to WAVE converter
3 Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20 #ifndef TIMIDITY_H
21 #define TIMIDITY_H
22
23 #include "doomtype.h"
24 #include "pathexpander.h"
25
26 class FileReader;
27
28 namespace Timidity
29 {
30
31 /*
32 config.h
33 */
34
35 /* Acoustic Grand Piano seems to be the usual default instrument. */
36 #define DEFAULT_PROGRAM 0
37
38 /* 9 here is MIDI channel 10, which is the standard percussion channel.
39 Some files (notably C:\WINDOWS\CANYON.MID) think that 16 is one too.
40 On the other hand, some files know that 16 is not a drum channel and
41 try to play music on it. This is now a runtime option, so this isn't
42 a critical choice anymore. */
43 #define DEFAULT_DRUMCHANNELS (1<<9)
44 /*#define DEFAULT_DRUMCHANNELS ((1<<9) | (1<<15))*/
45
46 #define MAXCHAN 16
47 #define MAXNOTE 128
48
49 /* 1000 here will give a control ratio of 22:1 with 22 kHz output.
50 Higher CONTROLS_PER_SECOND values allow more accurate rendering
51 of envelopes and tremolo. The cost is CPU time. */
52 #define CONTROLS_PER_SECOND 1000
53
54 /* A scalar applied to the final mix to try and approximate the
55 volume level of FMOD's built-in MIDI player. */
56 #define FINAL_MIX_SCALE 0.5
57
58 /* How many bits to use for the fractional part of sample positions.
59 This affects tonal accuracy. The entire position counter must fit
60 in 32 bits, so with FRACTION_BITS equal to 12, the maximum size of
61 a sample is 1048576 samples (2 megabytes in memory). The GUS gets
62 by with just 9 bits and a little help from its friends...
63 "The GUS does not SUCK!!!" -- a happy user :) */
64 #define FRACTION_BITS 12
65
66 /* For some reason the sample volume is always set to maximum in all
67 patch files. Define this for a crude adjustment that may help
68 equalize instrument volumes. */
69 //#define ADJUST_SAMPLE_VOLUMES
70
71 /* The number of samples to use for ramping out a dying note. Affects
72 click removal. */
73 #define MAX_DIE_TIME 20
74
75 /**************************************************************************/
76 /* Anything below this shouldn't need to be changed unless you're porting
77 to a new machine with other than 32-bit, big-endian words. */
78 /**************************************************************************/
79
80 /* change FRACTION_BITS above, not these */
81 #define INTEGER_BITS (32 - FRACTION_BITS)
82 #define INTEGER_MASK (0xFFFFFFFF << FRACTION_BITS)
83 #define FRACTION_MASK (~ INTEGER_MASK)
84 #define MAX_SAMPLE_SIZE (1 << INTEGER_BITS)
85
86 /* This is enforced by some computations that must fit in an int */
87 #define MAX_CONTROL_RATIO 255
88
89 #define MAX_AMPLIFICATION 800
90
91 /* The TiMiditiy configuration file */
92 #define CONFIG_FILE "timidity.cfg"
93
94 typedef float sample_t;
95 typedef float final_volume_t;
96 #define FINAL_VOLUME(v) (v)
97
98 #define FSCALE(a,b) ((a) * (float)(1<<(b)))
99 #define FSCALENEG(a,b) ((a) * (1.0L / (float)(1<<(b))))
100
101 /* Vibrato and tremolo Choices of the Day */
102 #define SWEEP_TUNING 38
103 #define VIBRATO_AMPLITUDE_TUNING 1.0
104 #define VIBRATO_RATE_TUNING 38
105 #define TREMOLO_AMPLITUDE_TUNING 1.0
106 #define TREMOLO_RATE_TUNING 38
107
108 #define SWEEP_SHIFT 16
109 #define RATE_SHIFT 5
110
111 #define VIBRATO_SAMPLE_INCREMENTS 32
112
113 #ifndef PI
114 #define PI 3.14159265358979323846
115 #endif
116
117 #if defined(__GNUC__) && !defined(__clang__) && (defined(__i386__) || defined(__x86_64__))
118 // [RH] MinGW's pow() function is terribly slow compared to VC8's
119 // (I suppose because it's using an old version from MSVCRT.DLL).
120 // On an Opteron running x86-64 Linux, this also ended up being about
121 // 100 cycles faster than libm's pow(), which is why I'm using this
122 // for GCC in general and not just for MinGW.
123 // [CE] Clang doesn't yet support some inline ASM operations so I disabled it for that instance
124
pow_x87_inline(double x,double y)125 extern __inline__ double pow_x87_inline(double x,double y)
126 {
127 double result;
128
129 if (y == 0)
130 {
131 return 1;
132 }
133 if (x == 0)
134 {
135 if (y > 0)
136 {
137 return 0;
138 }
139 else
140 {
141 union { double fp; long long ip; } infinity;
142 infinity.ip = 0x7FF0000000000000ll;
143 return infinity.fp;
144 }
145 }
146 __asm__ (
147 "fyl2x\n\t"
148 "fld %%st(0)\n\t"
149 "frndint\n\t"
150 "fxch\n\t"
151 "fsub %%st(1),%%st(0)\n\t"
152 "f2xm1\n\t"
153 "fld1\n\t"
154 "faddp\n\t"
155 "fxch\n\t"
156 "fld1\n\t"
157 "fscale\n\t"
158 "fstp %%st(1)\n\t"
159 "fmulp\n\t"
160 : "=t" (result)
161 : "0" (x), "u" (y)
162 : "st(1)", "st(7)" );
163 return result;
164 }
165 #define pow pow_x87_inline
166 #endif
167
168 /*
169 common.h
170 */
171
172 extern void *safe_malloc(size_t count);
173
174 /*
175 controls.h
176 */
177
178 enum
179 {
180 CMSG_INFO,
181 CMSG_WARNING,
182 CMSG_ERROR
183 };
184
185 enum
186 {
187 VERB_NORMAL,
188 VERB_VERBOSE,
189 VERB_NOISY,
190 VERB_DEBUG
191 };
192
193 void cmsg(int type, int verbosity_level, const char *fmt, ...);
194
195
196 /*
197 instrum.h
198 */
199
200 enum
201 {
202 PATCH_16 = (1<<0),
203 PATCH_UNSIGNED = (1<<1),
204 PATCH_LOOPEN = (1<<2),
205 PATCH_BIDIR = (1<<3),
206 PATCH_BACKWARD = (1<<4),
207 PATCH_SUSTAIN = (1<<5),
208 PATCH_NO_SRELEASE = (1<<6),
209 PATCH_FAST_REL = (1<<7),
210 };
211
212 struct Sample
213 {
214 SDWORD
215 loop_start, loop_end, data_length,
216 sample_rate;
217 float
218 low_freq, high_freq, root_freq;
219 union
220 {
221 struct
222 {
223 BYTE rate[6], offset[6];
224 } gf1;
225 struct
226 {
227 short delay_vol;
228 short attack_vol;
229 short hold_vol;
230 short decay_vol;
231 short sustain_vol;
232 short release_vol;
233 } sf2;
234 } envelope;
235 sample_t *data;
236 SDWORD
237 tremolo_sweep_increment, tremolo_phase_increment,
238 vibrato_sweep_increment, vibrato_control_ratio;
239 BYTE
240 tremolo_depth, vibrato_depth,
241 low_vel, high_vel,
242 type;
243 WORD
244 modes;
245 SWORD
246 panning;
247 WORD
248 scale_factor, key_group;
249 SWORD
250 scale_note;
251 bool
252 self_nonexclusive;
253 float
254 left_offset, right_offset;
255
256 // SF2 stuff
257 SWORD tune;
258 SBYTE velocity;
259
260 float initial_attenuation;
261 };
262
263 void convert_sample_data(Sample *sample, const void *data);
264 void free_instruments();
265
266 /* Magic file words */
267
268 #define ID_RIFF MAKE_ID('R','I','F','F')
269 #define ID_LIST MAKE_ID('L','I','S','T')
270 #define ID_INFO MAKE_ID('I','N','F','O')
271 #define ID_sfbk MAKE_ID('s','f','b','k')
272 #define ID_sdta MAKE_ID('s','d','t','a')
273 #define ID_pdta MAKE_ID('p','d','t','a')
274 #define ID_ifil MAKE_ID('i','f','i','l')
275 #define ID_iver MAKE_ID('i','v','e','r')
276 #define ID_irom MAKE_ID('i','r','o','m')
277 #define ID_smpl MAKE_ID('s','m','p','l')
278 #define ID_sm24 MAKE_ID('s','m','2','4')
279 #define ID_phdr MAKE_ID('p','h','d','r')
280 #define ID_pbag MAKE_ID('p','b','a','g')
281 #define ID_pmod MAKE_ID('p','m','o','d')
282 #define ID_pgen MAKE_ID('p','g','e','n')
283 #define ID_inst MAKE_ID('i','n','s','t')
284 #define ID_ibag MAKE_ID('i','b','a','g')
285 #define ID_imod MAKE_ID('i','m','o','d')
286 #define ID_igen MAKE_ID('i','g','e','n')
287 #define ID_shdr MAKE_ID('s','h','d','r')
288
289 /* Instrument definitions */
290
291 enum
292 {
293 INST_GUS,
294 INST_DLS,
295 INST_SF2
296 };
297
298 struct Instrument
299 {
300 Instrument();
301 ~Instrument();
302
303 int samples;
304 Sample *sample;
305 };
306
307 struct ToneBankElement
308 {
ToneBankElementToneBankElement309 ToneBankElement() :
310 note(0), pan(0), strip_loop(0), strip_envelope(0), strip_tail(0)
311 {}
312
313 FString name;
314 int note, pan, fontbank, fontpreset, fontnote;
315 SBYTE strip_loop, strip_envelope, strip_tail;
316 };
317
318 /* A hack to delay instrument loading until after reading the entire MIDI file. */
319 #define MAGIC_LOAD_INSTRUMENT ((Instrument *)(-1))
320
321 enum
322 {
323 MAXPROG = 128,
324 MAXBANK = 128
325 };
326
327 struct ToneBank
328 {
329 ToneBank();
330 ~ToneBank();
331
332 ToneBankElement *tone;
333 Instrument *instrument[MAXPROG];
334 };
335
336
337 #define SPECIAL_PROGRAM -1
338
339 /*
340 instrum_font.cpp
341 */
342
343 class FontFile
344 {
345 public:
346 FontFile(FString filename);
347 virtual ~FontFile();
348
349 FString Filename;
350 FontFile *Next;
351
352 virtual Instrument *LoadInstrument(struct Renderer *song, int drum, int bank, int program) = 0;
353 virtual Instrument *LoadInstrumentOrder(struct Renderer *song, int order, int drum, int bank, int program) = 0;
354 virtual void SetOrder(int order, int drum, int bank, int program) = 0;
355 virtual void SetAllOrders(int order) = 0;
356 };
357
358 void font_freeall();
359 FontFile *font_find(const char *filename);
360 void font_add(const char *filename, int load_order);
361 void font_remove(const char *filename);
362 void font_order(int order, int bank, int preset, int keynote);
363 Instrument *load_instrument_font(struct Renderer *song, const char *font, int drum, int bank, int instrument);
364 Instrument *load_instrument_font_order(struct Renderer *song, int order, int drum, int bank, int instrument);
365
366 FontFile *ReadDLS(const char *filename, FileReader *f);
367
368 /*
369 mix.h
370 */
371
372 extern void mix_voice(struct Renderer *song, float *buf, struct Voice *v, int c);
373 extern int recompute_envelope(struct Voice *v);
374 extern void apply_envelope_to_amp(struct Voice *v);
375
376 /*
377 playmidi.h
378 */
379
380 /* Midi events */
381 enum
382 {
383 ME_NOTEOFF = 0x80,
384 ME_NOTEON = 0x90,
385 ME_KEYPRESSURE = 0xA0,
386 ME_CONTROLCHANGE = 0xB0,
387 ME_PROGRAM = 0xC0,
388 ME_CHANNELPRESSURE = 0xD0,
389 ME_PITCHWHEEL = 0xE0
390 };
391
392 /* Controllers */
393 enum
394 {
395 CTRL_BANK_SELECT = 0,
396 CTRL_DATA_ENTRY = 6,
397 CTRL_VOLUME = 7,
398 CTRL_PAN = 10,
399 CTRL_EXPRESSION = 11,
400 CTRL_SUSTAIN = 64,
401 CTRL_HARMONICCONTENT = 71,
402 CTRL_RELEASETIME = 72,
403 CTRL_ATTACKTIME = 73,
404 CTRL_BRIGHTNESS = 74,
405 CTRL_REVERBERATION = 91,
406 CTRL_CHORUSDEPTH = 93,
407 CTRL_NRPN_LSB = 98,
408 CTRL_NRPN_MSB = 99,
409 CTRL_RPN_LSB = 100,
410 CTRL_RPN_MSB = 101,
411 CTRL_ALL_SOUNDS_OFF = 120,
412 CTRL_RESET_CONTROLLERS = 121,
413 CTRL_ALL_NOTES_OFF = 123
414 };
415
416 /* RPNs */
417 enum
418 {
419 RPN_PITCH_SENS = 0x0000,
420 RPN_FINE_TUNING = 0x0001,
421 RPN_COARSE_TUNING = 0x0002,
422 RPN_RESET = 0x3fff
423 };
424
425 struct Channel
426 {
427 int
428 bank, program, sustain, pitchbend,
429 mono, /* one note only on this channel */
430 pitchsens;
431 BYTE
432 volume, expression;
433 SBYTE
434 panning;
435 WORD
436 rpn, nrpn;
437 bool
438 nrpn_mode;
439 float
440 pitchfactor; /* precomputed pitch bend factor to save some fdiv's */
441 };
442
443 /* Causes the instrument's default panning to be used. */
444 #define NO_PANNING -1
445
446 struct MinEnvelope
447 {
448 BYTE stage;
449 BYTE bUpdating;
450 };
451
452 struct GF1Envelope : public MinEnvelope
453 {
454 int volume, target, increment;
455 int rate[6], offset[6];
456
457 void Init(struct Renderer *song, Voice *v);
458 bool Update(struct Voice *v);
459 bool Recompute(struct Voice *v);
460 void ApplyToAmp(struct Voice *v);
461 void Release(struct Voice *v);
462 };
463
464 struct SF2Envelope : public MinEnvelope
465 {
466 float volume;
467 float DelayTime; // timecents
468 float AttackTime; // timecents
469 float HoldTime; // timecents
470 float DecayTime; // timecents
471 float SustainLevel; // -0.1%
472 float ReleaseTime; // timecents
473 float SampleRate;
474 int HoldStart;
475 float RateMul;
476 float RateMul_cB;
477
478 void Init(struct Renderer *song, Voice *v);
479 bool Update(struct Voice *v);
480 void ApplyToAmp(struct Voice *v);
481 void Release(struct Voice *v);
482 };
483
484 struct Envelope
485 {
486 union
487 {
488 MinEnvelope env;
489 GF1Envelope gf1;
490 SF2Envelope sf2;
491 };
492
493 BYTE Type;
494
495 void Init(struct Renderer *song, struct Voice *v);
UpdateEnvelope496 bool Update(struct Voice *v)
497 {
498 if (Type == INST_GUS)
499 return gf1.Update(v);
500 return sf2.Update(v);
501 }
ApplyToAmpEnvelope502 void ApplyToAmp(struct Voice *v)
503 {
504 if (Type == INST_GUS)
505 return gf1.ApplyToAmp(v);
506 return sf2.ApplyToAmp(v);
507 }
ReleaseEnvelope508 void Release(struct Voice *v)
509 {
510 if (Type == INST_GUS)
511 return gf1.Release(v);
512 return sf2.Release(v);
513 }
514 };
515
516 struct Voice
517 {
518 BYTE
519 status, channel, note, velocity;
520 Sample *sample;
521 float
522 orig_frequency, frequency;
523 int
524 sample_offset, sample_increment,
525 tremolo_sweep, tremolo_sweep_position,
526 tremolo_phase, tremolo_phase_increment,
527 vibrato_sweep, vibrato_sweep_position;
528
529 Envelope eg1, eg2;
530
531 final_volume_t left_mix, right_mix;
532
533 float
534 attenuation, left_offset, right_offset;
535 float
536 tremolo_volume;
537 int
538 vibrato_sample_increment[VIBRATO_SAMPLE_INCREMENTS];
539 int
540 vibrato_phase, vibrato_control_ratio, vibrato_control_counter,
541 control_counter;
542
543 int
544 sample_count;
545 };
546
547 /* Voice status options: */
548 enum
549 {
550 VOICE_RUNNING = (1<<0),
551 VOICE_SUSTAINING = (1<<1),
552 VOICE_RELEASING = (1<<2),
553 VOICE_STOPPING = (1<<3),
554
555 VOICE_LPE = (1<<4),
556 NOTE_SUSTAIN = (1<<5),
557 };
558
559 /* Envelope stages: */
560 enum
561 {
562 GF1_ATTACK,
563 GF1_HOLD,
564 GF1_DECAY,
565 GF1_RELEASE,
566 GF1_RELEASEB,
567 GF1_RELEASEC
568 };
569
570 enum
571 {
572 SF2_DELAY,
573 SF2_ATTACK,
574 SF2_HOLD,
575 SF2_DECAY,
576 SF2_SUSTAIN,
577 SF2_RELEASE,
578 SF2_FINISHED
579 };
580
581 #define ISDRUMCHANNEL(c) ((drumchannels & (1<<(c))))
582
583 /*
584 resample.h
585 */
586
587 extern sample_t *resample_voice(struct Renderer *song, Voice *v, int *countptr);
588 extern void pre_resample(struct Renderer *song, Sample *sp);
589
590 /*
591 tables.h
592 */
593
594 const double log_of_2 = 0.69314718055994529;
595
596 #define sine(x) (sin((2*PI/1024.0) * (x)))
597
598 #define note_to_freq(x) (float(8175.7989473096690661233836992789 * pow(2.0, (x) / 12.0)))
599 #define freq_to_note(x) (log((x) / 8175.7989473096690661233836992789) * (12.0 / log_of_2))
600
601 #define calc_gf1_amp(x) (pow(2.0,((x)*16.0 - 16.0))) // Actual GUS equation
602
603 /*
604 timidity.h
605 */
606 struct DLS_Data;
607 int LoadConfig(const char *filename);
608 int LoadDMXGUS();
609 extern int LoadConfig();
610 extern void FreeAll();
611 extern PathExpander pathExpander;
612
613 extern ToneBank *tonebank[MAXBANK];
614 extern ToneBank *drumset[MAXBANK];
615
616 struct Renderer
617 {
618 float rate;
619 DLS_Data *patches;
620 Instrument *default_instrument;
621 int default_program;
622 int resample_buffer_size;
623 sample_t *resample_buffer;
624 Channel channel[16];
625 Voice *voice;
626 int control_ratio, amp_with_poly;
627 int drumchannels;
628 int adjust_panning_immediately;
629 int voices;
630 int lost_notes, cut_notes;
631
632 Renderer(float sample_rate, const char *args);
633 ~Renderer();
634
635 void HandleEvent(int status, int parm1, int parm2);
636 void HandleLongMessage(const BYTE *data, int len);
637 void HandleController(int chan, int ctrl, int val);
638 void ComputeOutput(float *buffer, int num_samples);
639 void MarkInstrument(int bank, int percussion, int instr);
640 void Reset();
641
642 int load_missing_instruments();
643 int set_default_instrument(const char *name);
644 int convert_tremolo_sweep(BYTE sweep);
645 int convert_vibrato_sweep(BYTE sweep, int vib_control_ratio);
646 int convert_tremolo_rate(BYTE rate);
647 int convert_vibrato_rate(BYTE rate);
648
649 void recompute_freq(int voice);
650 void recompute_amp(Voice *v);
651 void recompute_pan(Channel *chan);
652
653 void kill_key_group(int voice);
654 float calculate_scaled_frequency(Sample *sample, int note);
655 void start_note(int chan, int note, int vel);
656 bool start_region(int chan, int note, int vel, Sample *sp, float freq);
657
658 void note_on(int chan, int note, int vel);
659 void note_off(int chan, int note, int vel);
660 void all_notes_off(int chan);
661 void all_sounds_off(int chan);
662 void adjust_pressure(int chan, int note, int amount);
663 void adjust_panning(int chan);
664 void drop_sustain(int chan);
665 void adjust_pitchbend(int chan);
666 void adjust_volume(int chan);
667
668 void reset_voices();
669 void reset_controllers(int chan);
670 void reset_midi();
671
672 int allocate_voice();
673
674 void kill_note(int voice);
675 void finish_note(int voice);
676
677 void DataEntryCoarseRPN(int chan, int rpn, int val);
678 void DataEntryFineRPN(int chan, int rpn, int val);
679 void DataEntryCoarseNRPN(int chan, int nrpn, int val);
680 void DataEntryFineNRPN(int chan, int nrpn, int val);
681
682 static void compute_pan(double panning, int type, float &left_offset, float &right_offset);
683 };
684
685 }
686 #endif
687