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