1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2009 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     playmidi.c -- random stuff in need of rearrangement
21 */
22 
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif /* HAVE_CONFIG_H */
26 #ifdef __POCC__
27 #include <sys/types.h>
28 #endif // for off_t
29 #ifdef __W32__
30 #include "interface.h"
31 #endif
32 #include <stdio.h>
33 #include <stdlib.h>
34 
35 #ifndef NO_STRING_H
36 #include <string.h>
37 #else
38 #include <strings.h>
39 #endif
40 #include <math.h>
41 #ifdef __W32__
42 #include <windows.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif /* HAVE_UNISTD_H */
47 #include "timidity.h"
48 #include "common.h"
49 #include "instrum.h"
50 #include "playmidi.h"
51 #include "readmidi.h"
52 #include "output.h"
53 #include "mix.h"
54 #include "controls.h"
55 #include "miditrace.h"
56 #include "recache.h"
57 #include "arc.h"
58 #include "reverb.h"
59 #include "wrd.h"
60 #include "aq.h"
61 #include "freq.h"
62 #include "quantity.h"
63 
64 extern int convert_mod_to_midi_file(MidiEvent * ev);
65 
66 #define ABORT_AT_FATAL 1 /*#################*/
67 #define MYCHECK(s) do { if(s == 0) { printf("## L %d\n", __LINE__); abort(); } } while(0)
68 
69 extern VOLATILE int intr;
70 
71 /* #define SUPPRESS_CHANNEL_LAYER */
72 
73 #ifdef SOLARIS
74 /* shut gcc warning up */
75 int usleep(unsigned int useconds);
76 #endif
77 
78 #ifdef SUPPORT_SOUNDSPEC
79 #include "soundspec.h"
80 #endif /* SUPPORT_SOUNDSPEC */
81 
82 #include "tables.h"
83 
84 #define PLAY_INTERLEAVE_SEC		1.0
85 #define PORTAMENTO_TIME_TUNING		(1.0 / 5000.0)
86 #define PORTAMENTO_CONTROL_RATIO	256	/* controls per sec */
87 #define DEFAULT_CHORUS_DELAY1		0.02
88 #define DEFAULT_CHORUS_DELAY2		0.003
89 #define CHORUS_OPPOSITE_THRESHOLD	32
90 #define EOT_PRESEARCH_LEN		32
91 #define SPEED_CHANGE_RATE		1.0594630943592953  /* 2^(1/12) */
92 
93 /* Undefine if you don't want to use auto voice reduce implementation */
94 #define REDUCE_VOICE_TIME_TUNING	(play_mode->rate/5) /* 0.2 sec */
95 #ifdef REDUCE_VOICE_TIME_TUNING
96 static int max_good_nv = 1;
97 static int min_bad_nv = 256;
98 static int32 ok_nv_total = 32;
99 static int32 ok_nv_counts = 1;
100 static int32 ok_nv_sample = 0;
101 static int ok_nv = 32;
102 static int old_rate = -1;
103 #endif
104 
105 static int midi_streaming = 0;
106 int volatile stream_max_compute = 500; /* compute time limit (in msec) when streaming */
107 static int prescanning_flag;
108 static int32 midi_restart_time = 0;
109 Channel channel[MAX_CHANNELS];
110 int max_voices = DEFAULT_VOICES;
111 Voice *voice = NULL;
112 int8 current_keysig = 0;
113 int8 current_temper_keysig = 0;
114 int temper_adj = 0;
115 int8 opt_init_keysig = 8;
116 int8 opt_force_keysig = 8;
117 int32 current_play_tempo = 500000;
118 int opt_realtime_playing = 0;
119 int reduce_voice_threshold = -1;
120 static MBlockList playmidi_pool;
121 int check_eot_flag;
122 int special_tonebank = -1;
123 int default_tonebank = 0;
124 int playmidi_seek_flag = 0;
125 int play_pause_flag = 0;
126 static int file_from_stdin;
127 int key_adjust = 0;
128 FLOAT_T tempo_adjust = 1.0;
129 int opt_pure_intonation = 0;
130 int current_freq_table = 0;
131 int current_temper_freq_table = 0;
132 static int master_tuning = 0;
133 
134 static void set_reverb_level(int ch, int level);
135 static int make_rvid_flag = 0; /* For reverb optimization */
136 
137 /* Ring voice id for each notes.  This ID enables duplicated note. */
138 static uint8 vidq_head[128 * MAX_CHANNELS], vidq_tail[128 * MAX_CHANNELS];
139 
140 #ifdef MODULATION_WHEEL_ALLOW
141 int opt_modulation_wheel = 1;
142 #else
143 int opt_modulation_wheel = 0;
144 #endif /* MODULATION_WHEEL_ALLOW */
145 
146 #ifdef PORTAMENTO_ALLOW
147 int opt_portamento = 1;
148 #else
149 int opt_portamento = 0;
150 #endif /* PORTAMENTO_ALLOW */
151 
152 #ifdef NRPN_VIBRATO_ALLOW
153 int opt_nrpn_vibrato = 1;
154 #else
155 int opt_nrpn_vibrato = 0;
156 #endif /* NRPN_VIBRATO_ALLOW */
157 
158 #ifdef REVERB_CONTROL_ALLOW
159 int opt_reverb_control = 1;
160 #else
161 #ifdef FREEVERB_CONTROL_ALLOW
162 int opt_reverb_control = 3;
163 #else
164 int opt_reverb_control = 0;
165 #endif /* FREEVERB_CONTROL_ALLOW */
166 #endif /* REVERB_CONTROL_ALLOW */
167 
168 #ifdef CHORUS_CONTROL_ALLOW
169 int opt_chorus_control = 1;
170 #else
171 int opt_chorus_control = 0;
172 #endif /* CHORUS_CONTROL_ALLOW */
173 
174 #ifdef SURROUND_CHORUS_ALLOW
175 int opt_surround_chorus = 1;
176 #else
177 int opt_surround_chorus = 0;
178 #endif /* SURROUND_CHORUS_ALLOW */
179 
180 #ifdef GM_CHANNEL_PRESSURE_ALLOW
181 int opt_channel_pressure = 1;
182 #else
183 int opt_channel_pressure = 0;
184 #endif /* GM_CHANNEL_PRESSURE_ALLOW */
185 
186 #ifdef VOICE_CHAMBERLIN_LPF_ALLOW
187 int opt_lpf_def = 1;
188 #else
189 #ifdef VOICE_MOOG_LPF_ALLOW
190 int opt_lpf_def = 2;
191 #else
192 int opt_lpf_def = 0;
193 #endif /* VOICE_MOOG_LPF_ALLOW */
194 #endif /* VOICE_CHAMBERLIN_LPF_ALLOW */
195 
196 #ifdef OVERLAP_VOICE_ALLOW
197 int opt_overlap_voice_allow = 1;
198 #else
199 int opt_overlap_voice_allow = 0;
200 #endif /* OVERLAP_VOICE_ALLOW */
201 
202 #ifdef TEMPER_CONTROL_ALLOW
203 int opt_temper_control = 1;
204 #else
205 int opt_temper_control = 0;
206 #endif /* TEMPER_CONTROL_ALLOW */
207 
208 int opt_tva_attack = 0;	/* attack envelope control */
209 int opt_tva_decay = 0;	/* decay envelope control */
210 int opt_tva_release = 0;	/* release envelope control */
211 int opt_delay_control = 0;	/* CC#94 delay(celeste) effect control */
212 int opt_eq_control = 0;		/* channel equalizer control */
213 int opt_insertion_effect = 0;	/* insertion effect control */
214 int opt_drum_effect = 0;	/* drumpart effect control */
215 int32 opt_drum_power = 100;		/* coef. of drum amplitude */
216 int opt_amp_compensation = 0;
217 int opt_modulation_envelope = 0;
218 int opt_pan_delay = 0;	/* phase difference between left ear and right ear. */
219 int opt_user_volume_curve = 0;
220 int opt_default_module = MODULE_TIMIDITY_DEFAULT;
221 int opt_preserve_silence = 0;
222 
223 int voices=DEFAULT_VOICES, upper_voices;
224 
225 int32
226     control_ratio=0,
227     amplification=DEFAULT_AMPLIFICATION;
228 
229 static FLOAT_T
230     master_volume;
231 static int32 master_volume_ratio = 0xFFFF;
232 ChannelBitMask default_drumchannel_mask;
233 ChannelBitMask default_drumchannels;
234 ChannelBitMask drumchannel_mask;
235 ChannelBitMask drumchannels;
236 int adjust_panning_immediately = 1;
237 int auto_reduce_polyphony = 1;
238 double envelope_modify_rate = 1.0;
239 int reduce_quality_flag = 0;
240 int no_4point_interpolation = 0;
241 char* pcm_alternate_file = NULL; /* NULL or "none": Nothing (default)
242 				  * "auto": Auto select
243 				  * filename: Use it
244 				  */
245 
246 static int32 lost_notes, cut_notes;
247 static int32 common_buffer[AUDIO_BUFFER_SIZE*2], /* stereo samples */
248              *buffer_pointer;
249 static int16 wav_buffer[AUDIO_BUFFER_SIZE*2];
250 static int32 buffered_count;
251 static char *reverb_buffer = NULL; /* MAX_CHANNELS*AUDIO_BUFFER_SIZE*8 */
252 
253 #ifdef USE_DSP_EFFECT
254 static int32 insertion_effect_buffer[AUDIO_BUFFER_SIZE * 2];
255 #endif /* USE_DSP_EFFECT */
256 
257 #define VIBRATO_DEPTH_MAX 384	/* 600 cent */
258 
259 static MidiEvent *event_list;
260 static MidiEvent *current_event;
261 static int32 sample_count;	/* Length of event_list */
262 int32 current_sample;		/* Number of calclated samples */
263 
264 int note_key_offset = 0;		/* For key up/down */
265 FLOAT_T midi_time_ratio = 1.0;	/* For speed up/down */
266 ChannelBitMask channel_mute;	/* For channel mute */
267 int temper_type_mute;			/* For temperament type mute */
268 
269 /* for auto amplitude compensation */
270 static int mainvolume_max; /* maximum value of mainvolume */
271 static double compensation_ratio = 1.0; /* compensation ratio */
272 
273 static int find_samples(MidiEvent *, int *);
274 static int select_play_sample(Sample *, int, int *, int *, MidiEvent *);
275 static double get_play_note_ratio(int, int);
276 static int find_voice(MidiEvent *);
277 static void finish_note(int i);
278 static void update_portamento_controls(int ch);
279 static void update_rpn_map(int ch, int addr, int update_now);
280 static void ctl_prog_event(int ch);
281 static void ctl_timestamp(void);
282 static void ctl_updatetime(int32 samples);
283 static void ctl_pause_event(int pause, int32 samples);
284 static void update_legato_controls(int ch);
285 static void set_master_tuning(int);
286 static void set_single_note_tuning(int, int, int, int);
287 static void set_user_temper_entry(int, int, int);
288 static void set_cuepoint(int, int, int);
289 void recompute_bank_parameter(int, int);
290 
291 static void init_voice_filter(int);
292 /* XG Part EQ */
293 void init_part_eq_xg(struct part_eq_xg *);
294 void recompute_part_eq_xg(struct part_eq_xg *);
295 /* MIDI controllers (MW, Bend, CAf, PAf,...) */
296 static void init_midi_controller(midi_controller *);
297 static float get_midi_controller_amp(midi_controller *);
298 static float get_midi_controller_filter_cutoff(midi_controller *);
299 static float get_midi_controller_filter_depth(midi_controller *);
300 static int32 get_midi_controller_pitch(midi_controller *);
301 static int16 get_midi_controller_pitch_depth(midi_controller *);
302 static int16 get_midi_controller_amp_depth(midi_controller *);
303 /* Rx. ~ (Rcv ~) */
304 static void init_rx(int);
305 static void set_rx(int, int32, int);
306 static void init_rx_drum(struct DrumParts *);
307 static void set_rx_drum(struct DrumParts *, int32, int);
308 static int32 get_rx_drum(struct DrumParts *, int32);
309 
310 #define IS_SYSEX_EVENT_TYPE(event) ((event)->type == ME_NONE || (event)->type >= ME_RANDOM_PAN || (event)->b == SYSEX_TAG)
311 
event_name(int type)312 static char *event_name(int type)
313 {
314 #define EVENT_NAME(X) case X: return #X
315 	switch (type) {
316 	EVENT_NAME(ME_NONE);
317 	EVENT_NAME(ME_NOTEOFF);
318 	EVENT_NAME(ME_NOTEON);
319 	EVENT_NAME(ME_KEYPRESSURE);
320 	EVENT_NAME(ME_PROGRAM);
321 	EVENT_NAME(ME_CHANNEL_PRESSURE);
322 	EVENT_NAME(ME_PITCHWHEEL);
323 	EVENT_NAME(ME_TONE_BANK_MSB);
324 	EVENT_NAME(ME_TONE_BANK_LSB);
325 	EVENT_NAME(ME_MODULATION_WHEEL);
326 	EVENT_NAME(ME_BREATH);
327 	EVENT_NAME(ME_FOOT);
328 	EVENT_NAME(ME_MAINVOLUME);
329 	EVENT_NAME(ME_BALANCE);
330 	EVENT_NAME(ME_PAN);
331 	EVENT_NAME(ME_EXPRESSION);
332 	EVENT_NAME(ME_SUSTAIN);
333 	EVENT_NAME(ME_PORTAMENTO_TIME_MSB);
334 	EVENT_NAME(ME_PORTAMENTO_TIME_LSB);
335 	EVENT_NAME(ME_PORTAMENTO);
336 	EVENT_NAME(ME_PORTAMENTO_CONTROL);
337 	EVENT_NAME(ME_DATA_ENTRY_MSB);
338 	EVENT_NAME(ME_DATA_ENTRY_LSB);
339 	EVENT_NAME(ME_SOSTENUTO);
340 	EVENT_NAME(ME_SOFT_PEDAL);
341 	EVENT_NAME(ME_LEGATO_FOOTSWITCH);
342 	EVENT_NAME(ME_HOLD2);
343 	EVENT_NAME(ME_HARMONIC_CONTENT);
344 	EVENT_NAME(ME_RELEASE_TIME);
345 	EVENT_NAME(ME_ATTACK_TIME);
346 	EVENT_NAME(ME_BRIGHTNESS);
347 	EVENT_NAME(ME_REVERB_EFFECT);
348 	EVENT_NAME(ME_TREMOLO_EFFECT);
349 	EVENT_NAME(ME_CHORUS_EFFECT);
350 	EVENT_NAME(ME_CELESTE_EFFECT);
351 	EVENT_NAME(ME_PHASER_EFFECT);
352 	EVENT_NAME(ME_RPN_INC);
353 	EVENT_NAME(ME_RPN_DEC);
354 	EVENT_NAME(ME_NRPN_LSB);
355 	EVENT_NAME(ME_NRPN_MSB);
356 	EVENT_NAME(ME_RPN_LSB);
357 	EVENT_NAME(ME_RPN_MSB);
358 	EVENT_NAME(ME_ALL_SOUNDS_OFF);
359 	EVENT_NAME(ME_RESET_CONTROLLERS);
360 	EVENT_NAME(ME_ALL_NOTES_OFF);
361 	EVENT_NAME(ME_MONO);
362 	EVENT_NAME(ME_POLY);
363 #if 0
364 	EVENT_NAME(ME_VOLUME_ONOFF);		/* Not supported */
365 #endif
366 	EVENT_NAME(ME_MASTER_TUNING);
367 	EVENT_NAME(ME_SCALE_TUNING);
368 	EVENT_NAME(ME_BULK_TUNING_DUMP);
369 	EVENT_NAME(ME_SINGLE_NOTE_TUNING);
370 	EVENT_NAME(ME_RANDOM_PAN);
371 	EVENT_NAME(ME_SET_PATCH);
372 	EVENT_NAME(ME_DRUMPART);
373 	EVENT_NAME(ME_KEYSHIFT);
374 	EVENT_NAME(ME_PATCH_OFFS);
375 	EVENT_NAME(ME_TEMPO);
376 	EVENT_NAME(ME_CHORUS_TEXT);
377 	EVENT_NAME(ME_LYRIC);
378 	EVENT_NAME(ME_GSLCD);
379 	EVENT_NAME(ME_MARKER);
380 	EVENT_NAME(ME_INSERT_TEXT);
381 	EVENT_NAME(ME_TEXT);
382 	EVENT_NAME(ME_KARAOKE_LYRIC);
383 	EVENT_NAME(ME_MASTER_VOLUME);
384 	EVENT_NAME(ME_RESET);
385 	EVENT_NAME(ME_NOTE_STEP);
386 	EVENT_NAME(ME_CUEPOINT);
387 	EVENT_NAME(ME_TIMESIG);
388 	EVENT_NAME(ME_KEYSIG);
389 	EVENT_NAME(ME_TEMPER_KEYSIG);
390 	EVENT_NAME(ME_TEMPER_TYPE);
391 	EVENT_NAME(ME_MASTER_TEMPER_TYPE);
392 	EVENT_NAME(ME_USER_TEMPER_ENTRY);
393 	EVENT_NAME(ME_SYSEX_LSB);
394 	EVENT_NAME(ME_SYSEX_MSB);
395 	EVENT_NAME(ME_SYSEX_GS_LSB);
396 	EVENT_NAME(ME_SYSEX_GS_MSB);
397 	EVENT_NAME(ME_SYSEX_XG_LSB);
398 	EVENT_NAME(ME_SYSEX_XG_MSB);
399 	EVENT_NAME(ME_WRD);
400 	EVENT_NAME(ME_SHERRY);
401 	EVENT_NAME(ME_BARMARKER);
402 	EVENT_NAME(ME_STEP);
403 	EVENT_NAME(ME_LAST);
404 	EVENT_NAME(ME_EOT);
405 	}
406 	return "Unknown";
407 #undef EVENT_NAME
408 }
409 
410 /*! convert Hz to internal vibrato control ratio. */
cnv_Hz_to_vib_ratio(FLOAT_T freq)411 static FLOAT_T cnv_Hz_to_vib_ratio(FLOAT_T freq)
412 {
413 	return ((FLOAT_T)(play_mode->rate) / (freq * 2.0f * VIBRATO_SAMPLE_INCREMENTS));
414 }
415 
adjust_amplification(void)416 static void adjust_amplification(void)
417 {
418     /* compensate master volume */
419     master_volume = (double)(amplification) / 100.0 *
420 	((double)master_volume_ratio * (compensation_ratio/0xFFFF));
421 }
422 
new_vidq(int ch,int note)423 static int new_vidq(int ch, int note)
424 {
425     int i;
426 
427     if(opt_overlap_voice_allow)
428     {
429 	i = ch * 128 + note;
430 	return vidq_head[i]++;
431     }
432     return 0;
433 }
434 
last_vidq(int ch,int note)435 static int last_vidq(int ch, int note)
436 {
437     int i;
438 
439     if(opt_overlap_voice_allow)
440     {
441 	i = ch * 128 + note;
442 	if(vidq_head[i] == vidq_tail[i])
443 	{
444 	    ctl->cmsg(CMSG_WARNING, VERB_DEBUG_SILLY,
445 		      "channel=%d, note=%d: Voice is already OFF", ch, note);
446 	    return -1;
447 	}
448 	return vidq_tail[i]++;
449     }
450     return 0;
451 }
452 
reset_voices(void)453 static void reset_voices(void)
454 {
455     int i;
456     for(i = 0; i < max_voices; i++)
457     {
458 	voice[i].status = VOICE_FREE;
459 	voice[i].temper_instant = 0;
460 	voice[i].chorus_link = i;
461     }
462     upper_voices = 0;
463     memset(vidq_head, 0, sizeof(vidq_head));
464     memset(vidq_tail, 0, sizeof(vidq_tail));
465 }
466 
kill_note(int i)467 static void kill_note(int i)
468 {
469     voice[i].status = VOICE_DIE;
470     if(!prescanning_flag)
471 	ctl_note_event(i);
472 }
473 
kill_all_voices(void)474 void kill_all_voices(void)
475 {
476     int i, uv = upper_voices;
477 
478     for(i = 0; i < uv; i++)
479 	if(voice[i].status & ~(VOICE_FREE | VOICE_DIE))
480 	    kill_note(i);
481     memset(vidq_head, 0, sizeof(vidq_head));
482     memset(vidq_tail, 0, sizeof(vidq_tail));
483 }
484 
reset_drum_controllers(struct DrumParts * d[],int note)485 static void reset_drum_controllers(struct DrumParts *d[], int note)
486 {
487     int i,j;
488 
489     if(note == -1)
490     {
491 	for(i = 0; i < 128; i++)
492 	    if(d[i] != NULL)
493 	    {
494 		d[i]->drum_panning = NO_PANNING;
495 		for(j=0;j<6;j++) {d[i]->drum_envelope_rate[j] = -1;}
496 		d[i]->pan_random = 0;
497 		d[i]->drum_level = 1.0f;
498 		d[i]->coarse = 0;
499 		d[i]->fine = 0;
500 		d[i]->delay_level = -1;
501 		d[i]->chorus_level = -1;
502 		d[i]->reverb_level = -1;
503 		d[i]->play_note = -1;
504 		d[i]->drum_cutoff_freq = 0;
505 		d[i]->drum_resonance = 0;
506 		init_rx_drum(d[i]);
507 	    }
508     }
509     else
510     {
511 	d[note]->drum_panning = NO_PANNING;
512 	for(j = 0; j < 6; j++) {d[note]->drum_envelope_rate[j] = -1;}
513 	d[note]->pan_random = 0;
514 	d[note]->drum_level = 1.0f;
515 	d[note]->coarse = 0;
516 	d[note]->fine = 0;
517 	d[note]->delay_level = -1;
518 	d[note]->chorus_level = -1;
519 	d[note]->reverb_level = -1;
520 	d[note]->play_note = -1;
521 	d[note]->drum_cutoff_freq = 0;
522 	d[note]->drum_resonance = 0;
523 	init_rx_drum(d[note]);
524     }
525 }
526 
reset_module_dependent_controllers(int c)527 static void reset_module_dependent_controllers(int c)
528 {
529 	int module = get_module();
530 	switch(module) {	/* TONE MAP-0 NUMBER */
531 	case MODULE_SC55:
532 		channel[c].tone_map0_number = 1;
533 		break;
534 	case MODULE_SC88:
535 		channel[c].tone_map0_number = 2;
536 		break;
537 	case MODULE_SC88PRO:
538 		channel[c].tone_map0_number = 3;
539 		break;
540 	case MODULE_SC8850:
541 		channel[c].tone_map0_number = 4;
542 		break;
543 	default:
544 		channel[c].tone_map0_number = 0;
545 		break;
546 	}
547 	switch(module) {	/* MIDI Controllers */
548 	case MODULE_SC55:
549 		channel[c].mod.lfo1_pitch_depth = 10;
550 		break;
551 	case MODULE_SC88:
552 		channel[c].mod.lfo1_pitch_depth = 10;
553 		break;
554 	case MODULE_SC88PRO:
555 		channel[c].mod.lfo1_pitch_depth = 10;
556 		break;
557 	default:
558 		channel[c].mod.lfo1_pitch_depth = 50;
559 		break;
560 	}
561 }
562 
reset_nrpn_controllers(int c)563 static void reset_nrpn_controllers(int c)
564 {
565   int i;
566 
567   /* NRPN */
568   reset_drum_controllers(channel[c].drums, -1);
569   channel[c].vibrato_ratio = 1.0;
570   channel[c].vibrato_depth = 0;
571   channel[c].vibrato_delay = 0;
572   channel[c].param_cutoff_freq = 0;
573   channel[c].param_resonance = 0;
574   channel[c].cutoff_freq_coef = 1.0;
575   channel[c].resonance_dB = 0;
576 
577   /* System Exclusive */
578   channel[c].dry_level = 127;
579   channel[c].eq_gs = 1;
580   channel[c].insertion_effect = 0;
581   channel[c].velocity_sense_depth = 0x40;
582   channel[c].velocity_sense_offset = 0x40;
583   channel[c].pitch_offset_fine = 0;
584   if(play_system_mode == GS_SYSTEM_MODE) {channel[c].assign_mode = 1;}
585   else {
586 	  if(ISDRUMCHANNEL(c)) {channel[c].assign_mode = 1;}
587 	  else {channel[c].assign_mode = 2;}
588   }
589   for (i = 0; i < 12; i++)
590 	  channel[c].scale_tuning[i] = 0;
591   channel[c].prev_scale_tuning = 0;
592   channel[c].temper_type = 0;
593 
594   init_channel_layer(c);
595   init_part_eq_xg(&(channel[c].eq_xg));
596 
597   /* channel pressure & polyphonic key pressure control */
598   init_midi_controller(&(channel[c].mod));
599   init_midi_controller(&(channel[c].bend));
600   init_midi_controller(&(channel[c].caf));
601   init_midi_controller(&(channel[c].paf));
602   init_midi_controller(&(channel[c].cc1));
603   init_midi_controller(&(channel[c].cc2));
604   channel[c].bend.pitch = 2;
605 
606   init_rx(c);
607   channel[c].note_limit_high = 127;
608   channel[c].note_limit_low = 0;
609   channel[c].vel_limit_high = 127;
610   channel[c].vel_limit_low = 0;
611 
612   free_drum_effect(c);
613 
614   channel[c].legato = 0;
615   channel[c].damper_mode = 0;
616   channel[c].loop_timeout = 0;
617 
618   channel[c].sysex_gs_msb_addr = channel[c].sysex_gs_msb_val =
619 	channel[c].sysex_xg_msb_addr = channel[c].sysex_xg_msb_val =
620 	channel[c].sysex_msb_addr = channel[c].sysex_msb_val = 0;
621 }
622 
623 /* Process the Reset All Controllers event */
reset_controllers(int c)624 static void reset_controllers(int c)
625 {
626   int j;
627     /* Some standard says, although the SCC docs say 0. */
628 
629   if(play_system_mode == XG_SYSTEM_MODE)
630       channel[c].volume = 100;
631   else
632       channel[c].volume = 90;
633   if (prescanning_flag) {
634     if (channel[c].volume > mainvolume_max) {	/* pick maximum value of mainvolume */
635       mainvolume_max = channel[c].volume;
636       ctl->cmsg(CMSG_INFO,VERB_DEBUG,"ME_MAINVOLUME/max (CH:%d VAL:%#x)",c,mainvolume_max);
637     }
638   }
639 
640   channel[c].expression = 127; /* SCC-1 does this. */
641   channel[c].sustain = 0;
642   channel[c].sostenuto = 0;
643   channel[c].pitchbend = 0x2000;
644   channel[c].pitchfactor = 0; /* to be computed */
645   channel[c].mod.val = 0;
646   channel[c].bend.val = 0;
647   channel[c].caf.val = 0;
648   channel[c].paf.val = 0;
649   channel[c].cc1.val = 0;
650   channel[c].cc2.val = 0;
651   channel[c].portamento_time_lsb = 0;
652   channel[c].portamento_time_msb = 0;
653   channel[c].porta_control_ratio = 0;
654   channel[c].portamento = 0;
655   channel[c].last_note_fine = -1;
656   for(j = 0; j < 6; j++) {channel[c].envelope_rate[j] = -1;}
657   update_portamento_controls(c);
658   set_reverb_level(c, -1);
659   if(opt_chorus_control == 1)
660       channel[c].chorus_level = 0;
661   else
662       channel[c].chorus_level = -opt_chorus_control;
663   channel[c].mono = 0;
664   channel[c].delay_level = 0;
665 }
666 
redraw_controllers(int c)667 static void redraw_controllers(int c)
668 {
669     ctl_mode_event(CTLE_VOLUME, 1, c, channel[c].volume);
670     ctl_mode_event(CTLE_EXPRESSION, 1, c, channel[c].expression);
671     ctl_mode_event(CTLE_SUSTAIN, 1, c, channel[c].sustain);
672     ctl_mode_event(CTLE_MOD_WHEEL, 1, c, channel[c].mod.val);
673     ctl_mode_event(CTLE_PITCH_BEND, 1, c, channel[c].pitchbend);
674     ctl_prog_event(c);
675     ctl_mode_event(CTLE_TEMPER_TYPE, 1, c, channel[c].temper_type);
676     ctl_mode_event(CTLE_MUTE, 1,
677     		c, (IS_SET_CHANNELMASK(channel_mute, c)) ? 1 : 0);
678     ctl_mode_event(CTLE_CHORUS_EFFECT, 1, c, get_chorus_level(c));
679     ctl_mode_event(CTLE_REVERB_EFFECT, 1, c, get_reverb_level(c));
680 }
681 
reset_midi(int playing)682 void reset_midi(int playing)
683 {
684 	int i, cnt;
685 
686 	for (i = 0; i < MAX_CHANNELS; i++) {
687 		reset_controllers(i);
688 		reset_nrpn_controllers(i);
689      	reset_module_dependent_controllers(i);
690 		/* The rest of these are unaffected
691 		 * by the Reset All Controllers event
692 		 */
693 		channel[i].program = default_program[i];
694 		channel[i].panning = NO_PANNING;
695 		channel[i].pan_random = 0;
696 		/* tone bank or drum set */
697 		if (ISDRUMCHANNEL(i)) {
698 			channel[i].bank = 0;
699 			channel[i].altassign = drumset[0]->alt;
700 		} else {
701 			if (special_tonebank >= 0)
702 				channel[i].bank = special_tonebank;
703 			else
704 				channel[i].bank = default_tonebank;
705 		}
706 		channel[i].bank_lsb = channel[i].bank_msb = 0;
707 		if (play_system_mode == XG_SYSTEM_MODE && i % 16 == 9)
708 			channel[i].bank_msb = 127;	/* Use MSB=127 for XG */
709 		update_rpn_map(i, RPN_ADDR_FFFF, 0);
710 		channel[i].special_sample = 0;
711 		channel[i].key_shift = 0;
712 		channel[i].mapID = get_default_mapID(i);
713 		channel[i].lasttime = 0;
714 	}
715 	if (playing) {
716 		kill_all_voices();
717 		if (temper_type_mute) {
718 			if (temper_type_mute & 1)
719 				FILL_CHANNELMASK(channel_mute);
720 			else
721 				CLEAR_CHANNELMASK(channel_mute);
722 		}
723 		for (i = 0; i < MAX_CHANNELS; i++)
724 			redraw_controllers(i);
725 		if (midi_streaming && free_instruments_afterwards) {
726 			free_instruments(0);
727 			/* free unused memory */
728 			cnt = free_global_mblock();
729 			if (cnt > 0)
730 				ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
731 						"%d memory blocks are free", cnt);
732 		}
733 	} else
734 		reset_voices();
735 	master_volume_ratio = 0xffff;
736 	adjust_amplification();
737 	init_freq_table_tuning();
738 	master_tuning = 0;
739 	if (current_file_info) {
740 		COPY_CHANNELMASK(drumchannels, current_file_info->drumchannels);
741 		COPY_CHANNELMASK(drumchannel_mask,
742 				current_file_info->drumchannel_mask);
743 	} else {
744 		COPY_CHANNELMASK(drumchannels, default_drumchannels);
745 		COPY_CHANNELMASK(drumchannel_mask, default_drumchannel_mask);
746 	}
747 	ctl_mode_event(CTLE_MASTER_VOLUME, 0, amplification, 0);
748 	ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
749 	ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
750 }
751 
recompute_freq(int v)752 void recompute_freq(int v)
753 {
754 	int i;
755 	int ch = voice[v].channel;
756 	int note = voice[v].note;
757 	int32 tuning = 0;
758 	int8 st = channel[ch].scale_tuning[note % 12];
759 	int8 tt = channel[ch].temper_type;
760 	uint8 tp = channel[ch].rpnmap[RPN_ADDR_0003];
761 	int32 f;
762 	int pb = channel[ch].pitchbend;
763 	int32 tmp;
764 	FLOAT_T pf, root_freq;
765 	int32 a;
766 	Voice *vp = &(voice[v]);
767 
768 	if (! voice[v].sample->sample_rate)
769 		return;
770 	if (! opt_modulation_wheel)
771 		channel[ch].mod.val = 0;
772 	if (! opt_portamento)
773 		voice[v].porta_control_ratio = 0;
774 	voice[v].vibrato_control_ratio = voice[v].orig_vibrato_control_ratio;
775 	if (voice[v].vibrato_control_ratio || channel[ch].mod.val > 0) {
776 		/* This instrument has vibrato. Invalidate any precomputed
777 		 * sample_increments.
778 		 */
779 
780 		/* MIDI controllers LFO pitch depth */
781 		if (opt_channel_pressure || opt_modulation_wheel) {
782 			vp->vibrato_depth = vp->sample->vibrato_depth + channel[ch].vibrato_depth;
783 			vp->vibrato_depth += get_midi_controller_pitch_depth(&(channel[ch].mod))
784 				+ get_midi_controller_pitch_depth(&(channel[ch].bend))
785 				+ get_midi_controller_pitch_depth(&(channel[ch].caf))
786 				+ get_midi_controller_pitch_depth(&(channel[ch].paf))
787 				+ get_midi_controller_pitch_depth(&(channel[ch].cc1))
788 				+ get_midi_controller_pitch_depth(&(channel[ch].cc2));
789 			if (vp->vibrato_depth > VIBRATO_DEPTH_MAX) {vp->vibrato_depth = VIBRATO_DEPTH_MAX;}
790 			else if (vp->vibrato_depth < 1) {vp->vibrato_depth = 1;}
791 			if (vp->sample->vibrato_depth < 0) {	/* in opposite phase */
792 				vp->vibrato_depth = -vp->vibrato_depth;
793 			}
794 		}
795 
796 		/* fill parameters for modulation wheel */
797 		if (channel[ch].mod.val > 0) {
798 			if(vp->vibrato_control_ratio == 0) {
799 				vp->vibrato_control_ratio =
800 					vp->orig_vibrato_control_ratio = (int)(cnv_Hz_to_vib_ratio(5.0) * channel[ch].vibrato_ratio);
801 			}
802 			vp->vibrato_delay = 0;
803 		}
804 
805 		for (i = 0; i < VIBRATO_SAMPLE_INCREMENTS; i++)
806 			vp->vibrato_sample_increment[i] = 0;
807 		vp->cache = NULL;
808 	}
809 	/* At least for GM2, it's recommended not to apply master_tuning for drum channels */
810 	tuning = ISDRUMCHANNEL(ch) ? 0 : master_tuning;
811 	/* fine: [0..128] => [-256..256]
812 	 * 1 coarse = 256 fine (= 1 note)
813 	 * 1 fine = 2^5 tuning
814 	 */
815 	tuning += (channel[ch].rpnmap[RPN_ADDR_0001] - 0x40
816 			+ (channel[ch].rpnmap[RPN_ADDR_0002] - 0x40) * 64) << 7;
817 	/* for NRPN Coarse Pitch of Drum (GS) & Fine Pitch of Drum (XG) */
818 	if (ISDRUMCHANNEL(ch) && channel[ch].drums[note] != NULL
819 			&& (channel[ch].drums[note]->fine
820 			|| channel[ch].drums[note]->coarse)) {
821 		tuning += (channel[ch].drums[note]->fine
822 				+ channel[ch].drums[note]->coarse * 64) << 7;
823 	}
824 	/* MIDI controllers pitch control */
825 	if (opt_channel_pressure) {
826 		tuning += get_midi_controller_pitch(&(channel[ch].mod))
827 			+ get_midi_controller_pitch(&(channel[ch].bend))
828 			+ get_midi_controller_pitch(&(channel[ch].caf))
829 			+ get_midi_controller_pitch(&(channel[ch].paf))
830 			+ get_midi_controller_pitch(&(channel[ch].cc1))
831 			+ get_midi_controller_pitch(&(channel[ch].cc2));
832 	}
833 	if (opt_modulation_envelope) {
834 		if (voice[v].sample->tremolo_to_pitch) {
835 			tuning += lookup_triangular(voice[v].tremolo_phase >> RATE_SHIFT)
836 					* (voice[v].sample->tremolo_to_pitch << 13) / 100.0 + 0.5;
837 			channel[ch].pitchfactor = 0;
838 		}
839 		if (voice[v].sample->modenv_to_pitch) {
840 			tuning += voice[v].last_modenv_volume
841 					* (voice[v].sample->modenv_to_pitch << 13) / 100.0 + 0.5;
842 			channel[ch].pitchfactor = 0;
843 		}
844 	}
845 	/* GS/XG - Scale Tuning */
846 	if (! ISDRUMCHANNEL(ch)) {
847 		tuning += ((st << 13) + 50) / 100;
848 		if (st != channel[ch].prev_scale_tuning) {
849 			channel[ch].pitchfactor = 0;
850 			channel[ch].prev_scale_tuning = st;
851 		}
852 	}
853 	if (! opt_pure_intonation
854 			&& opt_temper_control && voice[v].temper_instant) {
855 		switch (tt) {
856 		case 0:
857 			f = freq_table_tuning[tp][note];
858 			break;
859 		case 1:
860 			if (current_temper_keysig < 8)
861 				f = freq_table_pytha[current_temper_freq_table][note];
862 			else
863 				f = freq_table_pytha[current_temper_freq_table + 12][note];
864 			break;
865 		case 2:
866 			if (current_temper_keysig < 8)
867 				f = freq_table_meantone[current_temper_freq_table
868 						+ ((temper_adj) ? 36 : 0)][note];
869 			else
870 				f = freq_table_meantone[current_temper_freq_table
871 						+ ((temper_adj) ? 24 : 12)][note];
872 			break;
873 		case 3:
874 			if (current_temper_keysig < 8)
875 				f = freq_table_pureint[current_temper_freq_table
876 						+ ((temper_adj) ? 36 : 0)][note];
877 			else
878 				f = freq_table_pureint[current_temper_freq_table
879 						+ ((temper_adj) ? 24 : 12)][note];
880 			break;
881 		default:	/* user-defined temperament */
882 			if ((tt -= 0x40) >= 0 && tt < 4) {
883 				if (current_temper_keysig < 8)
884 					f = freq_table_user[tt][current_temper_freq_table
885 							+ ((temper_adj) ? 36 : 0)][note];
886 				else
887 					f = freq_table_user[tt][current_temper_freq_table
888 							+ ((temper_adj) ? 24 : 12)][note];
889 			} else
890 				f = freq_table[note];
891 			break;
892 		}
893 		voice[v].orig_frequency = f;
894 	}
895 	if (! voice[v].porta_control_ratio) {
896 		if (tuning == 0 && pb == 0x2000)
897 			voice[v].frequency = voice[v].orig_frequency;
898 		else {
899 			pb -= 0x2000;
900 			if (! channel[ch].pitchfactor) {
901 				/* Damn.  Somebody bent the pitch. */
902 				tmp = pb * channel[ch].rpnmap[RPN_ADDR_0000] + tuning;
903 				if (tmp >= 0)
904 					channel[ch].pitchfactor = bend_fine[tmp >> 5 & 0xff]
905 							* bend_coarse[tmp >> 13 & 0x7f];
906 				else
907 					channel[ch].pitchfactor = 1.0 /
908 							(bend_fine[-tmp >> 5 & 0xff]
909 							* bend_coarse[-tmp >> 13 & 0x7f]);
910 			}
911 			voice[v].frequency =
912 					voice[v].orig_frequency * channel[ch].pitchfactor;
913 			if (voice[v].frequency != voice[v].orig_frequency)
914 				voice[v].cache = NULL;
915 		}
916 	} else {	/* Portamento */
917 		pb -= 0x2000;
918 		tmp = pb * channel[ch].rpnmap[RPN_ADDR_0000]
919 				+ (voice[v].porta_pb << 5) + tuning;
920 		if (tmp >= 0)
921 			pf = bend_fine[tmp >> 5 & 0xff]
922 					* bend_coarse[tmp >> 13 & 0x7f];
923 		else
924 			pf = 1.0 / (bend_fine[-tmp >> 5 & 0xff]
925 					* bend_coarse[-tmp >> 13 & 0x7f]);
926 		voice[v].frequency = voice[v].orig_frequency * pf;
927 		voice[v].cache = NULL;
928 	}
929 	root_freq = voice[v].sample->root_freq;
930 	a = TIM_FSCALE(((double) voice[v].sample->sample_rate
931 			* ((double)voice[v].frequency + channel[ch].pitch_offset_fine))
932 			/ (root_freq * play_mode->rate), FRACTION_BITS) + 0.5;
933 	/* need to preserve the loop direction */
934 	voice[v].sample_increment = (voice[v].sample_increment >= 0) ? a : -a;
935 #ifdef ABORT_AT_FATAL
936 	if (voice[v].sample_increment == 0) {
937 		fprintf(stderr, "Invalid sample increment a=%e %ld %ld %ld %ld%s\n",
938 				(double)a, (long) voice[v].sample->sample_rate,
939 				(long) voice[v].frequency, (long) voice[v].sample->root_freq,
940 				(long) play_mode->rate, (voice[v].cache) ? " (Cached)" : "");
941 		abort();
942 	}
943 #endif	/* ABORT_AT_FATAL */
944 }
945 
calc_velocity(int32 ch,int32 vel)946 static int32 calc_velocity(int32 ch,int32 vel)
947 {
948 	int32 velocity;
949 	velocity = channel[ch].velocity_sense_depth * vel / 64 + (channel[ch].velocity_sense_offset - 64) * 2;
950 	if(velocity > 127) {velocity = 127;}
951 	return velocity;
952 }
953 
recompute_voice_tremolo(int v)954 static void recompute_voice_tremolo(int v)
955 {
956 	Voice *vp = &(voice[v]);
957 	int ch = vp->channel;
958 	int32 depth = vp->sample->tremolo_depth;
959 	depth += get_midi_controller_amp_depth(&(channel[ch].mod))
960 		+ get_midi_controller_amp_depth(&(channel[ch].bend))
961 		+ get_midi_controller_amp_depth(&(channel[ch].caf))
962 		+ get_midi_controller_amp_depth(&(channel[ch].paf))
963 		+ get_midi_controller_amp_depth(&(channel[ch].cc1))
964 		+ get_midi_controller_amp_depth(&(channel[ch].cc2));
965 	if(depth > 256) {depth = 256;}
966 	vp->tremolo_depth = depth;
967 }
968 
recompute_amp(int v)969 static void recompute_amp(int v)
970 {
971 	FLOAT_T tempamp;
972 	int ch = voice[v].channel;
973 
974 	/* master_volume and sample->volume are percentages, used to scale
975 	 *  amplitude directly, NOT perceived volume
976 	 *
977 	 * all other MIDI volumes are linear in perceived volume, 0-127
978 	 * use a lookup table for the non-linear scalings
979 	 */
980 	if (opt_user_volume_curve) {
981 	tempamp = master_volume *
982 		   voice[v].sample->volume *
983 		   user_vol_table[calc_velocity(ch, voice[v].velocity)] *
984 		   user_vol_table[channel[ch].volume] *
985 		   user_vol_table[channel[ch].expression]; /* 21 bits */
986 	} else if (play_system_mode == GM2_SYSTEM_MODE) {
987 	tempamp = master_volume *
988 		  voice[v].sample->volume *
989 		  gm2_vol_table[calc_velocity(ch, voice[v].velocity)] *	/* velocity: not in GM2 standard */
990 		  gm2_vol_table[channel[ch].volume] *
991 		  gm2_vol_table[channel[ch].expression]; /* 21 bits */
992 	} else if(play_system_mode == GS_SYSTEM_MODE) {	/* use measured curve */
993 	tempamp = master_volume *
994 		   voice[v].sample->volume *
995 		   sc_vel_table[calc_velocity(ch, voice[v].velocity)] *
996 		   sc_vol_table[channel[ch].volume] *
997 		   sc_vol_table[channel[ch].expression]; /* 21 bits */
998 	} else if (IS_CURRENT_MOD_FILE) {	/* use linear curve */
999 	tempamp = master_volume *
1000 		  voice[v].sample->volume *
1001 		  calc_velocity(ch, voice[v].velocity) *
1002 		  channel[ch].volume *
1003 		  channel[ch].expression; /* 21 bits */
1004 	} else {	/* use generic exponential curve */
1005 	tempamp = master_volume *
1006 		  voice[v].sample->volume *
1007 		  perceived_vol_table[calc_velocity(ch, voice[v].velocity)] *
1008 		  perceived_vol_table[channel[ch].volume] *
1009 		  perceived_vol_table[channel[ch].expression]; /* 21 bits */
1010 	}
1011 
1012 	/* every digital effect increases amplitude,
1013 	 * so that it must be reduced in advance.
1014 	 */
1015 	if (! (play_mode->encoding & PE_MONO)
1016 	    && (opt_reverb_control || opt_chorus_control || opt_delay_control
1017 		|| (opt_eq_control && (eq_status_gs.low_gain != 0x40
1018 				       || eq_status_gs.high_gain != 0x40))
1019 		|| opt_insertion_effect))
1020 		tempamp *= 1.35f * 0.55f;
1021 	else
1022 		tempamp *= 1.35f;
1023 
1024 	/* Reduce amplitude for chorus partners.
1025 	 * 2x voices -> 2x power -> sqrt(2)x amplitude.
1026 	 * 1 / sqrt(2) = ~0.7071, which is very close to the old
1027 	 * CHORUS_VELOCITY_TUNING1 value of 0.7.
1028 	 *
1029 	 * The previous amp scaling for the various digital effects should
1030 	 * really be redone to split them into separate scalings for each
1031 	 * effect, rather than a single scaling if any one of them is used
1032 	 * (which is NOT correct).  As it is now, if partner chorus is the
1033 	 * only effect in use, then it is reduced in volume twice and winds
1034 	 * up too quiet.  Compare the output of "-EFreverb=0 -EFchorus=0",
1035 	 * "-EFreverb=0 -EFchorus=2", "-EFreverb=4 -EFchorus=2", and
1036 	 * "-EFreverb=4 -EFchorus=0" to see how the digital effect volumes
1037 	 * are not scaled properly.  Idealy, all the resulting output should
1038 	 * have the same volume, regardless of effects used.  This will
1039 	 * require empirically determining the amount to scale for each
1040 	 * individual effect.
1041 	 */
1042     	if (voice[v].chorus_link != v)
1043     	    tempamp *= 0.7071067811865f;
1044 
1045 	/* NRPN - drum instrument tva level */
1046 	if(ISDRUMCHANNEL(ch)) {
1047 		if(channel[ch].drums[voice[v].note] != NULL) {
1048 			tempamp *= channel[ch].drums[voice[v].note]->drum_level;
1049 		}
1050 		tempamp *= (double)opt_drum_power * 0.01f;	/* global drum power */
1051 	}
1052 
1053 	/* MIDI controllers amplitude control */
1054 	if(opt_channel_pressure) {
1055 		tempamp *= get_midi_controller_amp(&(channel[ch].mod))
1056 			* get_midi_controller_amp(&(channel[ch].bend))
1057 			* get_midi_controller_amp(&(channel[ch].caf))
1058 			* get_midi_controller_amp(&(channel[ch].paf))
1059 			* get_midi_controller_amp(&(channel[ch].cc1))
1060 			* get_midi_controller_amp(&(channel[ch].cc2));
1061 		recompute_voice_tremolo(v);
1062 	}
1063 
1064 	if (voice[v].fc.type != 0) {
1065 		tempamp *= voice[v].fc.gain;	/* filter gain */
1066 	}
1067 
1068 	/* applying panning to amplitude */
1069 	if(!(play_mode->encoding & PE_MONO))
1070     	{
1071 		if(voice[v].panning == 64)
1072 		{
1073 			voice[v].panned = PANNED_CENTER;
1074 			voice[v].left_amp = voice[v].right_amp = TIM_FSCALENEG(tempamp * pan_table[64], 27);
1075 		}
1076 		else if (voice[v].panning < 2)
1077 		{
1078 			voice[v].panned = PANNED_LEFT;
1079 			voice[v].left_amp = TIM_FSCALENEG(tempamp, 20);
1080 			voice[v].right_amp = 0;
1081 		}
1082 		else if(voice[v].panning == 127)
1083 		{
1084 #ifdef SMOOTH_MIXING
1085 			if(voice[v].panned == PANNED_MYSTERY) {
1086 				voice[v].old_left_mix = voice[v].old_right_mix;
1087 				voice[v].old_right_mix = 0;
1088 			}
1089 #endif
1090 			voice[v].panned = PANNED_RIGHT;
1091 			voice[v].left_amp =  TIM_FSCALENEG(tempamp, 20);
1092 			voice[v].right_amp = 0;
1093 		}
1094 		else
1095 		{
1096 #ifdef SMOOTH_MIXING
1097 			if(voice[v].panned == PANNED_RIGHT) {
1098 				voice[v].old_right_mix = voice[v].old_left_mix;
1099 				voice[v].old_left_mix = 0;
1100 			}
1101 #endif
1102 			voice[v].panned = PANNED_MYSTERY;
1103 			voice[v].left_amp = TIM_FSCALENEG(tempamp * pan_table[128 - voice[v].panning], 27);
1104 			voice[v].right_amp = TIM_FSCALENEG(tempamp * pan_table[voice[v].panning], 27);
1105 		}
1106     	}
1107     	else
1108     	{
1109 		voice[v].panned = PANNED_CENTER;
1110 		voice[v].left_amp = TIM_FSCALENEG(tempamp, 21);
1111     	}
1112 }
1113 
1114 #define RESONANCE_COEFF 0.2393
1115 
recompute_channel_filter(int ch,int note)1116 void recompute_channel_filter(int ch, int note)
1117 {
1118 	double coef = 1.0f, reso = 0;
1119 
1120 	if(channel[ch].special_sample > 0) {return;}
1121 
1122 	/* Soft Pedal */
1123 	if(channel[ch].soft_pedal != 0) {
1124 		if(note > 49) {	/* tre corde */
1125 			coef *= 1.0 - 0.20 * ((double)channel[ch].soft_pedal) / 127.0f;
1126 		} else {	/* una corda (due corde) */
1127 			coef *= 1.0 - 0.25 * ((double)channel[ch].soft_pedal) / 127.0f;
1128 		}
1129 	}
1130 
1131 	if(!ISDRUMCHANNEL(ch)) {
1132 		/* NRPN Filter Cutoff */
1133 		coef *= pow(1.26, (double)(channel[ch].param_cutoff_freq) / 8.0f);
1134 		/* NRPN Resonance */
1135 		reso = (double)channel[ch].param_resonance * RESONANCE_COEFF;
1136 	}
1137 
1138 	channel[ch].cutoff_freq_coef = coef;
1139 	channel[ch].resonance_dB = reso;
1140 }
1141 
init_voice_filter(int i)1142 void init_voice_filter(int i)
1143 {
1144   memset(&(voice[i].fc), 0, sizeof(FilterCoefficients));
1145   if(opt_lpf_def && voice[i].sample->cutoff_freq) {
1146 	  voice[i].fc.orig_freq = voice[i].sample->cutoff_freq;
1147 	  voice[i].fc.orig_reso_dB = (double)voice[i].sample->resonance / 10.0f - 3.01f;
1148 	  if (voice[i].fc.orig_reso_dB < 0.0f) {voice[i].fc.orig_reso_dB = 0.0f;}
1149 	  if (opt_lpf_def == 2) {
1150 		  voice[i].fc.gain = 1.0;
1151 		  voice[i].fc.type = 2;
1152 	  } else if(opt_lpf_def == 1) {
1153 		  voice[i].fc.gain = pow(10.0f, -voice[i].fc.orig_reso_dB / 2.0f / 20.0f);
1154 		  voice[i].fc.type = 1;
1155 	  }
1156 	  voice[i].fc.start_flag = 0;
1157   } else {
1158 	  voice[i].fc.type = 0;
1159   }
1160 }
1161 
1162 #define CHAMBERLIN_RESONANCE_MAX 24.0
1163 
recompute_voice_filter(int v)1164 void recompute_voice_filter(int v)
1165 {
1166 	int ch = voice[v].channel, note = voice[v].note;
1167 	double coef = 1.0, reso = 0, cent = 0, depth_cent = 0, freq;
1168 	FilterCoefficients *fc = &(voice[v].fc);
1169 	Sample *sp = (Sample *) &voice[v].sample;
1170 
1171 	if(fc->type == 0) {return;}
1172 	coef = channel[ch].cutoff_freq_coef;
1173 
1174 	if(ISDRUMCHANNEL(ch) && channel[ch].drums[note] != NULL) {
1175 		/* NRPN Drum Instrument Filter Cutoff */
1176 		coef *= pow(1.26, (double)(channel[ch].drums[note]->drum_cutoff_freq) / 8.0f);
1177 		/* NRPN Drum Instrument Filter Resonance */
1178 		reso += (double)channel[ch].drums[note]->drum_resonance * RESONANCE_COEFF;
1179 	}
1180 
1181 	/* MIDI controllers filter cutoff control and LFO filter depth */
1182 	if(opt_channel_pressure) {
1183 		cent += get_midi_controller_filter_cutoff(&(channel[ch].mod))
1184 			+ get_midi_controller_filter_cutoff(&(channel[ch].bend))
1185 			+ get_midi_controller_filter_cutoff(&(channel[ch].caf))
1186 			+ get_midi_controller_filter_cutoff(&(channel[ch].paf))
1187 			+ get_midi_controller_filter_cutoff(&(channel[ch].cc1))
1188 			+ get_midi_controller_filter_cutoff(&(channel[ch].cc2));
1189 		depth_cent += get_midi_controller_filter_depth(&(channel[ch].mod))
1190 			+ get_midi_controller_filter_depth(&(channel[ch].bend))
1191 			+ get_midi_controller_filter_depth(&(channel[ch].caf))
1192 			+ get_midi_controller_filter_depth(&(channel[ch].paf))
1193 			+ get_midi_controller_filter_depth(&(channel[ch].cc1))
1194 			+ get_midi_controller_filter_depth(&(channel[ch].cc2));
1195 	}
1196 
1197 	if(sp->vel_to_fc) {	/* velocity to filter cutoff frequency */
1198 		if(voice[v].velocity > sp->vel_to_fc_threshold)
1199 			cent += sp->vel_to_fc * (double)(127 - voice[v].velocity) / 127.0f;
1200 		else
1201 			coef += sp->vel_to_fc * (double)(127 - sp->vel_to_fc_threshold) / 127.0f;
1202 	}
1203 	if(sp->vel_to_resonance) {	/* velocity to filter resonance */
1204 		reso += (double)voice[v].velocity * sp->vel_to_resonance / 127.0f / 10.0f;
1205 	}
1206 	if(sp->key_to_fc) {	/* filter cutoff key-follow */
1207 		cent += sp->key_to_fc * (double)(voice[v].note - sp->key_to_fc_bpo);
1208 	}
1209 
1210 	if(opt_modulation_envelope) {
1211 		if(voice[v].sample->tremolo_to_fc + (int16)depth_cent) {
1212 			cent += ((double)voice[v].sample->tremolo_to_fc + depth_cent) * lookup_triangular(voice[v].tremolo_phase >> RATE_SHIFT);
1213 		}
1214 		if(voice[v].sample->modenv_to_fc) {
1215 			cent += (double)voice[v].sample->modenv_to_fc * voice[v].last_modenv_volume;
1216 		}
1217 	}
1218 
1219 	if(cent != 0) {coef *= pow(2.0, cent / 1200.0f);}
1220 
1221 	freq = (double)fc->orig_freq * coef;
1222 
1223 	if (freq > play_mode->rate / 2) {freq = play_mode->rate / 2;}
1224 	else if(freq < 5) {freq = 5;}
1225 	fc->freq = (int32)freq;
1226 
1227 	fc->reso_dB = fc->orig_reso_dB + channel[ch].resonance_dB + reso;
1228 	if(fc->reso_dB < 0.0f) {fc->reso_dB = 0.0f;}
1229 	else if(fc->reso_dB > 96.0f) {fc->reso_dB = 96.0f;}
1230 
1231 	if(fc->type == 1) {	/* Chamberlin filter */
1232 		if(fc->freq > play_mode->rate / 6) {
1233 			if (fc->start_flag == 0) {fc->type = 0;}	/* turn off. */
1234 			else {fc->freq = play_mode->rate / 6;}
1235 		}
1236 		if(fc->reso_dB > CHAMBERLIN_RESONANCE_MAX) {fc->reso_dB = CHAMBERLIN_RESONANCE_MAX;}
1237 	} else if(fc->type == 2) {	/* Moog VCF */
1238 		if(fc->reso_dB > fc->orig_reso_dB / 2) {
1239 			fc->gain = pow(10.0f, (fc->reso_dB - fc->orig_reso_dB / 2) / 20.0f);
1240 		}
1241 	}
1242 	fc->start_flag = 1;	/* filter is started. */
1243 }
1244 
calc_drum_tva_level(int ch,int note,int level)1245 float calc_drum_tva_level(int ch, int note, int level)
1246 {
1247 	int def_level, nbank, nprog;
1248 	ToneBank *bank;
1249 
1250 	if(channel[ch].special_sample > 0) {return 1.0;}
1251 
1252 	nbank = channel[ch].bank;
1253 	nprog = note;
1254 	instrument_map(channel[ch].mapID, &nbank, &nprog);
1255 
1256 	if(ISDRUMCHANNEL(ch)) {
1257 		bank = drumset[nbank];
1258 		if(bank == NULL) {bank = drumset[0];}
1259 	} else {
1260 		return 1.0;
1261 	}
1262 
1263 	def_level = bank->tone[nprog].tva_level;
1264 
1265 	if(def_level == -1 || def_level == 0) {def_level = 127;}
1266 	else if(def_level > 127) {def_level = 127;}
1267 
1268 	return (sc_drum_level_table[level] / sc_drum_level_table[def_level]);
1269 }
1270 
calc_random_delay(int ch,int note)1271 static int32 calc_random_delay(int ch, int note)
1272 {
1273 	int nbank, nprog;
1274 	ToneBank *bank;
1275 
1276 	if(channel[ch].special_sample > 0) {return 0;}
1277 
1278 	nbank = channel[ch].bank;
1279 
1280 	if(ISDRUMCHANNEL(ch)) {
1281 		nprog = note;
1282 		instrument_map(channel[ch].mapID, &nbank, &nprog);
1283 		bank = drumset[nbank];
1284 		if (bank == NULL) {bank = drumset[0];}
1285 	} else {
1286 		nprog = channel[ch].program;
1287 		if(nprog == SPECIAL_PROGRAM) {return 0;}
1288 		instrument_map(channel[ch].mapID, &nbank, &nprog);
1289 		bank = tonebank[nbank];
1290 		if(bank == NULL) {bank = tonebank[0];}
1291 	}
1292 
1293 	if (bank->tone[nprog].rnddelay == 0) {return 0;}
1294 	else {return (int32)((double)bank->tone[nprog].rnddelay * play_mode->rate / 1000.0
1295 		* (get_pink_noise_light(&global_pink_noise_light) + 1.0f) * 0.5);}
1296 }
1297 
recompute_bank_parameter(int ch,int note)1298 void recompute_bank_parameter(int ch, int note)
1299 {
1300 	int nbank, nprog;
1301 	ToneBank *bank;
1302 	struct DrumParts *drum;
1303 
1304 	if(channel[ch].special_sample > 0) {return;}
1305 
1306 	nbank = channel[ch].bank;
1307 
1308 	if(ISDRUMCHANNEL(ch)) {
1309 		nprog = note;
1310 		instrument_map(channel[ch].mapID, &nbank, &nprog);
1311 		bank = drumset[nbank];
1312 		if (bank == NULL) {bank = drumset[0];}
1313 		if (channel[ch].drums[note] == NULL)
1314 				play_midi_setup_drums(ch, note);
1315 		drum = channel[ch].drums[note];
1316 		if (drum->reverb_level == -1 && bank->tone[nprog].reverb_send != -1) {
1317 			drum->reverb_level = bank->tone[nprog].reverb_send;
1318 		}
1319 		if (drum->chorus_level == -1 && bank->tone[nprog].chorus_send != -1) {
1320 			drum->chorus_level = bank->tone[nprog].chorus_send;
1321 		}
1322 		if (drum->delay_level == -1 && bank->tone[nprog].delay_send != -1) {
1323 			drum->delay_level = bank->tone[nprog].delay_send;
1324 		}
1325 	} else {
1326 		nprog = channel[ch].program;
1327 		if (nprog == SPECIAL_PROGRAM) {return;}
1328 		instrument_map(channel[ch].mapID, &nbank, &nprog);
1329 		bank = tonebank[nbank];
1330 		if (bank == NULL) {bank = tonebank[0];}
1331 		channel[ch].legato = bank->tone[nprog].legato;
1332 		channel[ch].damper_mode = bank->tone[nprog].damper_mode;
1333 		channel[ch].loop_timeout = bank->tone[nprog].loop_timeout;
1334 	}
1335 }
1336 
play_midi_load_instrument(int dr,int bk,int prog)1337 Instrument *play_midi_load_instrument(int dr, int bk, int prog)
1338 {
1339 	ToneBank **bank = (dr) ? drumset : tonebank;
1340 	ToneBankElement *tone;
1341 	Instrument *ip;
1342 	int load_success = 0;
1343 
1344 	if (bank[bk] == NULL)
1345 		alloc_instrument_bank(dr, bk);
1346 
1347 	tone = &bank[bk]->tone[prog];
1348 	/* tone->name is NULL if "soundfont" directive is used, and ip is NULL when not preloaded */
1349 	/* dr: not sure but only drumsets are concerned at the moment */
1350 	if (dr && !tone->name && ((ip = tone->instrument) == MAGIC_LOAD_INSTRUMENT || ip == NULL)
1351 		  && (ip = load_instrument(dr, bk, prog)) != NULL) {
1352 		tone->instrument = ip;
1353 		tone->name = safe_strdup(DYNAMIC_INSTRUMENT_NAME);
1354 		load_success = 1;
1355 	} else if (tone->name) {
1356 		/* Instrument is found. */
1357 		if ((ip = tone->instrument) == MAGIC_LOAD_INSTRUMENT
1358 #ifndef SUPPRESS_CHANNEL_LAYER
1359 			|| ip == NULL	/* see also readmidi.c: groom_list(). */
1360 #endif
1361 		) {ip = tone->instrument = load_instrument(dr, bk, prog);}
1362 		if (ip == NULL || IS_MAGIC_INSTRUMENT(ip)) {
1363 			tone->instrument = MAGIC_ERROR_INSTRUMENT;
1364 		} else {
1365 			load_success = 1;
1366 		}
1367 	} else {
1368 		/* Instrument is not found.
1369 		   Try to load the instrument from bank 0 */
1370 		ToneBankElement *tone0 = &bank[0]->tone[prog];
1371 		if ((ip = tone0->instrument) == NULL
1372 			|| ip == MAGIC_LOAD_INSTRUMENT)
1373 			ip = tone0->instrument = load_instrument(dr, 0, prog);
1374 		if (ip == NULL || IS_MAGIC_INSTRUMENT(ip)) {
1375 			tone0->instrument = MAGIC_ERROR_INSTRUMENT;
1376 		} else {
1377 			copy_tone_bank_element(tone, tone0);
1378 			tone->instrument = ip;
1379 			load_success = 1;
1380 		}
1381 	}
1382 
1383 	if (load_success)
1384 		aq_add(NULL, 0);	/* Update software buffer */
1385 
1386 	if (ip == MAGIC_ERROR_INSTRUMENT)
1387 		return NULL;
1388 
1389 	return ip;
1390 }
1391 
1392 #if 0
1393 /* reduce_voice_CPU() may not have any speed advantage over reduce_voice().
1394  * So this function is not used, now.
1395  */
1396 
1397 /* The goal of this routine is to free as much CPU as possible without
1398    loosing too much sound quality.  We would like to know how long a note
1399    has been playing, but since we usually can't calculate this, we guess at
1400    the value instead.  A bad guess is better than nothing.  Notes which
1401    have been playing a short amount of time are killed first.  This causes
1402    decays and notes to be cut earlier, saving more CPU time.  It also causes
1403    notes which are closer to ending not to be cut as often, so it cuts
1404    a different note instead and saves more CPU in the long run.  ON voices
1405    are treated a little differently, since sound quality is more important
1406    than saving CPU at this point.  Duration guesses for loop regions are very
1407    crude, but are still better than nothing, they DO help.  Non-looping ON
1408    notes are cut before looping ON notes.  Since a looping ON note is more
1409    likely to have been playing for a long time, we want to keep it because it
1410    sounds better to keep long notes.
1411 */
1412 static int reduce_voice_CPU(void)
1413 {
1414     int32 lv, v, vr;
1415     int i, j, lowest=-0x7FFFFFFF;
1416     int32 duration;
1417 
1418     i = upper_voices;
1419     lv = 0x7FFFFFFF;
1420 
1421     /* Look for the decaying note with the longest remaining decay time */
1422     /* Protect drum decays.  They do not take as much CPU (?) and truncating
1423        them early sounds bad, especially on snares and cymbals */
1424     for(j = 0; j < i; j++)
1425     {
1426 	if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1427 	    continue;
1428 	/* skip notes that don't need resampling (most drums) */
1429 	if (voice[j].sample->note_to_use)
1430 	    continue;
1431 	if(voice[j].status & ~(VOICE_ON | VOICE_DIE | VOICE_SUSTAINED))
1432 	{
1433 	    /* Choose note with longest decay time remaining */
1434 	    /* This frees more CPU than choosing lowest volume */
1435 	    if (!voice[j].envelope_increment) duration = 0;
1436 	    else duration =
1437 	    	(voice[j].envelope_target - voice[j].envelope_volume) /
1438 	    	voice[j].envelope_increment;
1439 	    v = -duration;
1440 	    if(v < lv)
1441 	    {
1442 		lv = v;
1443 		lowest = j;
1444 	    }
1445 	}
1446     }
1447     if(lowest != -0x7FFFFFFF)
1448     {
1449 	/* This can still cause a click, but if we had a free voice to
1450 	   spare for ramping down this note, we wouldn't need to kill it
1451 	   in the first place... Still, this needs to be fixed. Perhaps
1452 	   we could use a reserve of voices to play dying notes only. */
1453 
1454 	cut_notes++;
1455 	return lowest;
1456     }
1457 
1458     /* try to remove VOICE_DIE before VOICE_ON */
1459     lv = 0x7FFFFFFF;
1460     lowest = -1;
1461     for(j = 0; j < i; j++)
1462     {
1463       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1464 	    continue;
1465       if(voice[j].status & ~(VOICE_ON | VOICE_SUSTAINED))
1466       {
1467 	/* continue protecting non-resample decays */
1468 	if (voice[j].status & ~(VOICE_DIE) && voice[j].sample->note_to_use)
1469 		continue;
1470 
1471 	/* choose note which has been on the shortest amount of time */
1472 	/* this is a VERY crude estimate... */
1473 	if (voice[j].sample->modes & MODES_LOOPING)
1474 	    duration = voice[j].sample_offset - voice[j].sample->loop_start;
1475 	else
1476 	    duration = voice[j].sample_offset;
1477 	if (voice[j].sample_increment > 0)
1478 	    duration /= voice[j].sample_increment;
1479 	v = duration;
1480 	if(v < lv)
1481 	{
1482 	    lv = v;
1483 	    lowest = j;
1484 	}
1485       }
1486     }
1487     if(lowest != -1)
1488     {
1489 	cut_notes++;
1490 	return lowest;
1491     }
1492 
1493     /* try to remove VOICE_SUSTAINED before VOICE_ON */
1494     lv = 0x7FFFFFFF;
1495     lowest = -0x7FFFFFFF;
1496     for(j = 0; j < i; j++)
1497     {
1498       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1499 	    continue;
1500       if(voice[j].status & VOICE_SUSTAINED)
1501       {
1502 	/* choose note which has been on the shortest amount of time */
1503 	/* this is a VERY crude estimate... */
1504 	if (voice[j].sample->modes & MODES_LOOPING)
1505 	    duration = voice[j].sample_offset - voice[j].sample->loop_start;
1506 	else
1507 	    duration = voice[j].sample_offset;
1508 	if (voice[j].sample_increment > 0)
1509 	    duration /= voice[j].sample_increment;
1510 	v = duration;
1511 	if(v < lv)
1512 	{
1513 	    lv = v;
1514 	    lowest = j;
1515 	}
1516       }
1517     }
1518     if(lowest != -0x7FFFFFFF)
1519     {
1520 	cut_notes++;
1521 	return lowest;
1522     }
1523 
1524     /* try to remove chorus before VOICE_ON */
1525     lv = 0x7FFFFFFF;
1526     lowest = -0x7FFFFFFF;
1527     for(j = 0; j < i; j++)
1528     {
1529       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1530 	    continue;
1531       if(voice[j].chorus_link < j)
1532       {
1533 	/* score notes based on both volume AND duration */
1534 	/* this scoring function needs some more tweaking... */
1535 	if (voice[j].sample->modes & MODES_LOOPING)
1536 	    duration = voice[j].sample_offset - voice[j].sample->loop_start;
1537 	else
1538 	    duration = voice[j].sample_offset;
1539 	if (voice[j].sample_increment > 0)
1540 	    duration /= voice[j].sample_increment;
1541 	v = voice[j].left_mix * duration;
1542 	vr = voice[j].right_mix * duration;
1543 	if(voice[j].panned == PANNED_MYSTERY && vr > v)
1544 	    v = vr;
1545 	if(v < lv)
1546 	{
1547 	    lv = v;
1548 	    lowest = j;
1549 	}
1550       }
1551     }
1552     if(lowest != -0x7FFFFFFF)
1553     {
1554 	cut_notes++;
1555 
1556 	/* fix pan */
1557 	j = voice[lowest].chorus_link;
1558     	voice[j].panning = channel[voice[lowest].channel].panning;
1559     	recompute_amp(j);
1560     	apply_envelope_to_amp(j);
1561 
1562 	return lowest;
1563     }
1564 
1565     lost_notes++;
1566 
1567     /* try to remove non-looping voices first */
1568     lv = 0x7FFFFFFF;
1569     lowest = -0x7FFFFFFF;
1570     for(j = 0; j < i; j++)
1571     {
1572       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1573 	    continue;
1574       if(!(voice[j].sample->modes & MODES_LOOPING))
1575       {
1576 	/* score notes based on both volume AND duration */
1577 	/* this scoring function needs some more tweaking... */
1578 	duration = voice[j].sample_offset;
1579 	if (voice[j].sample_increment > 0)
1580 	    duration /= voice[j].sample_increment;
1581 	v = voice[j].left_mix * duration;
1582 	vr = voice[j].right_mix * duration;
1583 	if(voice[j].panned == PANNED_MYSTERY && vr > v)
1584 	    v = vr;
1585 	if(v < lv)
1586 	{
1587 	    lv = v;
1588 	    lowest = j;
1589 	}
1590       }
1591     }
1592     if(lowest != -0x7FFFFFFF)
1593     {
1594 	return lowest;
1595     }
1596 
1597     lv = 0x7FFFFFFF;
1598     lowest = 0;
1599     for(j = 0; j < i; j++)
1600     {
1601 	if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
1602 	    continue;
1603 	if (!(voice[j].sample->modes & MODES_LOOPING)) continue;
1604 
1605 	/* score notes based on both volume AND duration */
1606 	/* this scoring function needs some more tweaking... */
1607 	duration = voice[j].sample_offset - voice[j].sample->loop_start;
1608 	if (voice[j].sample_increment > 0)
1609 	    duration /= voice[j].sample_increment;
1610 	v = voice[j].left_mix * duration;
1611 	vr = voice[j].right_mix * duration;
1612 	if(voice[j].panned == PANNED_MYSTERY && vr > v)
1613 	    v = vr;
1614 	if(v < lv)
1615 	{
1616 	    lv = v;
1617 	    lowest = j;
1618 	}
1619     }
1620 
1621     return lowest;
1622 }
1623 #endif
1624 
1625 /* this reduces voices while maintaining sound quality */
reduce_voice(void)1626 static int reduce_voice(void)
1627 {
1628     int32 lv, v;
1629     int i, j, lowest=-0x7FFFFFFF;
1630 
1631     i = upper_voices;
1632     lv = 0x7FFFFFFF;
1633 
1634     /* Look for the decaying note with the smallest volume */
1635     /* Protect drum decays.  Truncating them early sounds bad, especially on
1636        snares and cymbals */
1637     for(j = 0; j < i; j++)
1638     {
1639 	if(voice[j].status & VOICE_FREE ||
1640 	   (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
1641 	    continue;
1642 
1643 	if(voice[j].status & ~(VOICE_ON | VOICE_DIE | VOICE_SUSTAINED))
1644 	{
1645 	    /* find lowest volume */
1646 	    v = voice[j].left_mix;
1647 	    if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1648 	    	v = voice[j].right_mix;
1649 	    if(v < lv)
1650 	    {
1651 		lv = v;
1652 		lowest = j;
1653 	    }
1654 	}
1655     }
1656     if(lowest != -0x7FFFFFFF)
1657     {
1658 	/* This can still cause a click, but if we had a free voice to
1659 	   spare for ramping down this note, we wouldn't need to kill it
1660 	   in the first place... Still, this needs to be fixed. Perhaps
1661 	   we could use a reserve of voices to play dying notes only. */
1662 
1663 	cut_notes++;
1664 	free_voice(lowest);
1665 	if(!prescanning_flag)
1666 	    ctl_note_event(lowest);
1667 	return lowest;
1668     }
1669 
1670     /* try to remove VOICE_DIE before VOICE_ON */
1671     lv = 0x7FFFFFFF;
1672     lowest = -1;
1673     for(j = 0; j < i; j++)
1674     {
1675       if(voice[j].status & VOICE_FREE)
1676 	    continue;
1677       if(voice[j].status & ~(VOICE_ON | VOICE_SUSTAINED))
1678       {
1679 	/* continue protecting drum decays */
1680 	if (voice[j].status & ~(VOICE_DIE) &&
1681 	    (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
1682 		continue;
1683 	/* find lowest volume */
1684 	v = voice[j].left_mix;
1685 	if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1686 	    v = voice[j].right_mix;
1687 	if(v < lv)
1688 	{
1689 	    lv = v;
1690 	    lowest = j;
1691 	}
1692       }
1693     }
1694     if(lowest != -1)
1695     {
1696 	cut_notes++;
1697 	free_voice(lowest);
1698 	if(!prescanning_flag)
1699 	    ctl_note_event(lowest);
1700 	return lowest;
1701     }
1702 
1703     /* try to remove VOICE_SUSTAINED before VOICE_ON */
1704     lv = 0x7FFFFFFF;
1705     lowest = -0x7FFFFFFF;
1706     for(j = 0; j < i; j++)
1707     {
1708       if(voice[j].status & VOICE_FREE)
1709 	    continue;
1710       if(voice[j].status & VOICE_SUSTAINED)
1711       {
1712 	/* find lowest volume */
1713 	v = voice[j].left_mix;
1714 	if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1715 	    v = voice[j].right_mix;
1716 	if(v < lv)
1717 	{
1718 	    lv = v;
1719 	    lowest = j;
1720 	}
1721       }
1722     }
1723     if(lowest != -0x7FFFFFFF)
1724     {
1725 	cut_notes++;
1726 	free_voice(lowest);
1727 	if(!prescanning_flag)
1728 	    ctl_note_event(lowest);
1729 	return lowest;
1730     }
1731 
1732     /* try to remove chorus before VOICE_ON */
1733     lv = 0x7FFFFFFF;
1734     lowest = -0x7FFFFFFF;
1735     for(j = 0; j < i; j++)
1736     {
1737       if(voice[j].status & VOICE_FREE)
1738 	    continue;
1739       if(voice[j].chorus_link < j)
1740       {
1741 	/* find lowest volume */
1742 	v = voice[j].left_mix;
1743 	if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1744 	    v = voice[j].right_mix;
1745 	if(v < lv)
1746 	{
1747 	    lv = v;
1748 	    lowest = j;
1749 	}
1750       }
1751     }
1752     if(lowest != -0x7FFFFFFF)
1753     {
1754 	cut_notes++;
1755 
1756 	/* fix pan */
1757 	j = voice[lowest].chorus_link;
1758     	voice[j].panning = channel[voice[lowest].channel].panning;
1759     	recompute_amp(j);
1760     	apply_envelope_to_amp(j);
1761 
1762 	free_voice(lowest);
1763 	if(!prescanning_flag)
1764 	    ctl_note_event(lowest);
1765 	return lowest;
1766     }
1767 
1768     lost_notes++;
1769 
1770     /* remove non-drum VOICE_ON */
1771     lv = 0x7FFFFFFF;
1772     lowest = -0x7FFFFFFF;
1773     for(j = 0; j < i; j++)
1774     {
1775         if(voice[j].status & VOICE_FREE ||
1776 	   (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
1777 	   	continue;
1778 
1779 	/* find lowest volume */
1780 	v = voice[j].left_mix;
1781 	if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1782 	    v = voice[j].right_mix;
1783 	if(v < lv)
1784 	{
1785 	    lv = v;
1786 	    lowest = j;
1787 	}
1788     }
1789     if(lowest != -0x7FFFFFFF)
1790     {
1791 	free_voice(lowest);
1792 	if(!prescanning_flag)
1793 	    ctl_note_event(lowest);
1794 	return lowest;
1795     }
1796 
1797     /* remove all other types of notes */
1798     lv = 0x7FFFFFFF;
1799     lowest = 0;
1800     for(j = 0; j < i; j++)
1801     {
1802 	if(voice[j].status & VOICE_FREE)
1803 	    continue;
1804 	/* find lowest volume */
1805 	v = voice[j].left_mix;
1806 	if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
1807 	    v = voice[j].right_mix;
1808 	if(v < lv)
1809 	{
1810 	    lv = v;
1811 	    lowest = j;
1812 	}
1813     }
1814 
1815     free_voice(lowest);
1816     if(!prescanning_flag)
1817 	ctl_note_event(lowest);
1818     return lowest;
1819 }
1820 
free_voice(int v1)1821 void free_voice(int v1)
1822 {
1823     int v2;
1824 
1825 #ifdef ENABLE_PAN_DELAY
1826 	if (voice[v1].pan_delay_buf != NULL) {
1827 		free(voice[v1].pan_delay_buf);
1828 		voice[v1].pan_delay_buf = NULL;
1829 	}
1830 #endif /* ENABLE_PAN_DELAY */
1831 
1832     v2 = voice[v1].chorus_link;
1833     if(v1 != v2)
1834     {
1835 	/* Unlink chorus link */
1836 	voice[v1].chorus_link = v1;
1837 	voice[v2].chorus_link = v2;
1838     }
1839     voice[v1].status = VOICE_FREE;
1840     voice[v1].temper_instant = 0;
1841 }
1842 
find_free_voice(void)1843 static int find_free_voice(void)
1844 {
1845     int i, nv = voices, lowest;
1846     int32 lv, v;
1847 
1848     for(i = 0; i < nv; i++)
1849 	if(voice[i].status == VOICE_FREE)
1850 	{
1851 	    if(upper_voices <= i)
1852 		upper_voices = i + 1;
1853 	    return i;
1854 	}
1855 
1856     upper_voices = voices;
1857 
1858     /* Look for the decaying note with the lowest volume */
1859     lv = 0x7FFFFFFF;
1860     lowest = -1;
1861     for(i = 0; i < nv; i++)
1862     {
1863 	if(voice[i].status & ~(VOICE_ON | VOICE_DIE) &&
1864 	   !(voice[i].sample && voice[i].sample->note_to_use && ISDRUMCHANNEL(voice[i].channel)))
1865 	{
1866 	    v = voice[i].left_mix;
1867 	    if((voice[i].panned==PANNED_MYSTERY) && (voice[i].right_mix>v))
1868 		v = voice[i].right_mix;
1869 	    if(v<lv)
1870 	    {
1871 		lv = v;
1872 		lowest = i;
1873 	    }
1874 	}
1875     }
1876     if(lowest != -1 && !prescanning_flag)
1877     {
1878 	free_voice(lowest);
1879 	ctl_note_event(lowest);
1880     }
1881     return lowest;
1882 }
1883 
find_samples(MidiEvent * e,int * vlist)1884 static int find_samples(MidiEvent *e, int *vlist)
1885 {
1886 	int i, j, ch, bank, prog, note, nv;
1887 	SpecialPatch *s;
1888 	Instrument *ip;
1889 
1890 	ch = e->channel;
1891 	if (channel[ch].special_sample > 0) {
1892 		if ((s = special_patch[channel[ch].special_sample]) == NULL) {
1893 			ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
1894 					"Strange: Special patch %d is not installed",
1895 					channel[ch].special_sample);
1896 			return 0;
1897 		}
1898 		note = e->a + channel[ch].key_shift + note_key_offset;
1899 		note = (note < 0) ? 0 : ((note > 127) ? 127 : note);
1900 		return select_play_sample(s->sample, s->samples, &note, vlist, e);
1901 	}
1902 	bank = channel[ch].bank;
1903 	if (ISDRUMCHANNEL(ch)) {
1904 		note = e->a & 0x7f;
1905 		instrument_map(channel[ch].mapID, &bank, &note);
1906 		if (! (ip = play_midi_load_instrument(1, bank, note)))
1907 			return 0;	/* No instrument? Then we can't play. */
1908 		/* if (ip->type == INST_GUS && ip->samples != 1)
1909 			ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
1910 					"Strange: percussion instrument with %d samples!",
1911 					ip->samples); */
1912 		/* "keynum" of SF2, and patch option "note=" */
1913 		if (ip->sample->note_to_use)
1914 			note = ip->sample->note_to_use;
1915 	} else {
1916 		if ((prog = channel[ch].program) == SPECIAL_PROGRAM)
1917 			ip = default_instrument;
1918 		else {
1919 			instrument_map(channel[ch].mapID, &bank, &prog);
1920 			if (! (ip = play_midi_load_instrument(0, bank, prog)))
1921 				return 0;	/* No instrument? Then we can't play. */
1922 		}
1923 		note = ((ip->sample->note_to_use) ? ip->sample->note_to_use : e->a)
1924 				+ channel[ch].key_shift + note_key_offset;
1925 		note = (note < 0) ? 0 : ((note > 127) ? 127 : note);
1926 	}
1927 	nv = select_play_sample(ip->sample, ip->samples, &note, vlist, e);
1928 	/* Replace the sample if the sample is cached. */
1929 	if (! prescanning_flag) {
1930 		if (ip->sample->note_to_use)
1931 			note = MIDI_EVENT_NOTE(e);
1932 		for (i = 0; i < nv; i++) {
1933 			j = vlist[i];
1934 			if (! opt_realtime_playing && allocate_cache_size > 0
1935 					&& ! channel[ch].portamento) {
1936 				voice[j].cache = resamp_cache_fetch(voice[j].sample, note);
1937 				if (voice[j].cache)	/* cache hit */
1938 					voice[j].sample = voice[j].cache->resampled;
1939 			} else
1940 				voice[j].cache = NULL;
1941 		}
1942 	}
1943 	return nv;
1944 }
1945 
select_play_sample(Sample * splist,int nsp,int * note,int * vlist,MidiEvent * e)1946 static int select_play_sample(Sample *splist,
1947 		int nsp, int *note, int *vlist, MidiEvent *e)
1948 {
1949 	int ch = e->channel, kn = e->a & 0x7f, vel = e->b;
1950 	int32 f, fs, ft, fst, fc, fr, cdiff, diff, sample_link;
1951 	int8 tt = channel[ch].temper_type;
1952 	uint8 tp = channel[ch].rpnmap[RPN_ADDR_0003];
1953 	Sample *sp, *spc, *spr;
1954 	int16 sf, sn;
1955 	double ratio;
1956 	int i, j, k, nv, nvc;
1957 
1958 	if (ISDRUMCHANNEL(ch))
1959 		f = fs = freq_table[*note];
1960 	else {
1961 		if (opt_pure_intonation) {
1962 			if (current_keysig < 8)
1963 				f = freq_table_pureint[current_freq_table][*note];
1964 			else
1965 				f = freq_table_pureint[current_freq_table + 12][*note];
1966 		} else if (opt_temper_control)
1967 			switch (tt) {
1968 			case 0:
1969 				f = freq_table_tuning[tp][*note];
1970 				break;
1971 			case 1:
1972 				if (current_temper_keysig < 8)
1973 					f = freq_table_pytha[
1974 							current_temper_freq_table][*note];
1975 				else
1976 					f = freq_table_pytha[
1977 							current_temper_freq_table + 12][*note];
1978 				break;
1979 			case 2:
1980 				if (current_temper_keysig < 8)
1981 					f = freq_table_meantone[current_temper_freq_table
1982 							+ ((temper_adj) ? 36 : 0)][*note];
1983 				else
1984 					f = freq_table_meantone[current_temper_freq_table
1985 							+ ((temper_adj) ? 24 : 12)][*note];
1986 				break;
1987 			case 3:
1988 				if (current_temper_keysig < 8)
1989 					f = freq_table_pureint[current_temper_freq_table
1990 							+ ((temper_adj) ? 36 : 0)][*note];
1991 				else
1992 					f = freq_table_pureint[current_temper_freq_table
1993 							+ ((temper_adj) ? 24 : 12)][*note];
1994 				break;
1995 			default:	/* user-defined temperament */
1996 				if ((tt -= 0x40) >= 0 && tt < 4) {
1997 					if (current_temper_keysig < 8)
1998 						f = freq_table_user[tt][current_temper_freq_table
1999 								+ ((temper_adj) ? 36 : 0)][*note];
2000 					else
2001 						f = freq_table_user[tt][current_temper_freq_table
2002 								+ ((temper_adj) ? 24 : 12)][*note];
2003 				} else
2004 					f = freq_table[*note];
2005 				break;
2006 			}
2007 		else
2008 			f = freq_table[*note];
2009 		if (! opt_pure_intonation && opt_temper_control
2010 				&& tt == 0 && f != freq_table[*note]) {
2011 			*note = log(f / 440000.0) / log(2) * 12 + 69.5;
2012 			*note = (*note < 0) ? 0 : ((*note > 127) ? 127 : *note);
2013 			fs = freq_table[*note];
2014 		} else
2015 			fs = freq_table[*note];
2016 	}
2017 	nv = 0;
2018 	for (i = 0, sp = splist; i < nsp; i++, sp++) {
2019 		/* GUS/SF2 - Scale Tuning */
2020 		if ((sf = sp->scale_factor) != 1024) {
2021 			sn = sp->scale_freq;
2022 			ratio = pow(2.0, (*note - sn) * (sf - 1024) / 12288.0);
2023 			ft = f * ratio + 0.5, fst = fs * ratio + 0.5;
2024 		} else
2025 			ft = f, fst = fs;
2026 		if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
2027 			if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
2028 				ft = ft * ratio + 0.5, fst = fst * ratio + 0.5;
2029 		if (sp->low_freq <= fst && sp->high_freq >= fst
2030 				&& sp->low_vel <= vel && sp->high_vel >= vel
2031 				&& ! (sp->inst_type == INST_SF2
2032 				&& sp->sample_type == SF_SAMPLETYPE_RIGHT)) {
2033 			j = vlist[nv] = find_voice(e);
2034 			voice[j].orig_frequency = ft;
2035 			MYCHECK(voice[j].orig_frequency);
2036 			voice[j].sample = sp;
2037 			voice[j].status = VOICE_ON;
2038 			nv++;
2039 		}
2040 	}
2041 	if (nv == 0) {	/* we must select at least one sample. */
2042 		fr = fc = 0;
2043 		spc = spr = NULL;
2044 		cdiff = 0x7fffffff;
2045 		for (i = 0, sp = splist; i < nsp; i++, sp++) {
2046 			/* GUS/SF2 - Scale Tuning */
2047 			if ((sf = sp->scale_factor) != 1024) {
2048 				sn = sp->scale_freq;
2049 				ratio = pow(2.0, (*note - sn) * (sf - 1024) / 12288.0);
2050 				ft = f * ratio + 0.5, fst = fs * ratio + 0.5;
2051 			} else
2052 				ft = f, fst = fs;
2053 			if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
2054 				if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
2055 					ft = ft * ratio + 0.5, fst = fst * ratio + 0.5;
2056 			diff = abs(sp->root_freq - fst);
2057 			if (diff < cdiff) {
2058 				if (sp->inst_type == INST_SF2
2059 						&& sp->sample_type == SF_SAMPLETYPE_RIGHT) {
2060 					fr = ft;	/* reserve */
2061 					spr = sp;	/* reserve */
2062 				} else {
2063 					fc = ft;
2064 					spc = sp;
2065 					cdiff = diff;
2066 				}
2067 			}
2068 		}
2069 		/* If spc is not NULL, a makeshift sample is found. */
2070 		/* Otherwise, it's a lonely right sample, but better than nothing. */
2071 		j = vlist[nv] = find_voice(e);
2072 		voice[j].orig_frequency = (spc) ? fc : fr;
2073 		MYCHECK(voice[j].orig_frequency);
2074 		voice[j].sample = (spc) ? spc : spr;
2075 		voice[j].status = VOICE_ON;
2076 		nv++;
2077 	}
2078 	nvc = nv;
2079 	for (i = 0; i < nvc; i++) {
2080 		spc = voice[vlist[i]].sample;
2081 		/* If it's left sample, there must be right sample. */
2082 		if (spc->inst_type == INST_SF2
2083 				&& spc->sample_type == SF_SAMPLETYPE_LEFT) {
2084 			sample_link = spc->sf_sample_link;
2085 			for (j = 0, sp = splist; j < nsp; j++, sp++)
2086 				if (sp->inst_type == INST_SF2
2087 						&& sp->sample_type == SF_SAMPLETYPE_RIGHT
2088 						&& sp->sf_sample_index == sample_link) {
2089 					/* right sample is found. */
2090 					/* GUS/SF2 - Scale Tuning */
2091 					if ((sf = sp->scale_factor) != 1024) {
2092 						sn = sp->scale_freq;
2093 						ratio = pow(2.0, (*note - sn) * (sf - 1024) / 12288.0);
2094 						ft = f * ratio + 0.5;
2095 					} else
2096 						ft = f;
2097 					if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
2098 						if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
2099 							ft = ft * ratio + 0.5;
2100 					k = vlist[nv] = find_voice(e);
2101 					voice[k].orig_frequency = ft;
2102 					MYCHECK(voice[k].orig_frequency);
2103 					voice[k].sample = sp;
2104 					voice[k].status = VOICE_ON;
2105 					nv++;
2106 					break;
2107 				}
2108 		}
2109 	}
2110 	return nv;
2111 }
2112 
get_play_note_ratio(int ch,int note)2113 static double get_play_note_ratio(int ch, int note)
2114 {
2115 	int play_note = channel[ch].drums[note]->play_note;
2116 	int bank = channel[ch].bank;
2117 	ToneBank *dbank;
2118 	int def_play_note;
2119 
2120 	if (play_note == -1)
2121 		return 1.0;
2122 	instrument_map(channel[ch].mapID, &bank, &note);
2123 	dbank = (drumset[bank]) ? drumset[bank] : drumset[0];
2124 	if ((def_play_note = dbank->tone[note].play_note) == -1)
2125 		return 1.0;
2126 	if (play_note >= def_play_note)
2127 		return bend_coarse[(play_note - def_play_note) & 0x7f];
2128 	else
2129 		return 1 / bend_coarse[(def_play_note - play_note) & 0x7f];
2130 }
2131 
2132 /* Only one instance of a note can be playing on a single channel. */
find_voice(MidiEvent * e)2133 static int find_voice(MidiEvent *e)
2134 {
2135 	int ch = e->channel;
2136 	int note = MIDI_EVENT_NOTE(e);
2137 	int status_check, mono_check;
2138 	AlternateAssign *altassign;
2139 	int i, lowest = -1;
2140 
2141 	status_check = (opt_overlap_voice_allow)
2142 			? (VOICE_OFF | VOICE_SUSTAINED) : 0xff;
2143 	mono_check = channel[ch].mono;
2144 	altassign = find_altassign(channel[ch].altassign, note);
2145 	for (i = 0; i < upper_voices; i++)
2146 		if (voice[i].status == VOICE_FREE) {
2147 			lowest = i;	/* lower volume */
2148 			break;
2149 		}
2150 	for (i = 0; i < upper_voices; i++)
2151 		if (voice[i].status != VOICE_FREE && voice[i].channel == ch) {
2152 			if (voice[i].note == note && (voice[i].status & status_check))
2153 				kill_note(i);
2154 			else if (mono_check)
2155 				kill_note(i);
2156 			else if (altassign && find_altassign(altassign, voice[i].note))
2157 				kill_note(i);
2158 			else if (voice[i].note == note && (channel[ch].assign_mode == 0
2159 					|| (channel[ch].assign_mode == 1 &&
2160 					    voice[i].proximate_flag == 0)))
2161 				kill_note(i);
2162 		}
2163 	for (i = 0; i < upper_voices; i++)
2164 		if (voice[i].channel == ch && voice[i].note == note)
2165 			voice[i].proximate_flag = 0;
2166 	if (lowest != -1)	/* Found a free voice. */
2167 		return lowest;
2168 	if (upper_voices < voices)
2169 		return upper_voices++;
2170 	return reduce_voice();
2171 }
2172 
get_note_freq(Sample * sp,int note)2173 int32 get_note_freq(Sample *sp, int note)
2174 {
2175 	int32 f;
2176 	int16 sf, sn;
2177 	double ratio;
2178 
2179 	f = freq_table[note];
2180 	/* GUS/SF2 - Scale Tuning */
2181 	if ((sf = sp->scale_factor) != 1024) {
2182 		sn = sp->scale_freq;
2183 		ratio = pow(2.0, (note - sn) * (sf - 1024) / 12288.0);
2184 		f = f * ratio + 0.5;
2185 	}
2186 	return f;
2187 }
2188 
get_panning(int ch,int note,int v)2189 static int get_panning(int ch, int note,int v)
2190 {
2191     int pan;
2192 
2193 	if(channel[ch].panning != NO_PANNING) {pan = (int)channel[ch].panning - 64;}
2194 	else {pan = 0;}
2195 	if(ISDRUMCHANNEL(ch) &&
2196 	 channel[ch].drums[note] != NULL &&
2197 	 channel[ch].drums[note]->drum_panning != NO_PANNING) {
2198 		pan += channel[ch].drums[note]->drum_panning;
2199 	} else {
2200 		pan += voice[v].sample->panning;
2201 	}
2202 
2203 	if (pan > 127) pan = 127;
2204 	else if (pan < 0) pan = 0;
2205 
2206 	return pan;
2207 }
2208 
2209 /*! initialize vibrato parameters for a voice. */
init_voice_vibrato(int v)2210 static void init_voice_vibrato(int v)
2211 {
2212 	Voice *vp = &(voice[v]);
2213 	int ch = vp->channel, j, nrpn_vib_flag;
2214 	double ratio;
2215 
2216 	/* if NRPN vibrato is set, it's believed that there must be vibrato. */
2217 	nrpn_vib_flag = opt_nrpn_vibrato
2218 		&& (channel[ch].vibrato_ratio != 1.0 || channel[ch].vibrato_depth != 0);
2219 
2220 	/* vibrato sweep */
2221 	vp->vibrato_sweep = vp->sample->vibrato_sweep_increment;
2222 	vp->vibrato_sweep_position = 0;
2223 
2224 	/* vibrato rate */
2225 	if (nrpn_vib_flag) {
2226 		if(vp->sample->vibrato_control_ratio == 0) {
2227 			ratio = cnv_Hz_to_vib_ratio(5.0) * channel[ch].vibrato_ratio;
2228 		} else {
2229 			ratio = (double)vp->sample->vibrato_control_ratio * channel[ch].vibrato_ratio;
2230 		}
2231 		if (ratio < 0) {ratio = 0;}
2232 		vp->vibrato_control_ratio = (int)ratio;
2233 	} else {
2234 		vp->vibrato_control_ratio = vp->sample->vibrato_control_ratio;
2235 	}
2236 
2237 	/* vibrato depth */
2238 	if (nrpn_vib_flag) {
2239 		vp->vibrato_depth = vp->sample->vibrato_depth + channel[ch].vibrato_depth;
2240 		if (vp->vibrato_depth > VIBRATO_DEPTH_MAX) {vp->vibrato_depth = VIBRATO_DEPTH_MAX;}
2241 		else if (vp->vibrato_depth < 1) {vp->vibrato_depth = 1;}
2242 		if (vp->sample->vibrato_depth < 0) {	/* in opposite phase */
2243 			vp->vibrato_depth = -vp->vibrato_depth;
2244 		}
2245 	} else {
2246 		vp->vibrato_depth = vp->sample->vibrato_depth;
2247 	}
2248 
2249 	/* vibrato delay */
2250 	vp->vibrato_delay = vp->sample->vibrato_delay + channel[ch].vibrato_delay;
2251 
2252 	/* internal parameters */
2253 	vp->orig_vibrato_control_ratio = vp->vibrato_control_ratio;
2254 	vp->vibrato_control_counter = vp->vibrato_phase = 0;
2255 	for (j = 0; j < VIBRATO_SAMPLE_INCREMENTS; j++) {
2256 		vp->vibrato_sample_increment[j] = 0;
2257 	}
2258 }
2259 
2260 /*! initialize panning-delay for a voice. */
init_voice_pan_delay(int v)2261 static void init_voice_pan_delay(int v)
2262 {
2263 #ifdef ENABLE_PAN_DELAY
2264 	Voice *vp = &(voice[v]);
2265 	int ch = vp->channel;
2266 	double pan_delay_diff;
2267 
2268 	if (vp->pan_delay_buf != NULL) {
2269 		free(vp->pan_delay_buf);
2270 		vp->pan_delay_buf = NULL;
2271 	}
2272 	vp->pan_delay_rpt = 0;
2273 	if (opt_pan_delay && channel[ch].insertion_effect == 0 && !opt_surround_chorus) {
2274 		if (vp->panning == 64) {vp->delay += pan_delay_table[64] * play_mode->rate / 1000;}
2275 		else {
2276 			if(pan_delay_table[vp->panning] > pan_delay_table[127 - vp->panning]) {
2277 				pan_delay_diff = pan_delay_table[vp->panning] - pan_delay_table[127 - vp->panning];
2278 				vp->delay += (pan_delay_table[vp->panning] - pan_delay_diff) * play_mode->rate / 1000;
2279 			} else {
2280 				pan_delay_diff = pan_delay_table[127 - vp->panning] - pan_delay_table[vp->panning];
2281 				vp->delay += (pan_delay_table[127 - vp->panning] - pan_delay_diff) * play_mode->rate / 1000;
2282 			}
2283 			vp->pan_delay_rpt = pan_delay_diff * play_mode->rate / 1000;
2284 		}
2285 		if(vp->pan_delay_rpt < 1) {vp->pan_delay_rpt = 0;}
2286 		vp->pan_delay_wpt = 0;
2287 		vp->pan_delay_spt = vp->pan_delay_wpt - vp->pan_delay_rpt;
2288 		if (vp->pan_delay_spt < 0) {vp->pan_delay_spt += PAN_DELAY_BUF_MAX;}
2289 		vp->pan_delay_buf = (int32 *)safe_malloc(sizeof(int32) * PAN_DELAY_BUF_MAX);
2290 		memset(vp->pan_delay_buf, 0, sizeof(int32) * PAN_DELAY_BUF_MAX);
2291 	}
2292 #endif	/* ENABLE_PAN_DELAY */
2293 }
2294 
2295 /*! initialize portamento or legato for a voice. */
init_voice_portamento(int v)2296 static void init_voice_portamento(int v)
2297 {
2298 	Voice *vp = &(voice[v]);
2299 	int ch = vp->channel;
2300 
2301   vp->porta_control_counter = 0;
2302   if(channel[ch].legato && channel[ch].legato_flag) {
2303 	  update_legato_controls(ch);
2304   } else if(channel[ch].portamento && !channel[ch].porta_control_ratio) {
2305       update_portamento_controls(ch);
2306   }
2307   vp->porta_control_ratio = 0;
2308   if(channel[ch].porta_control_ratio)
2309   {
2310       if(channel[ch].last_note_fine == -1) {
2311 	  /* first on */
2312 	  channel[ch].last_note_fine = vp->note * 256;
2313 	  channel[ch].porta_control_ratio = 0;
2314       } else {
2315 	  vp->porta_control_ratio = channel[ch].porta_control_ratio;
2316 	  vp->porta_dpb = channel[ch].porta_dpb;
2317 	  vp->porta_pb = channel[ch].last_note_fine -
2318 	      vp->note * 256;
2319 	  if(vp->porta_pb == 0) {vp->porta_control_ratio = 0;}
2320       }
2321   }
2322 }
2323 
2324 /*! initialize tremolo for a voice. */
init_voice_tremolo(int v)2325 static void init_voice_tremolo(int v)
2326 {
2327 	Voice *vp = &(voice[v]);
2328 
2329   vp->tremolo_delay = vp->sample->tremolo_delay;
2330   vp->tremolo_phase = 0;
2331   vp->tremolo_phase_increment = vp->sample->tremolo_phase_increment;
2332   vp->tremolo_sweep = vp->sample->tremolo_sweep_increment;
2333   vp->tremolo_sweep_position = 0;
2334   vp->tremolo_depth = vp->sample->tremolo_depth;
2335 }
2336 
start_note(MidiEvent * e,int i,int vid,int cnt)2337 static void start_note(MidiEvent *e, int i, int vid, int cnt)
2338 {
2339   int j, ch, note;
2340 
2341   ch = e->channel;
2342 
2343   note = MIDI_EVENT_NOTE(e);
2344   voice[i].status = VOICE_ON;
2345   voice[i].channel = ch;
2346   voice[i].note = note;
2347   voice[i].velocity = e->b;
2348   voice[i].chorus_link = i;	/* No link */
2349   voice[i].proximate_flag = 1;
2350 
2351   j = channel[ch].special_sample;
2352   if(j == 0 || special_patch[j] == NULL)
2353       voice[i].sample_offset = 0;
2354   else
2355   {
2356       voice[i].sample_offset =
2357 	  special_patch[j]->sample_offset << FRACTION_BITS;
2358       if(voice[i].sample->modes & MODES_LOOPING)
2359       {
2360 	  if(voice[i].sample_offset > voice[i].sample->loop_end)
2361 	      voice[i].sample_offset = voice[i].sample->loop_start;
2362       }
2363       else if(voice[i].sample_offset > voice[i].sample->data_length)
2364       {
2365 	  free_voice(i);
2366 	  return;
2367       }
2368   }
2369   voice[i].sample_increment = 0; /* make sure it isn't negative */
2370   voice[i].vid = vid;
2371   voice[i].delay = voice[i].sample->envelope_delay;
2372   voice[i].modenv_delay = voice[i].sample->modenv_delay;
2373   voice[i].delay_counter = 0;
2374 
2375   init_voice_tremolo(i);	/* tremolo */
2376   init_voice_filter(i);		/* resonant lowpass filter */
2377   init_voice_vibrato(i);	/* vibrato */
2378   voice[i].panning = get_panning(ch, note, i);	/* pan */
2379   init_voice_pan_delay(i);	/* panning-delay */
2380   init_voice_portamento(i);	/* portamento or legato */
2381 
2382   if(cnt == 0)
2383       channel[ch].last_note_fine = voice[i].note * 256;
2384 
2385   /* initialize modulation envelope */
2386   if (voice[i].sample->modes & MODES_ENVELOPE)
2387     {
2388 	  voice[i].modenv_stage = EG_GUS_ATTACK;
2389       voice[i].modenv_volume = 0;
2390       recompute_modulation_envelope(i);
2391 	  apply_modulation_envelope(i);
2392     }
2393   else
2394     {
2395 	  voice[i].modenv_increment=0;
2396 	  apply_modulation_envelope(i);
2397     }
2398   recompute_freq(i);
2399   recompute_voice_filter(i);
2400 
2401   recompute_amp(i);
2402   /* initialize volume envelope */
2403   if (voice[i].sample->modes & MODES_ENVELOPE)
2404     {
2405       /* Ramp up from 0 */
2406 	  voice[i].envelope_stage = EG_GUS_ATTACK;
2407       voice[i].envelope_volume = 0;
2408       voice[i].control_counter = 0;
2409       recompute_envelope(i);
2410 	  apply_envelope_to_amp(i);
2411     }
2412   else
2413     {
2414       voice[i].envelope_increment = 0;
2415       apply_envelope_to_amp(i);
2416     }
2417 
2418   voice[i].timeout = -1;
2419   if(!prescanning_flag)
2420       ctl_note_event(i);
2421 }
2422 
finish_note(int i)2423 static void finish_note(int i)
2424 {
2425     if (voice[i].sample->modes & MODES_ENVELOPE)
2426     {
2427 		/* We need to get the envelope out of Sustain stage. */
2428 		/* Note that voice[i].envelope_stage < EG_GUS_RELEASE1 */
2429 		voice[i].status = VOICE_OFF;
2430 		voice[i].envelope_stage = EG_GUS_RELEASE1;
2431 		recompute_envelope(i);
2432 		voice[i].modenv_stage = EG_GUS_RELEASE1;
2433 		recompute_modulation_envelope(i);
2434 		apply_modulation_envelope(i);
2435 		apply_envelope_to_amp(i);
2436 		ctl_note_event(i);
2437 	}
2438     else
2439     {
2440 		if(current_file_info->pcm_mode != PCM_MODE_NON)
2441 		{
2442 			free_voice(i);
2443 			ctl_note_event(i);
2444 		}
2445 		else
2446 		{
2447 			/* Set status to OFF so resample_voice() will let this voice out
2448 			of its loop, if any. In any case, this voice dies when it
2449 				hits the end of its data (ofs>=data_length). */
2450 			if(voice[i].status != VOICE_OFF)
2451 			{
2452 			voice[i].status = VOICE_OFF;
2453 			ctl_note_event(i);
2454 			}
2455 		}
2456     }
2457 }
2458 
set_envelope_time(int ch,int val,int stage)2459 static void set_envelope_time(int ch, int val, int stage)
2460 {
2461 	val = val & 0x7F;
2462 	switch(stage) {
2463 	case EG_ATTACK:	/* Attack */
2464 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"Attack Time (CH:%d VALUE:%d)", ch, val);
2465 		break;
2466 	case EG_DECAY: /* Decay */
2467 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"Decay Time (CH:%d VALUE:%d)", ch, val);
2468 		break;
2469 	case EG_RELEASE:	/* Release */
2470 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"Release Time (CH:%d VALUE:%d)", ch, val);
2471 		break;
2472 	default:
2473 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"? Time (CH:%d VALUE:%d)", ch, val);
2474 	}
2475 	channel[ch].envelope_rate[stage] = val;
2476 }
2477 
2478 /*! pseudo Delay Effect without DSP */
2479 #ifndef USE_DSP_EFFECT
new_delay_voice(int v1,int level)2480 static void new_delay_voice(int v1, int level)
2481 {
2482     int v2, ch = voice[v1].channel;
2483 	FLOAT_T delay, vol;
2484 	FLOAT_T threshold = 1.0;
2485 
2486 	/* NRPN Delay Send Level of Drum */
2487 	if(ISDRUMCHANNEL(ch) &&	channel[ch].drums[voice[v1].note] != NULL) {
2488 		level *= (FLOAT_T)channel[ch].drums[voice[v1].note]->delay_level / 127.0;
2489 	}
2490 
2491 	vol = voice[v1].velocity * level / 127.0 * delay_status_gs.level_ratio_c;
2492 
2493 	if (vol > threshold) {
2494 		delay = 0;
2495 		if((v2 = find_free_voice()) == -1) {return;}
2496 		voice[v2].cache = NULL;
2497 		delay += delay_status_gs.time_center;
2498 		voice[v2] = voice[v1];	/* copy all parameters */
2499 		voice[v2].velocity = (uint8)vol;
2500 		voice[v2].delay += (int32)(play_mode->rate * delay / 1000);
2501 		init_voice_pan_delay(v2);
2502 		recompute_amp(v2);
2503 		apply_envelope_to_amp(v2);
2504 		recompute_freq(v2);
2505 	}
2506 }
2507 
2508 
new_chorus_voice(int v1,int level)2509 static void new_chorus_voice(int v1, int level)
2510 {
2511     int v2, ch;
2512 
2513     if((v2 = find_free_voice()) == -1)
2514 	return;
2515     ch = voice[v1].channel;
2516     voice[v2] = voice[v1];	/* copy all parameters */
2517 
2518     /* NRPN Chorus Send Level of Drum */
2519     if(ISDRUMCHANNEL(ch) && channel[ch].drums[voice[v1].note] != NULL) {
2520 	level *= (FLOAT_T)channel[ch].drums[voice[v1].note]->chorus_level / 127.0;
2521     }
2522 
2523     /* Choose lower voice index for base voice (v1) */
2524     if(v1 > v2)
2525     {
2526     	v1 ^= v2;
2527     	v2 ^= v1;
2528     	v1 ^= v2;
2529     }
2530 
2531     /* v1: Base churos voice
2532      * v2: Sub chorus voice (detuned)
2533      */
2534 
2535     /* Make doubled link v1 and v2 */
2536     voice[v1].chorus_link = v2;
2537     voice[v2].chorus_link = v1;
2538 
2539     level >>= 2;		     /* scale level to a "better" value */
2540     if(channel[ch].pitchbend + level < 0x2000)
2541         voice[v2].orig_frequency *= bend_fine[level];
2542     else
2543 	voice[v2].orig_frequency /= bend_fine[level];
2544 
2545     MYCHECK(voice[v2].orig_frequency);
2546 
2547     voice[v2].cache = NULL;
2548 
2549     /* set panning & delay */
2550     if(!(play_mode->encoding & PE_MONO))
2551     {
2552 	double delay;
2553 
2554 	if(voice[v2].panned == PANNED_CENTER)
2555 	{
2556 	    voice[v2].panning = 64 + int_rand(40) - 20; /* 64 +- rand(20) */
2557 	    delay = 0;
2558 	}
2559 	else
2560 	{
2561 	    int panning = voice[v2].panning;
2562 
2563 	    if(panning < CHORUS_OPPOSITE_THRESHOLD)
2564 	    {
2565 		voice[v2].panning = 127;
2566 		delay = DEFAULT_CHORUS_DELAY1;
2567 	    }
2568 	    else if(panning > 127 - CHORUS_OPPOSITE_THRESHOLD)
2569 	    {
2570 		voice[v2].panning = 0;
2571 		delay = DEFAULT_CHORUS_DELAY1;
2572 	    }
2573 	    else
2574 	    {
2575 		voice[v2].panning = (panning < 64 ? 0 : 127);
2576 		delay = DEFAULT_CHORUS_DELAY2;
2577 	    }
2578 	}
2579 	voice[v2].delay += (int)(play_mode->rate * delay);
2580     }
2581 
2582     init_voice_pan_delay(v1);
2583     init_voice_pan_delay(v2);
2584 
2585     recompute_amp(v1);
2586     apply_envelope_to_amp(v1);
2587     recompute_amp(v2);
2588     apply_envelope_to_amp(v2);
2589 
2590     /* voice[v2].orig_frequency is changed.
2591      * Update the depened parameters.
2592      */
2593     recompute_freq(v2);
2594 }
2595 #endif /* !USE_DSP_EFFECT */
2596 
2597 
2598 /* Yet another chorus implementation
2599  *	by Eric A. Welsh <ewelsh@gpc.wustl.edu>.
2600  */
new_chorus_voice_alternate(int v1,int level)2601 static void new_chorus_voice_alternate(int v1, int level)
2602 {
2603     int v2, ch, panlevel;
2604     uint8 pan;
2605     double delay;
2606     double freq, frac;
2607     int note_adjusted;
2608 
2609     if((v2 = find_free_voice()) == -1)
2610 	return;
2611     ch = voice[v1].channel;
2612     voice[v2] = voice[v1];
2613 
2614     /* NRPN Chorus Send Level of Drum */
2615     if(ISDRUMCHANNEL(ch) && channel[ch].drums[voice[v1].note] != NULL) {
2616 	level *= (FLOAT_T)channel[ch].drums[voice[v1].note]->chorus_level / 127.0;
2617     }
2618 
2619     /* for our purposes, hard left will be equal to 1 instead of 0 */
2620     pan = voice[v1].panning;
2621     if (!pan) pan = 1;
2622 
2623     /* Choose lower voice index for base voice (v1) */
2624     if(v1 > v2)
2625     {
2626     	v1 ^= v2;
2627     	v2 ^= v1;
2628     	v1 ^= v2;
2629     }
2630 
2631     /* Make doubled link v1 and v2 */
2632     voice[v1].chorus_link = v2;
2633     voice[v2].chorus_link = v1;
2634 
2635     /* detune notes for chorus effect */
2636     level >>= 2;		/* scale to a "better" value */
2637     if (level)
2638     {
2639         if(channel[ch].pitchbend + level < 0x2000)
2640             voice[v2].orig_frequency *= bend_fine[level];
2641         else
2642 	    voice[v2].orig_frequency /= bend_fine[level];
2643         voice[v2].cache = NULL;
2644     }
2645 
2646     MYCHECK(voice[v2].orig_frequency);
2647 
2648     delay = 0.003;
2649 
2650     /* Try to keep the delayed voice from cancelling out the other voice */
2651     /* Pitch detection is used to find the real pitches for drums and MODs */
2652     note_adjusted = voice[v1].note + voice[v1].sample->transpose_detected;
2653     if (note_adjusted > 127) note_adjusted = 127;
2654     else if (note_adjusted < 0) note_adjusted = 0;
2655     freq = pitch_freq_table[note_adjusted];
2656     delay *= freq;
2657     frac = delay - floor(delay);
2658 
2659     /* force the delay away from 0.5 period */
2660     if (frac < 0.5 && frac > 0.40)
2661     {
2662     	delay = (floor(delay) + 0.40) / freq;
2663     	if (!(play_mode->encoding & PE_MONO))
2664     	    delay += (0.5 - frac) * (1.0 - labs(64 - pan) / 63.0) / freq;
2665     }
2666     else if (frac >= 0.5 && frac < 0.60)
2667     {
2668     	delay = (floor(delay) + 0.60) / freq;
2669     	if (!(play_mode->encoding & PE_MONO))
2670     	    delay += (0.5 - frac) * (1.0 - labs(64 - pan) / 63.0) / freq;
2671     }
2672     else
2673 	delay = 0.003;
2674 
2675     /* set panning & delay for pseudo-surround effect */
2676     if(play_mode->encoding & PE_MONO)    /* delay sounds good */
2677         voice[v2].delay += (int)(play_mode->rate * delay);
2678     else
2679     {
2680         panlevel = 63;
2681         if (pan - panlevel < 1) panlevel = pan - 1;
2682         if (pan + panlevel > 127) panlevel = 127 - pan;
2683         voice[v1].panning -= panlevel;
2684         voice[v2].panning += panlevel;
2685 
2686         /* choose which voice is delayed based on panning */
2687         if (voice[v1].panned == PANNED_CENTER) {
2688             /* randomly choose which voice is delayed */
2689             if (int_rand(2))
2690                 voice[v1].delay += (int)(play_mode->rate * delay);
2691             else
2692                 voice[v2].delay += (int)(play_mode->rate * delay);
2693         }
2694         else if (pan - 64 < 0) {
2695             voice[v2].delay += (int)(play_mode->rate * delay);
2696         }
2697         else {
2698             voice[v1].delay += (int)(play_mode->rate * delay);
2699         }
2700     }
2701 
2702     /* check for similar drums playing simultaneously with center pans */
2703     if (!(play_mode->encoding & PE_MONO) &&
2704     	ISDRUMCHANNEL(ch) && voice[v1].panned == PANNED_CENTER)
2705     {
2706     	int i, j;
2707 
2708     	/* force Rimshot (37), Snare1 (38), Snare2 (40), and XG #34 to have
2709     	 * the same delay, otherwise there will be bad voice cancellation.
2710     	 */
2711     	if (voice[v1].note == 37 ||
2712     	    voice[v1].note == 38 ||
2713     	    voice[v1].note == 40 ||
2714     	    (voice[v1].note == 34 && play_system_mode == XG_SYSTEM_MODE))
2715     	{
2716     	    for (i = 0; i < upper_voices; i++)
2717     	    {
2718     	    	if (voice[i].status & (VOICE_DIE | VOICE_FREE))
2719     	    	    continue;
2720 
2721     	    	if (!ISDRUMCHANNEL(voice[i].channel))
2722     	    	    continue;
2723 
2724 	    	if (i == v1 || i == v2)
2725 	    	    continue;
2726 
2727 	    	if (voice[i].note == 37 ||
2728 	    	    voice[i].note == 38 ||
2729 	    	    voice[i].note == 40 ||
2730 	    	    (voice[i].note == 34 &&
2731 	    	     play_system_mode == XG_SYSTEM_MODE))
2732 	    	{
2733 	    	    j = voice[i].chorus_link;
2734 
2735 	    	    if (voice[i].panned == PANNED_LEFT &&
2736 	    	        voice[j].panned == PANNED_RIGHT)
2737 	    	    {
2738 	    	    	voice[v1].delay = voice[i].delay;
2739 	    	    	voice[v2].delay = voice[j].delay;
2740 
2741 	    	    	break;
2742 	    	    }
2743 	    	}
2744     	    }
2745     	}
2746 
2747     	/* force Kick1 (35), Kick2 (36), and XG Kick #33 to have the same
2748     	 * delay, otherwise there will be bad voice cancellation.
2749     	 */
2750     	if (voice[v1].note == 35 ||
2751     	    voice[v1].note == 36 ||
2752     	    (voice[v1].note == 33 && play_system_mode == XG_SYSTEM_MODE))
2753     	{
2754     	    for (i = 0; i < upper_voices; i++)
2755     	    {
2756     	    	if (voice[i].status & (VOICE_DIE | VOICE_FREE))
2757     	    	    continue;
2758 
2759     	    	if (!ISDRUMCHANNEL(voice[i].channel))
2760     	    	    continue;
2761 
2762 	    	if (i == v1 || i == v2)
2763 	    	    continue;
2764 
2765 	    	if (voice[i].note == 35 ||
2766 	    	    voice[i].note == 36 ||
2767 	    	    (voice[i].note == 33 &&
2768 	    	     play_system_mode == XG_SYSTEM_MODE))
2769 	    	{
2770 	    	    j = voice[i].chorus_link;
2771 
2772 	    	    if (voice[i].panned == PANNED_LEFT &&
2773 	    	        voice[j].panned == PANNED_RIGHT)
2774 	    	    {
2775 	    	    	voice[v1].delay = voice[i].delay;
2776 	    	    	voice[v2].delay = voice[j].delay;
2777 
2778 	    	    	break;
2779 	    	    }
2780 	    	}
2781     	    }
2782     	}
2783     }
2784 
2785     init_voice_pan_delay(v1);
2786     init_voice_pan_delay(v2);
2787 
2788     recompute_amp(v1);
2789     apply_envelope_to_amp(v1);
2790     recompute_amp(v2);
2791     apply_envelope_to_amp(v2);
2792     if (level) recompute_freq(v2);
2793 }
2794 
2795 /*! note_on() (prescanning) */
note_on_prescan(MidiEvent * ev)2796 static void note_on_prescan(MidiEvent *ev)
2797 {
2798 	int i, ch = ev->channel, note = MIDI_EVENT_NOTE(ev);
2799 	int32 random_delay = 0;
2800 
2801 	if(ISDRUMCHANNEL(ch) &&
2802 	   channel[ch].drums[note] != NULL &&
2803 	   !get_rx_drum(channel[ch].drums[note], RX_NOTE_ON)) {	/* Rx. Note On */
2804 		return;
2805 	}
2806 	if(channel[ch].note_limit_low > note ||
2807 		channel[ch].note_limit_high < note ||
2808 		channel[ch].vel_limit_low > ev->b ||
2809 		channel[ch].vel_limit_high < ev->b) {
2810 		return;
2811 	}
2812 
2813     if((channel[ch].portamento_time_msb |
2814 		channel[ch].portamento_time_lsb) == 0 ||
2815 	    channel[ch].portamento == 0)
2816 	{
2817 		int nv;
2818 		int vlist[32];
2819 		Voice *vp;
2820 
2821 		nv = find_samples(ev, vlist);
2822 
2823 		for(i = 0; i < nv; i++)
2824 		{
2825 		    vp = voice + vlist[i];
2826 		    start_note(ev, vlist[i], 0, nv - i - 1);
2827 			vp->delay += random_delay;
2828 			vp->modenv_delay += random_delay;
2829 		    resamp_cache_refer_on(vp, ev->time);
2830 		    vp->status = VOICE_FREE;
2831 		    vp->temper_instant = 0;
2832 		}
2833 	}
2834 }
2835 
note_on(MidiEvent * e)2836 static void note_on(MidiEvent *e)
2837 {
2838     int i, nv, v, ch, note;
2839     int vlist[32];
2840     int vid;
2841 	int32 random_delay = 0;
2842 
2843 	ch = e->channel;
2844 	note = MIDI_EVENT_NOTE(e);
2845 
2846 	if(ISDRUMCHANNEL(ch) &&
2847 	   channel[ch].drums[note] != NULL &&
2848 	   !get_rx_drum(channel[ch].drums[note], RX_NOTE_ON)) {	/* Rx. Note On */
2849 		return;
2850 	}
2851 	if(channel[ch].note_limit_low > note ||
2852 		channel[ch].note_limit_high < note ||
2853 		channel[ch].vel_limit_low > e->b ||
2854 		channel[ch].vel_limit_high < e->b) {
2855 		return;
2856 	}
2857     if((nv = find_samples(e, vlist)) == 0)
2858 	return;
2859 
2860     vid = new_vidq(e->channel, note);
2861 
2862 	recompute_bank_parameter(ch, note);
2863 	recompute_channel_filter(ch, note);
2864 	random_delay = calc_random_delay(ch, note);
2865 
2866     for(i = 0; i < nv; i++)
2867     {
2868 	v = vlist[i];
2869 	if(ISDRUMCHANNEL(ch) &&
2870 	   channel[ch].drums[note] != NULL &&
2871 	   channel[ch].drums[note]->pan_random)
2872 	    channel[ch].drums[note]->drum_panning = int_rand(128);
2873 	else if(channel[ch].pan_random)
2874 	{
2875 	    channel[ch].panning = int_rand(128);
2876 	    ctl_mode_event(CTLE_PANNING, 1, ch, channel[ch].panning);
2877 	}
2878 	start_note(e, v, vid, nv - i - 1);
2879 	voice[v].delay += random_delay;
2880 	voice[v].modenv_delay += random_delay;
2881 #ifdef SMOOTH_MIXING
2882 	voice[v].old_left_mix = voice[v].old_right_mix =
2883 	voice[v].left_mix_inc = voice[v].left_mix_offset =
2884 	voice[v].right_mix_inc = voice[v].right_mix_offset = 0;
2885 #endif
2886 #ifdef USE_DSP_EFFECT
2887 	if(opt_surround_chorus)
2888 	    new_chorus_voice_alternate(v, 0);
2889 #else
2890 	if((channel[ch].chorus_level || opt_surround_chorus))
2891 	{
2892 	    if(opt_surround_chorus)
2893 		new_chorus_voice_alternate(v, channel[ch].chorus_level);
2894 	    else
2895 		new_chorus_voice(v, channel[ch].chorus_level);
2896 	}
2897 	if(channel[ch].delay_level)
2898 	{
2899 	    new_delay_voice(v, channel[ch].delay_level);
2900 	}
2901 #endif
2902     }
2903 
2904     channel[ch].legato_flag = 1;
2905 }
2906 
2907 /*! sostenuto is now implemented as an instant sustain */
update_sostenuto_controls(int ch)2908 static void update_sostenuto_controls(int ch)
2909 {
2910   int uv = upper_voices, i;
2911 
2912   if(ISDRUMCHANNEL(ch) || channel[ch].sostenuto == 0) {return;}
2913 
2914   for(i = 0; i < uv; i++)
2915   {
2916 	if ((voice[i].status & (VOICE_ON | VOICE_OFF))
2917 			&& voice[i].channel == ch)
2918 	 {
2919 		  voice[i].status = VOICE_SUSTAINED;
2920 		  ctl_note_event(i);
2921 		  voice[i].envelope_stage = EG_GUS_RELEASE1;
2922 		  recompute_envelope(i);
2923 	 }
2924   }
2925 }
2926 
2927 /*! redamper effect for piano instruments */
update_redamper_controls(int ch)2928 static void update_redamper_controls(int ch)
2929 {
2930   int uv = upper_voices, i;
2931 
2932   if(ISDRUMCHANNEL(ch) || channel[ch].damper_mode == 0) {return;}
2933 
2934   for(i = 0; i < uv; i++)
2935   {
2936 	if ((voice[i].status & (VOICE_ON | VOICE_OFF))
2937 			&& voice[i].channel == ch)
2938 	  {
2939 		  voice[i].status = VOICE_SUSTAINED;
2940 		  ctl_note_event(i);
2941 		  voice[i].envelope_stage = EG_GUS_RELEASE1;
2942 		  recompute_envelope(i);
2943 	  }
2944   }
2945 }
2946 
note_off(MidiEvent * e)2947 static void note_off(MidiEvent *e)
2948 {
2949   int uv = upper_voices, i;
2950   int ch, note, vid, sustain;
2951 
2952   ch = e->channel;
2953   note = MIDI_EVENT_NOTE(e);
2954 
2955   if(ISDRUMCHANNEL(ch))
2956   {
2957       int nbank, nprog;
2958 
2959       nbank = channel[ch].bank;
2960       nprog = note;
2961       instrument_map(channel[ch].mapID, &nbank, &nprog);
2962 
2963       if (channel[ch].drums[nprog] != NULL &&
2964           get_rx_drum(channel[ch].drums[nprog], RX_NOTE_OFF))
2965       {
2966           ToneBank *bank;
2967           bank = drumset[nbank];
2968           if(bank == NULL) bank = drumset[0];
2969 
2970           /* uh oh, this drum doesn't have an instrument loaded yet */
2971           if (bank->tone[nprog].instrument == NULL)
2972               return;
2973 
2974           /* this drum is not loaded for some reason (error occured?) */
2975           if (IS_MAGIC_INSTRUMENT(bank->tone[nprog].instrument))
2976               return;
2977 
2978           /* only disallow Note Off if the drum sample is not looped */
2979           if (!(bank->tone[nprog].instrument->sample->modes & MODES_LOOPING))
2980               return;	/* Note Off is not allowed. */
2981       }
2982   }
2983 
2984   if ((vid = last_vidq(ch, note)) == -1)
2985       return;
2986   sustain = channel[ch].sustain;
2987   for (i = 0; i < uv; i++)
2988   {
2989       if(voice[i].status == VOICE_ON &&
2990 	 voice[i].channel == ch &&
2991 	 voice[i].note == note &&
2992 	 voice[i].vid == vid)
2993       {
2994 	  if(sustain)
2995 	  {
2996 	      voice[i].status = VOICE_SUSTAINED;
2997 	      ctl_note_event(i);
2998 	  }
2999 	  else
3000 	      finish_note(i);
3001       }
3002   }
3003 
3004   channel[ch].legato_flag = 0;
3005 }
3006 
3007 /* Process the All Notes Off event */
all_notes_off(int c)3008 static void all_notes_off(int c)
3009 {
3010   int i, uv = upper_voices;
3011   ctl->cmsg(CMSG_INFO, VERB_DEBUG, "All notes off on channel %d", c);
3012   for(i = 0; i < uv; i++)
3013     if (voice[i].status==VOICE_ON &&
3014 	voice[i].channel==c)
3015       {
3016 	if (channel[c].sustain)
3017 	  {
3018 	    voice[i].status=VOICE_SUSTAINED;
3019 	    ctl_note_event(i);
3020 	  }
3021 	else
3022 	  finish_note(i);
3023       }
3024   for(i = 0; i < 128; i++)
3025       vidq_head[c * 128 + i] = vidq_tail[c * 128 + i] = 0;
3026 }
3027 
3028 /* Process the All Sounds Off event */
all_sounds_off(int c)3029 static void all_sounds_off(int c)
3030 {
3031   int i, uv = upper_voices;
3032   for(i = 0; i < uv; i++)
3033     if (voice[i].channel==c &&
3034 	(voice[i].status & ~(VOICE_FREE | VOICE_DIE)))
3035       {
3036 	kill_note(i);
3037       }
3038   for(i = 0; i < 128; i++)
3039       vidq_head[c * 128 + i] = vidq_tail[c * 128 + i] = 0;
3040 }
3041 
3042 /*! adjust polyphonic key pressure (PAf, PAT) */
adjust_pressure(MidiEvent * e)3043 static void adjust_pressure(MidiEvent *e)
3044 {
3045     int i, uv = upper_voices;
3046     int note, ch;
3047 
3048     if(opt_channel_pressure)
3049     {
3050 	ch = e->channel;
3051     note = MIDI_EVENT_NOTE(e);
3052 	channel[ch].paf.val = e->b;
3053 	if(channel[ch].paf.pitch != 0) {channel[ch].pitchfactor = 0;}
3054 
3055     for(i = 0; i < uv; i++)
3056     if(voice[i].status == VOICE_ON &&
3057        voice[i].channel == ch &&
3058        voice[i].note == note)
3059     {
3060 		recompute_amp(i);
3061 		apply_envelope_to_amp(i);
3062 		recompute_freq(i);
3063 		recompute_voice_filter(i);
3064     }
3065 	}
3066 }
3067 
3068 /*! adjust channel pressure (channel aftertouch, CAf, CAT) */
adjust_channel_pressure(MidiEvent * e)3069 static void adjust_channel_pressure(MidiEvent *e)
3070 {
3071     if(opt_channel_pressure)
3072     {
3073 	int i, uv = upper_voices;
3074 	int ch;
3075 
3076 	ch = e->channel;
3077 	channel[ch].caf.val = e->a;
3078 	if(channel[ch].caf.pitch != 0) {channel[ch].pitchfactor = 0;}
3079 
3080 	for(i = 0; i < uv; i++)
3081 	{
3082 	    if(voice[i].status == VOICE_ON && voice[i].channel == ch)
3083 	    {
3084 		recompute_amp(i);
3085 		apply_envelope_to_amp(i);
3086 		recompute_freq(i);
3087 		recompute_voice_filter(i);
3088 		}
3089 	}
3090     }
3091 }
3092 
adjust_panning(int c)3093 static void adjust_panning(int c)
3094 {
3095     int i, uv = upper_voices, pan = channel[c].panning;
3096     for(i = 0; i < uv; i++)
3097     {
3098 	if ((voice[i].channel==c) &&
3099 	    (voice[i].status & (VOICE_ON | VOICE_SUSTAINED)))
3100 	{
3101             /* adjust pan to include drum/sample pan offsets */
3102             pan = get_panning(c, voice[i].note, i);
3103 
3104 	    /* Hack to handle -EFchorus=2 in a "reasonable" way */
3105 #ifdef USE_DSP_EFFECT
3106 	    if(opt_surround_chorus && voice[i].chorus_link != i)
3107 #else
3108 	    if((channel[c].chorus_level || opt_surround_chorus) &&
3109 	       voice[i].chorus_link != i)
3110 #endif
3111 	    {
3112 		int v1, v2;
3113 
3114 		if(i >= voice[i].chorus_link)
3115 		    /* `i' is not base chorus voice.
3116 		     *  This sub voice is already updated.
3117 		     */
3118 		    continue;
3119 
3120 		v1 = i;				/* base voice */
3121 		v2 = voice[i].chorus_link;	/* sub voice (detuned) */
3122 
3123 		if(opt_surround_chorus) /* Surround chorus mode by Eric. */
3124 		{
3125 		    int panlevel;
3126 
3127 		    if (!pan) pan = 1;	/* make hard left be 1 instead of 0 */
3128 		    panlevel = 63;
3129 		    if (pan - panlevel < 1) panlevel = pan - 1;
3130 		    if (pan + panlevel > 127) panlevel = 127 - pan;
3131 		    voice[v1].panning = pan - panlevel;
3132 		    voice[v2].panning = pan + panlevel;
3133 		}
3134 		else
3135 		{
3136 		    voice[v1].panning = pan;
3137 		    if(pan > 60 && pan < 68) /* PANNED_CENTER */
3138 			voice[v2].panning =
3139 			    64 + int_rand(40) - 20; /* 64 +- rand(20) */
3140 		    else if(pan < CHORUS_OPPOSITE_THRESHOLD)
3141 			voice[v2].panning = 127;
3142 		    else if(pan > 127 - CHORUS_OPPOSITE_THRESHOLD)
3143 			voice[v2].panning = 0;
3144 		    else
3145 			voice[v2].panning = (pan < 64 ? 0 : 127);
3146 		}
3147 		recompute_amp(v2);
3148 		apply_envelope_to_amp(v2);
3149 		/* v1 == i, so v1 will be updated next */
3150 	    }
3151 	    else
3152 		voice[i].panning = pan;
3153 
3154 		recompute_amp(i);
3155 	    apply_envelope_to_amp(i);
3156 	}
3157     }
3158 }
3159 
play_midi_setup_drums(int ch,int note)3160 void play_midi_setup_drums(int ch, int note)
3161 {
3162     channel[ch].drums[note] = (struct DrumParts *)
3163 	new_segment(&playmidi_pool, sizeof(struct DrumParts));
3164     reset_drum_controllers(channel[ch].drums, note);
3165 }
3166 
adjust_drum_panning(int ch,int note)3167 static void adjust_drum_panning(int ch, int note)
3168 {
3169     int i, uv = upper_voices;
3170 
3171     for(i = 0; i < uv; i++) {
3172 		if(voice[i].channel == ch &&
3173 		   voice[i].note == note &&
3174 		   (voice[i].status & (VOICE_ON | VOICE_SUSTAINED)))
3175 		{
3176 			voice[i].panning = get_panning(ch, note, i);
3177 			recompute_amp(i);
3178 			apply_envelope_to_amp(i);
3179 		}
3180 	}
3181 }
3182 
drop_sustain(int c)3183 static void drop_sustain(int c)
3184 {
3185   int i, uv = upper_voices;
3186   for(i = 0; i < uv; i++)
3187     if (voice[i].status == VOICE_SUSTAINED && voice[i].channel == c)
3188       finish_note(i);
3189 }
3190 
adjust_all_pitch(void)3191 static void adjust_all_pitch(void)
3192 {
3193 	int ch, i, uv = upper_voices;
3194 
3195 	for (ch = 0; ch < MAX_CHANNELS; ch++)
3196 		channel[ch].pitchfactor = 0;
3197 	for (i = 0; i < uv; i++)
3198 		if (voice[i].status != VOICE_FREE)
3199 			recompute_freq(i);
3200 }
3201 
adjust_pitch(int c)3202 static void adjust_pitch(int c)
3203 {
3204   int i, uv = upper_voices;
3205   for(i = 0; i < uv; i++)
3206     if (voice[i].status != VOICE_FREE && voice[i].channel == c)
3207 	recompute_freq(i);
3208 }
3209 
adjust_volume(int c)3210 static void adjust_volume(int c)
3211 {
3212   int i, uv = upper_voices;
3213   for(i = 0; i < uv; i++)
3214     if (voice[i].channel == c &&
3215 	(voice[i].status & (VOICE_ON | VOICE_SUSTAINED)))
3216       {
3217 	recompute_amp(i);
3218 	apply_envelope_to_amp(i);
3219       }
3220 }
3221 
set_reverb_level(int ch,int level)3222 static void set_reverb_level(int ch, int level)
3223 {
3224 	if (level == -1) {
3225 		channel[ch].reverb_level = channel[ch].reverb_id =
3226 				(opt_reverb_control < 0)
3227 				? -opt_reverb_control & 0x7f : DEFAULT_REVERB_SEND_LEVEL;
3228 		make_rvid_flag = 1;
3229 		return;
3230 	}
3231 	channel[ch].reverb_level = level;
3232 	make_rvid_flag = 0;	/* to update reverb_id */
3233 }
3234 
get_reverb_level(int ch)3235 int get_reverb_level(int ch)
3236 {
3237 	if (channel[ch].reverb_level == -1)
3238 		return (opt_reverb_control < 0)
3239 			? -opt_reverb_control & 0x7f : DEFAULT_REVERB_SEND_LEVEL;
3240 	return channel[ch].reverb_level;
3241 }
3242 
get_chorus_level(int ch)3243 int get_chorus_level(int ch)
3244 {
3245 #ifdef DISALLOW_DRUM_BENDS
3246     if(ISDRUMCHANNEL(ch))
3247 	return 0; /* Not supported drum channel chorus */
3248 #endif
3249     if(opt_chorus_control == 1)
3250 	return channel[ch].chorus_level;
3251     return -opt_chorus_control;
3252 }
3253 
3254 #ifndef USE_DSP_EFFECT
make_rvid(void)3255 static void make_rvid(void)
3256 {
3257     int i, j, lv, maxrv;
3258 
3259     for(maxrv = MAX_CHANNELS - 1; maxrv >= 0; maxrv--)
3260     {
3261 	if(channel[maxrv].reverb_level == -1)
3262 	    channel[maxrv].reverb_id = -1;
3263 	else if(channel[maxrv].reverb_level >= 0)
3264 	    break;
3265     }
3266 
3267     /* collect same reverb level. */
3268     for(i = 0; i <= maxrv; i++)
3269     {
3270 	if((lv = channel[i].reverb_level) == -1)
3271 	{
3272 	    channel[i].reverb_id = -1;
3273 	    continue;
3274 	}
3275 	channel[i].reverb_id = i;
3276 	for(j = 0; j < i; j++)
3277 	{
3278 	    if(channel[j].reverb_level == lv)
3279 	    {
3280 		channel[i].reverb_id = j;
3281 		break;
3282 	    }
3283 	}
3284     }
3285 }
3286 #endif /* !USE_DSP_EFFECT */
3287 
free_drum_effect(int ch)3288 void free_drum_effect(int ch)
3289 {
3290 	int i;
3291 	if (channel[ch].drum_effect != NULL) {
3292 		for (i = 0; i < channel[ch].drum_effect_num; i++) {
3293 			if (channel[ch].drum_effect[i].buf != NULL) {
3294 				free(channel[ch].drum_effect[i].buf);
3295 				channel[ch].drum_effect[i].buf = NULL;
3296 			}
3297 		}
3298 		free(channel[ch].drum_effect);
3299 		channel[ch].drum_effect = NULL;
3300 	}
3301 	channel[ch].drum_effect_num = 0;
3302 	channel[ch].drum_effect_flag = 0;
3303 }
3304 
make_drum_effect(int ch)3305 static void make_drum_effect(int ch)
3306 {
3307 	int i, note, num = 0;
3308 	int8 note_table[128];
3309 	struct DrumParts *drum;
3310 	struct DrumPartEffect *de;
3311 
3312 	if (channel[ch].drums == NULL) {return;}
3313 
3314 	if (channel[ch].drum_effect_flag == 0) {
3315 		free_drum_effect(ch);
3316 		memset(note_table, 0, sizeof(int8) * 128);
3317 
3318 		for(i = 0; i < 128; i++) {
3319 			if ((drum = channel[ch].drums[i]) != NULL)
3320 			{
3321 				if (drum->reverb_level != -1
3322 				|| drum->chorus_level != -1 || drum->delay_level != -1) {
3323 					note_table[num++] = i;
3324 				}
3325 			}
3326 		}
3327 
3328 		channel[ch].drum_effect = (struct DrumPartEffect *)safe_malloc(sizeof(struct DrumPartEffect) * num);
3329 
3330 		for(i = 0; i < num; i++) {
3331 			de = &(channel[ch].drum_effect[i]);
3332 			de->note = note = note_table[i];
3333 			drum = channel[ch].drums[note];
3334 			de->reverb_send = (int32)drum->reverb_level * (int32)get_reverb_level(ch) / 127;
3335 			de->chorus_send = (int32)drum->chorus_level * (int32)channel[ch].chorus_level / 127;
3336 			de->delay_send = (int32)drum->delay_level * (int32)channel[ch].delay_level / 127;
3337 			de->buf = (int32 *)safe_malloc(AUDIO_BUFFER_SIZE * 8);
3338 			memset(de->buf, 0, AUDIO_BUFFER_SIZE * 8);
3339 		}
3340 
3341 		channel[ch].drum_effect_num = num;
3342 		channel[ch].drum_effect_flag = 1;
3343 	}
3344 }
3345 
adjust_master_volume(void)3346 static void adjust_master_volume(void)
3347 {
3348   int i, uv = upper_voices;
3349   adjust_amplification();
3350   for(i = 0; i < uv; i++)
3351       if(voice[i].status & (VOICE_ON | VOICE_SUSTAINED))
3352       {
3353 	  recompute_amp(i);
3354 	  apply_envelope_to_amp(i);
3355       }
3356 }
3357 
midi_drumpart_change(int ch,int isdrum)3358 int midi_drumpart_change(int ch, int isdrum)
3359 {
3360 	if (IS_SET_CHANNELMASK(drumchannel_mask, ch))
3361 		return 0;
3362 	if (isdrum) {
3363 		SET_CHANNELMASK(drumchannels, ch);
3364 		SET_CHANNELMASK(current_file_info->drumchannels, ch);
3365 	} else {
3366 		UNSET_CHANNELMASK(drumchannels, ch);
3367 		UNSET_CHANNELMASK(current_file_info->drumchannels, ch);
3368 	}
3369 	return 1;
3370 }
3371 
midi_program_change(int ch,int prog)3372 void midi_program_change(int ch, int prog)
3373 {
3374 	int dr = ISDRUMCHANNEL(ch);
3375 	int newbank, b, p, map;
3376 
3377 	switch (play_system_mode) {
3378 	case GS_SYSTEM_MODE:	/* GS */
3379 		if ((map = channel[ch].bank_lsb) == 0) {
3380 			map = channel[ch].tone_map0_number;
3381 		}
3382 		switch (map) {
3383 		case 0:		/* No change */
3384 			break;
3385 		case 1:
3386 			channel[ch].mapID = (dr) ? SC_55_DRUM_MAP : SC_55_TONE_MAP;
3387 			break;
3388 		case 2:
3389 			channel[ch].mapID = (dr) ? SC_88_DRUM_MAP : SC_88_TONE_MAP;
3390 			break;
3391 		case 3:
3392 			channel[ch].mapID = (dr) ? SC_88PRO_DRUM_MAP : SC_88PRO_TONE_MAP;
3393 			break;
3394 		case 4:
3395 			channel[ch].mapID = (dr) ? SC_8850_DRUM_MAP : SC_8850_TONE_MAP;
3396 			break;
3397 		default:
3398 			break;
3399 		}
3400 		newbank = channel[ch].bank_msb;
3401 		break;
3402 	case XG_SYSTEM_MODE:	/* XG */
3403 		switch (channel[ch].bank_msb) {
3404 		case 0:		/* Normal */
3405 #if 0
3406 			if (ch == 9 && channel[ch].bank_lsb == 127
3407 					&& channel[ch].mapID == XG_DRUM_MAP)
3408 				/* FIXME: Why this part is drum?  Is this correct? */
3409 				break;
3410 #endif
3411 /* Eric's explanation for the FIXME (March 2004):
3412  *
3413  * I don't have the original email from my archived inbox, but I found a
3414  * reply I made in my archived sent-mail from 1999.  A September 5th message
3415  * to Masanao Izumo is discussing a problem with a "reapxg.mid", a file which
3416  * I still have, and how it issues an MSB=0 with a program change on ch 9,
3417  * thus turning it into a melodic channel.  The strange thing is, this doesn't
3418  * happen on XG hardware, nor on the XG softsynth.  It continues to play as a
3419  * normal drum.  The author of the midi file obviously intended it to be
3420  * drumset 16 too.  The original fix was to detect LSB == -1, then break so
3421  * as to not set it to a melodic channel.  I'm guessing that this somehow got
3422  * mutated into checking for 127 instead, and the current FIXME is related to
3423  * the original hack from Sept 1999.  The Sept 5th email discusses patches
3424  * being applied to version 2.5.1 to get XG drums to work properly, and a
3425  * Sept 7th email to someone else discusses the fixes being part of the
3426  * latest 2.6.0-beta3.  A September 23rd email to Masanao Izumo specifically
3427  * mentions the LSB == -1 hack (and reapxg.mid not playing "correctly"
3428  * anymore), as well as new changes in 2.6.0 that broke a lot of other XG
3429  * files (XG drum support was extremely buggy in 1999 and we were still trying
3430  * to figure out how to initialize things to reproduce hardware behavior).  An
3431  * October 5th email says that 2.5.1 was correct, 2.6.0 had very broken XG
3432  * drum changes, and 2.6.1 still has problems.  Further discussions ensued
3433  * over what was "correct": to follow the XG spec, or to reproduce
3434  * "features" / bugs in the hardware.  I can't find the rest of the
3435  * discussions, but I think it ended with us agreeing to just follow the spec
3436  * and not try to reproduce the hardware strangeness.  I don't know how the
3437  * current FIXME wound up the way it is now.  I'm still going to guess it is
3438  * related to the old reapxg.mid hack.
3439  *
3440  * Now that reset_midi() initializes channel[ch].bank_lsb to 0 instead of -1,
3441  * checking for LSB == -1 won't do anything anymore, so changing the above
3442  * FIXME to the original == -1 won't do any good.  It is best to just #if 0
3443  * it out and leave it here as a reminder that there is at least one XG
3444  * hardware / softsynth "bug" that is not reproduced by timidity at the
3445  * moment.
3446  *
3447  * If the current FIXME actually reproduces some other XG hadware bug that
3448  * I don't know about, then it may have a valid purpose.  I just don't know
3449  * what that purpose is at the moment.  Perhaps someone else does?  I still
3450  * have src going back to 2.10.4, and the FIXME comment was already there by
3451  * then.  I don't see any entries in the Changelog that could explain it
3452  * either.  If someone has src from 2.5.1 through 2.10.3 and wants to
3453  * investigate this further, go for it :)
3454  */
3455 			midi_drumpart_change(ch, 0);
3456 			channel[ch].mapID = XG_NORMAL_MAP;
3457 			dr = ISDRUMCHANNEL(ch);
3458 			break;
3459 		case 64:	/* SFX voice */
3460 			midi_drumpart_change(ch, 0);
3461 			channel[ch].mapID = XG_SFX64_MAP;
3462 			dr = ISDRUMCHANNEL(ch);
3463 			break;
3464 		case 126:	/* SFX kit */
3465 			midi_drumpart_change(ch, 1);
3466 			channel[ch].mapID = XG_SFX126_MAP;
3467 			dr = ISDRUMCHANNEL(ch);
3468 			break;
3469 		case 127:	/* Drum kit */
3470 			midi_drumpart_change(ch, 1);
3471 			channel[ch].mapID = XG_DRUM_MAP;
3472 			dr = ISDRUMCHANNEL(ch);
3473 			break;
3474 		default:
3475 			break;
3476 		}
3477 		newbank = channel[ch].bank_lsb;
3478 		break;
3479 	case GM2_SYSTEM_MODE:	/* GM2 */
3480 		if ((channel[ch].bank_msb & 0xfe) == 0x78) {	/* 0x78/0x79 */
3481 			midi_drumpart_change(ch, channel[ch].bank_msb == 0x78);
3482 			dr = ISDRUMCHANNEL(ch);
3483 		}
3484 		channel[ch].mapID = (dr) ? GM2_DRUM_MAP : GM2_TONE_MAP;
3485 		newbank = channel[ch].bank_lsb;
3486 		break;
3487 	default:
3488 		newbank = channel[ch].bank_msb;
3489 		break;
3490 	}
3491 	if (dr) {
3492 		channel[ch].bank = prog;	/* newbank is ignored */
3493 		channel[ch].program = prog;
3494 		if (drumset[prog] == NULL || drumset[prog]->alt == NULL)
3495 			channel[ch].altassign = drumset[0]->alt;
3496 		else
3497 			channel[ch].altassign = drumset[prog]->alt;
3498 		ctl_mode_event(CTLE_DRUMPART, 1, ch, 1);
3499 	} else {
3500 		channel[ch].bank = (special_tonebank >= 0)
3501 				? special_tonebank : newbank;
3502 		channel[ch].program = (default_program[ch] == SPECIAL_PROGRAM)
3503 				? SPECIAL_PROGRAM : prog;
3504 		channel[ch].altassign = NULL;
3505 		ctl_mode_event(CTLE_DRUMPART, 1, ch, 0);
3506 		if (opt_realtime_playing && (play_mode->flag & PF_PCM_STREAM)) {
3507 			b = channel[ch].bank, p = prog;
3508 			instrument_map(channel[ch].mapID, &b, &p);
3509 			play_midi_load_instrument(0, b, p);
3510 		}
3511 	}
3512 }
3513 
conv_lfo_pitch_depth(float val)3514 static int16 conv_lfo_pitch_depth(float val)
3515 {
3516 	return (int16)(0.0318f * val * val + 0.6858f * val + 0.5f);
3517 }
3518 
conv_lfo_filter_depth(float val)3519 static int16 conv_lfo_filter_depth(float val)
3520 {
3521 	return (int16)((0.0318f * val * val + 0.6858f * val) * 4.0f + 0.5f);
3522 }
3523 
3524 /*! process system exclusive sent from parse_sysex_event_multi(). */
process_sysex_event(int ev,int ch,int val,int b)3525 static void process_sysex_event(int ev, int ch, int val, int b)
3526 {
3527 	int temp, msb, note;
3528 
3529 	if (ch >= MAX_CHANNELS)
3530 		return;
3531 	if (ev == ME_SYSEX_MSB) {
3532 		channel[ch].sysex_msb_addr = b;
3533 		channel[ch].sysex_msb_val = val;
3534 	} else if(ev == ME_SYSEX_GS_MSB) {
3535 		channel[ch].sysex_gs_msb_addr = b;
3536 		channel[ch].sysex_gs_msb_val = val;
3537 	} else if(ev == ME_SYSEX_XG_MSB) {
3538 		channel[ch].sysex_xg_msb_addr = b;
3539 		channel[ch].sysex_xg_msb_val = val;
3540 	} else if(ev == ME_SYSEX_LSB) {	/* Universal system exclusive message */
3541 		msb = channel[ch].sysex_msb_addr;
3542 		note = channel[ch].sysex_msb_val;
3543 		channel[ch].sysex_msb_addr = channel[ch].sysex_msb_val = 0;
3544 		switch(b)
3545 		{
3546 		case 0x00:	/* CAf Pitch Control */
3547 			if(val > 0x58) {val = 0x58;}
3548 			else if(val < 0x28) {val = 0x28;}
3549 			channel[ch].caf.pitch = val - 64;
3550 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Pitch Control (CH:%d %d semitones)", ch, channel[ch].caf.pitch);
3551 			break;
3552 		case 0x01:	/* CAf Filter Cutoff Control */
3553 			channel[ch].caf.cutoff = (val - 64) * 150;
3554 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].caf.cutoff);
3555 			break;
3556 		case 0x02:	/* CAf Amplitude Control */
3557 			channel[ch].caf.amp = (float)val / 64.0f - 1.0f;
3558 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Amplitude Control (CH:%d %.2f)", ch, channel[ch].caf.amp);
3559 			break;
3560 		case 0x03:	/* CAf LFO1 Rate Control */
3561 			channel[ch].caf.lfo1_rate = (float)(val - 64) / 6.4f;
3562 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].caf.lfo1_rate);
3563 			break;
3564 		case 0x04:	/* CAf LFO1 Pitch Depth */
3565 			channel[ch].caf.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3566 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].caf.lfo1_pitch_depth);
3567 			break;
3568 		case 0x05:	/* CAf LFO1 Filter Depth */
3569 			channel[ch].caf.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3570 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].caf.lfo1_tvf_depth);
3571 			break;
3572 		case 0x06:	/* CAf LFO1 Amplitude Depth */
3573 			channel[ch].caf.lfo1_tva_depth = (float)val / 127.0f;
3574 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].caf.lfo1_tva_depth);
3575 			break;
3576 		case 0x07:	/* CAf LFO2 Rate Control */
3577 			channel[ch].caf.lfo2_rate = (float)(val - 64) / 6.4f;
3578 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].caf.lfo2_rate);
3579 			break;
3580 		case 0x08:	/* CAf LFO2 Pitch Depth */
3581 			channel[ch].caf.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3582 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].caf.lfo2_pitch_depth);
3583 			break;
3584 		case 0x09:	/* CAf LFO2 Filter Depth */
3585 			channel[ch].caf.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3586 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].caf.lfo2_tvf_depth);
3587 			break;
3588 		case 0x0A:	/* CAf LFO2 Amplitude Depth */
3589 			channel[ch].caf.lfo2_tva_depth = (float)val / 127.0f;
3590 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].caf.lfo2_tva_depth);
3591 			break;
3592 		case 0x0B:	/* PAf Pitch Control */
3593 			if(val > 0x58) {val = 0x58;}
3594 			else if(val < 0x28) {val = 0x28;}
3595 			channel[ch].paf.pitch = val - 64;
3596 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Pitch Control (CH:%d %d semitones)", ch, channel[ch].paf.pitch);
3597 			break;
3598 		case 0x0C:	/* PAf Filter Cutoff Control */
3599 			channel[ch].paf.cutoff = (val - 64) * 150;
3600 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].paf.cutoff);
3601 			break;
3602 		case 0x0D:	/* PAf Amplitude Control */
3603 			channel[ch].paf.amp = (float)val / 64.0f - 1.0f;
3604 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Amplitude Control (CH:%d %.2f)", ch, channel[ch].paf.amp);
3605 			break;
3606 		case 0x0E:	/* PAf LFO1 Rate Control */
3607 			channel[ch].paf.lfo1_rate = (float)(val - 64) / 6.4f;
3608 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].paf.lfo1_rate);
3609 			break;
3610 		case 0x0F:	/* PAf LFO1 Pitch Depth */
3611 			channel[ch].paf.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3612 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].paf.lfo1_pitch_depth);
3613 			break;
3614 		case 0x10:	/* PAf LFO1 Filter Depth */
3615 			channel[ch].paf.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3616 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].paf.lfo1_tvf_depth);
3617 			break;
3618 		case 0x11:	/* PAf LFO1 Amplitude Depth */
3619 			channel[ch].paf.lfo1_tva_depth = (float)val / 127.0f;
3620 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].paf.lfo1_tva_depth);
3621 			break;
3622 		case 0x12:	/* PAf LFO2 Rate Control */
3623 			channel[ch].paf.lfo2_rate = (float)(val - 64) / 6.4f;
3624 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].paf.lfo2_rate);
3625 			break;
3626 		case 0x13:	/* PAf LFO2 Pitch Depth */
3627 			channel[ch].paf.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3628 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].paf.lfo2_pitch_depth);
3629 			break;
3630 		case 0x14:	/* PAf LFO2 Filter Depth */
3631 			channel[ch].paf.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3632 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].paf.lfo2_tvf_depth);
3633 			break;
3634 		case 0x15:	/* PAf LFO2 Amplitude Depth */
3635 			channel[ch].paf.lfo2_tva_depth = (float)val / 127.0f;
3636 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].paf.lfo2_tva_depth);
3637 			break;
3638 		case 0x16:	/* MOD Pitch Control */
3639 			if(val > 0x58) {val = 0x58;}
3640 			else if(val < 0x28) {val = 0x28;}
3641 			channel[ch].mod.pitch = val - 64;
3642 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Pitch Control (CH:%d %d semitones)", ch, channel[ch].mod.pitch);
3643 			break;
3644 		case 0x17:	/* MOD Filter Cutoff Control */
3645 			channel[ch].mod.cutoff = (val - 64) * 150;
3646 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].mod.cutoff);
3647 			break;
3648 		case 0x18:	/* MOD Amplitude Control */
3649 			channel[ch].mod.amp = (float)val / 64.0f - 1.0f;
3650 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Amplitude Control (CH:%d %.2f)", ch, channel[ch].mod.amp);
3651 			break;
3652 		case 0x19:	/* MOD LFO1 Rate Control */
3653 			channel[ch].mod.lfo1_rate = (float)(val - 64) / 6.4f;
3654 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].mod.lfo1_rate);
3655 			break;
3656 		case 0x1A:	/* MOD LFO1 Pitch Depth */
3657 			channel[ch].mod.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3658 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].mod.lfo1_pitch_depth);
3659 			break;
3660 		case 0x1B:	/* MOD LFO1 Filter Depth */
3661 			channel[ch].mod.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3662 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].mod.lfo1_tvf_depth);
3663 			break;
3664 		case 0x1C:	/* MOD LFO1 Amplitude Depth */
3665 			channel[ch].mod.lfo1_tva_depth = (float)val / 127.0f;
3666 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].mod.lfo1_tva_depth);
3667 			break;
3668 		case 0x1D:	/* MOD LFO2 Rate Control */
3669 			channel[ch].mod.lfo2_rate = (float)(val - 64) / 6.4f;
3670 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].mod.lfo2_rate);
3671 			break;
3672 		case 0x1E:	/* MOD LFO2 Pitch Depth */
3673 			channel[ch].mod.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3674 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].mod.lfo2_pitch_depth);
3675 			break;
3676 		case 0x1F:	/* MOD LFO2 Filter Depth */
3677 			channel[ch].mod.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3678 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].mod.lfo2_tvf_depth);
3679 			break;
3680 		case 0x20:	/* MOD LFO2 Amplitude Depth */
3681 			channel[ch].mod.lfo2_tva_depth = (float)val / 127.0f;
3682 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].mod.lfo2_tva_depth);
3683 			break;
3684 		case 0x21:	/* BEND Pitch Control */
3685 			if(val > 0x58) {val = 0x58;}
3686 			else if(val < 0x28) {val = 0x28;}
3687 			channel[ch].bend.pitch = val - 64;
3688 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Pitch Control (CH:%d %d semitones)", ch, channel[ch].bend.pitch);
3689 			break;
3690 		case 0x22:	/* BEND Filter Cutoff Control */
3691 			channel[ch].bend.cutoff = (val - 64) * 150;
3692 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].bend.cutoff);
3693 			break;
3694 		case 0x23:	/* BEND Amplitude Control */
3695 			channel[ch].bend.amp = (float)val / 64.0f - 1.0f;
3696 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Amplitude Control (CH:%d %.2f)", ch, channel[ch].bend.amp);
3697 			break;
3698 		case 0x24:	/* BEND LFO1 Rate Control */
3699 			channel[ch].bend.lfo1_rate = (float)(val - 64) / 6.4f;
3700 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].bend.lfo1_rate);
3701 			break;
3702 		case 0x25:	/* BEND LFO1 Pitch Depth */
3703 			channel[ch].bend.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3704 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].bend.lfo1_pitch_depth);
3705 			break;
3706 		case 0x26:	/* BEND LFO1 Filter Depth */
3707 			channel[ch].bend.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3708 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].bend.lfo1_tvf_depth);
3709 			break;
3710 		case 0x27:	/* BEND LFO1 Amplitude Depth */
3711 			channel[ch].bend.lfo1_tva_depth = (float)val / 127.0f;
3712 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].bend.lfo1_tva_depth);
3713 			break;
3714 		case 0x28:	/* BEND LFO2 Rate Control */
3715 			channel[ch].bend.lfo2_rate = (float)(val - 64) / 6.4f;
3716 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].bend.lfo2_rate);
3717 			break;
3718 		case 0x29:	/* BEND LFO2 Pitch Depth */
3719 			channel[ch].bend.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3720 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].bend.lfo2_pitch_depth);
3721 			break;
3722 		case 0x2A:	/* BEND LFO2 Filter Depth */
3723 			channel[ch].bend.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3724 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].bend.lfo2_tvf_depth);
3725 			break;
3726 		case 0x2B:	/* BEND LFO2 Amplitude Depth */
3727 			channel[ch].bend.lfo2_tva_depth = (float)val / 127.0f;
3728 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].bend.lfo2_tva_depth);
3729 			break;
3730 		case 0x2C:	/* CC1 Pitch Control */
3731 			if(val > 0x58) {val = 0x58;}
3732 			else if(val < 0x28) {val = 0x28;}
3733 			channel[ch].cc1.pitch = val - 64;
3734 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc1.pitch);
3735 			break;
3736 		case 0x2D:	/* CC1 Filter Cutoff Control */
3737 			channel[ch].cc1.cutoff = (val - 64) * 150;
3738 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc1.cutoff);
3739 			break;
3740 		case 0x2E:	/* CC1 Amplitude Control */
3741 			channel[ch].cc1.amp = (float)val / 64.0f - 1.0f;
3742 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc1.amp);
3743 			break;
3744 		case 0x2F:	/* CC1 LFO1 Rate Control */
3745 			channel[ch].cc1.lfo1_rate = (float)(val - 64) / 6.4f;
3746 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc1.lfo1_rate);
3747 			break;
3748 		case 0x30:	/* CC1 LFO1 Pitch Depth */
3749 			channel[ch].cc1.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3750 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].cc1.lfo1_pitch_depth);
3751 			break;
3752 		case 0x31:	/* CC1 LFO1 Filter Depth */
3753 			channel[ch].cc1.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3754 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].cc1.lfo1_tvf_depth);
3755 			break;
3756 		case 0x32:	/* CC1 LFO1 Amplitude Depth */
3757 			channel[ch].cc1.lfo1_tva_depth = (float)val / 127.0f;
3758 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc1.lfo1_tva_depth);
3759 			break;
3760 		case 0x33:	/* CC1 LFO2 Rate Control */
3761 			channel[ch].cc1.lfo2_rate = (float)(val - 64) / 6.4f;
3762 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc1.lfo2_rate);
3763 			break;
3764 		case 0x34:	/* CC1 LFO2 Pitch Depth */
3765 			channel[ch].cc1.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3766 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].cc1.lfo2_pitch_depth);
3767 			break;
3768 		case 0x35:	/* CC1 LFO2 Filter Depth */
3769 			channel[ch].cc1.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3770 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].cc1.lfo2_tvf_depth);
3771 			break;
3772 		case 0x36:	/* CC1 LFO2 Amplitude Depth */
3773 			channel[ch].cc1.lfo2_tva_depth = (float)val / 127.0f;
3774 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc1.lfo2_tva_depth);
3775 			break;
3776 		case 0x37:	/* CC2 Pitch Control */
3777 			if(val > 0x58) {val = 0x58;}
3778 			else if(val < 0x28) {val = 0x28;}
3779 			channel[ch].cc2.pitch = val - 64;
3780 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc2.pitch);
3781 			break;
3782 		case 0x38:	/* CC2 Filter Cutoff Control */
3783 			channel[ch].cc2.cutoff = (val - 64) * 150;
3784 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc2.cutoff);
3785 			break;
3786 		case 0x39:	/* CC2 Amplitude Control */
3787 			channel[ch].cc2.amp = (float)val / 64.0f - 1.0f;
3788 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc2.amp);
3789 			break;
3790 		case 0x3A:	/* CC2 LFO1 Rate Control */
3791 			channel[ch].cc2.lfo1_rate = (float)(val - 64) / 6.4f;
3792 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc2.lfo1_rate);
3793 			break;
3794 		case 0x3B:	/* CC2 LFO1 Pitch Depth */
3795 			channel[ch].cc2.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
3796 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Pitch Depth (CH:%d %d cents)", ch, channel[ch].cc2.lfo1_pitch_depth);
3797 			break;
3798 		case 0x3C:	/* CC2 LFO1 Filter Depth */
3799 			channel[ch].cc2.lfo1_tvf_depth = conv_lfo_filter_depth(val);
3800 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Filter Depth (CH:%d %d cents)", ch, channel[ch].cc2.lfo1_tvf_depth);
3801 			break;
3802 		case 0x3D:	/* CC2 LFO1 Amplitude Depth */
3803 			channel[ch].cc2.lfo1_tva_depth = (float)val / 127.0f;
3804 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc2.lfo1_tva_depth);
3805 			break;
3806 		case 0x3E:	/* CC2 LFO2 Rate Control */
3807 			channel[ch].cc2.lfo2_rate = (float)(val - 64) / 6.4f;
3808 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc2.lfo2_rate);
3809 			break;
3810 		case 0x3F:	/* CC2 LFO2 Pitch Depth */
3811 			channel[ch].cc2.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
3812 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Pitch Depth (CH:%d %d cents)", ch, channel[ch].cc2.lfo2_pitch_depth);
3813 			break;
3814 		case 0x40:	/* CC2 LFO2 Filter Depth */
3815 			channel[ch].cc2.lfo2_tvf_depth = conv_lfo_filter_depth(val);
3816 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Filter Depth (CH:%d %d cents)", ch, channel[ch].cc2.lfo2_tvf_depth);
3817 			break;
3818 		case 0x41:	/* CC2 LFO2 Amplitude Depth */
3819 			channel[ch].cc2.lfo2_tva_depth = (float)val / 127.0f;
3820 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc2.lfo2_tva_depth);
3821 			break;
3822 		case 0x42:	/* Note Limit Low */
3823 			channel[ch].note_limit_low = val;
3824 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Note Limit Low (CH:%d VAL:%d)", ch, val);
3825 			break;
3826 		case 0x43:	/* Note Limit High */
3827 			channel[ch].note_limit_high = val;
3828 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Note Limit High (CH:%d VAL:%d)", ch, val);
3829 			break;
3830 		case 0x44:	/* Velocity Limit Low */
3831 			channel[ch].vel_limit_low = val;
3832 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Velocity Limit Low (CH:%d VAL:%d)", ch, val);
3833 			break;
3834 		case 0x45:	/* Velocity Limit High */
3835 			channel[ch].vel_limit_high = val;
3836 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Velocity Limit High (CH:%d VAL:%d)", ch, val);
3837 			break;
3838 		case 0x46:	/* Rx. Note Off */
3839 			if (channel[ch].drums[note] == NULL)
3840 				play_midi_setup_drums(ch, note);
3841 			set_rx_drum(channel[ch].drums[note], RX_NOTE_OFF, val);
3842 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
3843 				"Drum Instrument Rx. Note Off (CH:%d NOTE:%d VAL:%d)",
3844 				ch, note, val);
3845 			break;
3846 		case 0x47:	/* Rx. Note On */
3847 			if (channel[ch].drums[note] == NULL)
3848 				play_midi_setup_drums(ch, note);
3849 			set_rx_drum(channel[ch].drums[note], RX_NOTE_ON, val);
3850 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
3851 				"Drum Instrument Rx. Note On (CH:%d NOTE:%d VAL:%d)",
3852 				ch, note, val);
3853 			break;
3854 		case 0x48:	/* Rx. Pitch Bend */
3855 			set_rx(ch, RX_PITCH_BEND, val);
3856 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Pitch Bend (CH:%d VAL:%d)", ch, val);
3857 			break;
3858 		case 0x49:	/* Rx. Channel Pressure */
3859 			set_rx(ch, RX_CH_PRESSURE, val);
3860 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Channel Pressure (CH:%d VAL:%d)", ch, val);
3861 			break;
3862 		case 0x4A:	/* Rx. Program Change */
3863 			set_rx(ch, RX_PROGRAM_CHANGE, val);
3864 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Program Change (CH:%d VAL:%d)", ch, val);
3865 			break;
3866 		case 0x4B:	/* Rx. Control Change */
3867 			set_rx(ch, RX_CONTROL_CHANGE, val);
3868 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Control Change (CH:%d VAL:%d)", ch, val);
3869 			break;
3870 		case 0x4C:	/* Rx. Poly Pressure */
3871 			set_rx(ch, RX_POLY_PRESSURE, val);
3872 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Poly Pressure (CH:%d VAL:%d)", ch, val);
3873 			break;
3874 		case 0x4D:	/* Rx. Note Message */
3875 			set_rx(ch, RX_NOTE_MESSAGE, val);
3876 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Note Message (CH:%d VAL:%d)", ch, val);
3877 			break;
3878 		case 0x4E:	/* Rx. RPN */
3879 			set_rx(ch, RX_RPN, val);
3880 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. RPN (CH:%d VAL:%d)", ch, val);
3881 			break;
3882 		case 0x4F:	/* Rx. NRPN */
3883 			set_rx(ch, RX_NRPN, val);
3884 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. NRPN (CH:%d VAL:%d)", ch, val);
3885 			break;
3886 		case 0x50:	/* Rx. Modulation */
3887 			set_rx(ch, RX_MODULATION, val);
3888 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Modulation (CH:%d VAL:%d)", ch, val);
3889 			break;
3890 		case 0x51:	/* Rx. Volume */
3891 			set_rx(ch, RX_VOLUME, val);
3892 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Volume (CH:%d VAL:%d)", ch, val);
3893 			break;
3894 		case 0x52:	/* Rx. Panpot */
3895 			set_rx(ch, RX_PANPOT, val);
3896 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Panpot (CH:%d VAL:%d)", ch, val);
3897 			break;
3898 		case 0x53:	/* Rx. Expression */
3899 			set_rx(ch, RX_EXPRESSION, val);
3900 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Expression (CH:%d VAL:%d)", ch, val);
3901 			break;
3902 		case 0x54:	/* Rx. Hold1 */
3903 			set_rx(ch, RX_HOLD1, val);
3904 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Hold1 (CH:%d VAL:%d)", ch, val);
3905 			break;
3906 		case 0x55:	/* Rx. Portamento */
3907 			set_rx(ch, RX_PORTAMENTO, val);
3908 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Portamento (CH:%d VAL:%d)", ch, val);
3909 			break;
3910 		case 0x56:	/* Rx. Sostenuto */
3911 			set_rx(ch, RX_SOSTENUTO, val);
3912 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Sostenuto (CH:%d VAL:%d)", ch, val);
3913 			break;
3914 		case 0x57:	/* Rx. Soft */
3915 			set_rx(ch, RX_SOFT, val);
3916 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Soft (CH:%d VAL:%d)", ch, val);
3917 			break;
3918 		case 0x58:	/* Rx. Bank Select */
3919 			set_rx(ch, RX_BANK_SELECT, val);
3920 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Bank Select (CH:%d VAL:%d)", ch, val);
3921 			break;
3922 		case 0x59:	/* Rx. Bank Select LSB */
3923 			set_rx(ch, RX_BANK_SELECT_LSB, val);
3924 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Bank Select LSB (CH:%d VAL:%d)", ch, val);
3925 			break;
3926 		case 0x60:	/* Reverb Type (GM2) */
3927 			if (val > 8) {val = 8;}
3928 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type (%d)", val);
3929 			set_reverb_macro_gm2(val);
3930 			recompute_reverb_status_gs();
3931 			init_reverb();
3932 			break;
3933 		case 0x61:	/* Chorus Type (GM2) */
3934 			if (val > 5) {val = 5;}
3935 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type (%d)", val);
3936 			set_chorus_macro_gs(val);
3937 			recompute_chorus_status_gs();
3938 			init_ch_chorus();
3939 			break;
3940 		default:
3941 			break;
3942 		}
3943 		return;
3944 	} else if(ev == ME_SYSEX_GS_LSB) {	/* GS system exclusive message */
3945 		msb = channel[ch].sysex_gs_msb_addr;
3946 		note = channel[ch].sysex_gs_msb_val;
3947 		channel[ch].sysex_gs_msb_addr = channel[ch].sysex_gs_msb_val = 0;
3948 		switch(b)
3949 		{
3950 		case 0x00:	/* EQ ON/OFF */
3951 			if(!opt_eq_control) {break;}
3952 			if(channel[ch].eq_gs != val) {
3953 				if(val) {
3954 					ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ ON (CH:%d)",ch);
3955 				} else {
3956 					ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ OFF (CH:%d)",ch);
3957 				}
3958 			}
3959 			channel[ch].eq_gs = val;
3960 			break;
3961 		case 0x01:	/* EQ LOW FREQ */
3962 			if(!opt_eq_control) {break;}
3963 			eq_status_gs.low_freq = val;
3964 			recompute_eq_status_gs();
3965 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ LOW FREQ (%d)",val);
3966 			break;
3967 		case 0x02:	/* EQ LOW GAIN */
3968 			if(!opt_eq_control) {break;}
3969 			eq_status_gs.low_gain = val;
3970 			recompute_eq_status_gs();
3971 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ LOW GAIN (%d dB)",val - 0x40);
3972 			break;
3973 		case 0x03:	/* EQ HIGH FREQ */
3974 			if(!opt_eq_control) {break;}
3975 			eq_status_gs.high_freq = val;
3976 			recompute_eq_status_gs();
3977 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ HIGH FREQ (%d)",val);
3978 			break;
3979 		case 0x04:	/* EQ HIGH GAIN */
3980 			if(!opt_eq_control) {break;}
3981 			eq_status_gs.high_gain = val;
3982 			recompute_eq_status_gs();
3983 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ HIGH GAIN (%d dB)",val - 0x40);
3984 			break;
3985 		case 0x05:	/* Reverb Macro */
3986 			if (val > 7) {val = 7;}
3987 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Macro (%d)",val);
3988 			set_reverb_macro_gs(val);
3989 			recompute_reverb_status_gs();
3990 			init_reverb();
3991 			break;
3992 		case 0x06:	/* Reverb Character */
3993 			if (val > 7) {val = 7;}
3994 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Character (%d)",val);
3995 			if (reverb_status_gs.character != val) {
3996 				reverb_status_gs.character = val;
3997 				recompute_reverb_status_gs();
3998 				init_reverb();
3999 			}
4000 			break;
4001 		case 0x07:	/* Reverb Pre-LPF */
4002 			if (val > 7) {val = 7;}
4003 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Pre-LPF (%d)",val);
4004 			if(reverb_status_gs.pre_lpf != val) {
4005 				reverb_status_gs.pre_lpf = val;
4006 				recompute_reverb_status_gs();
4007 			}
4008 			break;
4009 		case 0x08:	/* Reverb Level */
4010 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Level (%d)",val);
4011 			if(reverb_status_gs.level != val) {
4012 				reverb_status_gs.level = val;
4013 				recompute_reverb_status_gs();
4014 				init_reverb();
4015 			}
4016 			break;
4017 		case 0x09:	/* Reverb Time */
4018 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Time (%d)",val);
4019 			if(reverb_status_gs.time != val) {
4020 				reverb_status_gs.time = val;
4021 				recompute_reverb_status_gs();
4022 				init_reverb();
4023 			}
4024 			break;
4025 		case 0x0A:	/* Reverb Delay Feedback */
4026 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Delay Feedback (%d)",val);
4027 			if(reverb_status_gs.delay_feedback != val) {
4028 				reverb_status_gs.delay_feedback = val;
4029 				recompute_reverb_status_gs();
4030 				init_reverb();
4031 			}
4032 			break;
4033 		case 0x0C:	/* Reverb Predelay Time */
4034 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Predelay Time (%d)",val);
4035 			if(reverb_status_gs.pre_delay_time != val) {
4036 				reverb_status_gs.pre_delay_time = val;
4037 				recompute_reverb_status_gs();
4038 				init_reverb();
4039 			}
4040 			break;
4041 		case 0x0D:	/* Chorus Macro */
4042 			if (val > 7) {val = 7;}
4043 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Macro (%d)",val);
4044 			set_chorus_macro_gs(val);
4045 			recompute_chorus_status_gs();
4046 			init_ch_chorus();
4047 			break;
4048 		case 0x0E:	/* Chorus Pre-LPF */
4049 			if (val > 7) {val = 7;}
4050 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Pre-LPF (%d)",val);
4051 			if (chorus_status_gs.pre_lpf != val) {
4052 				chorus_status_gs.pre_lpf = val;
4053 				recompute_chorus_status_gs();
4054 			}
4055 			break;
4056 		case 0x0F:	/* Chorus Level */
4057 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Level (%d)",val);
4058 			if (chorus_status_gs.level != val) {
4059 				chorus_status_gs.level = val;
4060 				recompute_chorus_status_gs();
4061 				init_ch_chorus();
4062 			}
4063 			break;
4064 		case 0x10:	/* Chorus Feedback */
4065 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Feedback (%d)",val);
4066 			if (chorus_status_gs.feedback != val) {
4067 				chorus_status_gs.feedback = val;
4068 				recompute_chorus_status_gs();
4069 				init_ch_chorus();
4070 			}
4071 			break;
4072 		case 0x11:	/* Chorus Delay */
4073 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Delay (%d)",val);
4074 			if (chorus_status_gs.delay != val) {
4075 				chorus_status_gs.delay = val;
4076 				recompute_chorus_status_gs();
4077 				init_ch_chorus();
4078 			}
4079 			break;
4080 		case 0x12:	/* Chorus Rate */
4081 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Rate (%d)",val);
4082 			if (chorus_status_gs.rate != val) {
4083 				chorus_status_gs.rate = val;
4084 				recompute_chorus_status_gs();
4085 				init_ch_chorus();
4086 			}
4087 			break;
4088 		case 0x13:	/* Chorus Depth */
4089 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Depth (%d)",val);
4090 			if (chorus_status_gs.depth != val) {
4091 				chorus_status_gs.depth = val;
4092 				recompute_chorus_status_gs();
4093 				init_ch_chorus();
4094 			}
4095 			break;
4096 		case 0x14:	/* Chorus Send Level to Reverb */
4097 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send Level to Reverb (%d)",val);
4098 			if (chorus_status_gs.send_reverb != val) {
4099 				chorus_status_gs.send_reverb = val;
4100 				recompute_chorus_status_gs();
4101 				init_ch_chorus();
4102 			}
4103 			break;
4104 		case 0x15:	/* Chorus Send Level to Delay */
4105 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send Level to Delay (%d)",val);
4106 			if (chorus_status_gs.send_delay != val) {
4107 				chorus_status_gs.send_delay = val;
4108 				recompute_chorus_status_gs();
4109 				init_ch_chorus();
4110 			}
4111 			break;
4112 		case 0x16:	/* Delay Macro */
4113 			if (val > 7) {val = 7;}
4114 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Macro (%d)",val);
4115 			set_delay_macro_gs(val);
4116 			recompute_delay_status_gs();
4117 			init_ch_delay();
4118 			break;
4119 		case 0x17:	/* Delay Pre-LPF */
4120 			if (val > 7) {val = 7;}
4121 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Pre-LPF (%d)",val);
4122 			val &= 0x7;
4123 			if (delay_status_gs.pre_lpf != val) {
4124 				delay_status_gs.pre_lpf = val;
4125 				recompute_delay_status_gs();
4126 			}
4127 			break;
4128 		case 0x18:	/* Delay Time Center */
4129 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Center (%d)",val);
4130 			if (delay_status_gs.time_c != val) {
4131 				delay_status_gs.time_c = val;
4132 				recompute_delay_status_gs();
4133 				init_ch_delay();
4134 			}
4135 			break;
4136 		case 0x19:	/* Delay Time Ratio Left */
4137 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Ratio Left (%d)",val);
4138 			if (val == 0) {val = 1;}
4139 			if (delay_status_gs.time_l != val) {
4140 				delay_status_gs.time_l = val;
4141 				recompute_delay_status_gs();
4142 				init_ch_delay();
4143 			}
4144 			break;
4145 		case 0x1A:	/* Delay Time Ratio Right */
4146 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Ratio Right (%d)",val);
4147 			if (val == 0) {val = 1;}
4148 			if (delay_status_gs.time_r != val) {
4149 				delay_status_gs.time_r = val;
4150 				recompute_delay_status_gs();
4151 				init_ch_delay();
4152 			}
4153 			break;
4154 		case 0x1B:	/* Delay Level Center */
4155 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Center (%d)",val);
4156 			if (delay_status_gs.level_center != val) {
4157 				delay_status_gs.level_center = val;
4158 				recompute_delay_status_gs();
4159 				init_ch_delay();
4160 			}
4161 			break;
4162 		case 0x1C:	/* Delay Level Left */
4163 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Left (%d)",val);
4164 			if (delay_status_gs.level_left != val) {
4165 				delay_status_gs.level_left = val;
4166 				recompute_delay_status_gs();
4167 				init_ch_delay();
4168 			}
4169 			break;
4170 		case 0x1D:	/* Delay Level Right */
4171 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Right (%d)",val);
4172 			if (delay_status_gs.level_right != val) {
4173 				delay_status_gs.level_right = val;
4174 				recompute_delay_status_gs();
4175 				init_ch_delay();
4176 			}
4177 			break;
4178 		case 0x1E:	/* Delay Level */
4179 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level (%d)",val);
4180 			if (delay_status_gs.level != val) {
4181 				delay_status_gs.level = val;
4182 				recompute_delay_status_gs();
4183 				init_ch_delay();
4184 			}
4185 			break;
4186 		case 0x1F:	/* Delay Feedback */
4187 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Feedback (%d)",val);
4188 			if (delay_status_gs.feedback != val) {
4189 				delay_status_gs.feedback = val;
4190 				recompute_delay_status_gs();
4191 				init_ch_delay();
4192 			}
4193 			break;
4194 		case 0x20:	/* Delay Send Level to Reverb */
4195 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send Level to Reverb (%d)",val);
4196 			if (delay_status_gs.send_reverb != val) {
4197 				delay_status_gs.send_reverb = val;
4198 				recompute_delay_status_gs();
4199 				init_ch_delay();
4200 			}
4201 			break;
4202 		case 0x21:	/* Velocity Sense Depth */
4203 			channel[ch].velocity_sense_depth = val;
4204 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Velocity Sense Depth (CH:%d VAL:%d)",ch,val);
4205 			break;
4206 		case 0x22:	/* Velocity Sense Offset */
4207 			channel[ch].velocity_sense_offset = val;
4208 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Velocity Sense Offset (CH:%d VAL:%d)",ch,val);
4209 			break;
4210 		case 0x23:	/* Insertion Effect ON/OFF */
4211 			if(!opt_insertion_effect) {break;}
4212 			if(channel[ch].insertion_effect != val) {
4213 				if(val) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EFX ON (CH:%d)",ch);}
4214 				else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EFX OFF (CH:%d)",ch);}
4215 			}
4216 			channel[ch].insertion_effect = val;
4217 			break;
4218 		case 0x24:	/* Assign Mode */
4219 			channel[ch].assign_mode = val;
4220 			if(val == 0) {
4221 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Single (CH:%d)",ch);
4222 			} else if(val == 1) {
4223 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Limited-Multi (CH:%d)",ch);
4224 			} else if(val == 2) {
4225 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Full-Multi (CH:%d)",ch);
4226 			}
4227 			break;
4228 		case 0x25:	/* TONE MAP-0 NUMBER */
4229 			channel[ch].tone_map0_number = val;
4230 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tone Map-0 Number (CH:%d VAL:%d)",ch,val);
4231 			break;
4232 		case 0x26:	/* Pitch Offset Fine */
4233 			channel[ch].pitch_offset_fine = (FLOAT_T)((((int32)val << 4) | (int32)val) - 0x80) / 10.0;
4234 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Pitch Offset Fine (CH:%d %3fHz)",ch,channel[ch].pitch_offset_fine);
4235 			break;
4236 		case 0x27:	/* Insertion Effect Parameter */
4237 			if(!opt_insertion_effect) {break;}
4238 			temp = insertion_effect_gs.type;
4239 			insertion_effect_gs.type_msb = val;
4240 			insertion_effect_gs.type = ((int32)insertion_effect_gs.type_msb << 8) | (int32)insertion_effect_gs.type_lsb;
4241 			if(temp == insertion_effect_gs.type) {
4242 				recompute_insertion_effect_gs();
4243 			} else {
4244 				realloc_insertion_effect_gs();
4245 			}
4246 			break;
4247 		case 0x28:	/* Insertion Effect Parameter */
4248 			if(!opt_insertion_effect) {break;}
4249 			temp = insertion_effect_gs.type;
4250 			insertion_effect_gs.type_lsb = val;
4251 			insertion_effect_gs.type = ((int32)insertion_effect_gs.type_msb << 8) | (int32)insertion_effect_gs.type_lsb;
4252 			if(temp == insertion_effect_gs.type) {
4253 				recompute_insertion_effect_gs();
4254 			} else {
4255 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "EFX TYPE (%02X %02X)", insertion_effect_gs.type_msb, insertion_effect_gs.type_lsb);
4256 				realloc_insertion_effect_gs();
4257 			}
4258 			break;
4259 		case 0x29:
4260 			insertion_effect_gs.parameter[0] = val;
4261 			recompute_insertion_effect_gs();
4262 			break;
4263 		case 0x2A:
4264 			insertion_effect_gs.parameter[1] = val;
4265 			recompute_insertion_effect_gs();
4266 			break;
4267 		case 0x2B:
4268 			insertion_effect_gs.parameter[2] = val;
4269 			recompute_insertion_effect_gs();
4270 			break;
4271 		case 0x2C:
4272 			insertion_effect_gs.parameter[3] = val;
4273 			recompute_insertion_effect_gs();
4274 			break;
4275 		case 0x2D:
4276 			insertion_effect_gs.parameter[4] = val;
4277 			recompute_insertion_effect_gs();
4278 			break;
4279 		case 0x2E:
4280 			insertion_effect_gs.parameter[5] = val;
4281 			recompute_insertion_effect_gs();
4282 			break;
4283 		case 0x2F:
4284 			insertion_effect_gs.parameter[6] = val;
4285 			recompute_insertion_effect_gs();
4286 			break;
4287 		case 0x30:
4288 			insertion_effect_gs.parameter[7] = val;
4289 			recompute_insertion_effect_gs();
4290 			break;
4291 		case 0x31:
4292 			insertion_effect_gs.parameter[8] = val;
4293 			recompute_insertion_effect_gs();
4294 			break;
4295 		case 0x32:
4296 			insertion_effect_gs.parameter[9] = val;
4297 			recompute_insertion_effect_gs();
4298 			break;
4299 		case 0x33:
4300 			insertion_effect_gs.parameter[10] = val;
4301 			recompute_insertion_effect_gs();
4302 			break;
4303 		case 0x34:
4304 			insertion_effect_gs.parameter[11] = val;
4305 			recompute_insertion_effect_gs();
4306 			break;
4307 		case 0x35:
4308 			insertion_effect_gs.parameter[12] = val;
4309 			recompute_insertion_effect_gs();
4310 			break;
4311 		case 0x36:
4312 			insertion_effect_gs.parameter[13] = val;
4313 			recompute_insertion_effect_gs();
4314 			break;
4315 		case 0x37:
4316 			insertion_effect_gs.parameter[14] = val;
4317 			recompute_insertion_effect_gs();
4318 			break;
4319 		case 0x38:
4320 			insertion_effect_gs.parameter[15] = val;
4321 			recompute_insertion_effect_gs();
4322 			break;
4323 		case 0x39:
4324 			insertion_effect_gs.parameter[16] = val;
4325 			recompute_insertion_effect_gs();
4326 			break;
4327 		case 0x3A:
4328 			insertion_effect_gs.parameter[17] = val;
4329 			recompute_insertion_effect_gs();
4330 			break;
4331 		case 0x3B:
4332 			insertion_effect_gs.parameter[18] = val;
4333 			recompute_insertion_effect_gs();
4334 			break;
4335 		case 0x3C:
4336 			insertion_effect_gs.parameter[19] = val;
4337 			recompute_insertion_effect_gs();
4338 			break;
4339 		case 0x3D:
4340 			insertion_effect_gs.send_reverb = val;
4341 			recompute_insertion_effect_gs();
4342 			break;
4343 		case 0x3E:
4344 			insertion_effect_gs.send_chorus = val;
4345 			recompute_insertion_effect_gs();
4346 			break;
4347 		case 0x3F:
4348 			insertion_effect_gs.send_delay = val;
4349 			recompute_insertion_effect_gs();
4350 			break;
4351 		case 0x40:
4352 			insertion_effect_gs.control_source1 = val;
4353 			recompute_insertion_effect_gs();
4354 			break;
4355 		case 0x41:
4356 			insertion_effect_gs.control_depth1 = val;
4357 			recompute_insertion_effect_gs();
4358 			break;
4359 		case 0x42:
4360 			insertion_effect_gs.control_source2 = val;
4361 			recompute_insertion_effect_gs();
4362 			break;
4363 		case 0x43:
4364 			insertion_effect_gs.control_depth2 = val;
4365 			recompute_insertion_effect_gs();
4366 			break;
4367 		case 0x44:
4368 			insertion_effect_gs.send_eq_switch = val;
4369 			recompute_insertion_effect_gs();
4370 			break;
4371 		case 0x45:	/* Rx. Channel */
4372 			reset_controllers(ch);
4373 			redraw_controllers(ch);
4374 			all_notes_off(ch);
4375 			if (val == 0x80)
4376 				remove_channel_layer(ch);
4377 			else
4378 				add_channel_layer(ch, val);
4379 			break;
4380 		case 0x46:	/* Channel Msg Rx Port */
4381 			reset_controllers(ch);
4382 			redraw_controllers(ch);
4383 			all_notes_off(ch);
4384 			channel[ch].port_select = val;
4385 			break;
4386 		case 0x47:	/* Play Note Number */
4387 			if (channel[ch].drums[note] == NULL)
4388 				play_midi_setup_drums(ch, note);
4389 			channel[ch].drums[note]->play_note = val;
4390 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
4391 				"Drum Instrument Play Note (CH:%d NOTE:%d VAL:%d)",
4392 				ch, note, channel[ch].drums[note]->play_note);
4393 			channel[ch].pitchfactor = 0;
4394 			break;
4395 		default:
4396 			break;
4397 		}
4398 		return;
4399 	} else if(ev == ME_SYSEX_XG_LSB) {	/* XG system exclusive message */
4400 		msb = channel[ch].sysex_xg_msb_addr;
4401 		note = channel[ch].sysex_xg_msb_val;
4402 		if (note == 3 && msb == 0) {	/* Effect 2 */
4403 		note = 0;	/* force insertion effect num 0 ?? */
4404 		if (note >= XG_INSERTION_EFFECT_NUM || note < 0) {return;}
4405 		switch(b)
4406 		{
4407 		case 0x00:	/* Insertion Effect Type MSB */
4408 			if (insertion_effect_xg[note].type_msb != val) {
4409 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Type MSB (%d %02X)", note, val);
4410 				insertion_effect_xg[note].type_msb = val;
4411 				realloc_effect_xg(&insertion_effect_xg[note]);
4412 			}
4413 			break;
4414 		case 0x01:	/* Insertion Effect Type LSB */
4415 			if (insertion_effect_xg[note].type_lsb != val) {
4416 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Type LSB (%d %02X)", note, val);
4417 				insertion_effect_xg[note].type_lsb = val;
4418 				realloc_effect_xg(&insertion_effect_xg[note]);
4419 			}
4420 			break;
4421 		case 0x02:	/* Insertion Effect Parameter 1 - 10 */
4422 		case 0x03:
4423 		case 0x04:
4424 		case 0x05:
4425 		case 0x06:
4426 		case 0x07:
4427 		case 0x08:
4428 		case 0x09:
4429 		case 0x0A:
4430 		case 0x0B:
4431 			if (insertion_effect_xg[note].use_msb) {break;}
4432 			temp = b - 0x02;
4433 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Parameter %d (%d %d)", temp + 1, note, val);
4434 			if (insertion_effect_xg[note].param_lsb[temp] != val) {
4435 				insertion_effect_xg[note].param_lsb[temp] = val;
4436 				recompute_effect_xg(&insertion_effect_xg[note]);
4437 			}
4438 			break;
4439 		case 0x0C:	/* Insertion Effect Part */
4440 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Part (%d %d)", note, val);
4441 			if (insertion_effect_xg[note].part != val) {
4442 				insertion_effect_xg[note].part = val;
4443 				recompute_effect_xg(&insertion_effect_xg[note]);
4444 			}
4445 			break;
4446 		case 0x0D:	/* MW Insertion Control Depth */
4447 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MW Insertion Control Depth (%d %d)", note, val);
4448 			if (insertion_effect_xg[note].mw_depth != val) {
4449 				insertion_effect_xg[note].mw_depth = val;
4450 				recompute_effect_xg(&insertion_effect_xg[note]);
4451 			}
4452 			break;
4453 		case 0x0E:	/* BEND Insertion Control Depth */
4454 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Insertion Control Depth (%d %d)", note, val);
4455 			if (insertion_effect_xg[note].bend_depth != val) {
4456 				insertion_effect_xg[note].bend_depth = val;
4457 				recompute_effect_xg(&insertion_effect_xg[note]);
4458 			}
4459 			break;
4460 		case 0x0F:	/* CAT Insertion Control Depth */
4461 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAT Insertion Control Depth (%d %d)", note, val);
4462 			if (insertion_effect_xg[note].cat_depth != val) {
4463 				insertion_effect_xg[note].cat_depth = val;
4464 				recompute_effect_xg(&insertion_effect_xg[note]);
4465 			}
4466 			break;
4467 		case 0x10:	/* AC1 Insertion Control Depth */
4468 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC1 Insertion Control Depth (%d %d)", note, val);
4469 			if (insertion_effect_xg[note].ac1_depth != val) {
4470 				insertion_effect_xg[note].ac1_depth = val;
4471 				recompute_effect_xg(&insertion_effect_xg[note]);
4472 			}
4473 			break;
4474 		case 0x11:	/* AC2 Insertion Control Depth */
4475 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC2 Insertion Control Depth (%d %d)", note, val);
4476 			if (insertion_effect_xg[note].ac2_depth != val) {
4477 				insertion_effect_xg[note].ac2_depth = val;
4478 				recompute_effect_xg(&insertion_effect_xg[note]);
4479 			}
4480 			break;
4481 		case 0x12:	/* CBC1 Insertion Control Depth */
4482 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC1 Insertion Control Depth (%d %d)", note, val);
4483 			if (insertion_effect_xg[note].cbc1_depth != val) {
4484 				insertion_effect_xg[note].cbc1_depth = val;
4485 				recompute_effect_xg(&insertion_effect_xg[note]);
4486 			}
4487 			break;
4488 		case 0x13:	/* CBC2 Insertion Control Depth */
4489 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC2 Insertion Control Depth (%d %d)", note, val);
4490 			if (insertion_effect_xg[note].cbc2_depth != val) {
4491 				insertion_effect_xg[note].cbc2_depth = val;
4492 				recompute_effect_xg(&insertion_effect_xg[note]);
4493 			}
4494 			break;
4495 		case 0x20:	/* Insertion Effect Parameter 11 - 16 */
4496 		case 0x21:
4497 		case 0x22:
4498 		case 0x23:
4499 		case 0x24:
4500 		case 0x25:
4501 			temp = b - 0x20 + 10;
4502 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Parameter %d (%d %d)", temp + 1, note, val);
4503 			if (insertion_effect_xg[note].param_lsb[temp] != val) {
4504 				insertion_effect_xg[note].param_lsb[temp] = val;
4505 				recompute_effect_xg(&insertion_effect_xg[note]);
4506 			}
4507 			break;
4508 		case 0x30:	/* Insertion Effect Parameter 1 - 10 MSB */
4509 		case 0x32:
4510 		case 0x34:
4511 		case 0x36:
4512 		case 0x38:
4513 		case 0x3A:
4514 		case 0x3C:
4515 		case 0x3E:
4516 		case 0x40:
4517 		case 0x42:
4518 			if (!insertion_effect_xg[note].use_msb) {break;}
4519 			temp = (b - 0x30) / 2;
4520 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Parameter %d MSB (%d %d)", temp + 1, note, val);
4521 			if (insertion_effect_xg[note].param_msb[temp] != val) {
4522 				insertion_effect_xg[note].param_msb[temp] = val;
4523 				recompute_effect_xg(&insertion_effect_xg[note]);
4524 			}
4525 			break;
4526 		case 0x31:	/* Insertion Effect Parameter 1 - 10 LSB */
4527 		case 0x33:
4528 		case 0x35:
4529 		case 0x37:
4530 		case 0x39:
4531 		case 0x3B:
4532 		case 0x3D:
4533 		case 0x3F:
4534 		case 0x41:
4535 		case 0x43:
4536 			if (!insertion_effect_xg[note].use_msb) {break;}
4537 			temp = (b - 0x31) / 2;
4538 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Insertion Effect Parameter %d LSB (%d %d)", temp + 1, note, val);
4539 			if (insertion_effect_xg[note].param_lsb[temp] != val) {
4540 				insertion_effect_xg[note].param_lsb[temp] = val;
4541 				recompute_effect_xg(&insertion_effect_xg[note]);
4542 			}
4543 			break;
4544 		default:
4545 			break;
4546 		}
4547 		} else if (note == 2 && msb == 1) {	/* Effect 1 */
4548 		note = 0;	/* force variation effect num 0 ?? */
4549 		switch(b)
4550 		{
4551 		case 0x00:	/* Reverb Type MSB */
4552 			if (reverb_status_xg.type_msb != val) {
4553 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type MSB (%02X)", val);
4554 				reverb_status_xg.type_msb = val;
4555 				realloc_effect_xg(&reverb_status_xg);
4556 			}
4557 			break;
4558 		case 0x01:	/* Reverb Type LSB */
4559 			if (reverb_status_xg.type_lsb != val) {
4560 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type LSB (%02X)", val);
4561 				reverb_status_xg.type_lsb = val;
4562 				realloc_effect_xg(&reverb_status_xg);
4563 			}
4564 			break;
4565 		case 0x02:	/* Reverb Parameter 1 - 10 */
4566 		case 0x03:
4567 		case 0x04:
4568 		case 0x05:
4569 		case 0x06:
4570 		case 0x07:
4571 		case 0x08:
4572 		case 0x09:
4573 		case 0x0A:
4574 		case 0x0B:
4575 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Parameter %d (%d)", b - 0x02 + 1, val);
4576 			if (reverb_status_xg.param_lsb[b - 0x02] != val) {
4577 				reverb_status_xg.param_lsb[b - 0x02] = val;
4578 				recompute_effect_xg(&reverb_status_xg);
4579 			}
4580 			break;
4581 		case 0x0C:	/* Reverb Return */
4582 #if 0	/* XG specific reverb is not currently implemented */
4583 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Return (%d)", val);
4584 			if (reverb_status_xg.ret != val) {
4585 				reverb_status_xg.ret = val;
4586 				recompute_effect_xg(&reverb_status_xg);
4587 			}
4588 #else	/* use GS reverb instead */
4589 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Return (%d)", val);
4590 			if (reverb_status_gs.level != val) {
4591 				reverb_status_gs.level = val;
4592 				recompute_reverb_status_gs();
4593 				init_reverb();
4594 			}
4595 #endif
4596 			break;
4597 		case 0x0D:	/* Reverb Pan */
4598 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Pan (%d)", val);
4599 			if (reverb_status_xg.pan != val) {
4600 				reverb_status_xg.pan = val;
4601 				recompute_effect_xg(&reverb_status_xg);
4602 			}
4603 			break;
4604 		case 0x10:	/* Reverb Parameter 11 - 16 */
4605 		case 0x11:
4606 		case 0x12:
4607 		case 0x13:
4608 		case 0x14:
4609 		case 0x15:
4610 			temp = b - 0x10 + 10;
4611 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Parameter %d (%d)", temp + 1, val);
4612 			if (reverb_status_xg.param_lsb[temp] != val) {
4613 				reverb_status_xg.param_lsb[temp] = val;
4614 				recompute_effect_xg(&reverb_status_xg);
4615 			}
4616 			break;
4617 		case 0x20:	/* Chorus Type MSB */
4618 			if (chorus_status_xg.type_msb != val) {
4619 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type MSB (%02X)", val);
4620 				chorus_status_xg.type_msb = val;
4621 				realloc_effect_xg(&chorus_status_xg);
4622 			}
4623 			break;
4624 		case 0x21:	/* Chorus Type LSB */
4625 			if (chorus_status_xg.type_lsb != val) {
4626 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type LSB (%02X)", val);
4627 				chorus_status_xg.type_lsb = val;
4628 				realloc_effect_xg(&chorus_status_xg);
4629 			}
4630 			break;
4631 		case 0x22:	/* Chorus Parameter 1 - 10 */
4632 		case 0x23:
4633 		case 0x24:
4634 		case 0x25:
4635 		case 0x26:
4636 		case 0x27:
4637 		case 0x28:
4638 		case 0x29:
4639 		case 0x2A:
4640 		case 0x2B:
4641 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Parameter %d (%d)", b - 0x22 + 1, val);
4642 			if (chorus_status_xg.param_lsb[b - 0x22] != val) {
4643 				chorus_status_xg.param_lsb[b - 0x22] = val;
4644 				recompute_effect_xg(&chorus_status_xg);
4645 			}
4646 			break;
4647 		case 0x2C:	/* Chorus Return */
4648 #if 0	/* XG specific chorus is not currently implemented */
4649 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Return (%d)", val);
4650 			if (chorus_status_xg.ret != val) {
4651 				chorus_status_xg.ret = val;
4652 				recompute_effect_xg(&chorus_status_xg);
4653 			}
4654 #else	/* use GS chorus instead */
4655 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Return (%d)", val);
4656 			if (chorus_status_gs.level != val) {
4657 				chorus_status_gs.level = val;
4658 				recompute_chorus_status_gs();
4659 				init_ch_chorus();
4660 			}
4661 #endif
4662 			break;
4663 		case 0x2D:	/* Chorus Pan */
4664 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Pan (%d)", val);
4665 			if (chorus_status_xg.pan != val) {
4666 				chorus_status_xg.pan = val;
4667 				recompute_effect_xg(&chorus_status_xg);
4668 			}
4669 			break;
4670 		case 0x2E:	/* Send Chorus To Reverb */
4671 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Send Chorus To Reverb (%d)", val);
4672 			if (chorus_status_xg.send_reverb != val) {
4673 				chorus_status_xg.send_reverb = val;
4674 				recompute_effect_xg(&chorus_status_xg);
4675 			}
4676 			break;
4677 		case 0x30:	/* Chorus Parameter 11 - 16 */
4678 		case 0x31:
4679 		case 0x32:
4680 		case 0x33:
4681 		case 0x34:
4682 		case 0x35:
4683 			temp = b - 0x30 + 10;
4684 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Parameter %d (%d)", temp + 1, val);
4685 			if (chorus_status_xg.param_lsb[temp] != val) {
4686 				chorus_status_xg.param_lsb[temp] = val;
4687 				recompute_effect_xg(&chorus_status_xg);
4688 			}
4689 			break;
4690 		case 0x40:	/* Variation Type MSB */
4691 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4692 			if (variation_effect_xg[note].type_msb != val) {
4693 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Type MSB (%02X)", val);
4694 				variation_effect_xg[note].type_msb = val;
4695 				realloc_effect_xg(&variation_effect_xg[note]);
4696 			}
4697 			break;
4698 		case 0x41:	/* Variation Type LSB */
4699 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4700 			if (variation_effect_xg[note].type_lsb != val) {
4701 				ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Type LSB (%02X)", val);
4702 				variation_effect_xg[note].type_lsb = val;
4703 				realloc_effect_xg(&variation_effect_xg[note]);
4704 			}
4705 			break;
4706 		case 0x42:	/* Variation Parameter 1 - 10 MSB */
4707 		case 0x44:
4708 		case 0x46:
4709 		case 0x48:
4710 		case 0x4A:
4711 		case 0x4C:
4712 		case 0x4E:
4713 		case 0x50:
4714 		case 0x52:
4715 		case 0x54:
4716 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4717 			temp = (b - 0x42) / 2;
4718 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Parameter %d MSB (%d)", temp, val);
4719 			if (variation_effect_xg[note].param_msb[temp] != val) {
4720 				variation_effect_xg[note].param_msb[temp] = val;
4721 				recompute_effect_xg(&variation_effect_xg[note]);
4722 			}
4723 			break;
4724 		case 0x43:	/* Variation Parameter 1 - 10 LSB */
4725 		case 0x45:
4726 		case 0x47:
4727 		case 0x49:
4728 		case 0x4B:
4729 		case 0x4D:
4730 		case 0x4F:
4731 		case 0x51:
4732 		case 0x53:
4733 		case 0x55:
4734 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4735 			temp = (b - 0x43) / 2;
4736 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Parameter %d LSB (%d)", temp, val);
4737 			if (variation_effect_xg[note].param_lsb[temp] != val) {
4738 				variation_effect_xg[note].param_lsb[temp] = val;
4739 				recompute_effect_xg(&variation_effect_xg[note]);
4740 			}
4741 			break;
4742 		case 0x56:	/* Variation Return */
4743 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4744 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Return (%d)", val);
4745 			if (variation_effect_xg[note].ret != val) {
4746 				variation_effect_xg[note].ret = val;
4747 				recompute_effect_xg(&variation_effect_xg[note]);
4748 			}
4749 			break;
4750 		case 0x57:	/* Variation Pan */
4751 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4752 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Pan (%d)", val);
4753 			if (variation_effect_xg[note].pan != val) {
4754 				variation_effect_xg[note].pan = val;
4755 				recompute_effect_xg(&variation_effect_xg[note]);
4756 			}
4757 			break;
4758 		case 0x58:	/* Send Variation To Reverb */
4759 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4760 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Send Variation To Reverb (%d)", val);
4761 			if (variation_effect_xg[note].send_reverb != val) {
4762 				variation_effect_xg[note].send_reverb = val;
4763 				recompute_effect_xg(&variation_effect_xg[note]);
4764 			}
4765 			break;
4766 		case 0x59:	/* Send Variation To Chorus */
4767 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4768 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Send Variation To Chorus (%d)", val);
4769 			if (variation_effect_xg[note].send_chorus != val) {
4770 				variation_effect_xg[note].send_chorus = val;
4771 				recompute_effect_xg(&variation_effect_xg[note]);
4772 			}
4773 			break;
4774 		case 0x5A:	/* Variation Connection */
4775 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4776 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Connection (%d)", val);
4777 			if (variation_effect_xg[note].connection != val) {
4778 				variation_effect_xg[note].connection = val;
4779 				recompute_effect_xg(&variation_effect_xg[note]);
4780 			}
4781 			break;
4782 		case 0x5B:	/* Variation Part */
4783 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4784 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Part (%d)", val);
4785 			if (variation_effect_xg[note].part != val) {
4786 				variation_effect_xg[note].part = val;
4787 				recompute_effect_xg(&variation_effect_xg[note]);
4788 			}
4789 			break;
4790 		case 0x5C:	/* MW Variation Control Depth */
4791 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4792 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "MW Variation Control Depth (%d)", val);
4793 			if (variation_effect_xg[note].mw_depth != val) {
4794 				variation_effect_xg[note].mw_depth = val;
4795 				recompute_effect_xg(&variation_effect_xg[note]);
4796 			}
4797 			break;
4798 		case 0x5D:	/* BEND Variation Control Depth */
4799 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4800 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Variation Control Depth (%d)", val);
4801 			if (variation_effect_xg[note].bend_depth != val) {
4802 				variation_effect_xg[note].bend_depth = val;
4803 				recompute_effect_xg(&variation_effect_xg[note]);
4804 			}
4805 			break;
4806 		case 0x5E:	/* CAT Variation Control Depth */
4807 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4808 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAT Variation Control Depth (%d)", val);
4809 			if (variation_effect_xg[note].cat_depth != val) {
4810 				variation_effect_xg[note].cat_depth = val;
4811 				recompute_effect_xg(&variation_effect_xg[note]);
4812 			}
4813 			break;
4814 		case 0x5F:	/* AC1 Variation Control Depth */
4815 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4816 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC1 Variation Control Depth (%d)", val);
4817 			if (variation_effect_xg[note].ac1_depth != val) {
4818 				variation_effect_xg[note].ac1_depth = val;
4819 				recompute_effect_xg(&variation_effect_xg[note]);
4820 			}
4821 			break;
4822 		case 0x60:	/* AC2 Variation Control Depth */
4823 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4824 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC2 Variation Control Depth (%d)", val);
4825 			if (variation_effect_xg[note].ac2_depth != val) {
4826 				variation_effect_xg[note].ac2_depth = val;
4827 				recompute_effect_xg(&variation_effect_xg[note]);
4828 			}
4829 			break;
4830 		case 0x61:	/* CBC1 Variation Control Depth */
4831 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4832 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC1 Variation Control Depth (%d)", val);
4833 			if (variation_effect_xg[note].cbc1_depth != val) {
4834 				variation_effect_xg[note].cbc1_depth = val;
4835 				recompute_effect_xg(&variation_effect_xg[note]);
4836 			}
4837 			break;
4838 		case 0x62:	/* CBC2 Variation Control Depth */
4839 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4840 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC2 Variation Control Depth (%d)", val);
4841 			if (variation_effect_xg[note].cbc2_depth != val) {
4842 				variation_effect_xg[note].cbc2_depth = val;
4843 				recompute_effect_xg(&variation_effect_xg[note]);
4844 			}
4845 			break;
4846 		case 0x70:	/* Variation Parameter 11 - 16 */
4847 		case 0x71:
4848 		case 0x72:
4849 		case 0x73:
4850 		case 0x74:
4851 		case 0x75:
4852 			temp = b - 0x70 + 10;
4853 			if (note >= XG_VARIATION_EFFECT_NUM || note < 0) {break;}
4854 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Variation Parameter %d (%d)", temp + 1, val);
4855 			if (variation_effect_xg[note].param_lsb[temp] != val) {
4856 				variation_effect_xg[note].param_lsb[temp] = val;
4857 				recompute_effect_xg(&variation_effect_xg[note]);
4858 			}
4859 			break;
4860 		default:
4861 			break;
4862 		}
4863 		} else if (note == 2 && msb == 40) {	/* Multi EQ */
4864 		switch(b)
4865 		{
4866 		case 0x00:	/* EQ type */
4867 			if(opt_eq_control) {
4868 				if(val == 0) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ type (0: Flat)");}
4869 				else if(val == 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ type (1: Jazz)");}
4870 				else if(val == 2) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ type (2: Pops)");}
4871 				else if(val == 3) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ type (3: Rock)");}
4872 				else if(val == 4) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ type (4: Concert)");}
4873 				multi_eq_xg.type = val;
4874 				set_multi_eq_type_xg(val);
4875 				recompute_multi_eq_xg();
4876 			}
4877 			break;
4878 		case 0x01:	/* EQ gain1 */
4879 			if(opt_eq_control) {
4880 				if(val > 0x4C) {val = 0x4C;}
4881 				else if(val < 0x34) {val = 0x34;}
4882 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ gain1 (%d dB)", val - 0x40);
4883 				multi_eq_xg.gain1 = val;
4884 				recompute_multi_eq_xg();
4885 			}
4886 			break;
4887 		case 0x02:	/* EQ frequency1 */
4888 			if(opt_eq_control) {
4889 				if(val > 60) {val = 60;}
4890 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ frequency1 (%d Hz)", (int32)eq_freq_table_xg[val]);
4891 				multi_eq_xg.freq1 = val;
4892 				recompute_multi_eq_xg();
4893 			}
4894 			break;
4895 		case 0x03:	/* EQ Q1 */
4896 			if(opt_eq_control) {
4897 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ Q1 (%f)", (double)val / 10.0);
4898 				multi_eq_xg.q1 = val;
4899 				recompute_multi_eq_xg();
4900 			}
4901 			break;
4902 		case 0x04:	/* EQ shape1 */
4903 			if(opt_eq_control) {
4904 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ shape1 (%d)", val);
4905 				multi_eq_xg.shape1 = val;
4906 				recompute_multi_eq_xg();
4907 			}
4908 			break;
4909 		case 0x05:	/* EQ gain2 */
4910 			if(opt_eq_control) {
4911 				if(val > 0x4C) {val = 0x4C;}
4912 				else if(val < 0x34) {val = 0x34;}
4913 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ gain2 (%d dB)", val - 0x40);
4914 				multi_eq_xg.gain2 = val;
4915 				recompute_multi_eq_xg();
4916 			}
4917 			break;
4918 		case 0x06:	/* EQ frequency2 */
4919 			if(opt_eq_control) {
4920 				if(val > 60) {val = 60;}
4921 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ frequency2 (%d Hz)", (int32)eq_freq_table_xg[val]);
4922 				multi_eq_xg.freq2 = val;
4923 				recompute_multi_eq_xg();
4924 			}
4925 			break;
4926 		case 0x07:	/* EQ Q2 */
4927 			if(opt_eq_control) {
4928 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ Q2 (%f)", (double)val / 10.0);
4929 				multi_eq_xg.q2 = val;
4930 				recompute_multi_eq_xg();
4931 			}
4932 			break;
4933 		case 0x09:	/* EQ gain3 */
4934 			if(opt_eq_control) {
4935 				if(val > 0x4C) {val = 0x4C;}
4936 				else if(val < 0x34) {val = 0x34;}
4937 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ gain3 (%d dB)", val - 0x40);
4938 				multi_eq_xg.gain3 = val;
4939 				recompute_multi_eq_xg();
4940 			}
4941 			break;
4942 		case 0x0A:	/* EQ frequency3 */
4943 			if(opt_eq_control) {
4944 				if(val > 60) {val = 60;}
4945 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ frequency3 (%d Hz)", (int32)eq_freq_table_xg[val]);
4946 				multi_eq_xg.freq3 = val;
4947 				recompute_multi_eq_xg();
4948 			}
4949 			break;
4950 		case 0x0B:	/* EQ Q3 */
4951 			if(opt_eq_control) {
4952 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ Q3 (%f)", (double)val / 10.0);
4953 				multi_eq_xg.q3 = val;
4954 				recompute_multi_eq_xg();
4955 			}
4956 			break;
4957 		case 0x0D:	/* EQ gain4 */
4958 			if(opt_eq_control) {
4959 				if(val > 0x4C) {val = 0x4C;}
4960 				else if(val < 0x34) {val = 0x34;}
4961 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ gain4 (%d dB)", val - 0x40);
4962 				multi_eq_xg.gain4 = val;
4963 				recompute_multi_eq_xg();
4964 			}
4965 			break;
4966 		case 0x0E:	/* EQ frequency4 */
4967 			if(opt_eq_control) {
4968 				if(val > 60) {val = 60;}
4969 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ frequency4 (%d Hz)", (int32)eq_freq_table_xg[val]);
4970 				multi_eq_xg.freq4 = val;
4971 				recompute_multi_eq_xg();
4972 			}
4973 			break;
4974 		case 0x0F:	/* EQ Q4 */
4975 			if(opt_eq_control) {
4976 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ Q4 (%f)", (double)val / 10.0);
4977 				multi_eq_xg.q4 = val;
4978 				recompute_multi_eq_xg();
4979 			}
4980 			break;
4981 		case 0x11:	/* EQ gain5 */
4982 			if(opt_eq_control) {
4983 				if(val > 0x4C) {val = 0x4C;}
4984 				else if(val < 0x34) {val = 0x34;}
4985 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ gain5 (%d dB)", val - 0x40);
4986 				multi_eq_xg.gain5 = val;
4987 				recompute_multi_eq_xg();
4988 			}
4989 			break;
4990 		case 0x12:	/* EQ frequency5 */
4991 			if(opt_eq_control) {
4992 				if(val > 60) {val = 60;}
4993 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ frequency5 (%d Hz)", (int32)eq_freq_table_xg[val]);
4994 				multi_eq_xg.freq5 = val;
4995 				recompute_multi_eq_xg();
4996 			}
4997 			break;
4998 		case 0x13:	/* EQ Q5 */
4999 			if(opt_eq_control) {
5000 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ Q5 (%f)", (double)val / 10.0);
5001 				multi_eq_xg.q5 = val;
5002 				recompute_multi_eq_xg();
5003 			}
5004 			break;
5005 		case 0x14:	/* EQ shape5 */
5006 			if(opt_eq_control) {
5007 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ shape5 (%d)", val);
5008 				multi_eq_xg.shape5 = val;
5009 				recompute_multi_eq_xg();
5010 			}
5011 			break;
5012 		}
5013 		} else if (note == 8 && msb == 0) {	/* Multi Part */
5014 		switch(b)
5015 		{
5016 		case 0x99:	/* Rcv CHANNEL, remapped from 0x04 */
5017 			reset_controllers(ch);
5018 			redraw_controllers(ch);
5019 			all_notes_off(ch);
5020 			if (val == 0x7f)
5021 				remove_channel_layer(ch);
5022 			else {
5023 				if((ch < REDUCE_CHANNELS) != (val < REDUCE_CHANNELS)) {
5024 					channel[ch].port_select = ch < REDUCE_CHANNELS ? 1 : 0;
5025 				}
5026 				if((ch % REDUCE_CHANNELS) != (val % REDUCE_CHANNELS)) {
5027 					add_channel_layer(ch, val);
5028 				}
5029 			}
5030 			break;
5031 		case 0x06:	/* Same Note Number Key On Assign */
5032 			if(val == 0) {
5033 				channel[ch].assign_mode = 0;
5034 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Single (CH:%d)",ch);
5035 			} else if(val == 1) {
5036 				channel[ch].assign_mode = 2;
5037 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Multi (CH:%d)",ch);
5038 			} else if(val == 2) {
5039 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Inst is not supported. (CH:%d)",ch);
5040 			}
5041 			break;
5042 		case 0x11:	/* Dry Level */
5043 			channel[ch].dry_level = val;
5044 			ctl->cmsg(CMSG_INFO, VERB_NOISY, "Dry Level (CH:%d VAL:%d)", ch, val);
5045 			break;
5046 		}
5047 		} else if ((note & 0xF0) == 0x30) {	/* Drum Setup */
5048 		note = msb;
5049 		switch(b)
5050 		{
5051 		case 0x0E:	/* EG Decay1 */
5052 			if (channel[ch].drums[note] == NULL)
5053 				play_midi_setup_drums(ch, note);
5054 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5055 				"Drum Instrument EG Decay1 (CH:%d NOTE:%d VAL:%d)",
5056 				ch, note, val);
5057 			channel[ch].drums[note]->drum_envelope_rate[EG_DECAY1] = val;
5058 			break;
5059 		case 0x0F:	/* EG Decay2 */
5060 			if (channel[ch].drums[note] == NULL)
5061 				play_midi_setup_drums(ch, note);
5062 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5063 				"Drum Instrument EG Decay2 (CH:%d NOTE:%d VAL:%d)",
5064 				ch, note, val);
5065 			channel[ch].drums[note]->drum_envelope_rate[EG_DECAY2] = val;
5066 			break;
5067 		default:
5068 			break;
5069 		}
5070 		}
5071 		return;
5072 	}
5073 }
5074 
play_midi_prescan(MidiEvent * ev)5075 static void play_midi_prescan(MidiEvent *ev)
5076 {
5077     int i, j, k, ch, orig_ch, port_ch, offset, layered;
5078 
5079     if(opt_amp_compensation) {mainvolume_max = 0;}
5080     else {mainvolume_max = 0x7f;}
5081     compensation_ratio = 1.0;
5082 
5083     prescanning_flag = 1;
5084     change_system_mode(DEFAULT_SYSTEM_MODE);
5085     reset_midi(0);
5086     resamp_cache_reset();
5087 
5088 	while (ev->type != ME_EOT) {
5089 #ifndef SUPPRESS_CHANNEL_LAYER
5090 		orig_ch = ev->channel;
5091 		layered = ! IS_SYSEX_EVENT_TYPE(ev);
5092 		for (j = 0; j < MAX_CHANNELS; j += 16) {
5093 			port_ch = (orig_ch + j) % MAX_CHANNELS;
5094 			offset = port_ch & ~0xf;
5095 			for (k = offset; k < offset + 16; k++) {
5096 				if (! layered && (j || k != offset))
5097 					continue;
5098 				if (layered) {
5099 					if (! IS_SET_CHANNELMASK(
5100 							channel[k].channel_layer, port_ch)
5101 							|| channel[k].port_select != (orig_ch >> 4))
5102 						continue;
5103 					ev->channel = k;
5104 				}
5105 #endif
5106 	ch = ev->channel;
5107 
5108 	switch(ev->type)
5109 	{
5110 	  case ME_NOTEON:
5111 		note_on_prescan(ev);
5112 	    break;
5113 
5114 	  case ME_NOTEOFF:
5115 	    resamp_cache_refer_off(ch, MIDI_EVENT_NOTE(ev), ev->time);
5116 	    break;
5117 
5118 	  case ME_PORTAMENTO_TIME_MSB:
5119 	    channel[ch].portamento_time_msb = ev->a;
5120 	    break;
5121 
5122 	  case ME_PORTAMENTO_TIME_LSB:
5123 	    channel[ch].portamento_time_lsb = ev->a;
5124 	    break;
5125 
5126 	  case ME_PORTAMENTO:
5127 	    channel[ch].portamento = (ev->a >= 64);
5128 
5129 	  case ME_RESET_CONTROLLERS:
5130 	    reset_controllers(ch);
5131 	    resamp_cache_refer_alloff(ch, ev->time);
5132 	    break;
5133 
5134 	  case ME_PROGRAM:
5135 	    midi_program_change(ch, ev->a);
5136 	    break;
5137 
5138 	  case ME_TONE_BANK_MSB:
5139 	    channel[ch].bank_msb = ev->a;
5140 	    break;
5141 
5142 	  case ME_TONE_BANK_LSB:
5143 	    channel[ch].bank_lsb = ev->a;
5144 	    break;
5145 
5146 	  case ME_RESET:
5147 	    change_system_mode(ev->a);
5148 	    reset_midi(0);
5149 	    break;
5150 
5151 	  case ME_MASTER_TUNING:
5152 	  case ME_PITCHWHEEL:
5153 	  case ME_ALL_NOTES_OFF:
5154 	  case ME_ALL_SOUNDS_OFF:
5155 	  case ME_MONO:
5156 	  case ME_POLY:
5157 	    resamp_cache_refer_alloff(ch, ev->time);
5158 	    break;
5159 
5160 	  case ME_DRUMPART:
5161 	    if(midi_drumpart_change(ch, ev->a))
5162 		midi_program_change(ch, channel[ch].program);
5163 	    break;
5164 
5165 	  case ME_KEYSHIFT:
5166 	    resamp_cache_refer_alloff(ch, ev->time);
5167 	    channel[ch].key_shift = (int)ev->a - 0x40;
5168 	    break;
5169 
5170 	  case ME_SCALE_TUNING:
5171 		resamp_cache_refer_alloff(ch, ev->time);
5172 		channel[ch].scale_tuning[ev->a] = ev->b;
5173 		break;
5174 
5175 	  case ME_MAINVOLUME:
5176 	    if (ev->a > mainvolume_max) {
5177 	      mainvolume_max = ev->a;
5178 	      ctl->cmsg(CMSG_INFO,VERB_DEBUG,"ME_MAINVOLUME/max (CH:%d VAL:%#x)",ev->channel,ev->a);
5179 	    }
5180 	    break;
5181 	}
5182 #ifndef SUPPRESS_CHANNEL_LAYER
5183 			}
5184 		}
5185 		ev->channel = orig_ch;
5186 #endif
5187 	ev++;
5188     }
5189 
5190     /* calculate compensation ratio */
5191     if (0 < mainvolume_max && mainvolume_max < 0x7f) {
5192       compensation_ratio = pow((double)0x7f/(double)mainvolume_max, 4);
5193       ctl->cmsg(CMSG_INFO,VERB_DEBUG,"Compensation ratio:%lf",compensation_ratio);
5194     }
5195 
5196     for(i = 0; i < MAX_CHANNELS; i++)
5197 	resamp_cache_refer_alloff(i, ev->time);
5198     resamp_cache_create();
5199     prescanning_flag = 0;
5200 }
5201 
5202 /*! convert GS NRPN to vibrato rate ratio. */
5203 /* from 0 to 3.0. */
gs_cnv_vib_rate(int rate)5204 static double gs_cnv_vib_rate(int rate)
5205 {
5206 	double ratio;
5207 
5208 	if(rate == 0) {
5209 		ratio = 1.6 / 100.0;
5210 	} else if(rate == 64) {
5211 		ratio = 1.0;
5212 	} else if(rate <= 100) {
5213 		ratio = (double)rate * 1.6 / 100.0;
5214 	} else {
5215 		ratio = (double)(rate - 101) * 1.33 / 26.0 + 1.67;
5216 	}
5217 	return (1.0 / ratio);
5218 }
5219 
5220 /*! convert GS NRPN to vibrato depth. */
5221 /* from -9.6 cents to +9.45 cents. */
gs_cnv_vib_depth(int depth)5222 static int32 gs_cnv_vib_depth(int depth)
5223 {
5224 	double cent;
5225 	cent = (double)(depth - 64) * 0.15;
5226 
5227 	return (int32)(cent * 256.0 / 400.0);
5228 }
5229 
5230 /*! convert GS NRPN to vibrato delay. */
5231 /* from 0 ms to 5074 ms. */
gs_cnv_vib_delay(int delay)5232 static int32 gs_cnv_vib_delay(int delay)
5233 {
5234 	double ms;
5235 	ms = 0.2092 * exp(0.0795 * (double)delay);
5236 	if(delay == 0) {ms = 0;}
5237 	return (int32)((double)play_mode->rate * ms * 0.001);
5238 }
5239 
last_rpn_addr(int ch)5240 static int last_rpn_addr(int ch)
5241 {
5242 	int lsb, msb, addr, i;
5243 	struct rpn_tag_map_t *addrmap;
5244 	struct rpn_tag_map_t {
5245 		int addr, mask, tag;
5246 	};
5247 	static struct rpn_tag_map_t nrpn_addr_map[] = {
5248 		{0x0108, 0xffff, NRPN_ADDR_0108},
5249 		{0x0109, 0xffff, NRPN_ADDR_0109},
5250 		{0x010a, 0xffff, NRPN_ADDR_010A},
5251 		{0x0120, 0xffff, NRPN_ADDR_0120},
5252 		{0x0121, 0xffff, NRPN_ADDR_0121},
5253 		{0x0130, 0xffff, NRPN_ADDR_0130},
5254 		{0x0131, 0xffff, NRPN_ADDR_0131},
5255 		{0x0134, 0xffff, NRPN_ADDR_0134},
5256 		{0x0135, 0xffff, NRPN_ADDR_0135},
5257 		{0x0163, 0xffff, NRPN_ADDR_0163},
5258 		{0x0164, 0xffff, NRPN_ADDR_0164},
5259 		{0x0166, 0xffff, NRPN_ADDR_0166},
5260 		{0x1400, 0xff00, NRPN_ADDR_1400},
5261 		{0x1500, 0xff00, NRPN_ADDR_1500},
5262 		{0x1600, 0xff00, NRPN_ADDR_1600},
5263 		{0x1700, 0xff00, NRPN_ADDR_1700},
5264 		{0x1800, 0xff00, NRPN_ADDR_1800},
5265 		{0x1900, 0xff00, NRPN_ADDR_1900},
5266 		{0x1a00, 0xff00, NRPN_ADDR_1A00},
5267 		{0x1c00, 0xff00, NRPN_ADDR_1C00},
5268 		{0x1d00, 0xff00, NRPN_ADDR_1D00},
5269 		{0x1e00, 0xff00, NRPN_ADDR_1E00},
5270 		{0x1f00, 0xff00, NRPN_ADDR_1F00},
5271 		{0x3000, 0xff00, NRPN_ADDR_3000},
5272 		{0x3100, 0xff00, NRPN_ADDR_3100},
5273 		{0x3400, 0xff00, NRPN_ADDR_3400},
5274 		{0x3500, 0xff00, NRPN_ADDR_3500},
5275 		{-1, -1, 0}
5276 	};
5277 	static struct rpn_tag_map_t rpn_addr_map[] = {
5278 		{0x0000, 0xffff, RPN_ADDR_0000},
5279 		{0x0001, 0xffff, RPN_ADDR_0001},
5280 		{0x0002, 0xffff, RPN_ADDR_0002},
5281 		{0x0003, 0xffff, RPN_ADDR_0003},
5282 		{0x0004, 0xffff, RPN_ADDR_0004},
5283 		{0x0005, 0xffff, RPN_ADDR_0005},
5284 		{0x7f7f, 0xffff, RPN_ADDR_7F7F},
5285 		{0xffff, 0xffff, RPN_ADDR_FFFF},
5286 		{-1, -1}
5287 	};
5288 
5289 	if (channel[ch].nrpn == -1)
5290 		return -1;
5291 	lsb = channel[ch].lastlrpn;
5292 	msb = channel[ch].lastmrpn;
5293 	if (lsb == 0xff || msb == 0xff)
5294 		return -1;
5295 	addr = (msb << 8 | lsb);
5296 	if (channel[ch].nrpn)
5297 		addrmap = nrpn_addr_map;
5298 	else
5299 		addrmap = rpn_addr_map;
5300 	for (i = 0; addrmap[i].addr != -1; i++)
5301 		if (addrmap[i].addr == (addr & addrmap[i].mask))
5302 			return addrmap[i].tag;
5303 	return -1;
5304 }
5305 
update_rpn_map(int ch,int addr,int update_now)5306 static void update_rpn_map(int ch, int addr, int update_now)
5307 {
5308 	int val, drumflag, i, note;
5309 
5310 	val = channel[ch].rpnmap[addr];
5311 	drumflag = 0;
5312 	switch (addr) {
5313 	case NRPN_ADDR_0108:	/* Vibrato Rate */
5314 		if (opt_nrpn_vibrato) {
5315 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5316 					"Vibrato Rate (CH:%d VAL:%d)", ch, val - 64);
5317 			channel[ch].vibrato_ratio = gs_cnv_vib_rate(val);
5318 		}
5319 		if (update_now)
5320 			adjust_pitch(ch);
5321 		break;
5322 	case NRPN_ADDR_0109:	/* Vibrato Depth */
5323 		if (opt_nrpn_vibrato) {
5324 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5325 					"Vibrato Depth (CH:%d VAL:%d)", ch, val - 64);
5326 			channel[ch].vibrato_depth = gs_cnv_vib_depth(val);
5327 		}
5328 		if (update_now)
5329 			adjust_pitch(ch);
5330 		break;
5331 	case NRPN_ADDR_010A:	/* Vibrato Delay */
5332 		if (opt_nrpn_vibrato) {
5333 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5334 					"Vibrato Delay (CH:%d VAL:%d)", ch, val);
5335 			channel[ch].vibrato_delay = gs_cnv_vib_delay(val);
5336 		}
5337 		if (update_now)
5338 			adjust_pitch(ch);
5339 		break;
5340 	case NRPN_ADDR_0120:	/* Filter Cutoff Frequency */
5341 		if (opt_lpf_def) {
5342 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5343 					"Filter Cutoff (CH:%d VAL:%d)", ch, val - 64);
5344 			channel[ch].param_cutoff_freq = val - 64;
5345 		}
5346 		break;
5347 	case NRPN_ADDR_0121:	/* Filter Resonance */
5348 		if (opt_lpf_def) {
5349 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5350 					"Filter Resonance (CH:%d VAL:%d)", ch, val - 64);
5351 			channel[ch].param_resonance = val - 64;
5352 		}
5353 		break;
5354 	case NRPN_ADDR_0130:	/* EQ BASS */
5355 		if (opt_eq_control) {
5356 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ BASS (CH:%d %.2f dB)", ch, 0.19 * (double)(val - 0x40));
5357 			channel[ch].eq_xg.bass = val;
5358 			recompute_part_eq_xg(&(channel[ch].eq_xg));
5359 		}
5360 		break;
5361 	case NRPN_ADDR_0131:	/* EQ TREBLE */
5362 		if (opt_eq_control) {
5363 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ TREBLE (CH:%d %.2f dB)", ch, 0.19 * (double)(val - 0x40));
5364 			channel[ch].eq_xg.treble = val;
5365 			recompute_part_eq_xg(&(channel[ch].eq_xg));
5366 		}
5367 		break;
5368 	case NRPN_ADDR_0134:	/* EQ BASS frequency */
5369 		if (opt_eq_control) {
5370 			if(val < 4) {val = 4;}
5371 			else if(val > 40) {val = 40;}
5372 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ BASS frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
5373 			channel[ch].eq_xg.bass_freq = val;
5374 			recompute_part_eq_xg(&(channel[ch].eq_xg));
5375 		}
5376 		break;
5377 	case NRPN_ADDR_0135:	/* EQ TREBLE frequency */
5378 		if (opt_eq_control) {
5379 			if(val < 28) {val = 28;}
5380 			else if(val > 58) {val = 58;}
5381 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"EQ TREBLE frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
5382 			channel[ch].eq_xg.treble_freq = val;
5383 			recompute_part_eq_xg(&(channel[ch].eq_xg));
5384 		}
5385 		break;
5386 	case NRPN_ADDR_0163:	/* Attack Time */
5387 		if (opt_tva_attack) {set_envelope_time(ch, val, EG_ATTACK);}
5388 		break;
5389 	case NRPN_ADDR_0164:	/* EG Decay Time */
5390 		if (opt_tva_decay) {set_envelope_time(ch, val, EG_DECAY);}
5391 		break;
5392 	case NRPN_ADDR_0166:	/* EG Release Time */
5393 		if (opt_tva_release) {set_envelope_time(ch, val, EG_RELEASE);}
5394 		break;
5395 	case NRPN_ADDR_1400:	/* Drum Filter Cutoff (XG) */
5396 		drumflag = 1;
5397 		note = channel[ch].lastlrpn;
5398 		if (channel[ch].drums[note] == NULL)
5399 			play_midi_setup_drums(ch, note);
5400 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5401 				"Drum Instrument Filter Cutoff (CH:%d NOTE:%d VAL:%d)",
5402 				ch, note, val);
5403 		channel[ch].drums[note]->drum_cutoff_freq = val - 64;
5404 		break;
5405 	case NRPN_ADDR_1500:	/* Drum Filter Resonance (XG) */
5406 		drumflag = 1;
5407 		note = channel[ch].lastlrpn;
5408 		if (channel[ch].drums[note] == NULL)
5409 			play_midi_setup_drums(ch, note);
5410 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5411 				"Drum Instrument Filter Resonance (CH:%d NOTE:%d VAL:%d)",
5412 				ch, note, val);
5413 		channel[ch].drums[note]->drum_resonance = val - 64;
5414 		break;
5415 	case NRPN_ADDR_1600:	/* Drum EG Attack Time (XG) */
5416 		drumflag = 1;
5417 		if (opt_tva_attack) {
5418 			val = val & 0x7f;
5419 			note = channel[ch].lastlrpn;
5420 			if (channel[ch].drums[note] == NULL)
5421 				play_midi_setup_drums(ch, note);
5422 			val	-= 64;
5423 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5424 					"Drum Instrument Attack Time (CH:%d NOTE:%d VAL:%d)",
5425 					ch, note, val);
5426 			channel[ch].drums[note]->drum_envelope_rate[EG_ATTACK] = val;
5427 		}
5428 		break;
5429 	case NRPN_ADDR_1700:	/* Drum EG Decay Time (XG) */
5430 		drumflag = 1;
5431 		if (opt_tva_decay) {
5432 			val = val & 0x7f;
5433 			note = channel[ch].lastlrpn;
5434 			if (channel[ch].drums[note] == NULL)
5435 				play_midi_setup_drums(ch, note);
5436 			val	-= 64;
5437 			ctl->cmsg(CMSG_INFO, VERB_NOISY,
5438 					"Drum Instrument Decay Time (CH:%d NOTE:%d VAL:%d)",
5439 					ch, note, val);
5440 			channel[ch].drums[note]->drum_envelope_rate[EG_DECAY1] =
5441 				channel[ch].drums[note]->drum_envelope_rate[EG_DECAY2] = val;
5442 		}
5443 		break;
5444 	case NRPN_ADDR_1800:	/* Coarse Pitch of Drum (GS) */
5445 		drumflag = 1;
5446 		note = channel[ch].lastlrpn;
5447 		if (channel[ch].drums[note] == NULL)
5448 			play_midi_setup_drums(ch, note);
5449 		channel[ch].drums[note]->coarse = val - 64;
5450 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5451 			"Drum Instrument Pitch Coarse (CH:%d NOTE:%d VAL:%d)",
5452 			ch, note, channel[ch].drums[note]->coarse);
5453 		channel[ch].pitchfactor = 0;
5454 		break;
5455 	case NRPN_ADDR_1900:	/* Fine Pitch of Drum (XG) */
5456 		drumflag = 1;
5457 		note = channel[ch].lastlrpn;
5458 		if (channel[ch].drums[note] == NULL)
5459 			play_midi_setup_drums(ch, note);
5460 		channel[ch].drums[note]->fine = val - 64;
5461 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5462 				"Drum Instrument Pitch Fine (CH:%d NOTE:%d VAL:%d)",
5463 				ch, note, channel[ch].drums[note]->fine);
5464 		channel[ch].pitchfactor = 0;
5465 		break;
5466 	case NRPN_ADDR_1A00:	/* Level of Drum */
5467 		drumflag = 1;
5468 		note = channel[ch].lastlrpn;
5469 		if (channel[ch].drums[note] == NULL)
5470 			play_midi_setup_drums(ch, note);
5471 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5472 				"Drum Instrument TVA Level (CH:%d NOTE:%d VAL:%d)",
5473 				ch, note, val);
5474 		channel[ch].drums[note]->drum_level =
5475 				calc_drum_tva_level(ch, note, val);
5476 		break;
5477 	case NRPN_ADDR_1C00:	/* Panpot of Drum */
5478 		drumflag = 1;
5479 		note = channel[ch].lastlrpn;
5480 		if (channel[ch].drums[note] == NULL)
5481 			play_midi_setup_drums(ch, note);
5482 		if(val == 0) {
5483 			val = int_rand(128);
5484 			channel[ch].drums[note]->pan_random = 1;
5485 		} else
5486 			channel[ch].drums[note]->pan_random = 0;
5487 		channel[ch].drums[note]->drum_panning = val;
5488 		if (update_now && adjust_panning_immediately
5489 				&& ! channel[ch].pan_random)
5490 			adjust_drum_panning(ch, note);
5491 		break;
5492 	case NRPN_ADDR_1D00:	/* Reverb Send Level of Drum */
5493 		drumflag = 1;
5494 		note = channel[ch].lastlrpn;
5495 		if (channel[ch].drums[note] == NULL)
5496 			play_midi_setup_drums(ch, note);
5497 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5498 				"Reverb Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
5499 				ch, note, val);
5500 		if (channel[ch].drums[note]->reverb_level != val) {
5501 			channel[ch].drum_effect_flag = 0;
5502 		}
5503 		channel[ch].drums[note]->reverb_level = val;
5504 		break;
5505 	case NRPN_ADDR_1E00:	/* Chorus Send Level of Drum */
5506 		drumflag = 1;
5507 		note = channel[ch].lastlrpn;
5508 		if (channel[ch].drums[note] == NULL)
5509 			play_midi_setup_drums(ch, note);
5510 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5511 				"Chorus Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
5512 				ch, note, val);
5513 		if (channel[ch].drums[note]->chorus_level != val) {
5514 			channel[ch].drum_effect_flag = 0;
5515 		}
5516 		channel[ch].drums[note]->chorus_level = val;
5517 
5518 		break;
5519 	case NRPN_ADDR_1F00:	/* Variation Send Level of Drum */
5520 		drumflag = 1;
5521 		note = channel[ch].lastlrpn;
5522 		if (channel[ch].drums[note] == NULL)
5523 			play_midi_setup_drums(ch, note);
5524 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5525 				"Delay Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
5526 				ch, note, val);
5527 		if (channel[ch].drums[note]->delay_level != val) {
5528 			channel[ch].drum_effect_flag = 0;
5529 		}
5530 		channel[ch].drums[note]->delay_level = val;
5531 		break;
5532 	case NRPN_ADDR_3000:	/* Drum EQ BASS */
5533 		drumflag = 1;
5534 		note = channel[ch].lastlrpn;
5535 		if (channel[ch].drums[note] == NULL)
5536 			play_midi_setup_drums(ch, note);
5537 		break;
5538 	case NRPN_ADDR_3100:	/* Drum EQ TREBLE */
5539 		drumflag = 1;
5540 		note = channel[ch].lastlrpn;
5541 		if (channel[ch].drums[note] == NULL)
5542 			play_midi_setup_drums(ch, note);
5543 		break;
5544 	case NRPN_ADDR_3400:	/* Drum EQ BASS frequency */
5545 		drumflag = 1;
5546 		note = channel[ch].lastlrpn;
5547 		if (channel[ch].drums[note] == NULL)
5548 			play_midi_setup_drums(ch, note);
5549 		break;
5550 	case NRPN_ADDR_3500:	/* Drum EQ TREBLE frequency */
5551 		drumflag = 1;
5552 		note = channel[ch].lastlrpn;
5553 		if (channel[ch].drums[note] == NULL)
5554 			play_midi_setup_drums(ch, note);
5555 		break;
5556 	case RPN_ADDR_0000:		/* Pitch bend sensitivity */
5557 		ctl->cmsg(CMSG_INFO, VERB_DEBUG,
5558 				"Pitch Bend Sensitivity (CH:%d VALUE:%d)", ch, val);
5559 		/* for mod2mid.c, arpeggio */
5560 		if (! IS_CURRENT_MOD_FILE && channel[ch].rpnmap[RPN_ADDR_0000] > 24)
5561 			channel[ch].rpnmap[RPN_ADDR_0000] = 24;
5562 		channel[ch].pitchfactor = 0;
5563 		break;
5564 	case RPN_ADDR_0001:		/* Master Fine Tuning */
5565 		ctl->cmsg(CMSG_INFO, VERB_DEBUG,
5566 				"Master Fine Tuning (CH:%d VALUE:%d)", ch, val);
5567 		channel[ch].pitchfactor = 0;
5568 		break;
5569 	case RPN_ADDR_0002:		/* Master Coarse Tuning */
5570 		ctl->cmsg(CMSG_INFO, VERB_DEBUG,
5571 				"Master Coarse Tuning (CH:%d VALUE:%d)", ch, val);
5572 		channel[ch].pitchfactor = 0;
5573 		break;
5574 	case RPN_ADDR_0003:		/* Tuning Program Select */
5575 		ctl->cmsg(CMSG_INFO, VERB_DEBUG,
5576 				"Tuning Program Select (CH:%d VALUE:%d)", ch, val);
5577 		for (i = 0; i < upper_voices; i++)
5578 			if (voice[i].status != VOICE_FREE) {
5579 				voice[i].temper_instant = 1;
5580 				recompute_freq(i);
5581 			}
5582 		break;
5583 	case RPN_ADDR_0004:		/* Tuning Bank Select */
5584 		ctl->cmsg(CMSG_INFO, VERB_DEBUG,
5585 				"Tuning Bank Select (CH:%d VALUE:%d)", ch, val);
5586 		for (i = 0; i < upper_voices; i++)
5587 			if (voice[i].status != VOICE_FREE) {
5588 				voice[i].temper_instant = 1;
5589 				recompute_freq(i);
5590 			}
5591 		break;
5592 	case RPN_ADDR_0005:		/* GM2: Modulation Depth Range */
5593 		channel[ch].mod.lfo1_pitch_depth = (((int32)channel[ch].rpnmap[RPN_ADDR_0005] << 7) | channel[ch].rpnmap_lsb[RPN_ADDR_0005]) * 100 / 128;
5594 		ctl->cmsg(CMSG_INFO, VERB_NOISY,
5595 				"Modulation Depth Range (CH:%d VALUE:%d)", ch, channel[ch].rpnmap[RPN_ADDR_0005]);
5596 		break;
5597 	case RPN_ADDR_7F7F:		/* RPN reset */
5598 		channel[ch].rpn_7f7f_flag = 1;
5599 		break;
5600 	case RPN_ADDR_FFFF:		/* RPN initialize */
5601 		/* All reset to defaults */
5602 		channel[ch].rpn_7f7f_flag = 0;
5603 		memset(channel[ch].rpnmap, 0, sizeof(channel[ch].rpnmap));
5604 		channel[ch].lastlrpn = channel[ch].lastmrpn = 0;
5605 		channel[ch].nrpn = 0;
5606 		channel[ch].rpnmap[RPN_ADDR_0000] = 2;
5607 		channel[ch].rpnmap[RPN_ADDR_0001] = 0x40;
5608 		channel[ch].rpnmap[RPN_ADDR_0002] = 0x40;
5609 		channel[ch].rpnmap_lsb[RPN_ADDR_0005] = 0x40;
5610 		channel[ch].rpnmap[RPN_ADDR_0005] = 0;	/* +- 50 cents */
5611 		channel[ch].pitchfactor = 0;
5612 		break;
5613 	}
5614 	drumflag = 0;
5615 	if (drumflag && midi_drumpart_change(ch, 1)) {
5616 		midi_program_change(ch, channel[ch].program);
5617 		if (update_now)
5618 			ctl_prog_event(ch);
5619 	}
5620 }
5621 
seek_forward(int32 until_time)5622 static void seek_forward(int32 until_time)
5623 {
5624     int32 i;
5625     int j, k, ch, orig_ch, port_ch, offset, layered;
5626 
5627     playmidi_seek_flag = 1;
5628     wrd_midi_event(WRD_START_SKIP, WRD_NOARG);
5629 	while (MIDI_EVENT_TIME(current_event) < until_time) {
5630 #ifndef SUPPRESS_CHANNEL_LAYER
5631 		orig_ch = current_event->channel;
5632 		layered = ! IS_SYSEX_EVENT_TYPE(current_event);
5633 		for (j = 0; j < MAX_CHANNELS; j += 16) {
5634 			port_ch = (orig_ch + j) % MAX_CHANNELS;
5635 			offset = port_ch & ~0xf;
5636 			for (k = offset; k < offset + 16; k++) {
5637 				if (! layered && (j || k != offset))
5638 					continue;
5639 				if (layered) {
5640 					if (! IS_SET_CHANNELMASK(
5641 							channel[k].channel_layer, port_ch)
5642 							|| channel[k].port_select != (orig_ch >> 4))
5643 						continue;
5644 					current_event->channel = k;
5645 				}
5646 #endif
5647 	ch = current_event->channel;
5648 
5649 	switch(current_event->type)
5650 	{
5651 	  case ME_PITCHWHEEL:
5652 	    channel[ch].pitchbend = current_event->a + current_event->b * 128;
5653 	    channel[ch].pitchfactor=0;
5654 	    break;
5655 
5656 	  case ME_MAINVOLUME:
5657 	    channel[ch].volume = current_event->a;
5658 	    break;
5659 
5660 	  case ME_MASTER_VOLUME:
5661 	    master_volume_ratio =
5662 		(int32)current_event->a + 256 * (int32)current_event->b;
5663 	    break;
5664 
5665 	  case ME_PAN:
5666 	    channel[ch].panning = current_event->a;
5667 	    channel[ch].pan_random = 0;
5668 	    break;
5669 
5670 	  case ME_EXPRESSION:
5671 	    channel[ch].expression=current_event->a;
5672 	    break;
5673 
5674 	  case ME_PROGRAM:
5675 	    midi_program_change(ch, current_event->a);
5676 	    break;
5677 
5678 	  case ME_SUSTAIN:
5679 		  channel[ch].sustain = current_event->a;
5680 		  if (channel[ch].damper_mode == 0) {	/* half-damper is not allowed. */
5681 			  if (channel[ch].sustain >= 64) {channel[ch].sustain = 127;}
5682 			  else {channel[ch].sustain = 0;}
5683 		  }
5684 	    break;
5685 
5686 	  case ME_SOSTENUTO:
5687 		  channel[ch].sostenuto = (current_event->a >= 64);
5688 	    break;
5689 
5690 	  case ME_LEGATO_FOOTSWITCH:
5691         channel[ch].legato = (current_event->a >= 64);
5692 	    break;
5693 
5694       case ME_HOLD2:
5695         break;
5696 
5697 	  case ME_FOOT:
5698 	    break;
5699 
5700 	  case ME_BREATH:
5701 	    break;
5702 
5703 	  case ME_BALANCE:
5704 	    break;
5705 
5706 	  case ME_RESET_CONTROLLERS:
5707 	    reset_controllers(ch);
5708 	    break;
5709 
5710 	  case ME_TONE_BANK_MSB:
5711 	    channel[ch].bank_msb = current_event->a;
5712 	    break;
5713 
5714 	  case ME_TONE_BANK_LSB:
5715 	    channel[ch].bank_lsb = current_event->a;
5716 	    break;
5717 
5718 	  case ME_MODULATION_WHEEL:
5719 	    channel[ch].mod.val = current_event->a;
5720 	    break;
5721 
5722 	  case ME_PORTAMENTO_TIME_MSB:
5723 	    channel[ch].portamento_time_msb = current_event->a;
5724 	    break;
5725 
5726 	  case ME_PORTAMENTO_TIME_LSB:
5727 	    channel[ch].portamento_time_lsb = current_event->a;
5728 	    break;
5729 
5730 	  case ME_PORTAMENTO:
5731 	    channel[ch].portamento = (current_event->a >= 64);
5732 	    break;
5733 
5734 	  case ME_MONO:
5735 	    channel[ch].mono = 1;
5736 	    break;
5737 
5738 	  case ME_POLY:
5739 	    channel[ch].mono = 0;
5740 	    break;
5741 
5742 	  case ME_SOFT_PEDAL:
5743 		  if(opt_lpf_def) {
5744 			  channel[ch].soft_pedal = current_event->a;
5745 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Soft Pedal (CH:%d VAL:%d)",ch,channel[ch].soft_pedal);
5746 		  }
5747 		  break;
5748 
5749 	  case ME_HARMONIC_CONTENT:
5750 		  if(opt_lpf_def) {
5751 			  channel[ch].param_resonance = current_event->a - 64;
5752 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Harmonic Content (CH:%d VAL:%d)",ch,channel[ch].param_resonance);
5753 		  }
5754 		  break;
5755 
5756 	  case ME_BRIGHTNESS:
5757 		  if(opt_lpf_def) {
5758 			  channel[ch].param_cutoff_freq = current_event->a - 64;
5759 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Brightness (CH:%d VAL:%d)",ch,channel[ch].param_cutoff_freq);
5760 		  }
5761 		  break;
5762 
5763 	    /* RPNs */
5764 	  case ME_NRPN_LSB:
5765 	    channel[ch].lastlrpn = current_event->a;
5766 	    channel[ch].nrpn = 1;
5767 	    break;
5768 	  case ME_NRPN_MSB:
5769 	    channel[ch].lastmrpn = current_event->a;
5770 	    channel[ch].nrpn = 1;
5771 	    break;
5772 	  case ME_RPN_LSB:
5773 	    channel[ch].lastlrpn = current_event->a;
5774 	    channel[ch].nrpn = 0;
5775 	    break;
5776 	  case ME_RPN_MSB:
5777 	    channel[ch].lastmrpn = current_event->a;
5778 	    channel[ch].nrpn = 0;
5779 	    break;
5780 	  case ME_RPN_INC:
5781 	    if(channel[ch].rpn_7f7f_flag) /* disable */
5782 		break;
5783 	    if((i = last_rpn_addr(ch)) >= 0)
5784 	    {
5785 		if(channel[ch].rpnmap[i] < 127)
5786 		    channel[ch].rpnmap[i]++;
5787 		update_rpn_map(ch, i, 0);
5788 	    }
5789 	    break;
5790 	case ME_RPN_DEC:
5791 	    if(channel[ch].rpn_7f7f_flag) /* disable */
5792 		break;
5793 	    if((i = last_rpn_addr(ch)) >= 0)
5794 	    {
5795 		if(channel[ch].rpnmap[i] > 0)
5796 		    channel[ch].rpnmap[i]--;
5797 		update_rpn_map(ch, i, 0);
5798 	    }
5799 	    break;
5800 	  case ME_DATA_ENTRY_MSB:
5801 	    if(channel[ch].rpn_7f7f_flag) /* disable */
5802 		break;
5803 	    if((i = last_rpn_addr(ch)) >= 0)
5804 	    {
5805 		channel[ch].rpnmap[i] = current_event->a;
5806 		update_rpn_map(ch, i, 0);
5807 	    }
5808 	    break;
5809 	  case ME_DATA_ENTRY_LSB:
5810 	    if(channel[ch].rpn_7f7f_flag) /* disable */
5811 		break;
5812 	    if((i = last_rpn_addr(ch)) >= 0)
5813 	    {
5814 		channel[ch].rpnmap_lsb[i] = current_event->a;
5815 	    }
5816 	    break;
5817 
5818 	  case ME_REVERB_EFFECT:
5819 		  if (opt_reverb_control) {
5820 			if (ISDRUMCHANNEL(ch) && get_reverb_level(ch) != current_event->a) {channel[ch].drum_effect_flag = 0;}
5821 			set_reverb_level(ch, current_event->a);
5822 		  }
5823 	    break;
5824 
5825 	  case ME_CHORUS_EFFECT:
5826 		if(opt_chorus_control == 1) {
5827 			if (ISDRUMCHANNEL(ch) && channel[ch].chorus_level != current_event->a) {channel[ch].drum_effect_flag = 0;}
5828 			channel[ch].chorus_level = current_event->a;
5829 		} else {
5830 			channel[ch].chorus_level = -opt_chorus_control;
5831 		}
5832 
5833 		if(current_event->a) {
5834 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send (CH:%d LEVEL:%d)",ch,current_event->a);
5835 		}
5836 		break;
5837 
5838 	  case ME_TREMOLO_EFFECT:
5839 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tremolo Send (CH:%d LEVEL:%d)",ch,current_event->a);
5840 		break;
5841 
5842 	  case ME_CELESTE_EFFECT:
5843 		if(opt_delay_control) {
5844 			if (ISDRUMCHANNEL(ch) && channel[ch].delay_level != current_event->a) {channel[ch].drum_effect_flag = 0;}
5845 			channel[ch].delay_level = current_event->a;
5846 			if (play_system_mode == XG_SYSTEM_MODE) {
5847 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send (CH:%d LEVEL:%d)",ch,current_event->a);
5848 			} else {
5849 				ctl->cmsg(CMSG_INFO,VERB_NOISY,"Variation Send (CH:%d LEVEL:%d)",ch,current_event->a);
5850 			}
5851 		}
5852 	    break;
5853 
5854 	  case ME_ATTACK_TIME:
5855 	  	if(!opt_tva_attack) { break; }
5856 		set_envelope_time(ch, current_event->a, EG_ATTACK);
5857 		break;
5858 
5859 	  case ME_RELEASE_TIME:
5860 	  	if(!opt_tva_release) { break; }
5861 		set_envelope_time(ch, current_event->a, EG_RELEASE);
5862 		break;
5863 
5864 	  case ME_PHASER_EFFECT:
5865 		ctl->cmsg(CMSG_INFO,VERB_NOISY,"Phaser Send (CH:%d LEVEL:%d)",ch,current_event->a);
5866 		break;
5867 
5868 	  case ME_RANDOM_PAN:
5869 	    channel[ch].panning = int_rand(128);
5870 	    channel[ch].pan_random = 1;
5871 	    break;
5872 
5873 	  case ME_SET_PATCH:
5874 	    i = channel[ch].special_sample = current_event->a;
5875 	    if(special_patch[i] != NULL)
5876 		special_patch[i]->sample_offset = 0;
5877 	    break;
5878 
5879 	  case ME_TEMPO:
5880 	    current_play_tempo = ch +
5881 		current_event->b * 256 + current_event->a * 65536;
5882 	    break;
5883 
5884 	  case ME_RESET:
5885 	    change_system_mode(current_event->a);
5886 	    reset_midi(0);
5887 	    break;
5888 
5889 	  case ME_PATCH_OFFS:
5890 	    i = channel[ch].special_sample;
5891 	    if(special_patch[i] != NULL)
5892 		special_patch[i]->sample_offset =
5893 		    (current_event->a | 256 * current_event->b);
5894 	    break;
5895 
5896 	  case ME_WRD:
5897 	    wrd_midi_event(ch, current_event->a | 256 * current_event->b);
5898 	    break;
5899 
5900 	  case ME_SHERRY:
5901 	    wrd_sherry_event(ch |
5902 			     (current_event->a<<8) |
5903 			     (current_event->b<<16));
5904 	    break;
5905 
5906 	  case ME_DRUMPART:
5907 	    if(midi_drumpart_change(ch, current_event->a))
5908 		midi_program_change(ch, channel[ch].program);
5909 	    break;
5910 
5911 	  case ME_KEYSHIFT:
5912 	    channel[ch].key_shift = (int)current_event->a - 0x40;
5913 	    break;
5914 
5915 	case ME_KEYSIG:
5916 		if (opt_init_keysig != 8)
5917 			break;
5918 		current_keysig = current_event->a + current_event->b * 16;
5919 		break;
5920 
5921 	case ME_MASTER_TUNING:
5922 		set_master_tuning((current_event->b << 8) | current_event->a);
5923 		break;
5924 
5925 	case ME_SCALE_TUNING:
5926 		channel[ch].scale_tuning[current_event->a] = current_event->b;
5927 		break;
5928 
5929 	case ME_BULK_TUNING_DUMP:
5930 		set_single_note_tuning(ch, current_event->a, current_event->b, 0);
5931 		break;
5932 
5933 	case ME_SINGLE_NOTE_TUNING:
5934 		set_single_note_tuning(ch, current_event->a, current_event->b, 0);
5935 		break;
5936 
5937 	case ME_TEMPER_KEYSIG:
5938 		current_temper_keysig = (current_event->a + 8) % 32 - 8;
5939 		temper_adj = ((current_event->a + 8) & 0x20) ? 1 : 0;
5940 		break;
5941 
5942 	case ME_TEMPER_TYPE:
5943 		channel[ch].temper_type = current_event->a;
5944 		break;
5945 
5946 	case ME_MASTER_TEMPER_TYPE:
5947 		for (i = 0; i < MAX_CHANNELS; i++)
5948 			channel[i].temper_type = current_event->a;
5949 		break;
5950 
5951 	case ME_USER_TEMPER_ENTRY:
5952 		set_user_temper_entry(ch, current_event->a, current_event->b);
5953 		break;
5954 
5955 	  case ME_SYSEX_LSB:
5956 	    process_sysex_event(ME_SYSEX_LSB,ch,current_event->a,current_event->b);
5957 	    break;
5958 
5959 	  case ME_SYSEX_MSB:
5960 	    process_sysex_event(ME_SYSEX_MSB,ch,current_event->a,current_event->b);
5961 	    break;
5962 
5963 	  case ME_SYSEX_GS_LSB:
5964 	    process_sysex_event(ME_SYSEX_GS_LSB,ch,current_event->a,current_event->b);
5965 	    break;
5966 
5967 	  case ME_SYSEX_GS_MSB:
5968 	    process_sysex_event(ME_SYSEX_GS_MSB,ch,current_event->a,current_event->b);
5969 	    break;
5970 
5971 	  case ME_SYSEX_XG_LSB:
5972 	    process_sysex_event(ME_SYSEX_XG_LSB,ch,current_event->a,current_event->b);
5973 	    break;
5974 
5975 	  case ME_SYSEX_XG_MSB:
5976 	    process_sysex_event(ME_SYSEX_XG_MSB,ch,current_event->a,current_event->b);
5977 	    break;
5978 
5979 	  case ME_EOT:
5980 	    current_sample = current_event->time;
5981 	    playmidi_seek_flag = 0;
5982 	    return;
5983 	}
5984 #ifndef SUPPRESS_CHANNEL_LAYER
5985 			}
5986 		}
5987 		current_event->channel = orig_ch;
5988 #endif
5989 	current_event++;
5990     }
5991     wrd_midi_event(WRD_END_SKIP, WRD_NOARG);
5992 
5993     playmidi_seek_flag = 0;
5994     if(current_event != event_list)
5995 	current_event--;
5996     current_sample = until_time;
5997 }
5998 
skip_to(int32 until_time)5999 static void skip_to(int32 until_time)
6000 {
6001   int ch;
6002 
6003   trace_flush();
6004   current_event = NULL;
6005 
6006   if (current_sample > until_time)
6007     current_sample=0;
6008 
6009   change_system_mode(DEFAULT_SYSTEM_MODE);
6010   reset_midi(0);
6011 
6012   buffered_count=0;
6013   buffer_pointer=common_buffer;
6014   current_event=event_list;
6015   current_play_tempo = 500000; /* 120 BPM */
6016 
6017   if (until_time)
6018     seek_forward(until_time);
6019   for(ch = 0; ch < MAX_CHANNELS; ch++)
6020       channel[ch].lasttime = current_sample;
6021 
6022   ctl_mode_event(CTLE_RESET, 0, 0, 0);
6023   trace_offset(until_time);
6024 
6025 #ifdef SUPPORT_SOUNDSPEC
6026   soundspec_update_wave(NULL, 0);
6027 #endif /* SUPPORT_SOUNDSPEC */
6028 }
6029 
sync_restart(int only_trace_ok)6030 static int32 sync_restart(int only_trace_ok)
6031 {
6032     int32 cur;
6033 
6034     cur = current_trace_samples();
6035     if(cur == -1)
6036     {
6037 	if(only_trace_ok)
6038 	    return -1;
6039 	cur = current_sample;
6040     }
6041     aq_flush(1);
6042     skip_to(cur);
6043     return cur;
6044 }
6045 
playmidi_change_rate(int32 rate,int restart)6046 static int playmidi_change_rate(int32 rate, int restart)
6047 {
6048     int arg;
6049 
6050     if(rate == play_mode->rate)
6051 	return 1; /* Not need to change */
6052 
6053     if(rate < MIN_OUTPUT_RATE || rate > MAX_OUTPUT_RATE)
6054     {
6055 	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
6056 		  "Out of sample rate: %d", rate);
6057 	return -1;
6058     }
6059 
6060     if(restart)
6061     {
6062 	if((midi_restart_time = current_trace_samples()) == -1)
6063 	    midi_restart_time = current_sample;
6064     }
6065     else
6066 	midi_restart_time = 0;
6067 
6068     arg = (int)rate;
6069     if(play_mode->acntl(PM_REQ_RATE, &arg) == -1)
6070     {
6071 	ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
6072 		  "Can't change sample rate to %d", rate);
6073 	return -1;
6074     }
6075 
6076     aq_flush(1);
6077     aq_setup();
6078     aq_set_soft_queue(-1.0, -1.0);
6079     free_instruments(1);
6080 #ifdef SUPPORT_SOUNDSPEC
6081     soundspec_reinit();
6082 #endif /* SUPPORT_SOUNDSPEC */
6083     return 0;
6084 }
6085 
playmidi_output_changed(int play_state)6086 void playmidi_output_changed(int play_state)
6087 {
6088     if(target_play_mode == NULL)
6089 	return;
6090     play_mode = target_play_mode;
6091 
6092     if(play_state == 0)
6093     {
6094 	/* Playing */
6095 	if((midi_restart_time = current_trace_samples()) == -1)
6096 	    midi_restart_time = current_sample;
6097     }
6098     else /* Not playing */
6099 	midi_restart_time = 0;
6100 
6101     if(play_state != 2)
6102     {
6103 	aq_flush(1);
6104 	aq_setup();
6105 	aq_set_soft_queue(-1.0, -1.0);
6106 	clear_magic_instruments();
6107     }
6108     free_instruments(1);
6109 #ifdef SUPPORT_SOUNDSPEC
6110     soundspec_reinit();
6111 #endif /* SUPPORT_SOUNDSPEC */
6112     target_play_mode = NULL;
6113 }
6114 
check_apply_control(void)6115 int check_apply_control(void)
6116 {
6117     int rc;
6118     int32 val;
6119 
6120     if(file_from_stdin)
6121 	return RC_NONE;
6122     rc = ctl->read(&val);
6123     switch(rc)
6124     {
6125       case RC_CHANGE_VOLUME:
6126 	if (val>0 || amplification > -val)
6127 	    amplification += val;
6128 	else
6129 	    amplification=0;
6130 	if (amplification > MAX_AMPLIFICATION)
6131 	    amplification=MAX_AMPLIFICATION;
6132 	adjust_amplification();
6133 	ctl_mode_event(CTLE_MASTER_VOLUME, 0, amplification, 0);
6134 	break;
6135       case RC_SYNC_RESTART:
6136 	aq_flush(1);
6137 	break;
6138       case RC_TOGGLE_PAUSE:
6139 	play_pause_flag = !play_pause_flag;
6140 	ctl_pause_event(play_pause_flag, 0);
6141 	return RC_NONE;
6142       case RC_TOGGLE_SNDSPEC:
6143 #ifdef SUPPORT_SOUNDSPEC
6144 	if(view_soundspec_flag)
6145 	    close_soundspec();
6146 	else
6147 	    open_soundspec();
6148 	if(view_soundspec_flag || ctl_speana_flag)
6149 	    soundspec_update_wave(NULL, -1);
6150 	return RC_NONE;
6151       case RC_TOGGLE_CTL_SPEANA:
6152 	ctl_speana_flag = !ctl_speana_flag;
6153 	if(view_soundspec_flag || ctl_speana_flag)
6154 	    soundspec_update_wave(NULL, -1);
6155 #endif /* SUPPORT_SOUNDSPEC */
6156 	return RC_NONE;
6157       case RC_CHANGE_RATE:
6158 	if(playmidi_change_rate(val, 0))
6159 	    return RC_NONE;
6160 	return RC_RELOAD;
6161       case RC_OUTPUT_CHANGED:
6162 	playmidi_output_changed(1);
6163 	return RC_RELOAD;
6164     }
6165     return rc;
6166 }
6167 
voice_increment(int n)6168 static void voice_increment(int n)
6169 {
6170     int i;
6171     for(i = 0; i < n; i++)
6172     {
6173 	if(voices == max_voices)
6174 	    break;
6175 	voice[voices].status = VOICE_FREE;
6176 	voice[voices].temper_instant = 0;
6177 	voice[voices].chorus_link = voices;
6178 	voices++;
6179     }
6180     if(n > 0)
6181 	ctl_mode_event(CTLE_MAXVOICES, 1, voices, 0);
6182 }
6183 
voice_decrement(int n)6184 static void voice_decrement(int n)
6185 {
6186     int i, j, lowest;
6187     int32 lv, v;
6188 
6189     /* decrease voice */
6190     for(i = 0; i < n && voices > 0; i++)
6191     {
6192 	voices--;
6193 	if(voice[voices].status == VOICE_FREE)
6194 	    continue;	/* found */
6195 
6196 	for(j = 0; j < voices; j++)
6197 	    if(voice[j].status == VOICE_FREE)
6198 		break;
6199 	if(j != voices)
6200 	{
6201 	    voice[j] = voice[voices];
6202 	    continue;	/* found */
6203 	}
6204 
6205 	/* Look for the decaying note with the lowest volume */
6206 	lv = 0x7FFFFFFF;
6207 	lowest = -1;
6208 	for(j = 0; j <= voices; j++)
6209 	{
6210 	    if(voice[j].status & ~(VOICE_ON | VOICE_DIE))
6211 	    {
6212 		v = voice[j].left_mix;
6213 		if((voice[j].panned==PANNED_MYSTERY) &&
6214 		   (voice[j].right_mix > v))
6215 		    v = voice[j].right_mix;
6216 		if(v < lv)
6217 		{
6218 		    lv = v;
6219 		    lowest = j;
6220 		}
6221 	    }
6222 	}
6223 
6224 	if(lowest != -1)
6225 	{
6226 	    cut_notes++;
6227 	    free_voice(lowest);
6228 	    ctl_note_event(lowest);
6229 	    voice[lowest] = voice[voices];
6230 	}
6231 	else
6232 	    lost_notes++;
6233     }
6234     if(upper_voices > voices)
6235 	upper_voices = voices;
6236     if(n > 0)
6237 	ctl_mode_event(CTLE_MAXVOICES, 1, voices, 0);
6238 }
6239 
6240 /* EAW -- do not throw away good notes, stop decrementing */
voice_decrement_conservative(int n)6241 static void voice_decrement_conservative(int n)
6242 {
6243     int i, j, lowest, finalnv;
6244     int32 lv, v;
6245 
6246     /* decrease voice */
6247     finalnv = voices - n;
6248     for(i = 1; i <= n && voices > 0; i++)
6249     {
6250 	if(voice[voices-1].status == VOICE_FREE) {
6251 	    voices--;
6252 	    continue;	/* found */
6253 	}
6254 
6255 	for(j = 0; j < finalnv; j++)
6256 	    if(voice[j].status == VOICE_FREE)
6257 		break;
6258 	if(j != finalnv)
6259 	{
6260 	    voice[j] = voice[voices-1];
6261 	    voices--;
6262 	    continue;	/* found */
6263 	}
6264 
6265 	/* Look for the decaying note with the lowest volume */
6266 	lv = 0x7FFFFFFF;
6267 	lowest = -1;
6268 	for(j = 0; j < voices; j++)
6269 	{
6270 	    if(voice[j].status & ~(VOICE_ON | VOICE_DIE) &&
6271 	       !(voice[j].sample->note_to_use &&
6272 	         ISDRUMCHANNEL(voice[j].channel)))
6273 	    {
6274 		v = voice[j].left_mix;
6275 		if((voice[j].panned==PANNED_MYSTERY) &&
6276 		   (voice[j].right_mix > v))
6277 		    v = voice[j].right_mix;
6278 		if(v < lv)
6279 		{
6280 		    lv = v;
6281 		    lowest = j;
6282 		}
6283 	    }
6284 	}
6285 
6286 	if(lowest != -1)
6287 	{
6288 	    voices--;
6289 	    cut_notes++;
6290 	    free_voice(lowest);
6291 	    ctl_note_event(lowest);
6292 	    voice[lowest] = voice[voices];
6293 	}
6294 	else break;
6295     }
6296     if(upper_voices > voices)
6297 	upper_voices = voices;
6298 }
6299 
restore_voices(int save_voices)6300 void restore_voices(int save_voices)
6301 {
6302 #ifdef REDUCE_VOICE_TIME_TUNING
6303     static int old_voices = -1;
6304     if(old_voices == -1 || save_voices)
6305 	old_voices = voices;
6306     else if (voices < old_voices)
6307 	voice_increment(old_voices - voices);
6308     else
6309 	voice_decrement(voices - old_voices);
6310 #endif /* REDUCE_VOICE_TIME_TUNING */
6311 }
6312 
6313 
apply_controls(void)6314 static int apply_controls(void)
6315 {
6316     int rc, i, jump_flag = 0;
6317     int32 val, cur;
6318     FLOAT_T r;
6319     ChannelBitMask tmp_chbitmask;
6320 
6321     /* ASCII renditions of CD player pictograms indicate approximate effect */
6322     do
6323     {
6324 	switch(rc=ctl->read(&val))
6325 	{
6326 	  case RC_STOP:
6327 	  case RC_QUIT:		/* [] */
6328 	  case RC_LOAD_FILE:
6329 	  case RC_NEXT:		/* >>| */
6330 	  case RC_REALLY_PREVIOUS: /* |<< */
6331 	  case RC_TUNE_END:	/* skip */
6332 	    aq_flush(1);
6333 	    return rc;
6334 
6335 	  case RC_CHANGE_VOLUME:
6336 	    if (val>0 || amplification > -val)
6337 		amplification += val;
6338 	    else
6339 		amplification=0;
6340 	    if (amplification > MAX_AMPLIFICATION)
6341 		amplification=MAX_AMPLIFICATION;
6342 	    adjust_amplification();
6343 	    for (i=0; i<upper_voices; i++)
6344 		if (voice[i].status != VOICE_FREE)
6345 		{
6346 		    recompute_amp(i);
6347 		    apply_envelope_to_amp(i);
6348 		}
6349 	    ctl_mode_event(CTLE_MASTER_VOLUME, 0, amplification, 0);
6350 	    continue;
6351 
6352 	  case RC_CHANGE_REV_EFFB:
6353 	  case RC_CHANGE_REV_TIME:
6354 	    reverb_rc_event(rc, val);
6355 	    sync_restart(0);
6356 	    continue;
6357 
6358 	  case RC_PREVIOUS:	/* |<< */
6359 	    aq_flush(1);
6360 	    if (current_sample < 2*play_mode->rate)
6361 		return RC_REALLY_PREVIOUS;
6362 	    return RC_RESTART;
6363 
6364 	  case RC_RESTART:	/* |<< */
6365 	    if(play_pause_flag)
6366 	    {
6367 		midi_restart_time = 0;
6368 		ctl_pause_event(1, 0);
6369 		continue;
6370 	    }
6371 	    aq_flush(1);
6372 	    skip_to(0);
6373 	    ctl_updatetime(0);
6374 	    jump_flag = 1;
6375 		midi_restart_time = 0;
6376 	    continue;
6377 
6378 	  case RC_JUMP:
6379 	    val = val * midi_time_ratio + 0.5;
6380 	    if(play_pause_flag)
6381 	    {
6382 		midi_restart_time = val;
6383 		ctl_pause_event(1, val);
6384 		continue;
6385 	    }
6386 	    aq_flush(1);
6387 	    if (val >= sample_count * midi_time_ratio + 0.5)
6388 		return RC_TUNE_END;
6389 	    skip_to(val);
6390 	    ctl_updatetime(val);
6391 	    return rc;
6392 
6393 	  case RC_FORWARD:	/* >> */
6394 	    if(play_pause_flag)
6395 	    {
6396 		midi_restart_time += val * midi_time_ratio + 0.5;
6397 		if(midi_restart_time > sample_count * midi_time_ratio + 0.5)
6398 		    midi_restart_time = sample_count * midi_time_ratio + 0.5;
6399 		ctl_pause_event(1, midi_restart_time);
6400 		continue;
6401 	    }
6402 	    cur = current_trace_samples();
6403 	    aq_flush(1);
6404 	    if(cur == -1)
6405 		cur = current_sample;
6406 	    if (val == 0x7fffffff)
6407 		return RC_TUNE_END;
6408 	    val = val * midi_time_ratio + 0.5;
6409 	    if(val + cur >= sample_count * midi_time_ratio + 0.5)
6410 		return RC_TUNE_END;
6411 	    skip_to(val + cur);
6412 	    ctl_updatetime(val + cur);
6413 	    return RC_JUMP;
6414 
6415 	  case RC_BACK:		/* << */
6416 	    if(play_pause_flag)
6417 	    {
6418 		midi_restart_time -= val * midi_time_ratio + 0.5;
6419 		if(midi_restart_time < 0)
6420 		    midi_restart_time = 0;
6421 		ctl_pause_event(1, midi_restart_time);
6422 		continue;
6423 	    }
6424 	    cur = current_trace_samples();
6425 	    aq_flush(1);
6426 	    if(cur == -1)
6427 		cur = current_sample;
6428 	    val = val * midi_time_ratio + 0.5;
6429 	    if(cur > val)
6430 	    {
6431 		skip_to(cur - val);
6432 		ctl_updatetime(cur - val);
6433 	    }
6434 	    else
6435 	    {
6436 		skip_to(0);
6437 		ctl_updatetime(0);
6438 		midi_restart_time = 0;
6439 	    }
6440 	    return RC_JUMP;
6441 
6442 	  case RC_TOGGLE_PAUSE:
6443 	    if(play_pause_flag)
6444 	    {
6445 		play_pause_flag = 0;
6446 		skip_to(midi_restart_time);
6447 	    }
6448 	    else
6449 	    {
6450 		midi_restart_time = current_trace_samples();
6451 		if(midi_restart_time == -1)
6452 		    midi_restart_time = current_sample;
6453 		aq_flush(1);
6454 		play_pause_flag = 1;
6455 	    }
6456 	    ctl_pause_event(play_pause_flag, midi_restart_time);
6457 	    jump_flag = 1;
6458 	    continue;
6459 
6460 	  case RC_KEYUP:
6461 	  case RC_KEYDOWN:
6462 	    note_key_offset += val;
6463 	    current_freq_table += val;
6464 	    current_freq_table -= floor(current_freq_table / 12.0) * 12;
6465 	    current_temper_freq_table += val;
6466 	    current_temper_freq_table -=
6467 	    		floor(current_temper_freq_table / 12.0) * 12;
6468 	    if(sync_restart(1) != -1)
6469 		jump_flag = 1;
6470 	    ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
6471 	    continue;
6472 
6473 	  case RC_SPEEDUP:
6474 	    r = 1.0;
6475 	    for(i = 0; i < val; i++)
6476 		r *= SPEED_CHANGE_RATE;
6477 	    sync_restart(0);
6478 	    midi_time_ratio /= r;
6479 	    current_sample = (int32)(current_sample / r + 0.5);
6480 	    trace_offset(current_sample);
6481 	    jump_flag = 1;
6482 	    ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
6483 	    continue;
6484 
6485 	  case RC_SPEEDDOWN:
6486 	    r = 1.0;
6487 	    for(i = 0; i < val; i++)
6488 		r *= SPEED_CHANGE_RATE;
6489 	    sync_restart(0);
6490 	    midi_time_ratio *= r;
6491 	    current_sample = (int32)(current_sample * r + 0.5);
6492 	    trace_offset(current_sample);
6493 	    jump_flag = 1;
6494 	    ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
6495 	    continue;
6496 
6497 	  case RC_VOICEINCR:
6498 	    restore_voices(0);
6499 	    voice_increment(val);
6500 	    if(sync_restart(1) != -1)
6501 		jump_flag = 1;
6502 	    restore_voices(1);
6503 	    continue;
6504 
6505 	  case RC_VOICEDECR:
6506 	    restore_voices(0);
6507 	    if(sync_restart(1) != -1)
6508 	    {
6509 		voices -= val;
6510 		if(voices < 0)
6511 		    voices = 0;
6512 		jump_flag = 1;
6513 	    }
6514 	    else
6515 		voice_decrement(val);
6516 	    restore_voices(1);
6517 	    continue;
6518 
6519 	  case RC_TOGGLE_DRUMCHAN:
6520 	    midi_restart_time = current_trace_samples();
6521 	    if(midi_restart_time == -1)
6522 		midi_restart_time = current_sample;
6523 	    SET_CHANNELMASK(drumchannel_mask, val);
6524 	    SET_CHANNELMASK(current_file_info->drumchannel_mask, val);
6525 	    if(IS_SET_CHANNELMASK(drumchannels, val))
6526 	    {
6527 		UNSET_CHANNELMASK(drumchannels, val);
6528 		UNSET_CHANNELMASK(current_file_info->drumchannels, val);
6529 	    }
6530 	    else
6531 	    {
6532 		SET_CHANNELMASK(drumchannels, val);
6533 		SET_CHANNELMASK(current_file_info->drumchannels, val);
6534 	    }
6535 	    aq_flush(1);
6536 	    return RC_RELOAD;
6537 
6538 	  case RC_TOGGLE_SNDSPEC:
6539 #ifdef SUPPORT_SOUNDSPEC
6540 	    if(view_soundspec_flag)
6541 		close_soundspec();
6542 	    else
6543 		open_soundspec();
6544 	    if(view_soundspec_flag || ctl_speana_flag)
6545 	    {
6546 		sync_restart(0);
6547 		soundspec_update_wave(NULL, -1);
6548 	    }
6549 #endif /* SUPPORT_SOUNDSPEC */
6550 	    continue;
6551 
6552 	  case RC_TOGGLE_CTL_SPEANA:
6553 #ifdef SUPPORT_SOUNDSPEC
6554 	    ctl_speana_flag = !ctl_speana_flag;
6555 	    if(view_soundspec_flag || ctl_speana_flag)
6556 	    {
6557 		sync_restart(0);
6558 		soundspec_update_wave(NULL, -1);
6559 	    }
6560 #endif /* SUPPORT_SOUNDSPEC */
6561 	    continue;
6562 
6563 	  case RC_SYNC_RESTART:
6564 	    sync_restart(val);
6565 	    jump_flag = 1;
6566 	    continue;
6567 
6568 	  case RC_RELOAD:
6569 	    midi_restart_time = current_trace_samples();
6570 	    if(midi_restart_time == -1)
6571 		midi_restart_time = current_sample;
6572 	    aq_flush(1);
6573 	    return RC_RELOAD;
6574 
6575 	  case RC_CHANGE_RATE:
6576 	    if(playmidi_change_rate(val, 1))
6577 		return RC_NONE;
6578 	    return RC_RELOAD;
6579 
6580 	  case RC_OUTPUT_CHANGED:
6581 	    playmidi_output_changed(0);
6582 	    return RC_RELOAD;
6583 
6584 	case RC_TOGGLE_MUTE:
6585 		TOGGLE_CHANNELMASK(channel_mute, val);
6586 		sync_restart(0);
6587 		jump_flag = 1;
6588 		ctl_mode_event(CTLE_MUTE, 0,
6589 				val, (IS_SET_CHANNELMASK(channel_mute, val)) ? 1 : 0);
6590 		continue;
6591 
6592 	case RC_SOLO_PLAY:
6593 		COPY_CHANNELMASK(tmp_chbitmask, channel_mute);
6594 		FILL_CHANNELMASK(channel_mute);
6595 		UNSET_CHANNELMASK(channel_mute, val);
6596 		if (! COMPARE_CHANNELMASK(tmp_chbitmask, channel_mute)) {
6597 			sync_restart(0);
6598 			jump_flag = 1;
6599 			for (i = 0; i < MAX_CHANNELS; i++)
6600 				ctl_mode_event(CTLE_MUTE, 0, i, 1);
6601 			ctl_mode_event(CTLE_MUTE, 0, val, 0);
6602 		}
6603 		continue;
6604 
6605 	case RC_MUTE_CLEAR:
6606 		COPY_CHANNELMASK(tmp_chbitmask, channel_mute);
6607 		CLEAR_CHANNELMASK(channel_mute);
6608 		if (! COMPARE_CHANNELMASK(tmp_chbitmask, channel_mute)) {
6609 			sync_restart(0);
6610 			jump_flag = 1;
6611 			for (i = 0; i < MAX_CHANNELS; i++)
6612 				ctl_mode_event(CTLE_MUTE, 0, i, 0);
6613 		}
6614 		continue;
6615 	}
6616 	if(intr)
6617 	    return RC_QUIT;
6618 	if(play_pause_flag)
6619 	    usleep(300000);
6620     } while (rc != RC_NONE || play_pause_flag);
6621     return jump_flag ? RC_JUMP : RC_NONE;
6622 }
6623 
mix_signal(int32 * dest,int32 * src,int32 count)6624 static void mix_signal(int32 *dest, int32 *src, int32 count)
6625 {
6626 	int32 i;
6627 	for (i = 0; i < count; i++) {
6628 		dest[i] += src[i];
6629 	}
6630 }
6631 
6632 #ifdef __BORLANDC__
is_insertion_effect_xg(int ch)6633 static int is_insertion_effect_xg(int ch)
6634 #else
6635 inline static int is_insertion_effect_xg(int ch)
6636 #endif
6637 {
6638 	int i;
6639 	for (i = 0; i < XG_INSERTION_EFFECT_NUM; i++) {
6640 		if (insertion_effect_xg[i].part == ch) {
6641 			return 1;
6642 		}
6643 	}
6644 	for (i = 0; i < XG_VARIATION_EFFECT_NUM; i++) {
6645 		if (variation_effect_xg[i].connection == XG_CONN_INSERTION
6646 			&& variation_effect_xg[i].part == ch) {
6647 			return 1;
6648 		}
6649 	}
6650 	return 0;
6651 }
6652 
6653 #ifdef USE_DSP_EFFECT
6654 /* do_compute_data_midi() with DSP Effect */
do_compute_data_midi(int32 count)6655 static void do_compute_data_midi(int32 count)
6656 {
6657 	int i, j, uv, stereo, n, ch, note;
6658 	int32 *vpblist[MAX_CHANNELS];
6659 	int channel_effect, channel_reverb, channel_chorus, channel_delay, channel_eq;
6660 	int32 cnt = count * 2, rev_max_delay_out;
6661 	struct DrumPartEffect *de;
6662 
6663 	stereo = ! (play_mode->encoding & PE_MONO);
6664 	n = count * ((stereo) ? 8 : 4); /* in bytes */
6665 
6666 	memset(buffer_pointer, 0, n);
6667 	memset(insertion_effect_buffer, 0, n);
6668 
6669 	if (opt_reverb_control == 3) {
6670 		rev_max_delay_out = 0x7fffffff;	/* disable */
6671 	} else {
6672 		rev_max_delay_out = REVERB_MAX_DELAY_OUT;
6673 	}
6674 
6675 	/* are effects valid? / don't supported in mono */
6676 	channel_reverb = (stereo && (opt_reverb_control == 1
6677 			|| opt_reverb_control == 3
6678 			|| (opt_reverb_control < 0 && opt_reverb_control & 0x80)));
6679 	channel_chorus = (stereo && opt_chorus_control && !opt_surround_chorus);
6680 	channel_delay = (stereo && opt_delay_control > 0);
6681 
6682 	/* is EQ valid? */
6683 	channel_eq = opt_eq_control && (eq_status_gs.low_gain != 0x40 || eq_status_gs.high_gain != 0x40 ||
6684 		play_system_mode == XG_SYSTEM_MODE);
6685 
6686 	channel_effect = (stereo && (channel_reverb || channel_chorus
6687 			|| channel_delay || channel_eq || opt_insertion_effect));
6688 
6689 	uv = upper_voices;
6690 	for(i = 0; i < uv; i++) {
6691 		if(voice[i].status != VOICE_FREE) {
6692 			channel[voice[i].channel].lasttime = current_sample + count;
6693 		}
6694 	}
6695 
6696 	/* appropriate buffers for channels */
6697 	if(channel_effect) {
6698 		int buf_index = 0;
6699 
6700 		if(reverb_buffer == NULL) {	/* allocating buffer for channel effect */
6701 			reverb_buffer = (char *)safe_malloc(MAX_CHANNELS * AUDIO_BUFFER_SIZE * 8);
6702 		}
6703 
6704 		for(i = 0; i < MAX_CHANNELS; i++) {
6705 			if(opt_insertion_effect && channel[i].insertion_effect) {
6706 				vpblist[i] = insertion_effect_buffer;
6707 			} else if(channel[i].eq_gs || (get_reverb_level(i) != DEFAULT_REVERB_SEND_LEVEL
6708 					&& current_sample - channel[i].lasttime < rev_max_delay_out)
6709 					|| channel[i].chorus_level > 0 || channel[i].delay_level > 0
6710 					|| channel[i].eq_xg.valid
6711 					|| channel[i].dry_level != 127
6712 					|| (opt_drum_effect && ISDRUMCHANNEL(i))
6713 					|| is_insertion_effect_xg(i)) {
6714 				vpblist[i] = (int32*)(reverb_buffer + buf_index);
6715 				buf_index += n;
6716 			} else {
6717 				vpblist[i] = buffer_pointer;
6718 			}
6719 			/* clear buffers of drum-part effect */
6720 			if (opt_drum_effect && ISDRUMCHANNEL(i)) {
6721 				for (j = 0; j < channel[i].drum_effect_num; j++) {
6722 					if (channel[i].drum_effect[j].buf != NULL) {
6723 						memset(channel[i].drum_effect[j].buf, 0, n);
6724 					}
6725 				}
6726 			}
6727 		}
6728 
6729 		if(buf_index) {memset(reverb_buffer, 0, buf_index);}
6730 	}
6731 
6732 	for (i = 0; i < uv; i++) {
6733 		if (voice[i].status != VOICE_FREE) {
6734 			int32 *vpb = NULL;
6735 			int8 flag;
6736 
6737 			if (channel_effect) {
6738 				flag = 0;
6739 				ch = voice[i].channel;
6740 				if (opt_drum_effect && ISDRUMCHANNEL(ch)) {
6741 					make_drum_effect(ch);
6742 					note = voice[i].note;
6743 					for (j = 0; j < channel[ch].drum_effect_num; j++) {
6744 						if (channel[ch].drum_effect[j].note == note) {
6745 							vpb = channel[ch].drum_effect[j].buf;
6746 							flag = 1;
6747 						}
6748 					}
6749 					if (flag == 0) {vpb = vpblist[ch];}
6750 				} else {
6751 					vpb = vpblist[ch];
6752 				}
6753 			} else {
6754 				vpb = buffer_pointer;
6755 			}
6756 
6757 			if(!IS_SET_CHANNELMASK(channel_mute, voice[i].channel)) {
6758 				mix_voice(vpb, i, count);
6759 			} else {
6760 				free_voice(i);
6761 				ctl_note_event(i);
6762 			}
6763 
6764 			if(voice[i].timeout == 1 && voice[i].timeout < current_sample) {
6765 				free_voice(i);
6766 				ctl_note_event(i);
6767 			}
6768 		}
6769 	}
6770 
6771 	while(uv > 0 && voice[uv - 1].status == VOICE_FREE)	{uv--;}
6772 	upper_voices = uv;
6773 
6774 	if(play_system_mode == XG_SYSTEM_MODE && channel_effect) {	/* XG */
6775 		if (opt_insertion_effect) { 	/* insertion effect */
6776 			for (i = 0; i < XG_INSERTION_EFFECT_NUM; i++) {
6777 				if (insertion_effect_xg[i].part <= MAX_CHANNELS) {
6778 					do_insertion_effect_xg(vpblist[insertion_effect_xg[i].part], cnt, &insertion_effect_xg[i]);
6779 				}
6780 			}
6781 			for (i = 0; i < XG_VARIATION_EFFECT_NUM; i++) {
6782 				if (variation_effect_xg[i].part <= MAX_CHANNELS) {
6783 					do_insertion_effect_xg(vpblist[variation_effect_xg[i].part], cnt, &variation_effect_xg[i]);
6784 				}
6785 			}
6786 		}
6787 		for(i = 0; i < MAX_CHANNELS; i++) {	/* system effects */
6788 			int32 *p;
6789 			p = vpblist[i];
6790 			if(p != buffer_pointer) {
6791 				if (opt_drum_effect && ISDRUMCHANNEL(i)) {
6792 					for (j = 0; j < channel[i].drum_effect_num; j++) {
6793 						de = &(channel[i].drum_effect[j]);
6794 						if (de->reverb_send > 0) {
6795 							set_ch_reverb(de->buf, cnt, de->reverb_send);
6796 						}
6797 						if (de->chorus_send > 0) {
6798 							set_ch_chorus(de->buf, cnt, de->chorus_send);
6799 						}
6800 						if (de->delay_send > 0) {
6801 							set_ch_delay(de->buf, cnt, de->delay_send);
6802 						}
6803 						mix_signal(p, de->buf, cnt);
6804 					}
6805 				} else {
6806 					if(channel_eq && channel[i].eq_xg.valid) {
6807 						do_ch_eq_xg(p, cnt, &(channel[i].eq_xg));
6808 					}
6809 					if(channel_chorus && channel[i].chorus_level > 0) {
6810 						set_ch_chorus(p, cnt, channel[i].chorus_level);
6811 					}
6812 					if(channel_delay && channel[i].delay_level > 0) {
6813 						set_ch_delay(p, cnt, channel[i].delay_level);
6814 					}
6815 					if(channel_reverb && channel[i].reverb_level > 0
6816 						&& current_sample - channel[i].lasttime < rev_max_delay_out) {
6817 						set_ch_reverb(p, cnt, channel[i].reverb_level);
6818 					}
6819 				}
6820 				if(channel[i].dry_level == 127) {
6821 					set_dry_signal(p, cnt);
6822 				} else {
6823 					set_dry_signal_xg(p, cnt, channel[i].dry_level);
6824 				}
6825 			}
6826 		}
6827 
6828 		if(channel_reverb) {
6829 			set_ch_reverb(buffer_pointer, cnt, DEFAULT_REVERB_SEND_LEVEL);
6830 		}
6831 		set_dry_signal(buffer_pointer, cnt);
6832 
6833 		/* mixing signal and applying system effects */
6834 		mix_dry_signal(buffer_pointer, cnt);
6835 		if(channel_delay) {do_variation_effect1_xg(buffer_pointer, cnt);}
6836 		if(channel_chorus) {do_ch_chorus_xg(buffer_pointer, cnt);}
6837 		if(channel_reverb) {do_ch_reverb(buffer_pointer, cnt);}
6838 		if(multi_eq_xg.valid) {do_multi_eq_xg(buffer_pointer, cnt);}
6839 	} else if(channel_effect) {	/* GM & GS */
6840 		if(opt_insertion_effect) { 	/* insertion effect */
6841 			/* applying insertion effect */
6842 			do_insertion_effect_gs(insertion_effect_buffer, cnt);
6843 			/* sending insertion effect voice to channel effect */
6844 			set_ch_chorus(insertion_effect_buffer, cnt, insertion_effect_gs.send_chorus);
6845 			set_ch_delay(insertion_effect_buffer, cnt, insertion_effect_gs.send_delay);
6846 			set_ch_reverb(insertion_effect_buffer, cnt,	insertion_effect_gs.send_reverb);
6847 			if(insertion_effect_gs.send_eq_switch && channel_eq) {
6848 				set_ch_eq_gs(insertion_effect_buffer, cnt);
6849 			} else {
6850 				set_dry_signal(insertion_effect_buffer, cnt);
6851 			}
6852 		}
6853 
6854 		for(i = 0; i < MAX_CHANNELS; i++) {	/* system effects */
6855 			int32 *p;
6856 			p = vpblist[i];
6857 			if(p != buffer_pointer && p != insertion_effect_buffer) {
6858 				if (opt_drum_effect && ISDRUMCHANNEL(i)) {
6859 					for (j = 0; j < channel[i].drum_effect_num; j++) {
6860 						de = &(channel[i].drum_effect[j]);
6861 						if (de->reverb_send > 0) {
6862 							set_ch_reverb(de->buf, cnt, de->reverb_send);
6863 						}
6864 						if (de->chorus_send > 0) {
6865 							set_ch_chorus(de->buf, cnt, de->chorus_send);
6866 						}
6867 						if (de->delay_send > 0) {
6868 							set_ch_delay(de->buf, cnt, de->delay_send);
6869 						}
6870 						mix_signal(p, de->buf, cnt);
6871 					}
6872 				} else {
6873 					if(channel_chorus && channel[i].chorus_level > 0) {
6874 						set_ch_chorus(p, cnt, channel[i].chorus_level);
6875 					}
6876 					if(channel_delay && channel[i].delay_level > 0) {
6877 						set_ch_delay(p, cnt, channel[i].delay_level);
6878 					}
6879 					if(channel_reverb && channel[i].reverb_level > 0
6880 						&& current_sample - channel[i].lasttime < rev_max_delay_out) {
6881 						set_ch_reverb(p, cnt, channel[i].reverb_level);
6882 					}
6883 				}
6884 				if(channel_eq && channel[i].eq_gs) {
6885 					set_ch_eq_gs(p, cnt);
6886 				} else {
6887 					set_dry_signal(p, cnt);
6888 				}
6889 			}
6890 		}
6891 
6892 		if(channel_reverb) {
6893 			set_ch_reverb(buffer_pointer, cnt, DEFAULT_REVERB_SEND_LEVEL);
6894 		}
6895 		set_dry_signal(buffer_pointer, cnt);
6896 
6897 		/* mixing signal and applying system effects */
6898 		mix_dry_signal(buffer_pointer, cnt);
6899 		if(channel_eq) {do_ch_eq_gs(buffer_pointer, cnt);}
6900 		if(channel_chorus) {do_ch_chorus(buffer_pointer, cnt);}
6901 		if(channel_delay) {do_ch_delay(buffer_pointer, cnt);}
6902 		if(channel_reverb) {do_ch_reverb(buffer_pointer, cnt);}
6903 	}
6904 
6905 	current_sample += count;
6906 }
6907 
6908 #else
6909 /* do_compute_data_midi() without DSP Effect */
do_compute_data_midi(int32 count)6910 static void do_compute_data_midi(int32 count)
6911 {
6912 	int i, j, uv, stereo, n, ch, note;
6913 	int32 *vpblist[MAX_CHANNELS];
6914 	int vc[MAX_CHANNELS];
6915 	int channel_reverb;
6916 	int channel_effect;
6917 	int32 cnt = count * 2;
6918 
6919 	stereo = ! (play_mode->encoding & PE_MONO);
6920 	n = count * ((stereo) ? 8 : 4); /* in bytes */
6921 	/* don't supported in mono */
6922 	channel_reverb = (stereo && (opt_reverb_control == 1
6923 			|| opt_reverb_control == 3
6924 			|| opt_reverb_control < 0 && opt_reverb_control & 0x80));
6925 	memset(buffer_pointer, 0, n);
6926 
6927 	channel_effect = (stereo && (opt_reverb_control || opt_chorus_control
6928 			|| opt_delay_control || opt_eq_control || opt_insertion_effect));
6929 	uv = upper_voices;
6930 	for (i = 0; i < uv; i++)
6931 		if (voice[i].status != VOICE_FREE)
6932 			channel[voice[i].channel].lasttime = current_sample + count;
6933 
6934 	if (channel_reverb) {
6935 		int chbufidx;
6936 
6937 		if (! make_rvid_flag) {
6938 			make_rvid();
6939 			make_rvid_flag = 1;
6940 		}
6941 		chbufidx = 0;
6942 		for (i = 0; i < MAX_CHANNELS; i++) {
6943 			vc[i] = 0;
6944 			if (channel[i].reverb_id != -1
6945 					&& current_sample - channel[i].lasttime
6946 					< REVERB_MAX_DELAY_OUT) {
6947 				if (reverb_buffer == NULL)
6948 					reverb_buffer = (char *) safe_malloc(MAX_CHANNELS
6949 							* AUDIO_BUFFER_SIZE * 8);
6950 				if (channel[i].reverb_id != i)
6951 					vpblist[i] = vpblist[channel[i].reverb_id];
6952 				else {
6953 					vpblist[i] = (int32 *) (reverb_buffer + chbufidx);
6954 					chbufidx += n;
6955 				}
6956 			} else
6957 				vpblist[i] = buffer_pointer;
6958 		}
6959 		if (chbufidx)
6960 			memset(reverb_buffer, 0, chbufidx);
6961 	}
6962 	for (i = 0; i < uv; i++)
6963 		if (voice[i].status != VOICE_FREE) {
6964 			int32 *vpb;
6965 
6966 			if (channel_reverb) {
6967 				int ch = voice[i].channel;
6968 
6969 				vpb = vpblist[ch];
6970 				vc[ch] = 1;
6971 			} else
6972 				vpb = buffer_pointer;
6973 			if (! IS_SET_CHANNELMASK(channel_mute, voice[i].channel))
6974 				mix_voice(vpb, i, count);
6975 			else {
6976 				free_voice(i);
6977 				ctl_note_event(i);
6978 			}
6979 			if (voice[i].timeout == 1 && voice[i].timeout < current_sample) {
6980 				free_voice(i);
6981 				ctl_note_event(i);
6982 			}
6983 		}
6984 
6985 	while (uv > 0 && voice[uv - 1].status == VOICE_FREE)
6986 		uv--;
6987 	upper_voices = uv;
6988 
6989 	if (channel_reverb) {
6990 		int k;
6991 
6992 		k = count * 2; /* calclated buffer length in int32 */
6993 		for (i = 0; i < MAX_CHANNELS; i++) {
6994 			int32 *p;
6995 
6996 			p = vpblist[i];
6997 			if (p != buffer_pointer && channel[i].reverb_id == i)
6998 				set_ch_reverb(p, k, channel[i].reverb_level);
6999 		}
7000 		set_ch_reverb(buffer_pointer, k, DEFAULT_REVERB_SEND_LEVEL);
7001 		do_ch_reverb(buffer_pointer, k);
7002 	}
7003 	current_sample += count;
7004 }
7005 #endif
7006 
do_compute_data_wav(int32 count)7007 static void do_compute_data_wav(int32 count)
7008 {
7009 	int i, stereo, samples, req_size, act_samples, v;
7010 
7011 	stereo = !(play_mode->encoding & PE_MONO);
7012 	samples = (stereo ? (count * 2) : count);
7013 	req_size = samples * 2; /* assume 16bit */
7014 
7015 	act_samples = tf_read(wav_buffer, 1, req_size, current_file_info->pcm_tf) / 2;
7016 	for(i = 0; i < act_samples; i++) {
7017 		v = (uint16)LE_SHORT(wav_buffer[i]);
7018 		buffer_pointer[i] = (int32)((v << 16) | (v ^ 0x8000)) / 4; /* 4 : level down */
7019 	}
7020 	for(; i < samples; i++)
7021 		buffer_pointer[i] = 0;
7022 
7023 	current_sample += count;
7024 }
7025 
do_compute_data_aiff(int32 count)7026 static void do_compute_data_aiff(int32 count)
7027 {
7028 	int i, stereo, samples, req_size, act_samples, v;
7029 
7030 	stereo = !(play_mode->encoding & PE_MONO);
7031 	samples = (stereo ? (count * 2) : count);
7032 	req_size = samples * 2; /* assume 16bit */
7033 
7034 	act_samples = tf_read(wav_buffer, 1, req_size, current_file_info->pcm_tf) / 2;
7035 	for(i = 0; i < act_samples; i++) {
7036 		v = (uint16)BE_SHORT(wav_buffer[i]);
7037 		buffer_pointer[i] = (int32)((v << 16) | (v ^ 0x8000)) / 4; /* 4 : level down */
7038 	}
7039 	for(; i < samples; i++)
7040 		buffer_pointer[i] = 0;
7041 
7042 	current_sample += count;
7043 }
7044 
7045 
do_compute_data(int32 count)7046 static void do_compute_data(int32 count)
7047 {
7048     switch(current_file_info->pcm_mode)
7049     {
7050       case PCM_MODE_NON:
7051     	do_compute_data_midi(count);
7052       	break;
7053       case PCM_MODE_WAV:
7054     	do_compute_data_wav(count);
7055         break;
7056       case PCM_MODE_AIFF:
7057     	do_compute_data_aiff(count);
7058         break;
7059       case PCM_MODE_AU:
7060         break;
7061       case PCM_MODE_MP3:
7062         break;
7063     }
7064 }
7065 
check_midi_play_end(MidiEvent * e,int len)7066 static int check_midi_play_end(MidiEvent *e, int len)
7067 {
7068     int i, type;
7069 
7070     for(i = 0; i < len; i++)
7071     {
7072 	type = e[i].type;
7073 	if(type == ME_NOTEON || type == ME_LAST || type == ME_WRD || type == ME_SHERRY)
7074 	    return 0;
7075 	if(type == ME_EOT)
7076 	    return i + 1;
7077     }
7078     return 0;
7079 }
7080 
7081 static int compute_data(int32 count);
midi_play_end(void)7082 static int midi_play_end(void)
7083 {
7084     int i, rc = RC_TUNE_END;
7085 
7086     check_eot_flag = 0;
7087 
7088     if(opt_realtime_playing && current_sample == 0)
7089     {
7090 	reset_voices();
7091 	return RC_TUNE_END;
7092     }
7093 
7094     if(upper_voices > 0)
7095     {
7096 	int fadeout_cnt;
7097 
7098 	rc = compute_data(play_mode->rate);
7099 	if(RC_IS_SKIP_FILE(rc))
7100 	    goto midi_end;
7101 
7102 	for(i = 0; i < upper_voices; i++)
7103 	    if(voice[i].status & (VOICE_ON | VOICE_SUSTAINED))
7104 		finish_note(i);
7105 	if(opt_realtime_playing)
7106 	    fadeout_cnt = 3;
7107 	else
7108 	    fadeout_cnt = 6;
7109 	for(i = 0; i < fadeout_cnt && upper_voices > 0; i++)
7110 	{
7111 	    rc = compute_data(play_mode->rate / 2);
7112 	    if(RC_IS_SKIP_FILE(rc))
7113 		goto midi_end;
7114 	}
7115 
7116 	/* kill voices */
7117 	kill_all_voices();
7118 	rc = compute_data(MAX_DIE_TIME);
7119 	if(RC_IS_SKIP_FILE(rc))
7120 	    goto midi_end;
7121 	upper_voices = 0;
7122     }
7123 
7124     /* clear reverb echo sound */
7125     init_reverb();
7126     for(i = 0; i < MAX_CHANNELS; i++)
7127     {
7128 	channel[i].reverb_level = -1;
7129 	channel[i].reverb_id = -1;
7130 	make_rvid_flag = 1;
7131     }
7132 
7133     /* output null sound */
7134     if(opt_realtime_playing)
7135 	rc = compute_data((int32)(play_mode->rate * PLAY_INTERLEAVE_SEC/2));
7136     else
7137 	rc = compute_data((int32)(play_mode->rate * PLAY_INTERLEAVE_SEC));
7138     if(RC_IS_SKIP_FILE(rc))
7139 	goto midi_end;
7140 
7141     compute_data(0); /* flush buffer to device */
7142 
7143     if(ctl->trace_playing)
7144     {
7145 	rc = aq_flush(0); /* Wait until play out */
7146 	if(RC_IS_SKIP_FILE(rc))
7147 	    goto midi_end;
7148     }
7149     else
7150     {
7151 	trace_flush();
7152 	rc = aq_soft_flush();
7153 	if(RC_IS_SKIP_FILE(rc))
7154 	    goto midi_end;
7155     }
7156 
7157   midi_end:
7158     if(RC_IS_SKIP_FILE(rc))
7159 	aq_flush(1);
7160 
7161     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Playing time: ~%d seconds",
7162 	      current_sample/play_mode->rate+2);
7163     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Notes cut: %d",
7164 	      cut_notes);
7165     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Notes lost totally: %d",
7166 	      lost_notes);
7167     if(RC_IS_SKIP_FILE(rc))
7168 	return rc;
7169     return RC_TUNE_END;
7170 }
7171 
7172 /* count=0 means flush remaining buffered data to output device, then
7173    flush the device itself */
compute_data(int32 count)7174 static int compute_data(int32 count)
7175 {
7176   int rc;
7177 
7178   if (!count)
7179     {
7180       if (buffered_count)
7181       {
7182 	  ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
7183 		    "output data (%d)", buffered_count);
7184 
7185 #ifdef SUPPORT_SOUNDSPEC
7186 	  soundspec_update_wave(common_buffer, buffered_count);
7187 #endif /* SUPPORT_SOUNDSPEC */
7188 
7189 	  if(aq_add(common_buffer, buffered_count) == -1)
7190 	      return RC_ERROR;
7191       }
7192       buffer_pointer=common_buffer;
7193       buffered_count=0;
7194       return RC_NONE;
7195     }
7196 
7197   while ((count+buffered_count) >= audio_buffer_size)
7198     {
7199       int i;
7200 
7201       if((rc = apply_controls()) != RC_NONE)
7202 	  return rc;
7203 
7204       do_compute_data(audio_buffer_size-buffered_count);
7205       count -= audio_buffer_size-buffered_count;
7206       ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
7207 		"output data (%d)", audio_buffer_size);
7208 
7209 #ifdef SUPPORT_SOUNDSPEC
7210       soundspec_update_wave(common_buffer, audio_buffer_size);
7211 #endif /* SUPPORT_SOUNDSPEC */
7212 
7213       /* fall back to linear interpolation when queue < 100% */
7214       if (! opt_realtime_playing && (play_mode->flag & PF_CAN_TRACE)) {
7215 	  if (!aq_fill_buffer_flag &&
7216 	      100 * ((double)(aq_filled() + aq_soft_filled()) /
7217 		     aq_get_dev_queuesize()) < 99)
7218 	      reduce_quality_flag = 1;
7219 	  else
7220 	      reduce_quality_flag = no_4point_interpolation;
7221       }
7222 
7223 #ifdef REDUCE_VOICE_TIME_TUNING
7224       /* Auto voice reduce implementation by Masanao Izumo */
7225       if(reduce_voice_threshold &&
7226 	 (play_mode->flag & PF_CAN_TRACE) &&
7227 	 !aq_fill_buffer_flag &&
7228 	 aq_get_dev_queuesize() > 0)
7229       {
7230 	  /* Reduce voices if there is not enough audio device buffer */
7231 
7232           int nv, filled, filled_limit, rate, rate_limit;
7233           static int last_filled;
7234 
7235 	  filled = aq_filled();
7236 
7237 	  rate_limit = 75;
7238 	  if(reduce_voice_threshold >= 0)
7239 	  {
7240 	      filled_limit = play_mode->rate * reduce_voice_threshold / 1000
7241 		  + 1; /* +1 disable zero */
7242 	  }
7243 	  else /* Use default threshold */
7244 	  {
7245 	      int32 maxfill;
7246 	      maxfill = aq_get_dev_queuesize();
7247 	      filled_limit = REDUCE_VOICE_TIME_TUNING;
7248 	      if(filled_limit > maxfill / 5) /* too small audio buffer */
7249 	      {
7250 		  rate_limit -= 100 * audio_buffer_size / maxfill / 5;
7251 		  filled_limit = 1;
7252 	      }
7253 	  }
7254 
7255 	  /* Calculate rate as it is displayed in ncurs_c.c */
7256 	  /* The old method of calculating rate resulted in very low values
7257 	     when using the new high order interplation methods on "slow"
7258 	     CPUs when the queue was being drained WAY too quickly.  This
7259 	     caused premature voice reduction under Linux, even if the queue
7260 	     was over 2000%, leading to major voice lossage. */
7261 	  rate = (int)(((double)(aq_filled() + aq_soft_filled()) /
7262                   	aq_get_dev_queuesize()) * 100 + 0.5);
7263 
7264           for(i = nv = 0; i < upper_voices; i++)
7265 	      if(voice[i].status != VOICE_FREE)
7266 	          nv++;
7267 
7268 	  if(! opt_realtime_playing)
7269 	  {
7270 	      /* calculate ok_nv, the "optimum" max polyphony */
7271 	      if (auto_reduce_polyphony && rate < 85) {
7272 		/* average in current nv */
7273 	        if ((rate == old_rate && nv > min_bad_nv) ||
7274 	            (rate >= old_rate && rate < 20)) {
7275 	        	ok_nv_total += nv;
7276 	        	ok_nv_counts++;
7277 	        }
7278 	        /* increase polyphony when it is too low */
7279 	        else if (nv == voices &&
7280 	                 (rate > old_rate && filled > last_filled)) {
7281 	          		ok_nv_total += nv + 1;
7282 	          		ok_nv_counts++;
7283 	        }
7284 	        /* reduce polyphony when loosing buffer */
7285 	        else if (rate < 75 &&
7286 	        	 (rate < old_rate && filled < last_filled)) {
7287 	        	ok_nv_total += min_bad_nv;
7288 	    		ok_nv_counts++;
7289 	        }
7290 	        else goto NO_RESCALE_NV;
7291 
7292 		/* rescale ok_nv stuff every 1 seconds */
7293 		if (current_sample >= ok_nv_sample && ok_nv_counts > 1) {
7294 			ok_nv_total >>= 1;
7295 			ok_nv_counts >>= 1;
7296 			ok_nv_sample = current_sample + (play_mode->rate);
7297 		}
7298 
7299 		NO_RESCALE_NV:;
7300 	      }
7301 	  }
7302 
7303 	  /* EAW -- if buffer is < 75%, start reducing some voices to
7304 	     try to let it recover.  This really helps a lot, preserves
7305 	     decent sound, and decreases the frequency of lost ON notes */
7306 	  if ((! opt_realtime_playing && rate < rate_limit)
7307 	      || filled < filled_limit)
7308 	  {
7309 	      if(filled <= last_filled)
7310 	      {
7311 	          int kill_nv, temp_nv;
7312 
7313 		  /* set bounds on "good" and "bad" nv */
7314 		  if (! opt_realtime_playing && rate > 20 &&
7315 		      nv < min_bad_nv) {
7316 		  	min_bad_nv = nv;
7317 	                if (max_good_nv < min_bad_nv)
7318 	                	max_good_nv = min_bad_nv;
7319 	          }
7320 
7321 		  /* EAW -- count number of !ON voices */
7322 		  /* treat chorus notes as !ON */
7323 		  for(i = kill_nv = 0; i < upper_voices; i++) {
7324 		      if(voice[i].status & VOICE_FREE ||
7325 		         voice[i].cache != NULL)
7326 		      		continue;
7327 
7328 		      if((voice[i].status & ~(VOICE_ON|VOICE_SUSTAINED) &&
7329 			  !(voice[i].status & ~(VOICE_DIE) &&
7330 			    voice[i].sample->note_to_use)))
7331 				kill_nv++;
7332 		  }
7333 
7334 		  /* EAW -- buffer is dangerously low, drasticly reduce
7335 		     voices to a hopefully "safe" amount */
7336 		  if (filled < filled_limit &&
7337 		      (opt_realtime_playing || rate < 10)) {
7338 		      FLOAT_T n;
7339 
7340 		      /* calculate the drastic voice reduction */
7341 		      if(nv > kill_nv) /* Avoid division by zero */
7342 		      {
7343 			  n = (FLOAT_T) nv / (nv - kill_nv);
7344 			  temp_nv = (int)(nv - nv / (n + 1));
7345 
7346 			  /* reduce by the larger of the estimates */
7347 			  if (kill_nv < temp_nv && temp_nv < nv)
7348 			      kill_nv = temp_nv;
7349 		      }
7350 		      else kill_nv = nv - 1; /* do not kill all the voices */
7351 		  }
7352 		  else {
7353 		      /* the buffer is still high enough that we can throw
7354 		         fewer voices away; keep the ON voices, use the
7355 		         minimum "bad" nv as a floor on voice reductions */
7356 		      temp_nv = nv - min_bad_nv;
7357 		      if (kill_nv > temp_nv)
7358 		          kill_nv = temp_nv;
7359 		  }
7360 
7361 		  for(i = 0; i < kill_nv; i++)
7362 		      reduce_voice();
7363 
7364 		  /* lower max # of allowed voices to let the buffer recover */
7365 		  if (auto_reduce_polyphony) {
7366 		  	temp_nv = nv - kill_nv;
7367 		  	ok_nv = ok_nv_total / ok_nv_counts;
7368 
7369 		  	/* decrease it to current nv left */
7370 		  	if (voices > temp_nv && temp_nv > ok_nv)
7371 			    voice_decrement_conservative(voices - temp_nv);
7372 			/* decrease it to ok_nv */
7373 		  	else if (voices > ok_nv && temp_nv <= ok_nv)
7374 			    voice_decrement_conservative(voices - ok_nv);
7375 		  	/* increase the polyphony */
7376 		  	else if (voices < ok_nv)
7377 			    voice_increment(ok_nv - voices);
7378 		  }
7379 
7380 		  while(upper_voices > 0 &&
7381 			voice[upper_voices - 1].status == VOICE_FREE)
7382 		      upper_voices--;
7383 	      }
7384 	      last_filled = filled;
7385 	  }
7386 	  else {
7387 	      if (! opt_realtime_playing && rate >= rate_limit &&
7388 	          filled > last_filled) {
7389 
7390 		    /* set bounds on "good" and "bad" nv */
7391 		    if (rate > 85 && nv > max_good_nv) {
7392 		  	max_good_nv = nv;
7393 		  	if (min_bad_nv > max_good_nv)
7394 		  	    min_bad_nv = max_good_nv;
7395 		    }
7396 
7397 		    if (auto_reduce_polyphony) {
7398 		    	/* reset ok_nv stuff when out of danger */
7399 		    	ok_nv_total = max_good_nv * ok_nv_counts;
7400 			if (ok_nv_counts > 1) {
7401 			    ok_nv_total >>= 1;
7402 			    ok_nv_counts >>= 1;
7403 			}
7404 
7405 		    	/* restore max # of allowed voices to normal */
7406 			restore_voices(0);
7407 		    }
7408 	      }
7409 
7410 	      last_filled = filled_limit;
7411           }
7412           old_rate = rate;
7413       }
7414 #endif
7415 
7416       if(aq_add(common_buffer, audio_buffer_size) == -1)
7417 	  return RC_ERROR;
7418 
7419       buffer_pointer=common_buffer;
7420       buffered_count=0;
7421       if(current_event->type != ME_EOT)
7422 	  ctl_timestamp();
7423 
7424       /* check break signals */
7425       VOLATILE_TOUCH(intr);
7426       if(intr)
7427 	  return RC_QUIT;
7428 
7429       if(upper_voices == 0 && check_eot_flag &&
7430 	 (i = check_midi_play_end(current_event, EOT_PRESEARCH_LEN)) > 0)
7431       {
7432 	  if(i > 1)
7433 	      ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
7434 			"Last %d MIDI events are ignored", i - 1);
7435 	  return midi_play_end();
7436       }
7437     }
7438   if (count>0)
7439     {
7440       do_compute_data(count);
7441       buffered_count += count;
7442       buffer_pointer += (play_mode->encoding & PE_MONO) ? count : count*2;
7443     }
7444   return RC_NONE;
7445 }
7446 
update_modulation_wheel(int ch)7447 static void update_modulation_wheel(int ch)
7448 {
7449     int i, uv = upper_voices;
7450 	channel[ch].pitchfactor = 0;
7451     for(i = 0; i < uv; i++)
7452 	if(voice[i].status != VOICE_FREE && voice[i].channel == ch)
7453 	{
7454 	    /* Set/Reset mod-wheel */
7455 		voice[i].vibrato_control_counter = voice[i].vibrato_phase = 0;
7456 	    recompute_amp(i);
7457 		apply_envelope_to_amp(i);
7458 	    recompute_freq(i);
7459 		recompute_voice_filter(i);
7460 	}
7461 }
7462 
drop_portamento(int ch)7463 static void drop_portamento(int ch)
7464 {
7465     int i, uv = upper_voices;
7466 
7467     channel[ch].porta_control_ratio = 0;
7468     for(i = 0; i < uv; i++)
7469 	if(voice[i].status != VOICE_FREE &&
7470 	   voice[i].channel == ch &&
7471 	   voice[i].porta_control_ratio)
7472 	{
7473 	    voice[i].porta_control_ratio = 0;
7474 	    recompute_freq(i);
7475 	}
7476     channel[ch].last_note_fine = -1;
7477 }
7478 
update_portamento_controls(int ch)7479 static void update_portamento_controls(int ch)
7480 {
7481     if(!channel[ch].portamento ||
7482        (channel[ch].portamento_time_msb | channel[ch].portamento_time_lsb)
7483        == 0)
7484 	drop_portamento(ch);
7485     else
7486     {
7487 	double mt, dc;
7488 	int d;
7489 
7490 	mt = midi_time_table[channel[ch].portamento_time_msb & 0x7F] *
7491 	    midi_time_table2[channel[ch].portamento_time_lsb & 0x7F] *
7492 		PORTAMENTO_TIME_TUNING;
7493 	dc = play_mode->rate * mt;
7494 	d = (int)(1.0 / (mt * PORTAMENTO_CONTROL_RATIO));
7495 	d++;
7496 	channel[ch].porta_control_ratio = (int)(d * dc + 0.5);
7497 	channel[ch].porta_dpb = d;
7498     }
7499 }
7500 
update_portamento_time(int ch)7501 static void update_portamento_time(int ch)
7502 {
7503     int i, uv = upper_voices;
7504     int dpb;
7505     int32 ratio;
7506 
7507     update_portamento_controls(ch);
7508     dpb = channel[ch].porta_dpb;
7509     ratio = channel[ch].porta_control_ratio;
7510 
7511     for(i = 0; i < uv; i++)
7512     {
7513 	if(voice[i].status != VOICE_FREE &&
7514 	   voice[i].channel == ch &&
7515 	   voice[i].porta_control_ratio)
7516 	{
7517 	    voice[i].porta_control_ratio = ratio;
7518 	    voice[i].porta_dpb = dpb;
7519 	    recompute_freq(i);
7520 	}
7521     }
7522 }
7523 
update_legato_controls(int ch)7524 static void update_legato_controls(int ch)
7525 {
7526 	double mt, dc;
7527 	int d;
7528 
7529 	mt = 0.06250 * PORTAMENTO_TIME_TUNING * 0.3;
7530 	dc = play_mode->rate * mt;
7531 	d = (int)(1.0 / (mt * PORTAMENTO_CONTROL_RATIO));
7532 	d++;
7533 	channel[ch].porta_control_ratio = (int)(d * dc + 0.5);
7534 	channel[ch].porta_dpb = d;
7535 }
7536 
play_event(MidiEvent * ev)7537 int play_event(MidiEvent *ev)
7538 {
7539     int32 i, j, cet;
7540     int k, l, ch, orig_ch, port_ch, offset, layered;
7541 
7542     if(play_mode->flag & PF_MIDI_EVENT)
7543 	return play_mode->acntl(PM_REQ_MIDI, ev);
7544     if(!(play_mode->flag & PF_PCM_STREAM))
7545 	return RC_NONE;
7546 
7547     current_event = ev;
7548     cet = MIDI_EVENT_TIME(ev);
7549 
7550     if(ctl->verbosity >= VERB_DEBUG_SILLY)
7551 	ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
7552 		  "Midi Event %d: %s %d %d %d", cet,
7553 		  event_name(ev->type), ev->channel, ev->a, ev->b);
7554     if(cet > current_sample)
7555     {
7556 	int rc;
7557 
7558 #if ! defined(IA_WINSYN) && ! defined(IA_PORTMIDISYN) && ! defined(IA_W32G_SYN)
7559 	if (midi_streaming != 0)
7560 		if ((cet - current_sample) * 1000 / play_mode->rate
7561 				> stream_max_compute) {
7562 			kill_all_voices();
7563 			/* reset_voices(); */
7564 			/* ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
7565 					"play_event: discard %d samples", cet - current_sample); */
7566 			current_sample = cet;
7567 		}
7568 #endif
7569 
7570 	rc = compute_data(cet - current_sample);
7571 	ctl_mode_event(CTLE_REFRESH, 0, 0, 0);
7572     if(rc == RC_JUMP)
7573 	{
7574 		ctl_timestamp();
7575 		return RC_NONE;
7576 	}
7577 	if(rc != RC_NONE)
7578 	    return rc;
7579 	}
7580 
7581 #ifndef SUPPRESS_CHANNEL_LAYER
7582 	orig_ch = ev->channel;
7583 	layered = ! IS_SYSEX_EVENT_TYPE(ev);
7584 	for (k = 0; k < MAX_CHANNELS; k += 16) {
7585 		port_ch = (orig_ch + k) % MAX_CHANNELS;
7586 		offset = port_ch & ~0xf;
7587 		for (l = offset; l < offset + 16; l++) {
7588 			if (! layered && (k || l != offset))
7589 				continue;
7590 			if (layered) {
7591 				if (! IS_SET_CHANNELMASK(channel[l].channel_layer, port_ch)
7592 						|| channel[l].port_select != (orig_ch >> 4))
7593 					continue;
7594 				ev->channel = l;
7595 			}
7596 #endif
7597 	ch = ev->channel;
7598 
7599     switch(ev->type)
7600     {
7601 	/* MIDI Events */
7602       case ME_NOTEOFF:
7603 	note_off(ev);
7604 	break;
7605 
7606       case ME_NOTEON:
7607 	note_on(ev);
7608 	break;
7609 
7610       case ME_KEYPRESSURE:
7611 	adjust_pressure(ev);
7612 	break;
7613 
7614       case ME_PROGRAM:
7615 	midi_program_change(ch, ev->a);
7616 	ctl_prog_event(ch);
7617 	break;
7618 
7619       case ME_CHANNEL_PRESSURE:
7620 	adjust_channel_pressure(ev);
7621 	break;
7622 
7623       case ME_PITCHWHEEL:
7624 	channel[ch].pitchbend = ev->a + ev->b * 128;
7625 	channel[ch].pitchfactor = 0;
7626 	/* Adjust pitch for notes already playing */
7627 	adjust_pitch(ch);
7628 	ctl_mode_event(CTLE_PITCH_BEND, 1, ch, channel[ch].pitchbend);
7629 	break;
7630 
7631 	/* Controls */
7632       case ME_TONE_BANK_MSB:
7633 	channel[ch].bank_msb = ev->a;
7634 	break;
7635 
7636       case ME_TONE_BANK_LSB:
7637 	channel[ch].bank_lsb = ev->a;
7638 	break;
7639 
7640       case ME_MODULATION_WHEEL:
7641 	channel[ch].mod.val = ev->a;
7642 	update_modulation_wheel(ch);
7643 	ctl_mode_event(CTLE_MOD_WHEEL, 1, ch, channel[ch].mod.val);
7644 	break;
7645 
7646       case ME_MAINVOLUME:
7647 	channel[ch].volume = ev->a;
7648 	adjust_volume(ch);
7649 	ctl_mode_event(CTLE_VOLUME, 1, ch, ev->a);
7650 	break;
7651 
7652       case ME_PAN:
7653 	channel[ch].panning = ev->a;
7654 	channel[ch].pan_random = 0;
7655 	if(adjust_panning_immediately && !channel[ch].pan_random)
7656 	    adjust_panning(ch);
7657 	ctl_mode_event(CTLE_PANNING, 1, ch, ev->a);
7658 	break;
7659 
7660       case ME_EXPRESSION:
7661 	channel[ch].expression = ev->a;
7662 	adjust_volume(ch);
7663 	ctl_mode_event(CTLE_EXPRESSION, 1, ch, ev->a);
7664 	break;
7665 
7666       case ME_SUSTAIN:
7667     if (channel[ch].sustain == 0 && ev->a >= 64) {
7668 		update_redamper_controls(ch);
7669 	}
7670 	channel[ch].sustain = ev->a;
7671 	if (channel[ch].damper_mode == 0) {	/* half-damper is not allowed. */
7672 		if (channel[ch].sustain >= 64) {channel[ch].sustain = 127;}
7673 		else {channel[ch].sustain = 0;}
7674 	}
7675 	if(channel[ch].sustain == 0 && channel[ch].sostenuto == 0)
7676 	    drop_sustain(ch);
7677 	ctl_mode_event(CTLE_SUSTAIN, 1, ch, channel[ch].sustain);
7678 	break;
7679 
7680       case ME_SOSTENUTO:
7681 	channel[ch].sostenuto = (ev->a >= 64);
7682 	if(channel[ch].sustain == 0 && channel[ch].sostenuto == 0)
7683 	    drop_sustain(ch);
7684 	else {update_sostenuto_controls(ch);}
7685 	ctl->cmsg(CMSG_INFO, VERB_NOISY, "Sostenuto %d", channel[ch].sostenuto);
7686 	break;
7687 
7688       case ME_LEGATO_FOOTSWITCH:
7689     channel[ch].legato = (ev->a >= 64);
7690 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Legato Footswitch (CH:%d VAL:%d)", ch, channel[ch].legato);
7691 	break;
7692 
7693       case ME_HOLD2:
7694 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Hold2 - this function is not supported.");
7695 	break;
7696 
7697       case ME_BREATH:
7698 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Breath - this function is not supported.");
7699 	break;
7700 
7701       case ME_FOOT:
7702 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Foot - this function is not supported.");
7703 	break;
7704 
7705       case ME_BALANCE:
7706 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Balance - this function is not supported.");
7707 	break;
7708 
7709       case ME_PORTAMENTO_TIME_MSB:
7710 	channel[ch].portamento_time_msb = ev->a;
7711 	update_portamento_time(ch);
7712 	break;
7713 
7714       case ME_PORTAMENTO_TIME_LSB:
7715 	channel[ch].portamento_time_lsb = ev->a;
7716 	update_portamento_time(ch);
7717 	break;
7718 
7719       case ME_PORTAMENTO:
7720 	channel[ch].portamento = (ev->a >= 64);
7721 	if(!channel[ch].portamento)
7722 	    drop_portamento(ch);
7723 	break;
7724 
7725 	  case ME_SOFT_PEDAL:
7726 		  if(opt_lpf_def) {
7727 			  channel[ch].soft_pedal = ev->a;
7728 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Soft Pedal (CH:%d VAL:%d)",ch,channel[ch].soft_pedal);
7729 		  }
7730 		  break;
7731 
7732 	  case ME_HARMONIC_CONTENT:
7733 		  if(opt_lpf_def) {
7734 			  channel[ch].param_resonance = ev->a - 64;
7735 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Harmonic Content (CH:%d VAL:%d)",ch,channel[ch].param_resonance);
7736 		  }
7737 		  break;
7738 
7739 	  case ME_BRIGHTNESS:
7740 		  if(opt_lpf_def) {
7741 			  channel[ch].param_cutoff_freq = ev->a - 64;
7742 			  ctl->cmsg(CMSG_INFO,VERB_NOISY,"Brightness (CH:%d VAL:%d)",ch,channel[ch].param_cutoff_freq);
7743 		  }
7744 		  break;
7745 
7746       case ME_DATA_ENTRY_MSB:
7747 	if(channel[ch].rpn_7f7f_flag) /* disable */
7748 	    break;
7749 	if((i = last_rpn_addr(ch)) >= 0)
7750 	{
7751 	    channel[ch].rpnmap[i] = ev->a;
7752 	    update_rpn_map(ch, i, 1);
7753 	}
7754 	break;
7755 
7756       case ME_DATA_ENTRY_LSB:
7757 	if(channel[ch].rpn_7f7f_flag) /* disable */
7758 	    break;
7759 	    if((i = last_rpn_addr(ch)) >= 0)
7760 	    {
7761 		channel[ch].rpnmap_lsb[i] = ev->a;
7762 	    }
7763 	break;
7764 
7765 	case ME_REVERB_EFFECT:
7766 		if (opt_reverb_control) {
7767 			if (ISDRUMCHANNEL(ch) && get_reverb_level(ch) != ev->a) {channel[ch].drum_effect_flag = 0;}
7768 			set_reverb_level(ch, ev->a);
7769 			ctl_mode_event(CTLE_REVERB_EFFECT, 1, ch, get_reverb_level(ch));
7770 		}
7771 		break;
7772 
7773       case ME_CHORUS_EFFECT:
7774 	if(opt_chorus_control)
7775 	{
7776 		if(opt_chorus_control == 1) {
7777 			if (ISDRUMCHANNEL(ch) && channel[ch].chorus_level != ev->a) {channel[ch].drum_effect_flag = 0;}
7778 			channel[ch].chorus_level = ev->a;
7779 		} else {
7780 			channel[ch].chorus_level = -opt_chorus_control;
7781 		}
7782 	    ctl_mode_event(CTLE_CHORUS_EFFECT, 1, ch, get_chorus_level(ch));
7783 		if(ev->a) {
7784 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send (CH:%d LEVEL:%d)",ch,ev->a);
7785 		}
7786 	}
7787 	break;
7788 
7789       case ME_TREMOLO_EFFECT:
7790 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tremolo Send (CH:%d LEVEL:%d)",ch,ev->a);
7791 	break;
7792 
7793       case ME_CELESTE_EFFECT:
7794 	if(opt_delay_control) {
7795 		if (ISDRUMCHANNEL(ch) && channel[ch].delay_level != ev->a) {channel[ch].drum_effect_flag = 0;}
7796 		channel[ch].delay_level = ev->a;
7797 		if (play_system_mode == XG_SYSTEM_MODE) {
7798 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Variation Send (CH:%d LEVEL:%d)",ch,ev->a);
7799 		} else {
7800 			ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send (CH:%d LEVEL:%d)",ch,ev->a);
7801 		}
7802 	}
7803 	break;
7804 
7805 	  case ME_ATTACK_TIME:
7806   	if(!opt_tva_attack) { break; }
7807 	set_envelope_time(ch, ev->a, EG_ATTACK);
7808 	break;
7809 
7810 	  case ME_RELEASE_TIME:
7811   	if(!opt_tva_release) { break; }
7812 	set_envelope_time(ch, ev->a, EG_RELEASE);
7813 	break;
7814 
7815       case ME_PHASER_EFFECT:
7816 	ctl->cmsg(CMSG_INFO,VERB_NOISY,"Phaser Send (CH:%d LEVEL:%d)",ch,ev->a);
7817 	break;
7818 
7819       case ME_RPN_INC:
7820 	if(channel[ch].rpn_7f7f_flag) /* disable */
7821 	    break;
7822 	if((i = last_rpn_addr(ch)) >= 0)
7823 	{
7824 	    if(channel[ch].rpnmap[i] < 127)
7825 		channel[ch].rpnmap[i]++;
7826 	    update_rpn_map(ch, i, 1);
7827 	}
7828 	break;
7829 
7830       case ME_RPN_DEC:
7831 	if(channel[ch].rpn_7f7f_flag) /* disable */
7832 	    break;
7833 	if((i = last_rpn_addr(ch)) >= 0)
7834 	{
7835 	    if(channel[ch].rpnmap[i] > 0)
7836 		channel[ch].rpnmap[i]--;
7837 	    update_rpn_map(ch, i, 1);
7838 	}
7839 	break;
7840 
7841       case ME_NRPN_LSB:
7842 	channel[ch].lastlrpn = ev->a;
7843 	channel[ch].nrpn = 1;
7844 	break;
7845 
7846       case ME_NRPN_MSB:
7847 	channel[ch].lastmrpn = ev->a;
7848 	channel[ch].nrpn = 1;
7849 	break;
7850 
7851       case ME_RPN_LSB:
7852 	channel[ch].lastlrpn = ev->a;
7853 	channel[ch].nrpn = 0;
7854 	break;
7855 
7856       case ME_RPN_MSB:
7857 	channel[ch].lastmrpn = ev->a;
7858 	channel[ch].nrpn = 0;
7859 	break;
7860 
7861       case ME_ALL_SOUNDS_OFF:
7862 	all_sounds_off(ch);
7863 	break;
7864 
7865       case ME_RESET_CONTROLLERS:
7866 	reset_controllers(ch);
7867 	redraw_controllers(ch);
7868 	break;
7869 
7870       case ME_ALL_NOTES_OFF:
7871 	all_notes_off(ch);
7872 	break;
7873 
7874       case ME_MONO:
7875 	channel[ch].mono = 1;
7876 	all_notes_off(ch);
7877 	break;
7878 
7879       case ME_POLY:
7880 	channel[ch].mono = 0;
7881 	all_notes_off(ch);
7882 	break;
7883 
7884 	/* TiMidity Extensionals */
7885       case ME_RANDOM_PAN:
7886 	channel[ch].panning = int_rand(128);
7887 	channel[ch].pan_random = 1;
7888 	if(adjust_panning_immediately && !channel[ch].pan_random)
7889 	    adjust_panning(ch);
7890 	break;
7891 
7892       case ME_SET_PATCH:
7893 	i = channel[ch].special_sample = current_event->a;
7894 	if(special_patch[i] != NULL)
7895 	    special_patch[i]->sample_offset = 0;
7896 	ctl_prog_event(ch);
7897 	break;
7898 
7899       case ME_TEMPO:
7900 	current_play_tempo = ch + ev->b * 256 + ev->a * 65536;
7901 	ctl_mode_event(CTLE_TEMPO, 1, current_play_tempo, 0);
7902 	break;
7903 
7904       case ME_CHORUS_TEXT:
7905       case ME_LYRIC:
7906       case ME_MARKER:
7907       case ME_INSERT_TEXT:
7908       case ME_TEXT:
7909       case ME_KARAOKE_LYRIC:
7910 	i = ev->a | ((int)ev->b << 8);
7911 	ctl_mode_event(CTLE_LYRIC, 1, i, 0);
7912 	break;
7913 
7914       case ME_GSLCD:
7915 	i = ev->a | ((int)ev->b << 8);
7916 	ctl_mode_event(CTLE_GSLCD, 1, i, 0);
7917 	break;
7918 
7919       case ME_MASTER_VOLUME:
7920 	master_volume_ratio = (int32)ev->a + 256 * (int32)ev->b;
7921 	adjust_master_volume();
7922 	break;
7923 
7924       case ME_RESET:
7925 	change_system_mode(ev->a);
7926 	reset_midi(1);
7927 	break;
7928 
7929       case ME_PATCH_OFFS:
7930 	i = channel[ch].special_sample;
7931 	if(special_patch[i] != NULL)
7932 	    special_patch[i]->sample_offset =
7933 		(current_event->a | 256 * current_event->b);
7934 	break;
7935 
7936       case ME_WRD:
7937 	push_midi_trace2(wrd_midi_event,
7938 			 ch, current_event->a | (current_event->b << 8));
7939 	break;
7940 
7941       case ME_SHERRY:
7942 	push_midi_trace1(wrd_sherry_event,
7943 			 ch | (current_event->a<<8) | (current_event->b<<16));
7944 	break;
7945 
7946       case ME_DRUMPART:
7947 	if(midi_drumpart_change(ch, current_event->a))
7948 	{
7949 	    /* Update bank information */
7950 	    midi_program_change(ch, channel[ch].program);
7951 	    ctl_mode_event(CTLE_DRUMPART, 1, ch, ISDRUMCHANNEL(ch));
7952 	    ctl_prog_event(ch);
7953 	}
7954 	break;
7955 
7956       case ME_KEYSHIFT:
7957 	i = (int)current_event->a - 0x40;
7958 	if(i != channel[ch].key_shift)
7959 	{
7960 	    all_sounds_off(ch);
7961 	    channel[ch].key_shift = (int8)i;
7962 	}
7963 	break;
7964 
7965 	case ME_KEYSIG:
7966 		if (opt_init_keysig != 8)
7967 			break;
7968 		current_keysig = current_event->a + current_event->b * 16;
7969 		ctl_mode_event(CTLE_KEYSIG, 1, current_keysig, 0);
7970 		if (opt_force_keysig != 8) {
7971 			i = current_keysig - ((current_keysig < 8) ? 0 : 16), j = 0;
7972 			while (i != opt_force_keysig && i != opt_force_keysig + 12)
7973 				i += (i > 0) ? -5 : 7, j++;
7974 			while (abs(j - note_key_offset) > 7)
7975 				j += (j > note_key_offset) ? -12 : 12;
7976 			if (abs(j - key_adjust) >= 12)
7977 				j += (j > key_adjust) ? -12 : 12;
7978 			note_key_offset = j;
7979 			kill_all_voices();
7980 			ctl_mode_event(CTLE_KEY_OFFSET, 1, note_key_offset, 0);
7981 		}
7982 		i = current_keysig + ((current_keysig < 8) ? 7 : -9), j = 0;
7983 		while (i != 7)
7984 			i += (i < 7) ? 5 : -7, j++;
7985 		j += note_key_offset, j -= floor(j / 12.0) * 12;
7986 		current_freq_table = j;
7987 		break;
7988 
7989 	case ME_MASTER_TUNING:
7990 		set_master_tuning((ev->b << 8) | ev->a);
7991 		adjust_all_pitch();
7992 		break;
7993 
7994 	case ME_SCALE_TUNING:
7995 		resamp_cache_refer_alloff(ch, current_event->time);
7996 		channel[ch].scale_tuning[current_event->a] = current_event->b;
7997 		adjust_pitch(ch);
7998 		break;
7999 
8000 	case ME_BULK_TUNING_DUMP:
8001 		set_single_note_tuning(ch, current_event->a, current_event->b, 0);
8002 		break;
8003 
8004 	case ME_SINGLE_NOTE_TUNING:
8005 		set_single_note_tuning(ch, current_event->a, current_event->b, 1);
8006 		break;
8007 
8008 	case ME_TEMPER_KEYSIG:
8009 		current_temper_keysig = (current_event->a + 8) % 32 - 8;
8010 		temper_adj = ((current_event->a + 8) & 0x20) ? 1 : 0;
8011 		ctl_mode_event(CTLE_TEMPER_KEYSIG, 1, current_event->a, 0);
8012 		i = current_temper_keysig + ((current_temper_keysig < 8) ? 7 : -9);
8013 		j = 0;
8014 		while (i != 7)
8015 			i += (i < 7) ? 5 : -7, j++;
8016 		j += note_key_offset, j -= floor(j / 12.0) * 12;
8017 		current_temper_freq_table = j;
8018 		if (current_event->b)
8019 			for (i = 0; i < upper_voices; i++)
8020 				if (voice[i].status != VOICE_FREE) {
8021 					voice[i].temper_instant = 1;
8022 					recompute_freq(i);
8023 				}
8024 		break;
8025 
8026 	case ME_TEMPER_TYPE:
8027 		channel[ch].temper_type = current_event->a;
8028 		ctl_mode_event(CTLE_TEMPER_TYPE, 1, ch, channel[ch].temper_type);
8029 		if (temper_type_mute) {
8030 			if (temper_type_mute & (1 << (current_event->a
8031 					- ((current_event->a >= 0x40) ? 0x3c : 0)))) {
8032 				SET_CHANNELMASK(channel_mute, ch);
8033 				ctl_mode_event(CTLE_MUTE, 1, ch, 1);
8034 			} else {
8035 				UNSET_CHANNELMASK(channel_mute, ch);
8036 				ctl_mode_event(CTLE_MUTE, 1, ch, 0);
8037 			}
8038 		}
8039 		if (current_event->b)
8040 			for (i = 0; i < upper_voices; i++)
8041 				if (voice[i].status != VOICE_FREE) {
8042 					voice[i].temper_instant = 1;
8043 					recompute_freq(i);
8044 				}
8045 		break;
8046 
8047 	case ME_MASTER_TEMPER_TYPE:
8048 		for (i = 0; i < MAX_CHANNELS; i++) {
8049 			channel[i].temper_type = current_event->a;
8050 			ctl_mode_event(CTLE_TEMPER_TYPE, 1, i, channel[i].temper_type);
8051 		}
8052 		if (temper_type_mute) {
8053 			if (temper_type_mute & (1 << (current_event->a
8054 					- ((current_event->a >= 0x40) ? 0x3c : 0)))) {
8055 				FILL_CHANNELMASK(channel_mute);
8056 				for (i = 0; i < MAX_CHANNELS; i++)
8057 					ctl_mode_event(CTLE_MUTE, 1, i, 1);
8058 			} else {
8059 				CLEAR_CHANNELMASK(channel_mute);
8060 				for (i = 0; i < MAX_CHANNELS; i++)
8061 					ctl_mode_event(CTLE_MUTE, 1, i, 0);
8062 			}
8063 		}
8064 		if (current_event->b)
8065 			for (i = 0; i < upper_voices; i++)
8066 				if (voice[i].status != VOICE_FREE) {
8067 					voice[i].temper_instant = 1;
8068 					recompute_freq(i);
8069 				}
8070 		break;
8071 
8072 	case ME_USER_TEMPER_ENTRY:
8073 		set_user_temper_entry(ch, current_event->a, current_event->b);
8074 		break;
8075 
8076 	case ME_SYSEX_LSB:
8077 		process_sysex_event(ME_SYSEX_LSB,ch,current_event->a,current_event->b);
8078 	    break;
8079 
8080 	case ME_SYSEX_MSB:
8081 		process_sysex_event(ME_SYSEX_MSB,ch,current_event->a,current_event->b);
8082 	    break;
8083 
8084 	case ME_SYSEX_GS_LSB:
8085 		process_sysex_event(ME_SYSEX_GS_LSB,ch,current_event->a,current_event->b);
8086 	    break;
8087 
8088 	case ME_SYSEX_GS_MSB:
8089 		process_sysex_event(ME_SYSEX_GS_MSB,ch,current_event->a,current_event->b);
8090 	    break;
8091 
8092 	case ME_SYSEX_XG_LSB:
8093 		process_sysex_event(ME_SYSEX_XG_LSB,ch,current_event->a,current_event->b);
8094 	    break;
8095 
8096 	case ME_SYSEX_XG_MSB:
8097 		process_sysex_event(ME_SYSEX_XG_MSB,ch,current_event->a,current_event->b);
8098 	    break;
8099 
8100 	case ME_NOTE_STEP:
8101 		i = ev->a + ((ev->b & 0x0f) << 8);
8102 		j = ev->b >> 4;
8103 		ctl_mode_event(CTLE_METRONOME, 1, i, j);
8104 		if (readmidi_wrd_mode)
8105 			wrdt->update_events();
8106 		break;
8107 
8108 	case ME_CUEPOINT:
8109 		set_cuepoint(ch, current_event->a, current_event->b);
8110 		break;
8111 
8112       case ME_EOT:
8113 	return midi_play_end();
8114     }
8115 #ifndef SUPPRESS_CHANNEL_LAYER
8116 		}
8117 	}
8118 	ev->channel = orig_ch;
8119 #endif
8120 
8121     return RC_NONE;
8122 }
8123 
set_master_tuning(int tune)8124 static void set_master_tuning(int tune)
8125 {
8126 	if (tune & 0x4000)	/* 1/8192 semitones + 0x2000 | 0x4000 */
8127 		tune = (tune & 0x3FFF) - 0x2000;
8128 	else if (tune & 0x8000)	/* 1 semitones | 0x8000 */
8129 		tune = ((tune & 0x7F) - 0x40) << 13;
8130 	else	/* millisemitones + 0x400 */
8131 		tune = (((tune - 0x400) << 13) + 500) / 1000;
8132 	master_tuning = tune;
8133 }
8134 
set_single_note_tuning(int part,int a,int b,int rt)8135 static void set_single_note_tuning(int part, int a, int b, int rt)
8136 {
8137 	static int tp;	/* tuning program number */
8138 	static int kn;	/* MIDI key number */
8139 	static int st;	/* the nearest equal-tempered semitone */
8140 	double f, fst;	/* fraction of semitone */
8141 	int i;
8142 
8143 	switch (part) {
8144 	case 0:
8145 		tp = a;
8146 		break;
8147 	case 1:
8148 		kn = a, st = b;
8149 		break;
8150 	case 2:
8151 		if (st == 0x7f && a == 0x7f && b == 0x7f)	/* no change */
8152 			break;
8153 		f = 440 * pow(2.0, (st - 69) / 12.0);
8154 		fst = pow(2.0, (a << 7 | b) / 196608.0);
8155 		freq_table_tuning[tp][kn] = f * fst * 1000 + 0.5;
8156 		if (rt)
8157 			for (i = 0; i < upper_voices; i++)
8158 				if (voice[i].status != VOICE_FREE) {
8159 					voice[i].temper_instant = 1;
8160 					recompute_freq(i);
8161 				}
8162 		break;
8163 	}
8164 }
8165 
set_user_temper_entry(int part,int a,int b)8166 static void set_user_temper_entry(int part, int a, int b)
8167 {
8168 	static int tp;		/* temperament program number */
8169 	static int ll;		/* number of formula */
8170 	static int fh, fl;	/* applying pitch bit mask (forward) */
8171 	static int bh, bl;	/* applying pitch bit mask (backward) */
8172 	static int aa, bb;	/* fraction (aa/bb) */
8173 	static int cc, dd;	/* power (cc/dd)^(ee/ff) */
8174 	static int ee, ff;
8175 	static int ifmax, ibmax, count;
8176 	static double rf[11], rb[11];
8177 	int i, j, k, l, n, m;
8178 	double ratio[12], f, sc;
8179 
8180 	switch (part) {
8181 	case 0:
8182 		for (i = 0; i < 11; i++)
8183 			rf[i] = rb[i] = 1;
8184 		ifmax = ibmax = 0;
8185 		count = 0;
8186 		tp = a, ll = b;
8187 		break;
8188 	case 1:
8189 		fh = a, fl = b;
8190 		break;
8191 	case 2:
8192 		bh = a, bl = b;
8193 		break;
8194 	case 3:
8195 		aa = a, bb = b;
8196 		break;
8197 	case 4:
8198 		cc = a, dd = b;
8199 		break;
8200 	case 5:
8201 		ee = a, ff = b;
8202 		for (i = 0; i < 11; i++) {
8203 			if (((fh & 0xf) << 7 | fl) & 1 << i) {
8204 				rf[i] *= (double) aa / bb
8205 						* pow((double) cc / dd, (double) ee / ff);
8206 				if (ifmax < i + 1)
8207 					ifmax = i + 1;
8208 			}
8209 			if (((bh & 0xf) << 7 | bl) & 1 << i) {
8210 				rb[i] *= (double) aa / bb
8211 						* pow((double) cc / dd, (double) ee / ff);
8212 				if (ibmax < i + 1)
8213 					ibmax = i + 1;
8214 			}
8215 		}
8216 		if (++count < ll)
8217 			break;
8218 		ratio[0] = 1;
8219 		for (i = n = m = 0; i < ifmax; i++, m = n) {
8220 			n += (n > 4) ? -5 : 7;
8221 			ratio[n] = ratio[m] * rf[i];
8222 			if (ratio[n] > 2)
8223 				ratio[n] /= 2;
8224 		}
8225 		for (i = n = m = 0; i < ibmax; i++, m = n) {
8226 			n += (n > 6) ? -7 : 5;
8227 			ratio[n] = ratio[m] / rb[i];
8228 			if (ratio[n] < 1)
8229 				ratio[n] *= 2;
8230 		}
8231 		sc = 27 / ratio[9] / 16;	/* syntonic comma */
8232 		for (i = 0; i < 12; i++)
8233 			for (j = -1; j < 11; j++) {
8234 				f = 440 * pow(2.0, (i - 9) / 12.0 + j - 5);
8235 				for (k = 0; k < 12; k++) {
8236 					l = i + j * 12 + k;
8237 					if (l < 0 || l >= 128)
8238 						continue;
8239 					if (! (fh & 0x40)) {	/* major */
8240 						freq_table_user[tp][i][l] =
8241 								f * ratio[k] * 1000 + 0.5;
8242 						freq_table_user[tp][i + 36][l] =
8243 								f * ratio[k] * sc * 1000 + 0.5;
8244 					}
8245 					if (! (bh & 0x40)) {	/* minor */
8246 						freq_table_user[tp][i + 12][l] =
8247 								f * ratio[k] * sc * 1000 + 0.5;
8248 						freq_table_user[tp][i + 24][l] =
8249 								f * ratio[k] * 1000 + 0.5;
8250 					}
8251 				}
8252 			}
8253 		break;
8254 	}
8255 }
8256 
set_cuepoint(int part,int a,int b)8257 static void set_cuepoint(int part, int a, int b)
8258 {
8259 	static int a0 = 0, b0 = 0;
8260 
8261 	if (part == 0) {
8262 		a0 = a, b0 = b;
8263 		return;
8264 	}
8265 	ctl_mode_event(CTLE_CUEPOINT, 1, a0 << 24 | b0 << 16 | a << 8 | b, 0);
8266 }
8267 
play_midi(MidiEvent * eventlist,int32 samples)8268 static int play_midi(MidiEvent *eventlist, int32 samples)
8269 {
8270     int rc;
8271     static int play_count = 0;
8272 
8273     if (play_mode->id_character == 'M') {
8274 	int cnt, err;
8275 
8276 	err = convert_mod_to_midi_file(eventlist);
8277 
8278 	play_count = 0;
8279 	cnt = free_global_mblock();	/* free unused memory */
8280 	if(cnt > 0)
8281 	    ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
8282 		      "%d memory blocks are free", cnt);
8283 	if (err) return RC_ERROR;
8284 	return RC_TUNE_END;
8285     }
8286 
8287     sample_count = samples;
8288     event_list = eventlist;
8289     lost_notes = cut_notes = 0;
8290     check_eot_flag = 1;
8291 
8292     wrd_midi_event(-1, -1); /* For initialize */
8293 
8294     reset_midi(0);
8295     if(!opt_realtime_playing &&
8296        allocate_cache_size > 0 &&
8297        !IS_CURRENT_MOD_FILE &&
8298        (play_mode->flag&PF_PCM_STREAM))
8299     {
8300 	play_midi_prescan(eventlist);
8301 	reset_midi(0);
8302     }
8303 
8304     rc = aq_flush(0);
8305     if(RC_IS_SKIP_FILE(rc))
8306 	return rc;
8307 
8308     skip_to(midi_restart_time);
8309 
8310     if(midi_restart_time > 0) { /* Need to update interface display */
8311       int i;
8312       for(i = 0; i < MAX_CHANNELS; i++)
8313 	redraw_controllers(i);
8314     }
8315     rc = RC_NONE;
8316     for(;;)
8317     {
8318 	midi_restart_time = 1;
8319 	rc = play_event(current_event);
8320 	if(rc != RC_NONE)
8321 	    break;
8322 	if (midi_restart_time)    /* don't skip the first event if == 0 */
8323 	    current_event++;
8324     }
8325 
8326     if(play_count++ > 3)
8327     {
8328 	int cnt;
8329 	play_count = 0;
8330 	cnt = free_global_mblock();	/* free unused memory */
8331 	if(cnt > 0)
8332 	    ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
8333 		      "%d memory blocks are free", cnt);
8334     }
8335     return rc;
8336 }
8337 
read_header_wav(struct timidity_file * tf)8338 static void read_header_wav(struct timidity_file* tf)
8339 {
8340     char buff[44];
8341     tf_read( buff, 1, 44, tf);
8342 }
8343 
read_header_aiff(struct timidity_file * tf)8344 static int read_header_aiff(struct timidity_file* tf)
8345 {
8346     char buff[5]="    ";
8347     int i;
8348 
8349     for( i=0; i<100; i++ ){
8350     	buff[0]=buff[1]; buff[1]=buff[2]; buff[2]=buff[3];
8351     	tf_read( &buff[3], 1, 1, tf);
8352     	if( strcmp(buff,"SSND")==0 ){
8353             /*SSND chunk found */
8354     	    tf_read( &buff[0], 1, 4, tf);
8355     	    tf_read( &buff[0], 1, 4, tf);
8356 	    ctl->cmsg(CMSG_INFO, VERB_NOISY,
8357 		      "aiff header read OK.");
8358 	    return 0;
8359     	}
8360     }
8361     /*SSND chunk not found */
8362     return -1;
8363 }
8364 
load_pcm_file_wav()8365 static int load_pcm_file_wav()
8366 {
8367     char *filename;
8368 
8369     if(strcmp(pcm_alternate_file, "auto") == 0)
8370     {
8371 	filename = safe_malloc(strlen(current_file_info->filename)+5);
8372 	strcpy(filename, current_file_info->filename);
8373 	strcat(filename, ".wav");
8374     }
8375     else if(strlen(pcm_alternate_file) >= 5 &&
8376 	    strncasecmp(pcm_alternate_file + strlen(pcm_alternate_file) - 4,
8377 			".wav", 4) == 0)
8378 	filename = safe_strdup(pcm_alternate_file);
8379     else
8380 	return -1;
8381 
8382     ctl->cmsg(CMSG_INFO, VERB_NOISY,
8383 		      "wav filename: %s", filename);
8384     current_file_info->pcm_tf = open_file(filename, 0, OF_SILENT);
8385     if( current_file_info->pcm_tf ){
8386 	ctl->cmsg(CMSG_INFO, VERB_NOISY,
8387 		      "open successed.");
8388 	read_header_wav(current_file_info->pcm_tf);
8389 	current_file_info->pcm_filename = filename;
8390 	current_file_info->pcm_mode = PCM_MODE_WAV;
8391 	return 0;
8392     }else{
8393 	ctl->cmsg(CMSG_INFO, VERB_NOISY,
8394 		      "open failed.");
8395 	free(filename);
8396 	current_file_info->pcm_filename = NULL;
8397 	return -1;
8398     }
8399 }
8400 
load_pcm_file_aiff()8401 static int load_pcm_file_aiff()
8402 {
8403     char *filename;
8404 
8405     if(strcmp(pcm_alternate_file, "auto") == 0)
8406     {
8407 	filename = safe_malloc(strlen(current_file_info->filename)+6);
8408 	strcpy(filename, current_file_info->filename);
8409 	strcat( filename, ".aiff");
8410     }
8411     else if(strlen(pcm_alternate_file) >= 6 &&
8412 	    strncasecmp(pcm_alternate_file + strlen(pcm_alternate_file) - 5,
8413 			".aiff", 5) == 0)
8414 	filename = safe_strdup(pcm_alternate_file);
8415     else
8416 	return -1;
8417 
8418     ctl->cmsg(CMSG_INFO, VERB_NOISY,
8419 		      "aiff filename: %s", filename);
8420     current_file_info->pcm_tf = open_file(filename, 0, OF_SILENT);
8421     if( current_file_info->pcm_tf ){
8422 	ctl->cmsg(CMSG_INFO, VERB_NOISY,
8423 		      "open successed.");
8424 	read_header_aiff(current_file_info->pcm_tf);
8425 	current_file_info->pcm_filename = filename;
8426 	current_file_info->pcm_mode = PCM_MODE_AIFF;
8427 	return 0;
8428     }else{
8429 	ctl->cmsg(CMSG_INFO, VERB_NOISY,
8430 		      "open failed.");
8431 	free(filename);
8432 	current_file_info->pcm_filename = NULL;
8433 	return -1;
8434     }
8435 }
8436 
load_pcm_file()8437 static void load_pcm_file()
8438 {
8439     if( load_pcm_file_wav()==0 ) return; /*load OK*/
8440     if( load_pcm_file_aiff()==0 ) return; /*load OK*/
8441 }
8442 
play_midi_load_file(char * fn,MidiEvent ** event,int32 * nsamples)8443 static int play_midi_load_file(char *fn,
8444 			       MidiEvent **event,
8445 			       int32 *nsamples)
8446 {
8447     int rc;
8448     struct timidity_file *tf;
8449     int32 nevents;
8450 
8451     *event = NULL;
8452 
8453     if(!strcmp(fn, "-"))
8454 	file_from_stdin = 1;
8455     else
8456 	file_from_stdin = 0;
8457 
8458     ctl_mode_event(CTLE_NOW_LOADING, 0, (long)fn, 0);
8459     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MIDI file: %s", fn);
8460     if((tf = open_midi_file(fn, 1, OF_VERBOSE)) == NULL)
8461     {
8462 	ctl_mode_event(CTLE_LOADING_DONE, 0, -1, 0);
8463 	return RC_ERROR;
8464     }
8465 
8466     *event = NULL;
8467     rc = check_apply_control();
8468     if(RC_IS_SKIP_FILE(rc))
8469     {
8470 	close_file(tf);
8471 	ctl_mode_event(CTLE_LOADING_DONE, 0, 1, 0);
8472 	return rc;
8473     }
8474 
8475     *event = read_midi_file(tf, &nevents, nsamples, fn);
8476     close_file(tf);
8477 
8478     if(*event == NULL)
8479     {
8480 	ctl_mode_event(CTLE_LOADING_DONE, 0, -1, 0);
8481 	return RC_ERROR;
8482     }
8483 
8484     ctl->cmsg(CMSG_INFO, VERB_NOISY,
8485 	      "%d supported events, %d samples, time %d:%02d",
8486 	      nevents, *nsamples,
8487 	      *nsamples / play_mode->rate / 60,
8488 	      (*nsamples / play_mode->rate) % 60);
8489 
8490     current_file_info->pcm_mode = PCM_MODE_NON; /*initialize*/
8491     if(pcm_alternate_file != NULL &&
8492        strcmp(pcm_alternate_file, "none") != 0 &&
8493        (play_mode->flag&PF_PCM_STREAM))
8494 	load_pcm_file();
8495 
8496     if(!IS_CURRENT_MOD_FILE &&
8497        (play_mode->flag&PF_PCM_STREAM))
8498     {
8499 	/* FIXME: Instruments is not need for pcm_alternate_file. */
8500 
8501 	/* Load instruments
8502 	 * If opt_realtime_playing, the instruments will be loaded later.
8503 	 */
8504 	if(!opt_realtime_playing)
8505 	{
8506 	    rc = RC_NONE;
8507 	    load_missing_instruments(&rc);
8508 	    if(RC_IS_SKIP_FILE(rc))
8509 	    {
8510 		/* Instrument loading is terminated */
8511 		ctl_mode_event(CTLE_LOADING_DONE, 0, 1, 0);
8512 		clear_magic_instruments();
8513 		return rc;
8514 	    }
8515 	}
8516     }
8517     else
8518 	clear_magic_instruments();	/* Clear load markers */
8519 
8520     ctl_mode_event(CTLE_LOADING_DONE, 0, 0, 0);
8521 
8522     return RC_NONE;
8523 }
8524 
play_midi_file(char * fn)8525 int play_midi_file(char *fn)
8526 {
8527     int i, j, rc;
8528     static int last_rc = RC_NONE;
8529     MidiEvent *event;
8530     int32 nsamples;
8531 
8532     /* Set current file information */
8533     current_file_info = get_midi_file_info(fn, 1);
8534 
8535     rc = check_apply_control();
8536     if(RC_IS_SKIP_FILE(rc) && rc != RC_RELOAD)
8537 	return rc;
8538 
8539     /* Reset key & speed each files */
8540     current_keysig = (opt_init_keysig == 8) ? 0 : opt_init_keysig;
8541     note_key_offset = key_adjust;
8542     midi_time_ratio = tempo_adjust;
8543 	for (i = 0; i < MAX_CHANNELS; i++) {
8544 		for (j = 0; j < 12; j++)
8545 			channel[i].scale_tuning[j] = 0;
8546 		channel[i].prev_scale_tuning = 0;
8547 		channel[i].temper_type = 0;
8548 	}
8549     CLEAR_CHANNELMASK(channel_mute);
8550 	if (temper_type_mute & 1)
8551 		FILL_CHANNELMASK(channel_mute);
8552 
8553     /* Reset restart offset */
8554     midi_restart_time = 0;
8555 
8556 #ifdef REDUCE_VOICE_TIME_TUNING
8557     /* Reset voice reduction stuff */
8558     min_bad_nv = 256;
8559     max_good_nv = 1;
8560     ok_nv_total = 32;
8561     ok_nv_counts = 1;
8562     ok_nv = 32;
8563     ok_nv_sample = 0;
8564     old_rate = -1;
8565     reduce_quality_flag = no_4point_interpolation;
8566     restore_voices(0);
8567 #endif
8568 
8569 	ctl_mode_event(CTLE_METRONOME, 0, 0, 0);
8570 	ctl_mode_event(CTLE_KEYSIG, 0, current_keysig, 0);
8571 	ctl_mode_event(CTLE_TEMPER_KEYSIG, 0, 0, 0);
8572 	ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
8573 	i = current_keysig + ((current_keysig < 8) ? 7 : -9), j = 0;
8574 	while (i != 7)
8575 		i += (i < 7) ? 5 : -7, j++;
8576 	j += note_key_offset, j -= floor(j / 12.0) * 12;
8577 	current_freq_table = j;
8578 	ctl_mode_event(CTLE_TEMPO, 0, current_play_tempo, 0);
8579 	ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
8580 	for (i = 0; i < MAX_CHANNELS; i++) {
8581 		ctl_mode_event(CTLE_TEMPER_TYPE, 0, i, channel[i].temper_type);
8582 		ctl_mode_event(CTLE_MUTE, 0, i, temper_type_mute & 1);
8583 	}
8584   play_reload: /* Come here to reload MIDI file */
8585     rc = play_midi_load_file(fn, &event, &nsamples);
8586     if(RC_IS_SKIP_FILE(rc))
8587 	goto play_end; /* skip playing */
8588 
8589     init_mblock(&playmidi_pool);
8590     ctl_mode_event(CTLE_PLAY_START, 0, nsamples, 0);
8591     play_mode->acntl(PM_REQ_PLAY_START, NULL);
8592     rc = play_midi(event, nsamples);
8593     play_mode->acntl(PM_REQ_PLAY_END, NULL);
8594     ctl_mode_event(CTLE_PLAY_END, 0, 0, 0);
8595     reuse_mblock(&playmidi_pool);
8596 
8597     for(i = 0; i < MAX_CHANNELS; i++)
8598 	memset(channel[i].drums, 0, sizeof(channel[i].drums));
8599 
8600   play_end:
8601     if(current_file_info->pcm_tf){
8602     	close_file(current_file_info->pcm_tf);
8603     	current_file_info->pcm_tf = NULL;
8604     	free( current_file_info->pcm_filename );
8605     	current_file_info->pcm_filename = NULL;
8606     }
8607 
8608     if(wrdt->opened)
8609 	wrdt->end();
8610 
8611     if(free_instruments_afterwards)
8612     {
8613 	int cnt;
8614 	free_instruments(0);
8615 	cnt = free_global_mblock(); /* free unused memory */
8616 	if(cnt > 0)
8617 	    ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "%d memory blocks are free",
8618 		      cnt);
8619     }
8620 
8621     free_special_patch(-1);
8622 
8623     if(event != NULL)
8624 	free(event);
8625     if(rc == RC_RELOAD)
8626 	goto play_reload;
8627 
8628     if(rc == RC_ERROR)
8629     {
8630 	if(current_file_info->file_type == IS_OTHER_FILE)
8631 	    current_file_info->file_type = IS_ERROR_FILE;
8632 	if(last_rc == RC_REALLY_PREVIOUS)
8633 	    return RC_REALLY_PREVIOUS;
8634     }
8635     last_rc = rc;
8636     return rc;
8637 }
8638 
dumb_pass_playing_list(int number_of_files,char * list_of_files[])8639 int dumb_pass_playing_list(int number_of_files, char *list_of_files[])
8640 {
8641     #ifndef CFG_FOR_SF
8642     int i = 0;
8643 
8644     for(;;)
8645     {
8646 	switch(play_midi_file(list_of_files[i]))
8647 	{
8648 	  case RC_REALLY_PREVIOUS:
8649 	    if(i > 0)
8650 		i--;
8651 	    break;
8652 
8653 	  default: /* An error or something */
8654 	  case RC_NEXT:
8655 	    if(i < number_of_files-1)
8656 	    {
8657 		i++;
8658 		break;
8659 	    }
8660 	    aq_flush(0);
8661 
8662 	    if(!(ctl->flags & CTLF_LIST_LOOP))
8663 		return 0;
8664 	    i = 0;
8665 	    break;
8666 
8667 	    case RC_QUIT:
8668 		return 0;
8669 	}
8670     }
8671     #endif
8672 }
8673 
default_ctl_lyric(int lyricid)8674 void default_ctl_lyric(int lyricid)
8675 {
8676     char *lyric;
8677 
8678     lyric = event2string(lyricid);
8679     if(lyric != NULL)
8680 	ctl->cmsg(CMSG_TEXT, VERB_VERBOSE, "%s", lyric + 1);
8681 }
8682 
ctl_mode_event(int type,int trace,ptr_size_t arg1,ptr_size_t arg2)8683 void ctl_mode_event(int type, int trace, ptr_size_t arg1, ptr_size_t arg2)
8684 {
8685     CtlEvent ce;
8686     ce.type = type;
8687     ce.v1 = arg1;
8688     ce.v2 = arg2;
8689     if(trace && ctl->trace_playing)
8690 	push_midi_trace_ce(ctl->event, &ce);
8691     else
8692 	ctl->event(&ce);
8693 }
8694 
ctl_note_event(int noteID)8695 void ctl_note_event(int noteID)
8696 {
8697     CtlEvent ce;
8698     ce.type = CTLE_NOTE;
8699     ce.v1 = voice[noteID].status;
8700     ce.v2 = voice[noteID].channel;
8701     ce.v3 = voice[noteID].note;
8702     ce.v4 = voice[noteID].velocity;
8703     if(ctl->trace_playing)
8704 	push_midi_trace_ce(ctl->event, &ce);
8705     else
8706 	ctl->event(&ce);
8707 }
8708 
ctl_timestamp(void)8709 static void ctl_timestamp(void)
8710 {
8711     long i, secs, voices;
8712     CtlEvent ce;
8713     static int last_secs = -1, last_voices = -1;
8714 
8715     secs = (long)(current_sample / (midi_time_ratio * play_mode->rate));
8716     for(i = voices = 0; i < upper_voices; i++)
8717 	if(voice[i].status != VOICE_FREE)
8718 	    voices++;
8719     if(secs == last_secs && voices == last_voices)
8720 	return;
8721     ce.type = CTLE_CURRENT_TIME;
8722     ce.v1 = last_secs = secs;
8723     ce.v2 = last_voices = voices;
8724     if(ctl->trace_playing)
8725 	push_midi_trace_ce(ctl->event, &ce);
8726     else
8727 	ctl->event(&ce);
8728 }
8729 
ctl_updatetime(int32 samples)8730 static void ctl_updatetime(int32 samples)
8731 {
8732     long secs;
8733     secs = (long)(samples / (midi_time_ratio * play_mode->rate));
8734     ctl_mode_event(CTLE_CURRENT_TIME, 0, secs, 0);
8735     ctl_mode_event(CTLE_REFRESH, 0, 0, 0);
8736 }
8737 
ctl_prog_event(int ch)8738 static void ctl_prog_event(int ch)
8739 {
8740     CtlEvent ce;
8741     int bank, prog;
8742 
8743     if(IS_CURRENT_MOD_FILE)
8744     {
8745 	bank = 0;
8746 	prog = channel[ch].special_sample;
8747     }
8748     else
8749     {
8750 	bank = channel[ch].bank;
8751 	prog = channel[ch].program;
8752     }
8753 
8754     ce.type = CTLE_PROGRAM;
8755     ce.v1 = ch;
8756     ce.v2 = prog;
8757     ce.v3 = (ptr_size_t)channel_instrum_name(ch);
8758     ce.v4 = (bank |
8759 	     (channel[ch].bank_lsb << 8) |
8760 	     (channel[ch].bank_msb << 16));
8761     if(ctl->trace_playing)
8762 	push_midi_trace_ce(ctl->event, &ce);
8763     else
8764 	ctl->event(&ce);
8765 }
8766 
ctl_pause_event(int pause,int32 s)8767 static void ctl_pause_event(int pause, int32 s)
8768 {
8769     long secs;
8770     secs = (long)(s / (midi_time_ratio * play_mode->rate));
8771     ctl_mode_event(CTLE_PAUSE, 0, pause, secs);
8772 }
8773 
channel_instrum_name(int ch)8774 char *channel_instrum_name(int ch)
8775 {
8776     char *comm;
8777     int bank, prog;
8778 
8779     if(ISDRUMCHANNEL(ch)) {
8780 	bank = channel[ch].bank;
8781 	if (drumset[bank] == NULL) return "";
8782 	prog = 0;
8783 	comm = drumset[bank]->tone[prog].comment;
8784 	if (comm == NULL) return "";
8785 	return comm;
8786     }
8787 
8788     if(channel[ch].program == SPECIAL_PROGRAM)
8789 	return "Special Program";
8790 
8791     if(IS_CURRENT_MOD_FILE)
8792     {
8793 	int pr;
8794 	pr = channel[ch].special_sample;
8795 	if(pr > 0 &&
8796 	   special_patch[pr] != NULL &&
8797 	   special_patch[pr]->name != NULL)
8798 	    return special_patch[pr]->name;
8799 	return "MOD";
8800     }
8801 
8802     bank = channel[ch].bank;
8803     prog = channel[ch].program;
8804     instrument_map(channel[ch].mapID, &bank, &prog);
8805 
8806 	if (tonebank[bank] == NULL) {alloc_instrument_bank(0, bank);}
8807 	if (tonebank[bank]->tone[prog].name) {
8808 	    comm = tonebank[bank]->tone[prog].comment;
8809 		if (comm == NULL) {comm = tonebank[bank]->tone[prog].name;}
8810 	} else {
8811 	    comm = tonebank[0]->tone[prog].comment;
8812 		if (comm == NULL) {comm = tonebank[0]->tone[prog].name;}
8813 	}
8814 
8815     return comm;
8816 }
8817 
8818 
8819 /*
8820  * For MIDI stream player.
8821  */
playmidi_stream_init(void)8822 void playmidi_stream_init(void)
8823 {
8824     int i;
8825     static int first = 1;
8826 
8827     note_key_offset = key_adjust;
8828     midi_time_ratio = tempo_adjust;
8829     CLEAR_CHANNELMASK(channel_mute);
8830 	if (temper_type_mute & 1)
8831 		FILL_CHANNELMASK(channel_mute);
8832     midi_restart_time = 0;
8833     if(first)
8834     {
8835 	first = 0;
8836         init_mblock(&playmidi_pool);
8837 	current_file_info = get_midi_file_info("TiMidity", 1);
8838     midi_streaming=1;
8839     }
8840     else
8841         reuse_mblock(&playmidi_pool);
8842 
8843     /* Fill in current_file_info */
8844     current_file_info->readflag = 1;
8845     current_file_info->seq_name = safe_strdup("TiMidity server");
8846     current_file_info->karaoke_title = current_file_info->first_text = NULL;
8847     current_file_info->mid = 0x7f;
8848     current_file_info->hdrsiz = 0;
8849     current_file_info->format = 0;
8850     current_file_info->tracks = 0;
8851     current_file_info->divisions = 192; /* ?? */
8852     current_file_info->time_sig_n = 4; /* 4/ */
8853     current_file_info->time_sig_d = 4; /* /4 */
8854     current_file_info->time_sig_c = 24; /* clock */
8855     current_file_info->time_sig_b = 8;  /* q.n. */
8856     current_file_info->samples = 0;
8857     current_file_info->max_channel = MAX_CHANNELS;
8858     current_file_info->compressed = 0;
8859     current_file_info->midi_data = NULL;
8860     current_file_info->midi_data_size = 0;
8861     current_file_info->file_type = IS_OTHER_FILE;
8862 
8863     current_play_tempo = 500000;
8864     check_eot_flag = 0;
8865 
8866     /* Setup default drums */
8867 	COPY_CHANNELMASK(current_file_info->drumchannels, default_drumchannels);
8868 	COPY_CHANNELMASK(current_file_info->drumchannel_mask, default_drumchannel_mask);
8869     for(i = 0; i < MAX_CHANNELS; i++)
8870 	memset(channel[i].drums, 0, sizeof(channel[i].drums));
8871     change_system_mode(DEFAULT_SYSTEM_MODE);
8872     reset_midi(0);
8873 
8874     playmidi_tmr_reset();
8875 }
8876 
playmidi_tmr_reset(void)8877 void playmidi_tmr_reset(void)
8878 {
8879     int i;
8880 
8881     aq_flush(0);
8882     if(ctl->id_character != 'N')
8883         current_sample = 0;
8884     buffered_count = 0;
8885     buffer_pointer = common_buffer;
8886     for(i = 0; i < MAX_CHANNELS; i++)
8887 	channel[i].lasttime = 0;
8888 }
8889 
playmidi_stream_free(void)8890 void playmidi_stream_free(void)
8891 {
8892 	reuse_mblock(&playmidi_pool);
8893 }
8894 
8895 /*! initialize Part EQ (XG) */
init_part_eq_xg(struct part_eq_xg * p)8896 void init_part_eq_xg(struct part_eq_xg *p)
8897 {
8898 	p->bass = 0x40;
8899 	p->treble = 0x40;
8900 	p->bass_freq = 0x0C;
8901 	p->treble_freq = 0x36;
8902 	p->valid = 0;
8903 }
8904 
8905 /*! recompute Part EQ (XG) */
recompute_part_eq_xg(struct part_eq_xg * p)8906 void recompute_part_eq_xg(struct part_eq_xg *p)
8907 {
8908 	int8 vbass, vtreble;
8909 
8910 	if(p->bass_freq >= 4 && p->bass_freq <= 40 && p->bass != 0x40) {
8911 		vbass = 1;
8912 		p->basss.q = 0.7;
8913 		p->basss.freq = eq_freq_table_xg[p->bass_freq];
8914 		if(p->bass == 0) {p->basss.gain = -12.0;}
8915 		else {p->basss.gain = 0.19 * (double)(p->bass - 0x40);}
8916 		calc_filter_shelving_low(&(p->basss));
8917 	} else {vbass = 0;}
8918 	if(p->treble_freq >= 28 && p->treble_freq <= 58 && p->treble != 0x40) {
8919 		vtreble = 1;
8920 		p->trebles.q = 0.7;
8921 		p->trebles.freq = eq_freq_table_xg[p->treble_freq];
8922 		if(p->treble == 0) {p->trebles.gain = -12.0;}
8923 		else {p->trebles.gain = 0.19 * (double)(p->treble - 0x40);}
8924 		calc_filter_shelving_high(&(p->trebles));
8925 	} else {vtreble = 0;}
8926 	p->valid = vbass || vtreble;
8927 }
8928 
init_midi_controller(midi_controller * p)8929 static void init_midi_controller(midi_controller *p)
8930 {
8931 	p->val = 0;
8932 	p->pitch = 0;
8933 	p->cutoff = 0;
8934 	p->amp = 0.0;
8935 	p->lfo1_rate = p->lfo2_rate = p->lfo1_tva_depth = p->lfo2_tva_depth = 0;
8936 	p->lfo1_pitch_depth = p->lfo2_pitch_depth = p->lfo1_tvf_depth = p->lfo2_tvf_depth = 0;
8937 	p->variation_control_depth = p->insertion_control_depth = 0;
8938 }
8939 
get_midi_controller_amp(midi_controller * p)8940 static float get_midi_controller_amp(midi_controller *p)
8941 {
8942 	return (1.0 + (float)p->val * (1.0f / 127.0f) * p->amp);
8943 }
8944 
get_midi_controller_filter_cutoff(midi_controller * p)8945 static float get_midi_controller_filter_cutoff(midi_controller *p)
8946 {
8947 	return ((float)p->val * (1.0f / 127.0f) * (float)p->cutoff);
8948 }
8949 
get_midi_controller_filter_depth(midi_controller * p)8950 static float get_midi_controller_filter_depth(midi_controller *p)
8951 {
8952 	return ((float)p->val * (1.0f / 127.0f) * (float)p->lfo1_tvf_depth);
8953 }
8954 
get_midi_controller_pitch(midi_controller * p)8955 static int32 get_midi_controller_pitch(midi_controller *p)
8956 {
8957 	return ((int32)(p->val * p->pitch) << 6);
8958 }
8959 
get_midi_controller_pitch_depth(midi_controller * p)8960 static int16 get_midi_controller_pitch_depth(midi_controller *p)
8961 {
8962 	return (int16)((float)p->val * (float)p->lfo1_pitch_depth * (1.0f / 127.0f * 256.0 / 400.0));
8963 }
8964 
get_midi_controller_amp_depth(midi_controller * p)8965 static int16 get_midi_controller_amp_depth(midi_controller *p)
8966 {
8967 	return (int16)((float)p->val * (float)p->lfo1_tva_depth * (1.0f / 127.0f * 256.0));
8968 }
8969 
init_rx(int ch)8970 static void init_rx(int ch)
8971 {
8972 	channel[ch].rx = 0xFFFFFFFF;	/* all on */
8973 }
8974 
set_rx(int ch,int32 rx,int flag)8975 static void set_rx(int ch, int32 rx, int flag)
8976 {
8977 	if(ch > MAX_CHANNELS) {return;}
8978 	if(flag) {channel[ch].rx |= rx;}
8979 	else {channel[ch].rx &= ~rx;}
8980 }
8981 
8982 #if 0
8983 static int32 get_rx(int ch, int32 rx)
8984 {
8985 	return (channel[ch].rx & rx);
8986 }
8987 #endif
8988 
init_rx_drum(struct DrumParts * p)8989 static void init_rx_drum(struct DrumParts *p)
8990 {
8991 	p->rx = 0xFFFFFFFF;	/* all on */
8992 }
8993 
set_rx_drum(struct DrumParts * p,int32 rx,int flag)8994 static void set_rx_drum(struct DrumParts *p, int32 rx, int flag)
8995 {
8996 	if(flag) {p->rx |= rx;}
8997 	else {p->rx &= ~rx;}
8998 }
8999 
get_rx_drum(struct DrumParts * p,int32 rx)9000 static int32 get_rx_drum(struct DrumParts *p, int32 rx)
9001 {
9002 	return (p->rx & rx);
9003 }
9004 
free_reverb_buffer(void)9005 void free_reverb_buffer(void)
9006 {
9007 	free(reverb_buffer);
9008 }
9009 
9010