OSDN Git Service

ea866319ab0bc31bb5bb1e1199a9b3ed93c117cd
[timidity41/timidity41.git] / timidity / playmidi.c
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 #ifdef HAVE_STDLIB_H
34 #include <stdlib.h>
35 #endif /* HAVE_STDLIB_H */
36
37 #ifndef NO_STRING_H
38 #include <string.h>
39 #else
40 #include <strings.h>
41 #endif
42 #include <math.h>
43 #ifdef __W32__
44 #include <windows.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif /* HAVE_UNISTD_H */
49 #include "timidity.h"
50 #include "common.h"
51 #include "instrum.h"
52 #include "playmidi.h"
53 #include "readmidi.h"
54 #include "output.h"
55 #include "mix.h"
56 #include "controls.h"
57 #include "miditrace.h"
58 #include "recache.h"
59 #include "arc.h"
60 #include "effect.h"
61 #include "wrd.h"
62 #include "aq.h"
63 #include "freq.h"
64 #include "quantity.h"
65 ///r
66 #include "resample.h"
67 #include "thread.h"
68 #include "sndfontini.h"
69
70 extern int convert_mod_to_midi_file(MidiEvent * ev);
71
72 #define ABORT_AT_FATAL 1 /*#################*/
73 #define MYCHECK(s) do { if(s == 0) { printf("## L %d\n", __LINE__); abort(); } } while(0)
74
75 extern VOLATILE int intr;
76
77 /* #define SUPPRESS_CHANNEL_LAYER */
78
79 #ifdef SOLARIS
80 /* shut gcc warning up */
81 int usleep(unsigned int useconds);
82 #endif
83
84 #ifdef SUPPORT_SOUNDSPEC
85 #include "soundspec.h"
86 #endif /* SUPPORT_SOUNDSPEC */
87
88 #include "tables.h"
89
90 ///r
91 #define ADD_PLAY_TIME   (1)// sec
92 #define ADD_SILENT_TIME (1) // sec
93 #define EMU_DELAY_TIME  (5) // 0.1msec
94
95 #define PORTAMENTO_TIME_TUNING          (0.0002) //  1.0 / 5000.0
96 #define PORTAMENTO_CONTROL_BIT      (13) // 13bit == tuning (see recompute_voice_pitch() // def 8bit
97 #define PORTAMENTO_CONTROL_RATIO        (1<<PORTAMENTO_CONTROL_BIT) // def 256(8bit)    /* controls per sec */
98 #define DEFAULT_CHORUS_DELAY1           (0.02)
99 #define DEFAULT_CHORUS_DELAY2           (0.003)
100 #define CHORUS_OPPOSITE_THRESHOLD       (32)
101 #define EOT_PRESEARCH_LEN               (32)
102 #define SPEED_CHANGE_RATE               (1.0594630943592952645618252949461)  /* 2^(1/12) */
103
104
105
106 /* Undefine if you don't want to use auto voice reduce implementation */
107 ///r to timidity.h
108 //#define REDUCE_VOICE_TIME_TUNING      (play_mode->rate/5) /* 0.2 sec */
109 //#define REDUCE_VOICE_TIME_TUNING      (play_mode->rate/200)
110 #ifdef REDUCE_VOICE_TIME_TUNING
111 static int max_good_nv = 1;
112 static int min_bad_nv = 256;
113 static int32 ok_nv_total = 32;
114 static int32 ok_nv_counts = 1;
115 static int32 ok_nv_sample = 0;
116 static int ok_nv = 32;
117 static int old_rate = -1;
118 #endif
119
120 static int midi_streaming = 0;
121 static int prescanning_flag;
122 static int32 midi_restart_time = 0;
123 Channel channel[MAX_CHANNELS];
124 int max_voices = DEFAULT_VOICES;
125 Voice *voice = NULL;
126 int8 current_keysig = 0;
127 int8 current_temper_keysig = 0;
128 int temper_adj = 0;
129 int8 opt_init_keysig = 8;
130 int8 opt_force_keysig = 8;
131 int32 current_play_tempo = 500000;
132 int opt_realtime_playing = 0;
133 ///r
134 int volatile stream_max_compute = 500; /* compute time limit (in msec) when streaming */
135 uint32 opt_rtsyn_latency = 200; 
136 int opt_rtsyn_skip_aq = 0;
137 int reduce_voice_threshold = -1;
138 ///r
139 int reduce_quality_threshold = -1;
140 int reduce_polyphony_threshold = -1;
141 int add_play_time = ADD_PLAY_TIME;
142 static int32 add_play_count = ADD_PLAY_TIME * 48000;
143 int add_silent_time = ADD_SILENT_TIME;
144 static int32 add_silent_count = ADD_SILENT_TIME * 48000;
145 int emu_delay_time = EMU_DELAY_TIME;
146
147 static MBlockList playmidi_pool;
148 int check_eot_flag;
149 int special_tonebank = -1;
150 int default_tonebank = 0;
151 int playmidi_seek_flag = 0;
152 int play_pause_flag = 0;
153 static int file_from_stdin;
154 int key_adjust = 0;
155 FLOAT_T tempo_adjust = 1.0;
156 int opt_pure_intonation = 0;
157 int current_freq_table = 0;
158 int current_temper_freq_table = 0;
159 static int master_tuning = 0;
160
161 static void set_reverb_level(int ch, int level);
162 static int make_rvid_flag = 0; /* For reverb optimization */
163
164 /* Ring voice id for each notes.  This ID enables duplicated note. */
165 static uint8 vidq_head[128 * MAX_CHANNELS], vidq_tail[128 * MAX_CHANNELS];
166
167 #ifdef MODULATION_WHEEL_ALLOW
168 int opt_modulation_wheel = 1;
169 #else
170 int opt_modulation_wheel = 0;
171 #endif /* MODULATION_WHEEL_ALLOW */
172
173 #ifdef PORTAMENTO_ALLOW
174 int opt_portamento = 1;
175 #else
176 int opt_portamento = 0;
177 #endif /* PORTAMENTO_ALLOW */
178
179 #ifdef NRPN_VIBRATO_ALLOW
180 int opt_nrpn_vibrato = 1;
181 #else
182 int opt_nrpn_vibrato = 0;
183 #endif /* NRPN_VIBRATO_ALLOW */
184
185 #ifdef REVERB_CONTROL_ALLOW
186 int opt_reverb_control = 1;
187 #else
188 #ifdef FREEVERB_CONTROL_ALLOW
189 int opt_reverb_control = 3;
190 #else
191 int opt_reverb_control = 0;
192 #endif /* FREEVERB_CONTROL_ALLOW */
193 #endif /* REVERB_CONTROL_ALLOW */
194
195 #ifdef CHORUS_CONTROL_ALLOW
196 int opt_chorus_control = 1;
197 #else
198 int opt_chorus_control = 0;
199 #endif /* CHORUS_CONTROL_ALLOW */
200
201 #ifdef SURROUND_CHORUS_ALLOW
202 int opt_surround_chorus = 1;
203 #else
204 int opt_surround_chorus = 0;
205 #endif /* SURROUND_CHORUS_ALLOW */
206
207 #ifdef GM_CHANNEL_PRESSURE_ALLOW
208 int opt_channel_pressure = 1;
209 #else
210 int opt_channel_pressure = 0;
211 #endif /* GM_CHANNEL_PRESSURE_ALLOW */
212
213 #ifdef VOICE_CHAMBERLIN_LPF_ALLOW
214 #define VOICE_LPF_DEFAULT 1
215 #elif defined(VOICE_MOOG_LPF_ALLOW)
216 #define VOICE_LPF_DEFAULT 2
217 #elif defined(VOICE_BW_LPF_ALLOW)
218 #define VOICE_LPF_DEFAULT 
219 #elif defined(VOICE_LPF12_2_ALLOW)
220 #define VOICE_LPF_DEFAULT 4
221 #else
222 #define VOICE_LPF_DEFAULT 0
223 #endif
224 int opt_lpf_def = VOICE_LPF_DEFAULT;
225 #undef VOICE_LPF_DEFAULT
226
227 int opt_hpf_def = 0;
228
229 #ifdef OVERLAP_VOICE_ALLOW
230 int opt_overlap_voice_allow = 1;
231 #else
232 int opt_overlap_voice_allow = 0;
233 #endif /* OVERLAP_VOICE_ALLOW */
234
235 ///r
236 #ifdef OVERLAP_VOICE_COUNT 
237 int opt_overlap_voice_count = OVERLAP_VOICE_COUNT;
238 #else
239 int opt_overlap_voice_count = 0;
240 #endif /* OVERLAP_VOICE_COUNT */
241
242 int opt_max_channel_voices = MAX_CHANNEL_VOICES;
243
244 #ifdef TEMPER_CONTROL_ALLOW
245 int opt_temper_control = 1;
246 #else
247 int opt_temper_control = 0;
248 #endif /* TEMPER_CONTROL_ALLOW */
249
250 int opt_tva_attack = 1; /* attack envelope control */
251 int opt_tva_decay = 1;  /* decay envelope control */
252 int opt_tva_release = 1;        /* release envelope control */
253 ///r
254 double gs_env_attack_calc = 1.0;
255 double gs_env_decay_calc = 1.0;
256 double gs_env_release_calc = 1.0;
257 double xg_env_attack_calc = 1.0;
258 double xg_env_decay_calc = 1.0;
259 double xg_env_release_calc = 1.0;
260 double gm2_env_attack_calc = 1.0;
261 double gm2_env_decay_calc = 1.0;
262 double gm2_env_release_calc = 1.0;
263 double gm_env_attack_calc = 1.0;
264 double gm_env_decay_calc = 1.0;
265 double gm_env_release_calc = 1.0;
266 double env_attack_calc = 1.0; 
267 double env_decay_calc = 1.0;
268 double env_release_calc = 1.0; 
269 double env_add_offdelay_time = 0.0; 
270 static int env_add_offdelay_count = 0;
271
272
273 int opt_delay_control = 1;      /* CC#94 delay(celeste) effect control */
274 int opt_eq_control = 1;         /* channel equalizer control */
275 int opt_insertion_effect = 1;   /* insertion effect control */
276 int opt_drum_effect = 1;        /* drumpart effect control */
277 int32 opt_drum_power = 100;             /* coef. of drum amplitude */
278 int opt_amp_compensation = 0;
279 int opt_modulation_envelope = 1;
280 ///r
281 double opt_user_volume_curve = 0;
282 int opt_default_module = MODULE_SC88PRO; //MODULE_TIMIDITY_DEFAULT;
283 int opt_preserve_silence = 0;
284
285 int voices=DEFAULT_VOICES, upper_voices;
286
287 int32 control_ratio=0;
288 double div_control_ratio;
289 int32 amplification=DEFAULT_AMPLIFICATION;
290 ///r
291 int32 output_amplification=DEFAULT_OUTPUT_AMPLIFICATION;
292 static FLOAT_T input_volume;
293 static int32 master_volume_ratio = 0xFFFF;
294 ChannelBitMask default_drumchannel_mask;
295 ChannelBitMask default_drumchannels;
296 ChannelBitMask drumchannel_mask;
297 ChannelBitMask drumchannels;
298 int adjust_panning_immediately = 1;
299 int auto_reduce_polyphony = 1;
300 double envelope_modify_rate = 1.0;
301 int reduce_quality_flag = 0;
302 int reduce_voice_flag = 0;
303 int reduce_polyphony_flag = 0;
304 int no_4point_interpolation = 0;
305 char* pcm_alternate_file = NULL; /* NULL or "none": Nothing (default)
306                                   * "auto": Auto select
307                                   * filename: Use it
308                                   */
309
310 static int32 lost_notes, cut_notes;
311 ///r
312 static ALIGN DATA_T common_buffer[AUDIO_BUFFER_SIZE*2], /* stereo samples */
313              *buffer_pointer;
314 static int16 wav_buffer[AUDIO_BUFFER_SIZE*2];
315 static int32 buffered_count;
316
317 ///r
318 int compute_buffer_bits = DEFAULT_COMPUTE_BUFFER_BITS;
319 int compute_buffer_size;
320 int synth_buffer_size; // stereo size
321 //int synth_buffer_size_mono;
322
323 static int vol_env_count, ch_vol_env_count;
324 int opt_mix_envelope = 1; // ON
325 int mix_env_mask = 0;
326 int opt_modulation_update = 1;
327 static int mix_env_count;
328 int ramp_out_count;
329 int opt_cut_short_time = CUT_SHORT_TIME2;
330
331 double ramp_out_rate;
332 double cut_short_rate;
333 double cut_short_rate2;
334
335 int min_sustain_time = 0; // ms
336 int min_sustain_count; // ms
337
338 #define TREMOLO_RATE_MAX (10.0) // Hz
339 #define TREMOLO_RATE_MIN (0.001) // Hz  
340 #define VIBRATO_RATE_MAX (10.0) // Hz
341 #define VIBRATO_RATE_MIN (0.001) // Hz
342 #define NRPN_VIBRATO_RATE (10.0) // Hz
343 #define NRPN_VIBRATO_DELAY (5000.0) // ms
344 #define NRPN_VIBRATO_DEPTH (50.0) // cent
345
346 static FLOAT_T nrpn_vib_depth_cent = NRPN_VIBRATO_DEPTH;
347 static FLOAT_T nrpn_vib_rate = NRPN_VIBRATO_RATE;
348 static FLOAT_T nrpn_vib_delay = NRPN_VIBRATO_DELAY * 48.0; // count def48kHz 
349 static int8 nrpn_vib_delay_mode = NRPN_PARAM_GM_DELAY;
350 static int8 nrpn_vib_rate_mode = NRPN_PARAM_GM_RATE;
351
352 #define NRPN_FILTER_FREQ_MAX (9600.0) // MOD TVF CUTOFF CONTROL \82Æ\93¯\82\95Ï\89»\95\9d
353 #define NRPN_FILTER_RESO_MAX (36.0) // \8ed\97l\95s\96¾ CUTOFF\93¯\97l\82Ì\95Ï\89»\95\9d
354 static FLOAT_T nrpn_filter_freq = NRPN_FILTER_FREQ_MAX;
355 static FLOAT_T nrpn_filter_reso = NRPN_FILTER_RESO_MAX;
356 static int8 nrpn_filter_freq_mode = NRPN_PARAM_GM_CUTOFF;
357 //static int8 nrpn_filter_reso_mode = NRPN_PARAM_GM_RESO;
358 static int8 nrpn_filter_hpf_freq_mode = NRPN_PARAM_GM_CUTOFF_HPF;
359 static int8 nrpn_env_attack_mode = NRPN_PARAM_GM_ATTACK;
360 static int8 nrpn_env_decay_mode = NRPN_PARAM_GM_DECAY;
361 static int8 nrpn_env_release_mode = NRPN_PARAM_GM_RELEASE;
362
363 static MidiEvent *event_list;
364 static MidiEvent *current_event;
365 static int32 sample_count;      /* Length of event_list */
366 int32 current_sample;           /* Number of calclated samples */
367
368 int note_key_offset = 0;                /* For key up/down */
369 FLOAT_T midi_time_ratio = 1.0;  /* For speed up/down */
370 ChannelBitMask channel_mute;    /* For channel mute */
371 int temper_type_mute;                   /* For temperament type mute */
372
373 /* for auto amplitude compensation */
374 static int mainvolume_max; /* maximum value of mainvolume */
375 static double compensation_ratio = 1.0; /* compensation ratio */
376
377 static int32 compute_skip_count = -1; // def use do_compute_data_midi()
378
379 static int find_samples(MidiEvent *, int *);
380 static int select_play_sample(Sample *, int, int *, int *, MidiEvent *, int);
381 static double get_play_note_ratio(int, int);
382 static int find_voice(MidiEvent *);
383 static void finish_note(int i);
384 static void update_portamento_controls(int ch);
385 static void update_legato_status(int ch);
386 static void update_rpn_map(int ch, int addr, int update_now);
387 static void ctl_prog_event(int ch);
388 ///r
389 static void ctl_note_event(int noteID);
390 static void ctl_note_event2(uint8 channel, uint8 note, uint8 status, uint8 velocity);
391 static void ctl_timestamp(void);
392 static void ctl_updatetime(int32 samples);
393 static void ctl_pause_event(int pause, int32 samples);
394 static void update_legato_controls(int ch);
395 static void set_master_tuning(int);
396 static void set_single_note_tuning(int, int, int, int);
397 static void set_user_temper_entry(int, int, int);
398 static void set_cuepoint(int, int, int);
399
400 static void init_voice_filter(int);
401 /* XG Part EQ */
402 void init_part_eq_xg(struct part_eq_xg *);
403 void recompute_part_eq_xg(struct part_eq_xg *);
404 /* MIDI controllers (MW, Bend, CAf, PAf,...) */
405 static void init_midi_controller(midi_controller *);
406 static float get_midi_controller_amp(midi_controller *);
407 static float get_midi_controller_filter_cutoff(midi_controller *);
408 static int32 get_midi_controller_pitch(midi_controller *);
409 static float get_midi_controller_lfo1_pitch_depth(midi_controller *);
410 static float get_midi_controller_lfo1_amp_depth(midi_controller *);
411 static float get_midi_controller_lfo1_filter_depth(midi_controller *);
412 static float get_midi_controller_lfo2_pitch_depth(midi_controller *);
413 static float get_midi_controller_lfo2_amp_depth(midi_controller *);
414 static float get_midi_controller_lfo2_filter_depth(midi_controller *);
415 /* Rx. ~ (Rcv ~) */
416 static void init_rx(int);
417 static void set_rx(int, int32, int);
418 static int32 get_rx(int ch, int32 rx);
419 static void init_rx_drum(struct DrumParts *);
420 static void set_rx_drum(struct DrumParts *, int32, int);
421 static int32 get_rx_drum(struct DrumParts *, int32);
422
423 static int is_insertion_effect_xg(int ch);
424 static int is_mfx_effect_sd(int ch);
425
426 // 
427 #define OFFSET_MAX (0x3FFFFFFFL)
428 #define OFFSET_MIN (1L)
429
430 ///r
431 const int32 delay_out_time_ms[] = {
432         10,     // 0 : buffer mix / effect thru / no feedback
433         300,    // 1 : filter (
434         600,    // 2 : multi filter + any
435         1500,   // 3 : pre_delay + feedback (chorus/flanger/phaser
436         6000,   // 4 : delay // long delay + max feedback\82¾\82Æ\91«\82è\82È\82¢\82©\82à
437         12000,  // 5 : reverb
438         30000,  // 6 : system reverb
439 };
440 static int32 delay_out_count[7];
441
442 ///r
443 // channel mixer
444 #if 0 // dim ch buffer
445 static ALIGN DATA_T ch_buffer_s[MAX_CHANNELS][AUDIO_BUFFER_SIZE * 2]; // max:4MB
446 #else // malloc ch buffer
447 #endif // malloc ch buffer
448 DATA_T *ch_buffer[MAX_CHANNELS];
449
450 // VST channel use flag
451 #ifdef VST_LOADER_ENABLE
452 int use_vst_channel = 0;
453 #endif
454
455
456
457 #ifndef POW2
458 #if 1 // lite
459 #define POW2(val) exp((float)(M_LN2 * val))
460 #else // precision
461 #define POW2(val) pow(2.0, val)
462 #endif
463 #endif /* POW2 */
464
465
466 static inline int clip_int(int val, int min, int max)
467 {
468         return ((val > max) ? max : (val < min) ? min : val);
469 }
470
471
472
473 #ifdef VOICE_EFFECT
474 int cfg_flg_vfx = 0;
475 #endif
476 #ifdef INT_SYNTH
477 int cfg_flg_int_synth_scc = 0;
478 int cfg_flg_int_synth_mms = 0;
479 #endif
480
481 // free voice[]
482 void free_voice_pointer(void)
483 {
484         int i, j;
485         
486         if (!voice)
487                 return;
488         
489         for(i = 0; i < max_voices; i++) {                       
490                 Voice *vp = voice + i;  
491
492                 if(!vp)
493                         continue;
494 #ifdef VOICE_EFFECT
495                 for(j = 0; j < VOICE_EFFECT_NUM; j++){
496                         if(vp->vfx[j]){
497                                 free(vp->vfx[j]);
498                                 vp->vfx[j] = NULL;
499                         }       
500                 }
501 #endif
502 #ifdef INT_SYNTH
503                 if(vp->scc){
504                         free(vp->scc);
505                         vp->scc = NULL;
506                 }
507                 if(vp->mms){
508                         free(vp->mms);
509                         vp->mms = NULL;
510                 }
511 #endif
512         }
513
514     safe_free(voice);
515         voice = NULL;
516 }
517
518 // Allocate voice[]
519 void init_voice_pointer(void)
520 {       
521         int i, j, error = 0;
522
523     voice = (Voice*) safe_calloc(max_voices, sizeof(Voice));
524         memset(voice, 0, sizeof(voice));
525         if (!voice)
526                 return;
527         for(i = 0; i < max_voices; i++) {                       
528                 Voice *vp = voice + i;  
529
530                 if(!vp){
531                         error++;
532                         break;
533                 }
534 #ifdef VOICE_EFFECT
535                 if(cfg_flg_vfx){
536                         for(j = 0; j < VOICE_EFFECT_NUM; j++){
537                                 if(!vp->vfx[j]){
538                                         vp->vfx[j] = (VoiceEffect *)safe_malloc(sizeof(VoiceEffect));
539                                         if(!vp->vfx[j]){
540                                                 error++;
541                                                 break;
542                                         }
543                                         memset(vp->vfx[j], 0, sizeof(VoiceEffect));
544                                 }       
545                         }
546                 }
547 #endif
548 #ifdef INT_SYNTH
549                 if(cfg_flg_int_synth_scc && !vp->scc){
550                         vp->scc = (InfoIS_SCC *)safe_malloc(sizeof(InfoIS_SCC));
551                         if(!vp->scc){
552                                 error++;
553                                 break;
554                         }
555                         memset(vp->scc, 0, sizeof(InfoIS_SCC));
556                 }       
557                 if(cfg_flg_int_synth_mms && !vp->mms){
558                         vp->mms = (InfoIS_MMS *)safe_malloc(sizeof(InfoIS_MMS));
559                         if(!vp->mms){
560                                 error++;
561                                 break;
562                         }
563                         memset(vp->mms, 0, sizeof(InfoIS_MMS));
564                 }
565 #endif
566         }
567
568         if(error)
569                 free_voice_pointer();
570 }
571
572
573
574
575 void init_playmidi(void){
576         int i, tmp, tmp2;
577 #ifdef ALIGN_SIZE
578         const int min_compute_sample = 8;
579         uint32 min_compute_sample_mask = ~(min_compute_sample - 1);
580 #endif
581         
582         if(compute_buffer_bits < 0){ // auto
583                 tmp = tmp2 = playmode_rate_ms * abs(compute_buffer_bits);
584 #ifdef ALIGN_SIZE
585                 tmp &= min_compute_sample_mask;
586                 if(tmp < tmp2)
587                         tmp += min_compute_sample; // >=1ms
588 #endif
589                 compute_buffer_size = tmp;
590         }else{ // ! auto
591                 compute_buffer_size = 1U << compute_buffer_bits;
592 #ifdef ALIGN_SIZE
593                 if(compute_buffer_size < min_compute_sample)
594                         compute_buffer_size = min_compute_sample; // AVX 256bit / float 32bit 
595 #endif
596         }               
597         if((compute_buffer_bits < 0) && (compute_buffer_size < (1<<audio_buffer_bits))){
598                 double cb_ms = compute_buffer_size * div_playmode_rate * 1000.0;
599                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Auto compute_buffer_size : %d : %.3f ms",
600                         compute_buffer_size, cb_ms);
601         }else if(compute_buffer_size < (1<<audio_buffer_bits)){
602                 double cb_ms = compute_buffer_size * div_playmode_rate * 1000.0;
603                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "compute_buffer_size : %d : %.3f ms",
604                         compute_buffer_size, cb_ms);
605         }else{
606                 compute_buffer_bits = DEFAULT_COMPUTE_BUFFER_BITS;
607                 compute_buffer_size = 1U << compute_buffer_bits;
608                 audio_buffer_bits = DEFAULT_AUDIO_BUFFER_BITS;
609                 ctl->cmsg(CMSG_INFO, VERB_NORMAL, "ERROR! : Auto Compute Buffer Size");
610                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "compute_buffer_bits Set default : %d", compute_buffer_bits);
611                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "audio_buffer_bits Set default : %d", audio_buffer_bits);
612         }
613
614 #ifdef ALIGN_SIZE       
615         synth_buffer_size = (compute_buffer_size + min_compute_sample) * 2 * sizeof(DATA_T); // 2ch // compute_buffer_size < AUDIO_BUFFER_SIZE
616         // +8 \8fI\92[\95t\8bß\82Å\82ÌSIMD store\91Î\8dô
617 #else
618 //      synth_buffer_size_mono = compute_buffer_size * sizeof(DATA_T); // 1ch // compute_buffer_size < AUDIO_BUFFER_SIZE        
619         synth_buffer_size = compute_buffer_size * 2 * sizeof(DATA_T); // 2ch // compute_buffer_size < AUDIO_BUFFER_SIZE
620 #endif
621                 
622         control_ratio = compute_buffer_size;
623         div_control_ratio = 1.0 / (double)control_ratio;
624         
625         add_play_count = add_play_time > 0 ? (add_play_time * play_mode->rate) : 1;
626         add_silent_count = add_silent_time > 0 ? (add_silent_time * play_mode->rate) : 1;
627         ch_vol_env_count = playmode_rate_ms * CH_VOL_ENV_TIME; // per ms channel
628         vol_env_count = playmode_rate_ms * VOL_ENV_TIME; // per ms voice
629         mix_env_count = playmode_rate_ms * VOL_ENV_TIME; // per ms
630         if(compute_buffer_size == 1)
631                 opt_mix_envelope = 0; // OFF
632         if(opt_mix_envelope > 0){
633                 if(control_ratio < compute_buffer_size)
634                         mix_env_count = control_ratio;
635                 else                    
636                         mix_env_count = compute_buffer_size; // per 0.1ms
637                 if(opt_mix_envelope >= compute_buffer_size)
638                         opt_mix_envelope = 1;
639                 if(!(opt_mix_envelope == 1 || opt_mix_envelope == 2 || opt_mix_envelope == 4
640                  || opt_mix_envelope == 8 || opt_mix_envelope == 16 || opt_mix_envelope == 32
641                  || opt_mix_envelope == 64 || opt_mix_envelope == 128 || opt_mix_envelope == 256))
642                         opt_mix_envelope = 1;
643                 mix_env_mask = opt_mix_envelope - 1;            
644
645         }else{
646                 opt_mix_envelope = 0;
647                 mix_env_mask = 0;
648         }
649         if(opt_modulation_update > 100){
650                 opt_modulation_update = 100;
651         }else if(opt_modulation_update < 1)     {
652                 opt_modulation_update = 1;
653         }
654
655         ramp_out_count = playmode_rate_dms * MAX_DIE_TIME;
656         ramp_out_rate = (double)OFFSET_MAX * div_playmode_rate * control_ratio * 1000.0 * 10.0 / MAX_DIE_TIME;
657         cut_short_rate = (double)OFFSET_MAX * div_playmode_rate * control_ratio * 1000.0 / CUT_SHORT_TIME;
658         if(opt_cut_short_time > 0){
659                 cut_short_rate2 = (double)OFFSET_MAX * div_playmode_rate * control_ratio * 1000.0 / opt_cut_short_time;
660                 if(cut_short_rate2 > OFFSET_MAX)
661                         cut_short_rate2 = OFFSET_MAX;
662                 else if(cut_short_rate2 < OFFSET_MIN)
663                         cut_short_rate2 = OFFSET_MIN;
664         }else
665                 cut_short_rate2 = (double)OFFSET_MAX * div_playmode_rate * control_ratio * 1000.0 / CUT_SHORT_TIME2;
666
667         ramp_out_rate *= div_control_ratio; // rate / sample
668         cut_short_rate *= div_control_ratio; // rate / sample
669         cut_short_rate2 *= div_control_ratio; // rate / sample
670         env_add_offdelay_count = playmode_rate_ms * env_add_offdelay_time;
671
672
673         if(min_sustain_time > 0)
674                 min_sustain_count = playmode_rate_ms * min_sustain_time; // per ms      
675         for(i = 0; i < 7; i++)
676                 delay_out_count[i] = playmode_rate_ms * delay_out_time_ms[i]; // init delay_out count
677         
678         for(i = 0; i < MAX_CHANNELS; i++){
679 #if 0 // dim ch buffer
680                 ch_buffer[i] = ch_buffer_s[i];
681 #else // malloc ch buffer
682 #ifdef ALIGN_SIZE
683                 if(ch_buffer[i]){
684                         aligned_free(ch_buffer[i]);
685                         ch_buffer[i] = NULL;
686                 }
687                 ch_buffer[i] = (DATA_T *)aligned_malloc(synth_buffer_size, ALIGN_SIZE);
688 #else
689                 if(ch_buffer[i]){
690                         safe_free(ch_buffer[i]);
691                         ch_buffer[i] = NULL;
692                 }
693                 ch_buffer[i] = (DATA_T *)safe_malloc(synth_buffer_size);
694 #endif
695 #endif // malloc ch buffer
696                 memset(ch_buffer[i], 0, synth_buffer_size);
697         }
698         
699 // VST channel use flag
700 #ifdef VST_LOADER_ENABLE
701         use_vst_channel = opt_reverb_control == 11;
702 #endif
703 }
704
705
706 void free_playmidi(void)
707 {
708         int i;
709
710 #if 0 // dim ch buffer
711 #else // malloc ch buffer
712         for(i = 0; i < MAX_CHANNELS; i++){ 
713                 if(ch_buffer[i]){
714 #ifdef ALIGN_SIZE
715                         aligned_free(ch_buffer[i]);
716 #else
717                         safe_free(ch_buffer[i]);
718 #endif
719                         ch_buffer[i] = NULL;
720                 }
721         }
722 #endif
723         
724 #ifdef VOICE_EFFECT
725         if (!voice)
726                 return; 
727         for(i = 0; i < max_voices; i++) {       
728                 free_voice_effect(i);
729         }
730 #endif
731 }
732
733
734
735 #define IS_SYSEX_EVENT_TYPE(event) ((event)->type == ME_NONE || (event)->type >= ME_RANDOM_PAN || (event)->b == SYSEX_TAG)
736
737 static char *event_name(int type)
738 {
739 #define EVENT_NAME(X) case X: return #X
740         switch (type) {
741         EVENT_NAME(ME_NONE);
742         EVENT_NAME(ME_NOTEOFF);
743         EVENT_NAME(ME_NOTEON);
744         EVENT_NAME(ME_KEYPRESSURE);
745         EVENT_NAME(ME_PROGRAM);
746         EVENT_NAME(ME_CHANNEL_PRESSURE);
747         EVENT_NAME(ME_PITCHWHEEL);
748         EVENT_NAME(ME_TONE_BANK_MSB);
749         EVENT_NAME(ME_TONE_BANK_LSB);
750         EVENT_NAME(ME_MODULATION_WHEEL);
751         EVENT_NAME(ME_BREATH);
752         EVENT_NAME(ME_FOOT);
753         EVENT_NAME(ME_MAINVOLUME);
754         EVENT_NAME(ME_BALANCE);
755         EVENT_NAME(ME_PAN);
756         EVENT_NAME(ME_EXPRESSION);      
757         EVENT_NAME(ME_SUSTAIN);
758         EVENT_NAME(ME_PORTAMENTO_TIME_MSB);
759         EVENT_NAME(ME_PORTAMENTO_TIME_LSB);
760         EVENT_NAME(ME_PORTAMENTO);
761         EVENT_NAME(ME_PORTAMENTO_CONTROL);
762         EVENT_NAME(ME_DATA_ENTRY_MSB);
763         EVENT_NAME(ME_DATA_ENTRY_LSB);
764         EVENT_NAME(ME_SOSTENUTO);
765         EVENT_NAME(ME_SOFT_PEDAL);
766         EVENT_NAME(ME_LEGATO_FOOTSWITCH);
767         EVENT_NAME(ME_HOLD2);
768         EVENT_NAME(ME_HARMONIC_CONTENT);
769         EVENT_NAME(ME_RELEASE_TIME);
770         EVENT_NAME(ME_DECAY_TIME);
771         EVENT_NAME(ME_ATTACK_TIME);
772         EVENT_NAME(ME_BRIGHTNESS);
773         EVENT_NAME(ME_VIBRATO_RATE);
774         EVENT_NAME(ME_VIBRATO_DEPTH);
775         EVENT_NAME(ME_VIBRATO_DELAY);
776         EVENT_NAME(ME_REVERB_EFFECT);
777         EVENT_NAME(ME_TREMOLO_EFFECT);
778         EVENT_NAME(ME_CHORUS_EFFECT);
779         EVENT_NAME(ME_CELESTE_EFFECT);
780         EVENT_NAME(ME_PHASER_EFFECT);
781         EVENT_NAME(ME_RPN_INC);
782         EVENT_NAME(ME_RPN_DEC);
783         EVENT_NAME(ME_NRPN_LSB);
784         EVENT_NAME(ME_NRPN_MSB);
785         EVENT_NAME(ME_RPN_LSB);
786         EVENT_NAME(ME_RPN_MSB);
787         EVENT_NAME(ME_ALL_SOUNDS_OFF);
788         EVENT_NAME(ME_RESET_CONTROLLERS);
789         EVENT_NAME(ME_ALL_NOTES_OFF);
790         EVENT_NAME(ME_MONO);
791         EVENT_NAME(ME_POLY);
792         EVENT_NAME(ME_UNDEF_CTRL_CHNG);
793 #if 0
794         EVENT_NAME(ME_VOLUME_ONOFF);            /* Not supported */
795 #endif
796         EVENT_NAME(ME_MASTER_TUNING);
797         EVENT_NAME(ME_SCALE_TUNING);
798         EVENT_NAME(ME_BULK_TUNING_DUMP);
799         EVENT_NAME(ME_SINGLE_NOTE_TUNING);
800         EVENT_NAME(ME_RANDOM_PAN);
801         EVENT_NAME(ME_SET_PATCH);
802         EVENT_NAME(ME_DRUMPART);
803         EVENT_NAME(ME_KEYSHIFT);
804         EVENT_NAME(ME_PATCH_OFFS);
805         EVENT_NAME(ME_TEMPO);
806         EVENT_NAME(ME_CHORUS_TEXT);
807         EVENT_NAME(ME_LYRIC);
808         EVENT_NAME(ME_GSLCD);
809         EVENT_NAME(ME_MARKER);
810         EVENT_NAME(ME_INSERT_TEXT);
811         EVENT_NAME(ME_TEXT);
812         EVENT_NAME(ME_KARAOKE_LYRIC);
813         EVENT_NAME(ME_MASTER_VOLUME);
814         EVENT_NAME(ME_RESET);
815         EVENT_NAME(ME_NOTE_STEP);
816         EVENT_NAME(ME_CUEPOINT);
817         EVENT_NAME(ME_TIMESIG);
818         EVENT_NAME(ME_KEYSIG);
819         EVENT_NAME(ME_TEMPER_KEYSIG);
820         EVENT_NAME(ME_TEMPER_TYPE);
821         EVENT_NAME(ME_MASTER_TEMPER_TYPE);
822         EVENT_NAME(ME_USER_TEMPER_ENTRY);
823         EVENT_NAME(ME_SYSEX_LSB);
824         EVENT_NAME(ME_SYSEX_MSB);
825         EVENT_NAME(ME_SYSEX_GS_LSB);
826         EVENT_NAME(ME_SYSEX_GS_MSB);
827         EVENT_NAME(ME_SYSEX_XG_LSB);
828         EVENT_NAME(ME_SYSEX_XG_MSB);
829         EVENT_NAME(ME_SYSEX_SD_LSB);
830         EVENT_NAME(ME_SYSEX_SD_MSB);
831         EVENT_NAME(ME_SYSEX_SD_HSB);
832         EVENT_NAME(ME_WRD);
833         EVENT_NAME(ME_SHERRY);
834         EVENT_NAME(ME_BARMARKER);
835         EVENT_NAME(ME_STEP);
836         EVENT_NAME(ME_LAST);
837         EVENT_NAME(ME_EOT);
838         }
839         return "Unknown";
840 #undef EVENT_NAME
841 }
842
843 ///r
844 #define DIV_COMPENSATION_RATIO_MAX ((double)(1.5259021896696421759365224689097e-5)) // 1/(0xFFFF)
845
846 static void adjust_amplification(void)
847 {
848     /* input volume */
849 //    input_volume = (double)(amplification) * DIV_100 * ((double)master_volume_ratio * (compensation_ratio/0xFFFF));
850         if (opt_user_volume_curve != 0) {
851                 input_volume = (double)(amplification) * DIV_100
852                         * user_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
853         } else if (play_system_mode == SD_SYSTEM_MODE) {
854                 input_volume = (double)(amplification) * DIV_100
855                         * gm2_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
856         } else if (play_system_mode == GM2_SYSTEM_MODE) {
857                 input_volume = (double)(amplification) * DIV_100
858                         * gm2_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
859         } else if(play_system_mode == GS_SYSTEM_MODE) { /* use measured curve */ 
860                 input_volume = (double)(amplification) * DIV_100
861                         * sc_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
862         } else if(play_system_mode == CM_SYSTEM_MODE) { /* use measured curve */ 
863                 input_volume = (double)(amplification) * DIV_100
864                         * sc_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
865         } else if (IS_CURRENT_MOD_FILE) {       /* use linear curve */
866                 input_volume = (double)(amplification) * DIV_100
867                         * (double)master_volume_ratio * DIV_COMPENSATION_RATIO_MAX;
868         } else {        /* use generic exponential curve */
869                 input_volume = (double)(amplification) * DIV_100
870                         * perceived_vol_table[(master_volume_ratio >> 9) & 0x7F] * DIV_127;
871         }       
872         if(opt_amp_compensation)        
873                 input_volume *= compensation_ratio;
874 }
875
876 static int new_vidq(int ch, int note)
877 {
878     int i;
879
880     if(opt_overlap_voice_allow)
881     {
882         i = ch * 128 + note;
883         return vidq_head[i]++;
884     }
885     return 0;
886 }
887
888 static int last_vidq(int ch, int note)
889 {
890     int i;
891
892     if(opt_overlap_voice_allow)
893     {
894         i = ch * 128 + note;
895         if(vidq_head[i] == vidq_tail[i])
896         {
897             ctl->cmsg(CMSG_WARNING, VERB_DEBUG_SILLY,
898                       "channel=%d, note=%d: Voice is already OFF", ch, note);
899             return -1;
900         }
901         return vidq_tail[i]++;
902     }
903     return 0;
904 }
905
906 static void swap_voices(Voice *a, Voice *b)
907 {
908     Voice swap;
909     memcpy(&swap, a, sizeof(Voice));
910     memmove(a, b, sizeof(Voice));
911     memcpy(b, &swap, sizeof(Voice));
912 }
913
914 static void reset_voices(void)
915 {
916     int i;
917     for(i = 0; i < max_voices; i++)
918     {
919         voice[i].status = VOICE_FREE;
920         voice[i].temper_instant = 0;
921     }
922     upper_voices = 0;
923     memset(vidq_head, 0, sizeof(vidq_head));
924     memset(vidq_tail, 0, sizeof(vidq_tail));
925 }
926
927 ///r
928 static void kill_note(int i)
929 {
930         if(voice[i].status & (VOICE_FREE | VOICE_DIE))
931                 return;
932     voice[i].status = VOICE_DIE;
933     if (voice[i].sample->modes & MODES_ENVELOPE)
934                 if(voice[i].update_voice < UPDATE_VOICE_KILL_NOTE)
935                         voice[i].update_voice = UPDATE_VOICE_KILL_NOTE; // kill_note
936     if(!prescanning_flag)
937         ctl_note_event(i);
938 }
939
940 static void cut_note(int i)
941 {
942         if(voice[i].status & (VOICE_FREE))
943                 return;
944     voice[i].status = VOICE_DIE;
945     if (voice[i].sample->modes & MODES_ENVELOPE)
946                 if(voice[i].update_voice < UPDATE_VOICE_CUT_NOTE)
947                         voice[i].update_voice = UPDATE_VOICE_CUT_NOTE; // cut_note
948     if(!prescanning_flag)
949         ctl_note_event(i);
950 }
951
952 static void cut_note2(int i)
953 {
954         if(voice[i].status & (VOICE_FREE))
955                 return;
956     voice[i].status = VOICE_DIE;
957     if (voice[i].sample->modes & MODES_ENVELOPE)
958                 if(voice[i].update_voice < UPDATE_VOICE_CUT_NOTE2)
959                         voice[i].update_voice = UPDATE_VOICE_CUT_NOTE2; // cut_note2
960     if(!prescanning_flag)
961         ctl_note_event(i);
962 }
963
964
965 void kill_all_voices(void)
966 {
967     int i, uv = upper_voices;
968
969     for(i = 0; i < uv; i++)
970         if(voice[i].status & ~(VOICE_FREE | VOICE_DIE))
971             kill_note(i);
972     memset(vidq_head, 0, sizeof(vidq_head));
973     memset(vidq_tail, 0, sizeof(vidq_tail));
974 }
975
976 static void reset_drum_controllers(struct DrumParts *d[], int note)
977 {
978     int i,j;
979
980
981     if(note == -1)
982     {
983         for(i = 0; i < 128; i++)
984             if(d[i] != NULL)
985             {
986                 d[i]->drum_panning = NO_PANNING;
987                 for(j=0;j<6;j++) {d[i]->drum_envelope_rate[j] = -1;}
988                 d[i]->pan_random = 0;
989                 d[i]->drum_level = 1.0f;
990                 d[i]->coarse = 0;
991                 d[i]->fine = 0;
992                 d[i]->delay_level = -1;
993                 d[i]->chorus_level = -1;
994                 d[i]->reverb_level = -1;
995                 d[i]->play_note = -1;
996                 d[i]->drum_cutoff_freq = 0;
997                 d[i]->drum_resonance = 0;
998 ///r
999                 d[i]->drum_hpf_cutoff_freq = 0;
1000                 d[i]->drum_hpf_resonance = 0;
1001                 d[i]->drum_velo_pitch_sens = 0;
1002                 d[i]->drum_velo_cutoff_sens = 0;
1003                 if(opt_eq_control && opt_drum_effect)
1004                         init_part_eq_xg(&d[i]->eq_xg);
1005                 init_rx_drum(d[i]);     
1006                 d[i]->rx_note_off = -1;
1007             }
1008     }
1009     else
1010     {
1011         d[note]->drum_panning = NO_PANNING;
1012         for(j = 0; j < 6; j++) {d[note]->drum_envelope_rate[j] = -1;}
1013         d[note]->pan_random = 0;
1014         d[note]->drum_level = 1.0f;
1015         d[note]->coarse = 0;
1016         d[note]->fine = 0;
1017         d[note]->delay_level = -1;
1018         d[note]->chorus_level = -1;
1019         d[note]->reverb_level = -1;
1020         d[note]->play_note = -1;
1021         d[note]->drum_cutoff_freq = 0;
1022         d[note]->drum_resonance = 0;
1023 ///r
1024         d[note]->drum_hpf_cutoff_freq = 0;
1025         d[note]->drum_hpf_resonance = 0;
1026         d[note]->drum_velo_pitch_sens = 0;
1027         d[note]->drum_velo_cutoff_sens = 0;
1028         if(opt_eq_control && opt_drum_effect)
1029                 init_part_eq_xg(&d[note]->eq_xg);
1030         init_rx_drum(d[note]);
1031         d[note]->rx_note_off = -1;
1032     }
1033 }
1034
1035 ///r
1036 static void initialize_controllers(int c)
1037 {
1038         /* Reset Controllers other CC#121 */
1039         int i, module = get_module();
1040         
1041         switch(module) {        /* TONE MAP-0 NUMBER */
1042         case MODULE_SC55:
1043                 channel[c].tone_map0_number = 1;
1044                 break;
1045         case MODULE_SC88:
1046                 channel[c].tone_map0_number = 2;
1047                 break;
1048         case MODULE_SC88PRO:
1049                 channel[c].tone_map0_number = 3;
1050                 break;
1051         case MODULE_SC8850:
1052                 channel[c].tone_map0_number = 4;
1053                 break;
1054         //      case MODULE_SDMODE:
1055         case MODULE_SD20:
1056         case MODULE_SD80:
1057         case MODULE_SD90:
1058         case MODULE_SD50:
1059                 channel[c].tone_map0_number = 120;
1060                 break;
1061                 break;
1062         default:
1063                 channel[c].tone_map0_number = 0;
1064                 break;
1065         }       
1066         
1067         channel[c].program_flag = 0;
1068
1069         channel[c].damper_mode = 0;
1070         channel[c].loop_timeout = 0;            
1071         if(play_system_mode == XG_SYSTEM_MODE)
1072                 channel[c].volume = 100;
1073         else
1074                 channel[c].volume = 90;
1075         if (prescanning_flag) {
1076                 if (channel[c].volume > mainvolume_max) {       /* pick maximum value of mainvolume */
1077                         mainvolume_max = channel[c].volume;
1078                         ctl->cmsg(CMSG_INFO,VERB_DEBUG,"ME_MAINVOLUME/max (CH:%d VAL:%#x)",c,mainvolume_max);
1079                 }
1080         }
1081         channel[c].mono = 0;
1082         channel[c].portamento_time_lsb = 0;
1083         channel[c].portamento_time_msb = 0;
1084         channel[c].porta_status = 0;
1085         channel[c].porta_last_note_fine = -1;
1086         channel[c].legato_status = 0;
1087         channel[c].legato_flag = 0;
1088         channel[c].legato_note = 255;
1089         channel[c].legato_note_time = 0;
1090
1091         set_reverb_level(c, -1);
1092         if(opt_chorus_control == 1)
1093                 channel[c].chorus_level = 0;
1094         else
1095                 channel[c].chorus_level = -opt_chorus_control;
1096         channel[c].delay_level = 0;
1097
1098         /* NRPN */
1099         reset_drum_controllers(channel[c].drums, -1);
1100         for(i = 0; i < 6; i++) {channel[c].envelope_rate[i] = -1;}
1101         channel[c].param_vibrato_rate = 0;
1102         channel[c].param_vibrato_depth = 0;
1103         channel[c].param_vibrato_delay = 0;     
1104         channel[c].vibrato_delay = 0;   
1105         channel[c].amp = 1.0;
1106         channel[c].ch_amp[0] = 1.0;
1107         channel[c].ch_amp[1] = 1.0;
1108         channel[c].lfo_amp_depth[0] = 0;
1109         channel[c].lfo_amp_depth[1] = 0;        
1110         channel[c].modenv_depth = 0;
1111         channel[c].param_cutoff_freq = 0;
1112         channel[c].param_resonance = 0;
1113         channel[c].cutoff_cent = 0;
1114         channel[c].resonance_dB = 0;
1115         channel[c].hpf_param_cutoff_freq = 0;
1116         channel[c].hpf_param_resonance = 0;
1117         channel[c].hpf_cutoff_cent = 0;
1118         channel[c].hpf_resonance_dB = 0;
1119         channel[c].lfo_cutoff_depth[0] = 0;
1120         channel[c].lfo_cutoff_depth[1] = 0;
1121         channel[c].pitch = 0;
1122         channel[c].lfo_pitch_depth[0] = 0;
1123         channel[c].lfo_pitch_depth[1] = 0;
1124         channel[c].freq_table = freq_table;
1125                 
1126         /* System Exclusive */
1127         channel[c].sysex_gs_msb_addr = channel[c].sysex_gs_msb_val =
1128         channel[c].sysex_xg_msb_addr = channel[c].sysex_xg_msb_val =
1129         channel[c].sysex_msb_addr = channel[c].sysex_msb_val = 0;
1130         channel[c].dry_level = 127;
1131         channel[c].eq_gs = 1;
1132         channel[c].insertion_effect = 0;
1133         channel[c].velocity_sense_depth = 0x40;
1134         channel[c].velocity_sense_offset = 0x40;
1135         channel[c].pit_env_level[0] = 0x40;
1136         channel[c].pit_env_level[1] = 0x40;
1137         channel[c].pit_env_level[2] = 0x40;
1138         channel[c].pit_env_level[3] = 0x40;
1139         channel[c].pit_env_level[4] = 0x40;
1140         channel[c].pit_env_time[0] = 0x40;
1141         channel[c].pit_env_time[1] = 0x40;
1142         channel[c].pit_env_time[2] = 0x40;
1143         channel[c].pit_env_time[3] = 0x40;
1144         channel[c].detune_param = 0x80;
1145         channel[c].detune = 1.0;
1146         channel[c].pitch_offset_fine = 0.0;
1147         
1148 #if 1 // fix limited multi
1149         channel[c].assign_mode = 1;
1150 #else // GS XG spec
1151         if(ISDRUMCHANNEL(c) && play_system_mode == GS_SYSTEM_MODE && module == MODULE_SC55 )
1152                 channel[c].assign_mode = 0;
1153         else
1154                 channel[c].assign_mode = 1;
1155 #endif
1156
1157         for (i = 0; i < 12; i++)
1158                 channel[c].scale_tuning[i] = 0;
1159         channel[c].prev_scale_tuning = 0;
1160         channel[c].temper_type = 0;
1161
1162         init_channel_layer(c);
1163         init_part_eq_xg(&(channel[c].eq_xg));
1164
1165         /* channel pressure & polyphonic key pressure control */
1166         init_midi_controller(&(channel[c].mod));
1167         init_midi_controller(&(channel[c].bend)); 
1168         init_midi_controller(&(channel[c].caf)); 
1169         init_midi_controller(&(channel[c].paf)); 
1170         init_midi_controller(&(channel[c].cc1)); 
1171         init_midi_controller(&(channel[c].cc2)); 
1172         channel[c].mod.mode = 0;
1173         channel[c].bend.mode = 0;
1174         channel[c].caf.mode = 0;
1175         channel[c].paf.mode = 0;  
1176         channel[c].cc1.mode = 0;
1177         channel[c].cc2.mode = 0;
1178         if(play_system_mode == XG_SYSTEM_MODE){
1179                 channel[c].cc3.mode = 1;
1180                 channel[c].cc4.mode = 1;
1181         }else{
1182                 channel[c].cc3.mode = 0;
1183                 channel[c].cc4.mode = 0;          
1184         }
1185         channel[c].mod.val = 0;
1186         channel[c].bend.val = 0;
1187         channel[c].caf.val = 0;
1188         channel[c].paf.val = 0;  
1189         channel[c].cc1.val = 0;
1190         channel[c].cc2.val = 0;
1191         channel[c].cc3.val = 0;
1192         channel[c].cc4.val = 0;
1193         channel[c].cc1.num = 16;
1194         channel[c].cc2.num = 17;
1195         channel[c].cc3.num = 18;
1196         channel[c].cc4.num = 19;        
1197         channel[c].bend.pitch = 2;
1198         if (play_system_mode == GM2_SYSTEM_MODE)
1199                 channel[c].mod.lfo1_pitch_depth = 50.0; // 50cent
1200         else
1201                 channel[c].mod.lfo1_pitch_depth = DIV_127 * 0x0A * 600.0; // max=600cent def=0x0A 47cent
1202
1203         init_rx(c);
1204         channel[c].note_limit_high = 127;
1205         channel[c].note_limit_low = 0;
1206         channel[c].vel_limit_high = 127;
1207         channel[c].vel_limit_low = 0;
1208
1209         free_drum_effect(c);
1210         
1211         /* SD */
1212         channel[c].gm2_inst = 1; // contemp set
1213         /* SD MFX */
1214         // assign 1ch:part 2ch:part 3:part other:none
1215         // select1ch:MFX1 2ch:MFX2 3ch:MFX3 other:MFX1
1216         channel[c].sd_output_assign = c < SD_MFX_EFFECT_NUM ? 2 : 1; // 0:mfx 1:none 2:part
1217         channel[c].sd_output_mfx_select = c < SD_MFX_EFFECT_NUM ? c : 0; // 0:MFX1 1:MFX2 2:MFX3
1218         channel[c].sd_dry_send_level = 127;
1219         channel[c].mfx_part_type = 0;
1220         memset(channel[c].mfx_part_param, 0, sizeof(channel[c].mfx_part_param));
1221         channel[c].mfx_part_dry_send = 127;
1222         channel[c].mfx_part_send_reverb = 0;
1223         channel[c].mfx_part_send_chorus = 0;
1224         channel[c].mfx_part_ctrl_source[0] = 0;
1225         channel[c].mfx_part_ctrl_source[1] = 0;
1226         channel[c].mfx_part_ctrl_source[2] = 0;
1227         channel[c].mfx_part_ctrl_source[3] = 0;
1228         channel[c].mfx_part_ctrl_sens[0] = 0x40;
1229         channel[c].mfx_part_ctrl_sens[1] = 0x40;
1230         channel[c].mfx_part_ctrl_sens[2] = 0x40;
1231         channel[c].mfx_part_ctrl_sens[3] = 0x40;
1232         channel[c].mfx_part_ctrl_assign[0] = 0;
1233         channel[c].mfx_part_ctrl_assign[1] = 0;
1234         channel[c].mfx_part_ctrl_assign[2] = 0;
1235         channel[c].mfx_part_ctrl_assign[3] = 0;
1236         /* SD Chorus */
1237         channel[c].chorus_part_type = 0;
1238         memset(channel[c].chorus_part_param, 0, sizeof(channel[c].chorus_part_param));
1239         channel[c].chorus_part_efx_level = 127;
1240         channel[c].chorus_part_send_reverb = 0;
1241         channel[c].chorus_part_output_select = 0;
1242         /* SD Reverb */
1243         channel[c].reverb_part_type = 0;
1244         memset(channel[c].reverb_part_param, 0, sizeof(channel[c].reverb_part_param));
1245         channel[c].reverb_part_efx_level = 100;
1246         
1247 }
1248
1249 /* Process the Reset All Controllers event CC#121 */
1250 static void reset_controllers(int c)
1251 {
1252         channel[c].expression = 127; /* SCC-1 does this. */
1253         channel[c].sustain = 0;
1254         channel[c].sostenuto = 0;
1255         channel[c].pitchbend = 0x2000;
1256         channel[c].portamento = 0;
1257         channel[c].portamento_control = -1;
1258         update_portamento_controls(c);
1259         channel[c].legato = -1;
1260         update_legato_status(c);
1261         channel[c].lastlrpn = channel[c].lastmrpn = 0;
1262         channel[c].nrpn = -1;
1263         channel[c].rpn_7f7f_flag = 1;
1264 }
1265
1266 static void redraw_controllers(int c)
1267 {
1268     ctl_mode_event(CTLE_VOLUME, 1, c, channel[c].volume);
1269     ctl_mode_event(CTLE_EXPRESSION, 1, c, channel[c].expression);
1270     ctl_mode_event(CTLE_SUSTAIN, 1, c, channel[c].sustain);
1271     ctl_mode_event(CTLE_MOD_WHEEL, 1, c, channel[c].mod.val);
1272     ctl_mode_event(CTLE_PITCH_BEND, 1, c, channel[c].pitchbend);
1273     ctl_prog_event(c);
1274     ctl_mode_event(CTLE_TEMPER_TYPE, 1, c, channel[c].temper_type);
1275     ctl_mode_event(CTLE_MUTE, 1,
1276                 c, (IS_SET_CHANNELMASK(channel_mute, c)) ? 1 : 0);
1277     ctl_mode_event(CTLE_CHORUS_EFFECT, 1, c, get_chorus_level(c));
1278     ctl_mode_event(CTLE_REVERB_EFFECT, 1, c, get_reverb_level(c));
1279     if (play_system_mode == XG_SYSTEM_MODE)
1280         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, c, is_insertion_effect_xg(c));
1281     else if (play_system_mode == SD_SYSTEM_MODE)
1282         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, c, is_mfx_effect_sd(c));
1283     else
1284         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, c, channel[c].insertion_effect);
1285 }
1286
1287 #ifdef MULTI_THREAD_COMPUTE
1288 static void reset_midi_thread(void);
1289 #endif
1290
1291 static void recompute_channel_lfo(int ch);
1292 static void recompute_channel_amp(int ch);
1293 static void recompute_channel_filter(int ch);
1294 static void recompute_channel_pitch(int ch);
1295
1296 ///r
1297 void reset_midi(int playing)
1298 {
1299         int i, cnt, module = get_module();
1300         
1301 #ifdef MULTI_THREAD_COMPUTE
1302         reset_midi_thread();
1303 #endif
1304         compute_skip_count = -1;
1305                 
1306         switch(play_system_mode){
1307         case GS_SYSTEM_MODE:
1308         case CM_SYSTEM_MODE:    
1309                 nrpn_vib_delay_mode = NRPN_PARAM_GS_DELAY;
1310                 nrpn_vib_rate_mode = NRPN_PARAM_GS_RATE;
1311                 nrpn_filter_freq_mode = NRPN_PARAM_GS_CUTOFF;
1312         //      nrpn_filter_reso_mode = NRPN_PARAM_GS_RESO;
1313                 nrpn_filter_hpf_freq_mode = NRPN_PARAM_GS_CUTOFF_HPF;
1314                 nrpn_env_attack_mode = NRPN_PARAM_GS_ATTACK;
1315                 nrpn_env_decay_mode = NRPN_PARAM_GS_DECAY;
1316                 nrpn_env_release_mode = NRPN_PARAM_GS_RELEASE;
1317                 break;
1318         case XG_SYSTEM_MODE:
1319                 nrpn_vib_delay_mode = NRPN_PARAM_XG_DELAY;
1320                 nrpn_vib_rate_mode = NRPN_PARAM_XG_RATE;
1321                 nrpn_filter_freq_mode = NRPN_PARAM_XG_CUTOFF;
1322         //      nrpn_filter_reso_mode = NRPN_PARAM_XG_RESO;
1323                 nrpn_filter_hpf_freq_mode = NRPN_PARAM_XG_CUTOFF_HPF;
1324                 nrpn_env_attack_mode = NRPN_PARAM_XG_ATTACK;
1325                 nrpn_env_decay_mode = NRPN_PARAM_XG_DECAY;
1326                 nrpn_env_release_mode = NRPN_PARAM_XG_RELEASE;
1327                 break;
1328         case SD_SYSTEM_MODE:
1329         case GM_SYSTEM_MODE:
1330         case GM2_SYSTEM_MODE:
1331         default:
1332                 nrpn_vib_delay_mode = NRPN_PARAM_GM_DELAY;
1333                 nrpn_vib_rate_mode = NRPN_PARAM_GM_RATE;
1334                 nrpn_filter_freq_mode = NRPN_PARAM_GM_CUTOFF;
1335         //      nrpn_filter_reso_mode = NRPN_PARAM_GM_RESO;
1336                 nrpn_filter_hpf_freq_mode = NRPN_PARAM_GM_CUTOFF_HPF;
1337                 nrpn_env_attack_mode = NRPN_PARAM_GM_ATTACK;
1338                 nrpn_env_decay_mode = NRPN_PARAM_GM_DECAY;
1339                 nrpn_env_release_mode = NRPN_PARAM_GM_RELEASE;
1340                 break;
1341         }
1342         if(otd.vibrato_rate != 0 )
1343                 nrpn_vib_rate = otd.vibrato_rate * DIV_100;
1344         else
1345                 nrpn_vib_rate = NRPN_VIBRATO_RATE;
1346         if (otd.vibrato_cent != 0 )
1347                 nrpn_vib_depth_cent = otd.vibrato_cent;
1348         else switch(play_system_mode){
1349         case GS_SYSTEM_MODE:
1350                 switch(module){
1351                 case MODULE_SC55:
1352                 case MODULE_SC88:
1353                 case MODULE_SC88PRO:
1354                 case MODULE_MT32:
1355                 case MODULE_CM32L:
1356                 case MODULE_CM32P:
1357                 case MODULE_CM64:
1358                 case MODULE_CM500A:
1359                 case MODULE_CM500D:
1360                 case MODULE_CM64_SN01:
1361                 case MODULE_CM64_SN02:
1362                 case MODULE_CM64_SN03:
1363                 case MODULE_CM64_SN04:
1364                 case MODULE_CM64_SN05:
1365                 case MODULE_CM64_SN06:
1366                 case MODULE_CM64_SN07:
1367                 case MODULE_CM64_SN08:
1368                 case MODULE_CM64_SN09:
1369                 case MODULE_CM64_SN10:
1370                 case MODULE_CM64_SN11:
1371                 case MODULE_CM64_SN12:
1372                 case MODULE_CM64_SN13:
1373                 case MODULE_CM64_SN14:
1374                 case MODULE_CM64_SN15:
1375                 // CM\8aÖ\98A\83\82\83W\83\85\81[\83\8b\82Å\82ÍGS\83\8a\83Z\83b\83g\96³\8cø\82¾\82ª\81E\81E\88ê\89\9e
1376                         nrpn_vib_depth_cent = 75; // 9.6cent ? /* GS NRPN from -9.6 cents to +9.45 cents. */
1377                         break;
1378                 case MODULE_SC8850:
1379                 default:
1380                         nrpn_vib_depth_cent = 100;
1381                         break;
1382                 }
1383                 break;
1384         case CM_SYSTEM_MODE:            
1385                 nrpn_vib_depth_cent = 75;
1386                 break;
1387         case SD_SYSTEM_MODE:
1388         case GM2_SYSTEM_MODE:
1389         default:
1390                 nrpn_vib_depth_cent = 100;
1391                 break;
1392         }
1393         if (otd.vibrato_delay != 0 )
1394                 nrpn_vib_delay = otd.vibrato_delay * playmode_rate_ms;
1395         else
1396                 nrpn_vib_delay = NRPN_VIBRATO_DELAY * playmode_rate_ms;
1397         if(otd.filter_freq != 0 )
1398                 nrpn_filter_freq = otd.filter_freq;
1399         else
1400                 nrpn_filter_freq = NRPN_FILTER_FREQ_MAX;
1401         if(otd.filter_reso != 0 )
1402                 nrpn_filter_reso = otd.filter_reso * DIV_10;
1403         else
1404                 nrpn_filter_reso = NRPN_FILTER_RESO_MAX;        
1405         // env calc
1406         switch(play_system_mode){
1407         case GS_SYSTEM_MODE:
1408                 env_attack_calc = gs_env_attack_calc;
1409                 env_decay_calc = gs_env_decay_calc;
1410                 env_release_calc = gs_env_release_calc;
1411                 break;
1412         case XG_SYSTEM_MODE:
1413                 env_attack_calc = xg_env_attack_calc;
1414                 env_decay_calc = xg_env_decay_calc;
1415                 env_release_calc = xg_env_release_calc;
1416                 break;
1417         case SD_SYSTEM_MODE:
1418         case GM2_SYSTEM_MODE:
1419                 env_attack_calc = gm2_env_attack_calc;
1420                 env_decay_calc = gm2_env_decay_calc;
1421                 env_release_calc = gm2_env_release_calc;
1422                 break;
1423         case GM_SYSTEM_MODE:
1424         default:
1425                 env_attack_calc = gm_env_attack_calc;
1426                 env_decay_calc = gm_env_decay_calc;
1427                 env_release_calc = gm_env_release_calc;
1428                 break;
1429         }
1430
1431         for (i = 0; i < MAX_CHANNELS; i++) {
1432                 initialize_controllers(i);
1433                 reset_controllers(i);
1434                 /* The rest of these are unaffected
1435                  * by the Reset All Controllers event
1436                  */
1437                 channel[i].program = default_program[i];
1438                 channel[i].panning = NO_PANNING;
1439                 channel[i].pan_random = 0;      
1440 ///r
1441                 if(adjust_panning_immediately && play_system_mode == XG_SYSTEM_MODE){
1442                         channel[i].ch_amp[0] = channel[i].ch_amp[1] = 0;
1443                         init_envelope2(&channel[i].vol_env , channel[i].ch_amp[0], channel[i].ch_amp[1], ch_vol_env_count);
1444                         if(opt_mix_envelope)
1445                                 init_envelope2(&channel[i].mix_env , channel[i].vol_env.vol[0], channel[i].vol_env.vol[1], mix_env_count);
1446                 }
1447                 memset(ch_buffer[i], 0, synth_buffer_size); // clear
1448
1449 // VST channel convert DATA_T to int32
1450 #ifdef VST_LOADER_ENABLE
1451 #if (defined(DATA_T_DOUBLE) || defined(DATA_T_FLOAT)) && !defined(VSTWRAP_EXT)  
1452                 memset(vst_ch_vpblist[i], 0, synth_buffer_size); // clear
1453 #endif
1454 #endif
1455
1456                 /* tone bank or drum set */
1457                 if (ISDRUMCHANNEL(i)) {
1458                         channel[i].bank = 0;
1459                         channel[i].altassign = drumset[0]->alt;
1460                 } else {
1461                         if (special_tonebank >= 0)
1462                                 channel[i].bank = special_tonebank;
1463                         else
1464                                 channel[i].bank = default_tonebank;
1465                 }
1466                 channel[i].bank_lsb = channel[i].bank_msb = 0;
1467 ///r
1468                 if (play_system_mode == XG_SYSTEM_MODE && i % 16 == 9)
1469                         channel[i].bank_msb = 127;      // Use MSB=127 for XG
1470                 else if (play_system_mode == GM2_SYSTEM_MODE && i % 16 == 9)
1471                         channel[i].bank_msb = 120;      // Use MSB=120 for GM2
1472                 else if (play_system_mode == SD_SYSTEM_MODE && i % 16 == 9)
1473                         channel[i].bank_msb = 104;      // Use MSB=105 for SD
1474                 else if (play_system_mode == KG_SYSTEM_MODE && i % 16 == 9)
1475                         channel[i].bank_msb = 61;       // Use MSB=61 for AG
1476                 update_rpn_map(i, RPN_ADDR_FFFF, 0);
1477                 channel[i].special_sample = 0;
1478                 channel[i].key_shift = 0;
1479                 channel[i].mapID = get_default_mapID(i);
1480                 channel[i].lasttime = INT_MIN / 2;
1481                 
1482                 recompute_channel_lfo(i);
1483                 recompute_channel_amp(i);
1484                 recompute_channel_filter(i);
1485                 recompute_channel_pitch(i);
1486
1487         }
1488         if (playing) {
1489                 kill_all_voices();
1490                 if (temper_type_mute) {
1491                         if (temper_type_mute & 1)
1492                                 FILL_CHANNELMASK(channel_mute);
1493                         else
1494                                 CLEAR_CHANNELMASK(channel_mute);
1495                 }
1496                 for (i = 0; i < MAX_CHANNELS; i++)
1497                         redraw_controllers(i);
1498                 if (midi_streaming && free_instruments_afterwards) {
1499                         free_instruments(0);
1500                         /* free unused memory */
1501                         cnt = free_global_mblock();
1502                         if (cnt > 0)
1503                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
1504                                                 "%d memory blocks are free", cnt);
1505                 }
1506         } else
1507                 reset_voices();
1508
1509         master_volume_ratio = 0xffff;
1510         adjust_amplification();
1511         init_freq_table_tuning();
1512         master_tuning = 0;
1513         if (current_file_info) {
1514                 COPY_CHANNELMASK(drumchannels, current_file_info->drumchannels);
1515                 COPY_CHANNELMASK(drumchannel_mask, current_file_info->drumchannel_mask);
1516         } else {
1517                 COPY_CHANNELMASK(drumchannels, default_drumchannels);
1518                 COPY_CHANNELMASK(drumchannel_mask, default_drumchannel_mask);
1519         }
1520 ///r
1521         change_output_volume(output_amplification);
1522         ctl_mode_event(CTLE_MASTER_VOLUME, 0, output_amplification, 0);
1523         ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
1524         ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
1525
1526
1527         //elion add
1528         {
1529                 int c;
1530                 CtlEvent ct;
1531                 for (c = 0; c < MAX_CHANNELS; c++) {
1532                         ct.type = CTLE_VOLUME;
1533                         ct.v1 = c;
1534                         ct.v2 = channel[c].volume;
1535                         ctl->event(&ct);
1536
1537                         ct.type = CTLE_EXPRESSION;
1538                         ct.v2 = channel[c].expression;
1539                         ctl->event(&ct);
1540                 }
1541         }
1542 }
1543
1544 static void recompute_channel_lfo(int ch)
1545 {       
1546         Channel *cp = channel + ch;
1547         /* MIDI controllers LFO */
1548         FLOAT_T rate1 = 0, rate2 = 0;
1549         FLOAT_T adepth1 = 0, adepth2 = 0;
1550         FLOAT_T fdepth1 = 0, fdepth2 = 0;
1551         FLOAT_T pdepth1 = 0, pdepth2 = 0;
1552
1553         if(opt_channel_pressure) {
1554                 rate1 += (cp->mod.lfo1_rate)
1555                         + (cp->bend.lfo1_rate)
1556                         + (cp->caf.lfo1_rate)
1557                         + (cp->cc1.lfo1_rate)
1558                         + (cp->cc2.lfo1_rate)
1559                         + (cp->cc3.lfo1_rate)
1560                         + (cp->cc4.lfo1_rate);
1561                 adepth1 += get_midi_controller_lfo1_amp_depth(&(cp->mod))
1562                         + get_midi_controller_lfo1_amp_depth(&(cp->bend))
1563                         + get_midi_controller_lfo1_amp_depth(&(cp->caf))
1564                         + get_midi_controller_lfo1_amp_depth(&(cp->cc1))
1565                         + get_midi_controller_lfo1_amp_depth(&(cp->cc2))
1566                         + get_midi_controller_lfo1_amp_depth(&(cp->cc3))
1567                         + get_midi_controller_lfo1_amp_depth(&(cp->cc4));
1568                 fdepth1 += get_midi_controller_lfo1_filter_depth(&(cp->mod))
1569                         + get_midi_controller_lfo1_filter_depth(&(cp->bend))
1570                         + get_midi_controller_lfo1_filter_depth(&(cp->caf))
1571                         + get_midi_controller_lfo1_filter_depth(&(cp->cc1))
1572                         + get_midi_controller_lfo1_filter_depth(&(cp->cc2))
1573                         + get_midi_controller_lfo1_filter_depth(&(cp->cc3))
1574                         + get_midi_controller_lfo1_filter_depth(&(cp->cc4));
1575                 pdepth1 += get_midi_controller_lfo1_pitch_depth(&(cp->mod))
1576                         + get_midi_controller_lfo1_pitch_depth(&(cp->bend))
1577                         + get_midi_controller_lfo1_pitch_depth(&(cp->caf))
1578                         + get_midi_controller_lfo1_pitch_depth(&(cp->cc1))
1579                         + get_midi_controller_lfo1_pitch_depth(&(cp->cc2))
1580                         + get_midi_controller_lfo1_pitch_depth(&(cp->cc3))
1581                         + get_midi_controller_lfo1_pitch_depth(&(cp->cc4));
1582                 rate2 += (cp->mod.lfo2_rate)
1583                         + (cp->bend.lfo2_rate)
1584                         + (cp->caf.lfo2_rate)
1585                         + (cp->cc1.lfo2_rate)
1586                         + (cp->cc2.lfo2_rate)
1587                         + (cp->cc3.lfo2_rate)
1588                         + (cp->cc4.lfo2_rate);
1589                 adepth2 += get_midi_controller_lfo2_amp_depth(&(cp->mod))
1590                         + get_midi_controller_lfo2_amp_depth(&(cp->bend))
1591                         + get_midi_controller_lfo2_amp_depth(&(cp->caf))
1592                         + get_midi_controller_lfo2_amp_depth(&(cp->cc1))
1593                         + get_midi_controller_lfo2_amp_depth(&(cp->cc2))
1594                         + get_midi_controller_lfo2_amp_depth(&(cp->cc3))
1595                         + get_midi_controller_lfo2_amp_depth(&(cp->cc4));
1596                 fdepth2 += get_midi_controller_lfo2_filter_depth(&(cp->mod))
1597                         + get_midi_controller_lfo2_filter_depth(&(cp->bend))
1598                         + get_midi_controller_lfo2_filter_depth(&(cp->caf))
1599                         + get_midi_controller_lfo2_filter_depth(&(cp->cc1))
1600                         + get_midi_controller_lfo2_filter_depth(&(cp->cc2))
1601                         + get_midi_controller_lfo2_filter_depth(&(cp->cc3))
1602                         + get_midi_controller_lfo2_filter_depth(&(cp->cc4));
1603                 pdepth2 += get_midi_controller_lfo2_pitch_depth(&(cp->mod))
1604                         + get_midi_controller_lfo2_pitch_depth(&(cp->bend))
1605                         + get_midi_controller_lfo2_pitch_depth(&(cp->caf))
1606                         + get_midi_controller_lfo2_pitch_depth(&(cp->cc1))
1607                         + get_midi_controller_lfo2_pitch_depth(&(cp->cc2))
1608                         + get_midi_controller_lfo2_pitch_depth(&(cp->cc3))
1609                         + get_midi_controller_lfo2_pitch_depth(&(cp->cc4));
1610         }       
1611         if(rate1 > 10.0)                        {rate1 = 10.0;}
1612         else if(rate1 < -10.0)          {rate1 = -10.0;}
1613         cp->lfo_rate[0] = rate1;
1614         if(adepth1 > 1.0)                        {adepth1 = 1.0;}
1615         cp->lfo_amp_depth[0] = adepth1; 
1616         if(fdepth1 > 2400.0)            {fdepth1 = 2400.0;}
1617         else if(fdepth1 < -2400.0)      {fdepth1 = -2400.0;}
1618         cp->lfo_cutoff_depth[0] = fdepth1;      
1619         pdepth1 += (double)cp->param_vibrato_depth * DIV_64 * nrpn_vib_depth_cent; // NRPN in -64~64
1620         if (pdepth1 > 600.0)            {pdepth1 = 600.0;}
1621         else if (pdepth1 < -600.0)      {pdepth1 = -600.0;}
1622         cp->lfo_pitch_depth[0] = pdepth1;
1623         if(rate2 > 10.0)                        {rate2 = 10.0;}
1624         else if(rate2 < -10.0)          {rate2 = -10.0;}
1625         cp->lfo_rate[1] = rate2;
1626         if(adepth2 > 1.0)                       {adepth2 = 1.0;}
1627         cp->lfo_amp_depth[1] = adepth2;
1628         if(fdepth2 > 2400.0)            {fdepth2 = 2400.0;}
1629         else if(fdepth2 < -2400.0)      {fdepth2 = -2400.0;}
1630         cp->lfo_cutoff_depth[1] = fdepth2;
1631         if (pdepth2 > 600.0)            {pdepth2 = 600.0;}
1632         else if (pdepth2 < -600.0)      {pdepth2 = -600.0;}
1633         cp->lfo_pitch_depth[1] = pdepth2;
1634 }
1635
1636 void recompute_voice_lfo(int v)
1637 {
1638         Voice *vp = voice + v;
1639         int ch = vp->channel;   
1640         Channel *cp = channel + ch;
1641         FLOAT_T rate1 = 0, rate2 = 0;
1642
1643         // rate
1644         rate1 = vp->lfo_rate[0];
1645         if(otd.vibrato_rate != 0 ){
1646                 rate1 += (double)cp->param_vibrato_rate * DIV_64 * nrpn_vib_rate; // NRPN in -64~63
1647         }else if(cp->param_vibrato_rate){ 
1648                 int mul = (nrpn_vib_rate_mode == NRPN_PARAM_XG_RATE) ? 1 : 2;
1649                 rate1 = calc_nrpn_param(rate1, cp->param_vibrato_rate * mul, nrpn_vib_rate_mode);// NRPN in -64~63
1650         }
1651         if(vp->paf_ctrl){ // PAf
1652                 rate1 += cp->paf.lfo1_rate;
1653                 rate2 += cp->paf.lfo2_rate;
1654         }
1655         rate1 += cp->lfo_rate[0];
1656         if(rate1 > VIBRATO_RATE_MAX)
1657                 rate1 = VIBRATO_RATE_MAX;
1658 #if 1 // 1:stop lfo
1659         else if(rate1 < 0)
1660                 rate1 = 0;      
1661 #else
1662         else if(rate1 < VIBRATO_RATE_MIN)
1663                 rate1 = VIBRATO_RATE_MIN;       
1664 #endif
1665         if(vp->sample->vibrato_freq < 0 || vp->sample->vibrato_sweep < 0)
1666                 init_oscillator(&vp->lfo1, 0, 0, 0, OSC_TYPE_SINE, 0);
1667         else
1668                 reset_oscillator(&vp->lfo1, rate1);     
1669         rate2 += vp->lfo_rate[1] + cp->lfo_rate[1];
1670         if(rate2 > TREMOLO_RATE_MAX)
1671                 rate2 = TREMOLO_RATE_MAX;
1672 #if 1 // 1:stop lfo
1673         else if(rate2 < 0)
1674                 rate2 = 0;      
1675 #else
1676         else if(rate2 < TREMOLO_RATE_MIN)
1677                 rate2 = TREMOLO_RATE_MIN;
1678 #endif
1679         if(vp->sample->tremolo_freq < 0 || vp->sample->tremolo_sweep < 0)
1680                 init_oscillator(&vp->lfo2, 0, 0, 0, OSC_TYPE_SINE, 0);
1681         else
1682                 reset_oscillator(&vp->lfo2, rate2);     
1683 }
1684
1685 static void init_voice_lfo(int v)
1686 {
1687         Voice *vp = voice + v;
1688         int ch = vp->channel;   
1689         Channel *cp = channel + ch;
1690         FLOAT_T rate1 = 0, rate2 = 0;
1691         int32 sweep1, sweep2, delay1, delay2;
1692
1693         /* lfo1 */
1694         if(vp->sample->vibrato_freq < 0 || vp->sample->vibrato_sweep < 0){
1695                 vp->lfo_amp_depth[0] = 0;
1696                 vp->lfo_rate[0] = 0;
1697                 init_oscillator(&vp->lfo1, 0, 0, 0, OSC_TYPE_SINE, 0);
1698         }else{
1699                 vp->lfo_amp_depth[0] = 0;
1700                 rate1 = vp->lfo_rate[0] = (FLOAT_T)vp->sample->vibrato_freq * DIV_1000;
1701                 rate1 += cp->lfo_rate[0];
1702                 if(rate1 > VIBRATO_RATE_MAX)
1703                         rate1 = VIBRATO_RATE_MAX;
1704 #if 1 // 1:stop lfo
1705                 else if(rate1 < 0)
1706                         rate1 = 0;      
1707 #else
1708                 else if(rate1 < VIBRATO_RATE_MIN)
1709                         rate1 = VIBRATO_RATE_MIN;       
1710 #endif
1711                 sweep1 = (FLOAT_T)vp->sample->vibrato_sweep * playmode_rate_ms;
1712                 delay1 = (FLOAT_T)vp->sample->vibrato_delay * DIV_1000; 
1713                 if(otd.vibrato_delay != 0 ){
1714                         delay1 += (double)cp->param_vibrato_delay * DIV_64 * nrpn_vib_delay; // NRPN in -64~63  
1715                 }else if(cp->param_vibrato_delay){ 
1716                         delay1 = calc_nrpn_param((double)delay1 * div_playmode_rate, cp->param_vibrato_delay * 2, nrpn_vib_delay_mode) * play_mode->rate; // NRPN in -64~63
1717                 }
1718                 delay1 += cp->vibrato_delay;
1719                 if(delay1 < 0) delay1 = 0;
1720                 init_oscillator(&vp->lfo1, rate1, delay1, sweep1, OSC_TYPE_SINE, 0);
1721         }
1722         /* lfo2 */      
1723         if(vp->sample->tremolo_freq < 0 || vp->sample->tremolo_sweep < 0){
1724                 vp->lfo_amp_depth[1] = 0;
1725                 vp->lfo_rate[1] = 0;
1726                 init_oscillator(&vp->lfo2, 0, 0, 0, OSC_TYPE_SINE, 0);
1727         }else{
1728                 vp->lfo_amp_depth[1] = 0;
1729                 rate2 = vp->lfo_rate[1] = (FLOAT_T)vp->sample->tremolo_freq * DIV_1000; 
1730                 rate2 += cp->lfo_rate[1];
1731                 if(rate2 > TREMOLO_RATE_MAX)
1732                         rate2 = TREMOLO_RATE_MAX;
1733 #if 1 // 1:stop lfo
1734                 else if(rate2 < 0)
1735                         rate2 = 0;      
1736 #else
1737                 else if(rate2 < TREMOLO_RATE_MIN)
1738                         rate2 = TREMOLO_RATE_MIN;
1739 #endif
1740                 sweep2 = (FLOAT_T)vp->sample->tremolo_sweep * playmode_rate_ms;
1741                 delay2 = (FLOAT_T)vp->sample->tremolo_delay * DIV_1000; 
1742                 if(delay2 < 0) delay2 = 0;
1743                 init_oscillator(&vp->lfo2, rate2, delay2, sweep2, OSC_TYPE_SINE, 0);
1744         }
1745 }
1746
1747 ///r
1748 const FLOAT_T cvt_pitch_cent_tune = (FLOAT_T)M_13BIT * DIV_100; 
1749 // cent to tuning (100cent = 1semitone = 13bit , 
1750 // bend_coarse[tuning >> 13] , bend_fine[(tuning >> 5) & 0xff]
1751
1752 static void recompute_channel_pitch(int ch)
1753 {
1754         Channel *cp = channel + ch;
1755         const int32 pitch_max = (24 << 13); // semitone to tune
1756         const int32 pitch_min = (-24 << 13); // semitone to tune
1757         int32 tuning = 0;       
1758
1759         /* MIDI controllers pitch control */
1760         if (opt_channel_pressure) {
1761                 tuning += get_midi_controller_pitch(&(cp->mod))
1762                 //      + get_midi_controller_pitch(&(cp->bend)) 
1763                         + get_midi_controller_pitch(&(cp->caf))
1764                         + get_midi_controller_pitch(&(cp->cc1))
1765                         + get_midi_controller_pitch(&(cp->cc2))
1766                         + get_midi_controller_pitch(&(cp->cc3))
1767                         + get_midi_controller_pitch(&(cp->cc4));
1768         }       
1769         if(tuning > pitch_max) {tuning = pitch_max;}
1770         else if(tuning < pitch_min) {tuning = pitch_min;}       
1771         /* At least for GM2, it's recommended not to apply master_tuning for drum channels */
1772         tuning += ISDRUMCHANNEL(ch) ? 0 : master_tuning;
1773         /* Pitch Bend Control */
1774         if (cp->pitchbend != 0x2000){
1775                 int val = cp->pitchbend - 0x2000;
1776                 int pitch = (val > 0) ? cp->rpnmap[RPN_ADDR_0000] : cp->rpnmap[RPN_ADDR_0040]; // - : low control
1777                 pitch = pitch > 0x7F ? (pitch - 128) : pitch; // uint8 to int
1778                 tuning += val * pitch; // 13bit
1779         }
1780         /* Master Fine Tuning, Master Coarse Tuning */
1781         /* fine: [0..128] => [-256..256]
1782          * 1 coarse = 256 fine (= 1 note)
1783          * 1 fine = 2^5 tuning
1784          */
1785         tuning += (cp->rpnmap[RPN_ADDR_0001] - 0x40
1786                         + (cp->rpnmap[RPN_ADDR_0002] - 0x40) * 64) << 7;        
1787         cp->pitch = tuning;
1788         /* XG Detune */
1789         /* -128~+127 to -12.8Hz~+12.7Hz (at A3 440Hz */
1790         if(cp->detune_param != 0x80)
1791                 cp->detune = (440.0 + (FLOAT_T)((int)cp->detune_param - 0x80) * DIV_10) * DIV_440;
1792         else
1793                 cp->detune = 1.0;
1794         /* Temper Control */
1795         if (! opt_pure_intonation && opt_temper_control) {
1796                 int8 tt = cp->temper_type;
1797                 uint8 tp = cp->rpnmap[RPN_ADDR_0003];
1798                 int32 *table = NULL;
1799                 switch (tt) {
1800                 case 0:
1801                         table = freq_table_tuning[tp];
1802                         break;
1803                 case 1:
1804                         if (current_temper_keysig < 8)
1805                                 table = freq_table_pytha[current_temper_freq_table];
1806                         else
1807                                 table = freq_table_pytha[current_temper_freq_table + 12];
1808                         break;
1809                 case 2:
1810                         if (current_temper_keysig < 8)
1811                                 table = freq_table_meantone[current_temper_freq_table + ((temper_adj) ? 36 : 0)];
1812                         else
1813                                 table = freq_table_meantone[current_temper_freq_table + ((temper_adj) ? 24 : 12)];
1814                         break;
1815                 case 3:
1816                         if (current_temper_keysig < 8)
1817                                 table = freq_table_pureint[current_temper_freq_table + ((temper_adj) ? 36 : 0)];
1818                         else
1819                                 table = freq_table_pureint[current_temper_freq_table + ((temper_adj) ? 24 : 12)];
1820                         break;
1821                 default:        /* user-defined temperament */
1822                         if ((tt -= 0x40) >= 0 && tt < 4) {
1823                                 if (current_temper_keysig < 8)
1824                                         table = freq_table_user[tt][current_temper_freq_table + ((temper_adj) ? 36 : 0)];
1825                                 else
1826                                         table = freq_table_user[tt][current_temper_freq_table + ((temper_adj) ? 24 : 12)];
1827                         } else
1828                                 table = freq_table;
1829                         break;
1830                 }
1831                 cp->freq_table = table;
1832         }
1833 }
1834
1835 ///r
1836 void recompute_voice_pitch(int v)
1837 {
1838         Voice *vp = voice + v;
1839         int ch = vp->channel, note = vp->note;
1840         Channel *cp = channel + ch;
1841         int32 tuning;
1842         FLOAT_T depth1 = 0, depth2 = 0;
1843         const int32 porta_shift = 13 - PORTAMENTO_CONTROL_BIT; // tuning(13bit) - PORTAMENTO_CONTROL_RATIO(bit)
1844
1845         if (! vp->sample->sample_rate)
1846                 return;
1847         
1848         /* master tune , MIDI controllers pitch control */
1849         tuning = vp->init_tuning;
1850         tuning += cp->pitch;
1851         /* MIDI controllers */
1852         if(vp->paf_ctrl){ // PAf
1853                 tuning += get_midi_controller_pitch(&(cp->paf));
1854                 depth1 += get_midi_controller_lfo1_pitch_depth(&(cp->paf));
1855                 depth2 += get_midi_controller_lfo2_pitch_depth(&(cp->paf));
1856         }
1857         /* LFO pitch depth */
1858         if(vp->lfo1.mode){
1859                 depth1 += vp->sample->vibrato_to_pitch;
1860                 depth1 += cp->lfo_pitch_depth[0];
1861                 if (depth1 > 600.0) {depth1 = 600.0;}
1862                 else if (depth1 < 0) {depth1 = 0;}
1863         //      tuning += vp->lfo1.out * (FLOAT_T)(depth1 << 13) * DIV_100 + 0.5;
1864                 tuning += vp->lfo1.out * depth1 * cvt_pitch_cent_tune + 0.5; // * (1 << 13) cent to bend_fine/course
1865         }
1866         if(vp->lfo2.mode){
1867                 depth2 += vp->sample->tremolo_to_pitch;         
1868                 depth2 += cp->lfo_pitch_depth[1];       
1869                 if (depth2 > 600.0) {depth2 = 600.0;}
1870                 else if (depth2 < 0) {depth2 = 0;}
1871         //      tuning += vp->lfo2.out * (FLOAT_T)(depth2 << 13) * DIV_100 + 0.5;
1872                 tuning += vp->lfo2.out * depth2 * cvt_pitch_cent_tune + 0.5; // * (1 << 13) cent to bend_fine/course
1873         }
1874         /* Modulation Envelope Pitch Depth , Pitch Envelope */
1875         if (opt_modulation_envelope) {
1876                 // modulation envelope
1877                 if (vp->sample->modenv_to_pitch) {
1878                 //      tuning += vp->last_modenv_volume * (vp->sample->modenv_to_pitch << 13) * DIV_100 + 0.5;
1879                         tuning += vp->mod_env.volume * (FLOAT_T)vp->sample->modenv_to_pitch * cvt_pitch_cent_tune + 0.5;
1880                 }
1881                 // pitch envelope
1882                 if(vp->pit_env.vol){
1883                         tuning += vp->pit_env.vol * cvt_pitch_cent_tune + 0.5; // cent to bend_fine/course
1884                 }
1885         }
1886         /* Portamento / Legato */
1887         if (opt_portamento){
1888 #if (PORTAMENTO_CONTROL_BIT == 13)
1889                 tuning += vp->porta_out;
1890 #else
1891                 tuning += (vp->porta_out << (13 - PORTAMENTO_CONTROL_BIT)); // tuning(13bit)
1892 #endif
1893         }
1894         /* calc freq */ /* XG Detune */ /* GS Pitch Offset Fine */
1895         if (tuning == 0){
1896                 if (cp->detune == 1.0 && vp->sample->tune == 1.0 && cp->pitch_offset_fine == 0.0){
1897                         vp->pitchfactor = 1.0;
1898                         vp->orig_pitchfactor = 1.0;
1899                         vp->frequency = vp->orig_frequency;
1900                 }else{
1901                         vp->pitchfactor = cp->detune * vp->sample->tune;
1902                         vp->orig_pitchfactor = 1.0;
1903                         vp->frequency = vp->orig_frequency * vp->pitchfactor + cp->pitch_offset_fine * 1000.0;
1904                         vp->cache = NULL;
1905                 }
1906                 vp->prev_tuning = 0; 
1907         } else {
1908                 if (vp->prev_tuning != tuning) {
1909                         if (tuning >= 0)
1910                                 vp->pitchfactor = bend_fine[(tuning >> 5) & 0xff] * bend_coarse[(tuning >> 13) & 0x7f];
1911                         else
1912                                 vp->pitchfactor = 1.0 / (bend_fine[((-tuning) >> 5) & 0xff] * bend_coarse[((-tuning) >> 13) & 0x7f]);
1913                         vp->orig_pitchfactor = vp->pitchfactor;
1914                         vp->prev_tuning = tuning;
1915                 }
1916                 vp->pitchfactor = vp->orig_pitchfactor * cp->detune * vp->sample->tune;
1917                 vp->frequency = vp->orig_frequency * vp->pitchfactor + cp->pitch_offset_fine * 1000.0;
1918                 vp->cache = NULL;
1919         }
1920         
1921 }
1922
1923 static void init_voice_pitch(int v)
1924 {
1925         Voice *vp = voice + v;
1926         int ch = vp->channel, note = vp->note;
1927         Channel *cp = channel + ch;
1928         int32 tuning = 0;
1929         
1930         if (! vp->sample->sample_rate)
1931                 return;
1932         /* for Drum */
1933         if (ISDRUMCHANNEL(ch) && cp->drums[note] != NULL){
1934                 /* for NRPN Coarse Pitch of Drum (GS) & Fine Pitch of Drum (XG) */
1935                 if(cp->drums[note]->fine || cp->drums[note]->coarse)
1936                         tuning += (cp->drums[note]->fine + cp->drums[note]->coarse * 64) << 7;          
1937                 /* Velocity Pitch Sense */
1938                 if(cp->drums[note]->drum_velo_pitch_sens)
1939                         tuning += (FLOAT_T)cp->drums[note]->drum_velo_pitch_sens * DIV_16
1940                                 * (FLOAT_T)vp->velocity * DIV_127 * 150.0 * cvt_pitch_cent_tune + 0.5; // -16~+16 max150cent
1941         }
1942         /* GS/XG - Scale Tuning */
1943         if (! ISDRUMCHANNEL(ch)) {
1944                 int8 st = cp->scale_tuning[note % 12];
1945                 tuning += ((st << 13) + 50) / 100;
1946                 if (cp->prev_scale_tuning != st) {
1947                         cp->prev_scale_tuning = st;
1948                 }
1949         }
1950         /* Temper Control */
1951         if (! opt_pure_intonation && opt_temper_control && vp->temper_instant) {
1952                 vp->orig_frequency = cp->freq_table[note];
1953         }
1954         /* init_tuning */
1955         vp->init_tuning = tuning;
1956 }
1957
1958 ///r
1959 static void recompute_channel_amp(int ch)
1960 {       
1961         Channel *cp = channel + ch;
1962         FLOAT_T tempamp;
1963
1964         /* MIDI volume expression are linear in perceived volume, 0-127
1965          * use a lookup table for the non-linear scalings                */     
1966         if (opt_user_volume_curve != 0)
1967                 tempamp = user_vol_table[cp->volume] * user_vol_table[cp->expression]; /* 14 bits */
1968         else switch(play_system_mode){
1969         case SD_SYSTEM_MODE:
1970         case GM2_SYSTEM_MODE:
1971                 tempamp = gm2_vol_table[cp->volume] * gm2_vol_table[cp->expression]; /* 14 bits */
1972                 break;
1973         case GS_SYSTEM_MODE:    /* use measured curve */ 
1974         case CM_SYSTEM_MODE:    /* use measured curve */ 
1975                 tempamp = sc_vol_table[cp->volume] * sc_vol_table[cp->expression]; /* 14 bits */
1976                 break;
1977         default:
1978                 if (IS_CURRENT_MOD_FILE)        /* use linear curve */
1979                         tempamp = cp->volume * cp->expression; /* 14 bits */
1980                 else    /* use generic exponential curve */
1981                         tempamp = perceived_vol_table[cp->volume] *     perceived_vol_table[cp->expression]; /* 14 bits */
1982                 break;
1983         }
1984         /* MIDI controllers amplitude control */
1985         if(opt_channel_pressure) {
1986                 FLOAT_T ctrl = 1.0;
1987                 ctrl += get_midi_controller_amp(&(cp->mod))
1988                         + get_midi_controller_amp(&(cp->bend))
1989                         + get_midi_controller_amp(&(cp->caf))
1990                         + get_midi_controller_amp(&(cp->cc1))
1991                         + get_midi_controller_amp(&(cp->cc2))
1992                         + get_midi_controller_amp(&(cp->cc3))
1993                         + get_midi_controller_amp(&(cp->cc4));
1994                 if(ctrl > 2.0) ctrl = 2.0; // +100% 
1995                 else if(ctrl < 0.0) ctrl = 0.0; // -100%
1996                 tempamp *= ctrl;
1997         }
1998         tempamp *= DIV_14BIT;
1999         if(tempamp > 1.0)       tempamp = 1.0;
2000         /* for XG channel mixer */
2001         if(adjust_panning_immediately && play_system_mode == XG_SYSTEM_MODE){
2002                 cp->amp = 1.0;  // for voice amp
2003                 if(!(play_mode->encoding & PE_MONO)){           
2004                         int pan = (cp->panning == NO_PANNING) ? 64 : cp->panning;
2005                         tempamp *= DIV_7BIT; // pan_table 7bit
2006                         cp->ch_amp[0] = tempamp * pan_table[128 - pan];
2007                         cp->ch_amp[1] = tempamp * pan_table[pan];
2008                 }else{
2009                         cp->ch_amp[0] = cp->ch_amp[1] = tempamp;
2010                 }
2011         }else{
2012                 cp->amp = tempamp;      // for voice amp
2013                 cp->ch_amp[0] = cp->ch_amp[1] = 1.0;
2014         }
2015 }       
2016
2017 ///r
2018 void recompute_voice_amp(int v)
2019 {
2020         Voice *vp = voice + v;
2021         int ch = vp->channel;
2022         Channel *cp = channel + ch;
2023         FLOAT_T tempamp;        
2024         FLOAT_T depth1 = 0, depth2 = 0;
2025         
2026         /* velocity, NRPN MIDI controllers amplitude control */
2027         tempamp = vp->init_amp;
2028         /* volume, expression, MIDI controllers amplitude control */
2029         tempamp *= cp->amp;     
2030         if(vp->paf_ctrl){ // PAf
2031                 tempamp *= 1.0 + get_midi_controller_amp(&(cp->paf));
2032                 // LFO amp
2033                 depth1 += get_midi_controller_lfo1_amp_depth(&(cp->paf));
2034                 depth2 += get_midi_controller_lfo2_amp_depth(&(cp->paf));
2035         }       
2036         /* applying panning to amplitude */
2037         if(vp->panned == PANNED_MYSTERY)
2038         {
2039                 if(vp->pan_ctrl){ // update panning
2040                         // panning : 0 ~ 127 // \93ü\97Í\82³\82ê\82é\83p\83\93,\83e\81[\83u\83\8b\82Ì\92l\88æ
2041                         // pan : 0=center // \83p\83\93\82Ì\89Á\8c¸\82Í\83Z\83\93\83^\81[0\8aî\8f\80\82Å\8f\88\97\9d
2042                         // sample_pan : -0.5~+0.5 0.0=center
2043                         int pan = 0, note = vp->note;
2044                         
2045                         if(ISDRUMCHANNEL(ch) && cp->drums[note] != NULL && cp->drums[note]->drum_panning != NO_PANNING)
2046                                 pan += (int)cp->drums[note]->drum_panning - 64;
2047                         else
2048                                 pan += (int)vp->sample->def_pan - 64;
2049                         if(!(adjust_panning_immediately && play_system_mode == XG_SYSTEM_MODE) && cp->panning != NO_PANNING)
2050                                 pan += (int)cp->panning - 64;
2051                         pan += 64;
2052                         if (pan > 127)
2053                                 pan = 127;
2054                         else if (pan < 0)
2055                                 pan = 0;
2056                         vp->pan_amp[0] = pan_table[128 - pan] * (0.5 - vp->sample->sample_pan);
2057                         vp->pan_amp[1] = pan_table[pan] * (0.5 + vp->sample->sample_pan);
2058                         vp->pan_ctrl = 0; // done
2059                 }
2060                 tempamp *= DIV_6BIT; // 7bit-1
2061                 vp->left_amp = tempamp * vp->pan_amp[0];
2062                 vp->right_amp = tempamp * vp->pan_amp[1];
2063         } else { // mono
2064                 vp->right_amp = vp->left_amp = tempamp * DIV_7BIT; // 7bit
2065     }
2066         
2067         // LFO to amp
2068         // vol_env\82ð\8eg\97p\82µ\82È\82¢ \8cã\82Ì\8dH\92ö  mix.c update_tremolo() -> apply_envelope_to_amp() -> mix_mystery_signal()
2069         depth1 += (FLOAT_T)vp->sample->vibrato_to_amp * DIV_10000;
2070         depth1 += cp->lfo_amp_depth[0];
2071         if(depth1 > 1.0) {depth1 = 1.0;}
2072         else if(depth1 < 0.0) {depth1 = 0.0;}
2073         vp->lfo_amp_depth[0] = depth1;  
2074         depth2 += (FLOAT_T)vp->sample->tremolo_to_amp * DIV_10000;
2075         depth2 += cp->lfo_amp_depth[1];
2076         if(depth2 > 1.0) {depth2 = 1.0;}
2077         else if(depth2 < 0.0) {depth2 = 0.0;}
2078         vp->lfo_amp_depth[1] = depth2;
2079 }
2080
2081 static int32 calc_velocity(int32 ch,int32 vel)
2082 {
2083         int32 velocity;
2084         velocity = channel[ch].velocity_sense_depth * vel / 64 + (channel[ch].velocity_sense_offset - 64) * 2;
2085         if(velocity > 127) {velocity = 127;}
2086         return velocity;
2087 }
2088
2089 ///r
2090 static void init_voice_amp(int v)
2091 {
2092         Voice *vp = &voice[v];
2093         int ch = vp->channel;
2094         int32 velo = calc_velocity(ch, vp->velocity) & 0x7F;
2095         FLOAT_T tempamp;
2096
2097         /* input_volume and other are percentages, used to scale
2098          *  amplitude directly, NOT perceived volume    */      
2099         tempamp = input_volume * vp->sample->volume * vp->sample->cfg_amp;
2100         /* MIDI velocity are linear in perceived volume, 0-127
2101          * use a lookup table for the non-linear scalings                */     
2102         if (opt_user_volume_curve != 0)
2103                 tempamp *= user_vol_table[velo]; /* 7 bits */
2104         else switch(play_system_mode){
2105         case SD_SYSTEM_MODE:
2106         case GM2_SYSTEM_MODE:
2107                 tempamp *= gm2_vol_table[velo]; /* velocity: not in GM2 standard *//* 7 bits */
2108                 break;
2109         case GS_SYSTEM_MODE:    /* use measured curve */ 
2110         case CM_SYSTEM_MODE:    /* use measured curve */ 
2111                 tempamp *= sc_vel_table[velo]; /* 7 bits */
2112                 break;
2113         default:
2114                 if (IS_CURRENT_MOD_FILE)        /* use linear curve */
2115                         tempamp *= velo; /* 7 bits */
2116                 else    /* use generic exponential curve */
2117                         tempamp *= perceived_vol_table[velo]; /* 7 bits */
2118                 break;
2119         }       
2120         tempamp *= DIV_7BIT; // 7bit
2121         /* NRPN - drum instrument tva level */
2122         if(ISDRUMCHANNEL(ch)) {
2123                 int note = vp->note;
2124                 if(channel[ch].drums[note] != NULL)
2125                         tempamp *= channel[ch].drums[note]->drum_level;
2126                 tempamp *= (double)opt_drum_power * DIV_100;    /* global drum power */
2127         }
2128         /* filter gain */
2129         if (vp->fc.type != 0) {
2130                 tempamp *= vp->lpf_gain;
2131         }
2132         /* init_amp */
2133         vp->init_amp = tempamp;
2134 }
2135
2136 ///r
2137 double voice_filter_reso = 1.0;
2138 double voice_filter_gain = 1.0;
2139
2140 #define VOICE_FILTER_FREQ_MIN (100) // Hz
2141 #define VOICE_FILTER2_FREQ_MAX (2000) // Hz
2142
2143 /* lowpass/highpass filter */
2144 static void recompute_channel_filter(int ch)
2145 {
2146         Channel *cp = channel + ch;
2147         FLOAT_T reso = 0;
2148         FLOAT_T cutoff_cent = 0;
2149
2150         if(cp->special_sample > 0) {return;}
2151         //if(!ISDRUMCHANNEL(ch)) {
2152         //              cp->cutoff_cent = 10000.0*sin(((double)cp->param_cutoff_freq + 128.0) * DIV_256 * M_PI + 4.71238898); // elion
2153                 if(otd.filter_freq != 0)
2154                         cutoff_cent += (FLOAT_T)cp->param_cutoff_freq * DIV_64 * nrpn_filter_freq;
2155         //      cp->hpf_cutoff_cent = (FLOAT_T)cp->hpf_param_cutoff_freq * DIV_64 * nrpn_filter_freq;
2156         //      }
2157         //      cp->resonance_dB = (double)cp->param_resonance * RESONANCE_COEFF; // elion
2158                 reso += (FLOAT_T)cp->param_resonance * DIV_64 * nrpn_filter_reso;
2159                 cp->hpf_resonance_dB = (FLOAT_T)cp->hpf_param_resonance * DIV_64 * nrpn_filter_reso;
2160         //}     
2161         cp->resonance_dB = reso;
2162         if(opt_channel_pressure) {
2163                 cutoff_cent += get_midi_controller_filter_cutoff(&(cp->mod))
2164                         + get_midi_controller_filter_cutoff(&(cp->bend))
2165                         + get_midi_controller_filter_cutoff(&(cp->caf))
2166                         + get_midi_controller_filter_cutoff(&(cp->cc1))
2167                         + get_midi_controller_filter_cutoff(&(cp->cc2))
2168                         + get_midi_controller_filter_cutoff(&(cp->cc3))
2169                         + get_midi_controller_filter_cutoff(&(cp->cc4));
2170         }       
2171         if(cutoff_cent > 9600.0)
2172                 cutoff_cent = 9600.0;
2173         else if(cutoff_cent < -9600.0)
2174                 cutoff_cent = -9600.0;
2175         cp->cutoff_cent = cutoff_cent;
2176 }
2177
2178 static void recompute_voice_filter2(int v)
2179 {
2180         Voice *vp = voice + v;
2181         int ch = vp->channel, note = vp->note;
2182         Channel *cp = channel + ch;
2183         int val;
2184         FLOAT_T freq, reso, cent, coef = 1.0;
2185         FilterCoefficients *fc = &vp->fc2;
2186
2187         if(fc->type == 0) {return;}
2188         
2189         /* MIDI controllers filter control */
2190         val = vp->init_hpf_val;
2191         freq = vp->hpf_orig_freq;
2192 //      cent = vp->init_hpf_cent;
2193         reso = vp->init_hpf_reso;
2194         val += cp->hpf_param_cutoff_freq;
2195 //      cent += cp->hpf_cutoff_cent;
2196         reso += cp->hpf_resonance_dB;   
2197         /* NRPN */
2198         if(val)
2199                 freq = calc_nrpn_param(freq, val * 2, nrpn_filter_hpf_freq_mode); // NRPN in -64~63
2200         // convert cent to mul
2201 //      if(cent != 0) {coef *= POW2(cent * DIV_1200);}
2202         // original param       
2203 //      freq = vp->hpf_orig_freq * (coef);
2204         reso = vp->hpf_orig_reso + reso;
2205         // Resonace effect control 
2206         reso *= voice_filter_reso;
2207         // Spec limit (SoundFont Spec 2.01 , other Sampler
2208         if(freq > VOICE_FILTER2_FREQ_MAX)       {freq = VOICE_FILTER2_FREQ_MAX;}
2209         else if(freq < 20)      {freq = 20;}
2210         if(reso > 96.0f)        {reso = 96.0f;}
2211         else if(reso < 0.0f){reso = 0.0f;}
2212         // set filter param
2213         set_voice_filter2_freq(fc, freq);
2214         set_voice_filter2_reso(fc, reso);
2215 }
2216
2217 void recompute_voice_filter(int v)
2218 {
2219         Voice *vp = voice + v;
2220         int ch = vp->channel, note = vp->note;
2221         Channel *cp = channel + ch;
2222         int val;
2223         FLOAT_T freq, reso, cent, coef = 1.0, depth1 = 0, depth2 = 0;
2224         FilterCoefficients *fc = &vp->fc;
2225         Sample *sp = vp->sample;
2226
2227         recompute_voice_filter2(v); // hpf
2228         if(fc->type == 0) {return;}     
2229         
2230         // original param 
2231         freq = vp->lpf_orig_freq;       
2232         reso = vp->lpf_orig_reso;
2233         /* MIDI controllers filter control */   
2234         val = vp->init_lpf_val;
2235         cent = vp->init_lpf_cent;
2236         reso += vp->init_lpf_reso;
2237         val += cp->param_cutoff_freq;
2238         cent += cp->cutoff_cent;
2239         reso += cp->resonance_dB;
2240         /* NRPN */
2241         if(otd.filter_freq == 0)
2242                 if(val)
2243                         freq = calc_nrpn_param(freq, val * 2, nrpn_filter_freq_mode); // NRPN in -64~63
2244         /* Soft Pedal */
2245         if(cp->soft_pedal != 0) {
2246                 if(note > 49) { /* tre corde */
2247                         coef *= 1.0 - 0.20 * ((FLOAT_T)cp->soft_pedal) * DIV_127;
2248                 } else {        /* una corda (due corde) */
2249                         coef *= 1.0 - 0.25 * ((FLOAT_T)cp->soft_pedal) * DIV_127;
2250                 }
2251         }       
2252         if(vp->paf_ctrl){ // PAf
2253                 cent += get_midi_controller_filter_cutoff(&(cp->paf));
2254                 depth1 += get_midi_controller_lfo1_filter_depth(&(cp->paf));
2255                 depth2 += get_midi_controller_lfo2_filter_depth(&(cp->paf));            
2256         }
2257         /* lfo1,lfo2 to filter cutoff frequency */
2258         if(vp->lfo1.mode){
2259                 depth1 += (FLOAT_T)sp->vibrato_to_fc;
2260                 depth1 += cp->lfo_cutoff_depth[0];
2261                 cent += vp->lfo1.out * depth1;
2262         }       
2263         if(vp->lfo2.mode){
2264                 depth2 += (FLOAT_T)sp->tremolo_to_fc;
2265                 depth2 += cp->lfo_cutoff_depth[1];
2266                 cent += vp->lfo2.out * depth2;
2267         }
2268         /* modulation_envelope to filter cutoff frequency */
2269         if(opt_modulation_envelope) {
2270                 if(sp->modenv_to_fc || cp->modenv_depth) {
2271                         cent += ((FLOAT_T)sp->modenv_to_fc + cp->modenv_depth) * vp->mod_env.volume;
2272                 }
2273         }
2274         // convert cent to mul
2275         if(cent != 0) {coef *= POW2(cent * DIV_1200);}  
2276         freq *= coef;   
2277         // Resonace effect control 
2278         reso *= voice_filter_reso;
2279         // filter test
2280 //      freq = 20; // test freq
2281 //      reso = 48.0f; // test reso
2282         // cutoff low limit
2283         if(sp->cutoff_low_limit < 0 && !ISDRUMCHANNEL(ch))
2284                 vp->lpf_freq_low_limit = (FLOAT_T)vp->frequency * DIV_1000; // update
2285         if(freq < vp->lpf_freq_low_limit)
2286                 freq = vp->lpf_freq_low_limit;
2287         // Spec limit (SoundFont Spec 2.01 , other Sampler
2288         if(freq > 20000)        {freq = 20000;}
2289         else if(freq < VOICE_FILTER_FREQ_MIN)   {freq = VOICE_FILTER_FREQ_MIN;}
2290         if(reso > 96.0f)        {reso = 96.0f;}
2291         else if(reso < 0.0f){reso = 0.0f;}              
2292         // set filter param
2293         set_voice_filter1_freq(fc, freq);
2294         set_voice_filter1_reso(fc, reso);
2295 }
2296
2297 void init_voice_filter2(int v)
2298 {
2299         Voice *vp = voice + v;
2300         int ch = vp->channel, note = vp->note;
2301         FilterCoefficients *fc = &vp->fc2;
2302         Sample *sp = vp->sample;
2303         FLOAT_T freq, reso;
2304         
2305 #ifdef __W32__
2306         if(IsBadReadPtr(sp, sizeof(Sample))){
2307 #else
2308         if(sp == NULL || sp == -1l){
2309 #endif          
2310                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "ERROR! ch:%d note:%d  sample null pointer.", ch, note);
2311                 fc->type = 0;
2312                 return;
2313         }
2314
2315         if(sp->hpf[0] >= 0)
2316                 set_voice_filter2_type(fc, sp->hpf[0]);
2317         else if(opt_hpf_def)
2318                 set_voice_filter2_type(fc, opt_hpf_def);
2319         else
2320                 set_voice_filter2_type(fc, 0);
2321         if(fc->type == 0)
2322                 return;
2323         set_voice_filter2_ext_rate(fc, 0); // set sample rate
2324
2325         if(sp->hpf[1] > 0)
2326                 freq = sp->hpf[1];
2327         else
2328                 freq = 10.0;    
2329         if(sp->hpf[2] > 0)
2330                 reso = (FLOAT_T)sp->hpf[2];
2331         else
2332                 reso = 0.0;
2333         // Resonace effect control 
2334         reso *= voice_filter_reso;
2335         // Spec limit (SoundFont Spec 2.01 , other Sampler
2336         if(freq > VOICE_FILTER2_FREQ_MAX)       {freq = VOICE_FILTER2_FREQ_MAX;}
2337         else if(freq < 10)      {freq = 10;}
2338         if(reso > 96.0f)        {reso = 96.0f;}
2339         else if(reso < 0.0f){reso = 0.0f;}
2340         // set filter param
2341         vp->hpf_orig_freq = freq;
2342         vp->hpf_orig_reso = reso;
2343         // optimize init
2344         {
2345                 Channel *cp = channel + ch;
2346                 int val = 0; 
2347         //      FLOAT_T cent = 0.0; 
2348                 FLOAT_T reso = 0.0;             
2349                 /* for Drum */
2350                 if(ISDRUMCHANNEL(ch) && cp->drums[note] != NULL) {
2351                         /* NRPN Drum Instrument HPF Cutoff */
2352                         val += cp->drums[note]->drum_hpf_cutoff_freq;
2353                 //      cent += (FLOAT_T)(cp->drums[note]->drum_hpf_cutoff_freq) * DIV_64 * nrpn_filter_freq;
2354                         /* NRPN Drum Instrument HPF Resonance */
2355                         reso += (FLOAT_T)cp->drums[note]->drum_hpf_resonance * DIV_64 * nrpn_filter_reso;
2356                 }
2357                 vp->init_hpf_val = val;
2358         //      vp->init_hpf_cent = cent;
2359                 vp->init_hpf_reso = reso;
2360         }
2361 }
2362
2363 void init_voice_filter(int v)
2364 {
2365         Voice *vp = voice + v;
2366         int ch = vp->channel, note = vp->note;
2367         FilterCoefficients *fc = &vp->fc;
2368         Sample *sp = vp->sample;
2369         FLOAT_T freq, reso;
2370         
2371 #ifdef __W32__
2372         if(IsBadReadPtr(sp, sizeof(Sample))){
2373 #else
2374         if(sp == NULL || sp == -1l){
2375 #endif          
2376                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "ERROR! ch:%d note:%d  sample null pointer.", ch, note);
2377                 fc->type = 0;
2378                 return;
2379         }
2380
2381         if(sp->lpf_type >= 0)
2382                 set_voice_filter1_type(fc, sp->lpf_type);
2383         else if(opt_lpf_def)
2384                 set_voice_filter1_type(fc, opt_lpf_def);
2385         else
2386                 set_voice_filter1_type(fc, 0);
2387         if(fc->type == 0)
2388                 return;
2389         set_voice_filter1_ext_rate(fc, 0); // set sample rate
2390         if(sp->cutoff_freq > 0)
2391                 freq = sp->cutoff_freq;
2392         else
2393                 freq = 20000;
2394         // SF2reso cB
2395         reso = (FLOAT_T)sp->resonance * DIV_10;
2396         // Resonace effect control 
2397         reso *= voice_filter_reso;
2398         // cutoff low limit     
2399         if(sp->cutoff_low_limit < 0){
2400                 vp->lpf_freq_low_limit = VOICE_FILTER_FREQ_MIN; // update recompute_voice_filter()
2401         }else{
2402                 double keyf = 1.0;
2403                 if(sp->cutoff_low_keyf)
2404                         keyf = POW2((double)(vp->note - 60) * (double)sp->cutoff_low_keyf * DIV_1200);  
2405                 vp->lpf_freq_low_limit = sp->cutoff_low_limit * keyf;
2406         }
2407         // Spec limit (SoundFont Spec 2.01 , other Sampler
2408         if(freq > 20000)        {freq = 20000;}
2409         else if(freq < VOICE_FILTER_FREQ_MIN)   {freq = VOICE_FILTER_FREQ_MIN;}
2410         if(reso > 96.0f)        {reso = 96.0f;}
2411         else if(reso < 0.0f){reso = 0.0f;}
2412         // set filter param
2413         vp->lpf_orig_freq = freq;
2414         vp->lpf_orig_reso = reso;
2415         // Filter gain control 
2416         vp->lpf_gain = voice_filter_gain;
2417         
2418         // optimize init
2419         {
2420                 int ch = vp->channel, note = vp->note;
2421                 Channel *cp = channel + ch;
2422                 int val = 0; 
2423                 FLOAT_T cent = 0.0; reso = 0.0; 
2424                 
2425                 /* for Drum */
2426                 if(ISDRUMCHANNEL(ch) && cp->drums[note] != NULL) {
2427                         /* NRPN Drum Instrument Filter Cutoff */
2428                         if(otd.filter_freq == 0)
2429                                 val += cp->drums[note]->drum_cutoff_freq;
2430                         else
2431                                 cent += (FLOAT_T)(cp->drums[note]->drum_cutoff_freq) * DIV_64 * nrpn_filter_freq;               
2432                         /* NRPN Drum Instrument Filter Resonance */
2433                         reso += (FLOAT_T)cp->drums[note]->drum_resonance * DIV_64 * nrpn_filter_reso;
2434                         /* Velocity LPF Cutoff Sense */
2435                         if(cp->drums[note]->drum_velo_cutoff_sens)
2436                         cent += (FLOAT_T)cp->drums[note]->drum_velo_cutoff_sens * DIV_16
2437                                 * (FLOAT_T)vp->velocity * DIV_127 * 150.0; // -16~+16 max600cent
2438                 }
2439                 /* velocity to filter cutoff frequency */
2440                 if(sp->vel_to_fc) {     
2441                         if(vp->velocity > sp->vel_to_fc_threshold)
2442                                 cent += (FLOAT_T)sp->vel_to_fc * ( (127.0 - (FLOAT_T)vp->velocity) * DIV_127);
2443                         else
2444                                 cent += (FLOAT_T)sp->vel_to_fc * ( (127.0 - (FLOAT_T)sp->vel_to_fc_threshold) * DIV_127);
2445                 }
2446                 /* velocity to filter resonance */
2447                 if(sp->vel_to_resonance) {
2448                         reso += (FLOAT_T)vp->velocity * DIV_127 * DIV_10 * sp->vel_to_resonance;
2449                 }
2450                 /* filter cutoff key-follow */
2451                 if(sp->key_to_fc) {
2452                         cent += (FLOAT_T)sp->key_to_fc * (FLOAT_T)(vp->note - sp->key_to_fc_bpo);
2453                 }
2454                 vp->init_lpf_val = val;
2455                 vp->init_lpf_cent = cent;
2456                 vp->init_lpf_reso = reso;
2457         }
2458 }
2459
2460 void recompute_resample_filter(int v)
2461 {
2462         Voice *vp = voice + v;
2463         FilterCoefficients *fc = &vp->rf_fc;
2464         FLOAT_T freq;
2465         
2466         if(!fc->type)
2467                 return; 
2468         freq = vp->rs_sample_rate_root * (FLOAT_T)vp->frequency;  // rate/2 rate>0
2469         if(freq > playmode_rate_div2) 
2470                 freq = playmode_rate_div2; // rate/2
2471         set_resample_filter_freq(fc, freq);
2472 }
2473
2474 void init_resample_filter(int v)
2475 {       
2476         Voice *vp = voice + v;
2477         Sample *sp = vp->sample;
2478         FilterCoefficients *fc = &vp->rf_fc;
2479         FLOAT_T freq;
2480
2481 #ifdef INT_SYNTH
2482         if(sp->inst_type == INST_MMS || sp->inst_type == INST_SCC){
2483                 set_resample_filter_type(fc, 0); // off
2484                 return;
2485         }
2486 #endif
2487         if(sp->sample_rate_org)
2488                 vp->rs_sample_rate_root = (FLOAT_T)sp->sample_rate_org * DIV_2 / (FLOAT_T)sp->root_freq_org;
2489         else
2490                 vp->rs_sample_rate_root = (FLOAT_T)sp->sample_rate * DIV_2 / (FLOAT_T)sp->root_freq;
2491         if(opt_resample_over_sampling)
2492                 set_resample_filter_ext_rate(fc, play_mode->rate * opt_resample_over_sampling); // set sample rate * n
2493         else
2494                 set_resample_filter_ext_rate(fc, 0); // set sample rate
2495         set_resample_filter_type(fc, opt_resample_filter);
2496 }
2497
2498 float calc_drum_tva_level(int ch, int note, int level)
2499 {
2500         int def_level, nbank, nprog;
2501         ToneBank *bank;
2502         int elm = 0;
2503
2504         if(channel[ch].special_sample > 0) {return 1.0;}
2505
2506         nbank = channel[ch].bank;
2507         nprog = note;
2508         instrument_map(channel[ch].mapID, &nbank, &nprog);
2509
2510         if(ISDRUMCHANNEL(ch)) {
2511                 bank = drumset[nbank];
2512                 if(bank == NULL) {bank = drumset[0];}
2513         } else {
2514                 return 1.0;
2515         }
2516 ///r
2517         if(bank->tone[nprog][elm] == NULL)
2518                 def_level = -1;
2519         else
2520                 def_level = bank->tone[nprog][elm]->tva_level;
2521
2522         if(def_level == -1 || def_level == 0) {def_level = 127;}
2523         else if(def_level > 127) {def_level = 127;}
2524
2525         return (sc_drum_level_table[level] / sc_drum_level_table[def_level]);
2526 }
2527
2528 ///r
2529 static int32 calc_emu_delay(MidiEvent *e)
2530 {
2531         static int32 cnt = 0, ptime = -1;
2532         static uint8 ch[MAX_CHANNELS * 128], note[MAX_CHANNELS * 128]; // note 0~127
2533         int i, match;
2534
2535         if(ISDRUMCHANNEL(e->channel)) return 0;
2536
2537         if(e->time != ptime)
2538                 cnt = 0;
2539         else
2540                 cnt++;
2541         ptime = e->time;
2542         ch[cnt] = e->channel;
2543         note[cnt] = MIDI_EVENT_NOTE(e);
2544
2545         if(cnt == 0) return 0;
2546
2547         match = 0;
2548         for(i = 0; i < cnt; i++)
2549                 if(ch[i] != ch[cnt] && note[i] == note[cnt])
2550                         match++;
2551
2552 //      ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "emu_delay_time: %d : %d", match, test); // test
2553
2554         if(match == 0)  return 0;
2555         return (int32)((FLOAT_T)match * playmode_rate_dms * emu_delay_time); // 0.1msec
2556
2557 }
2558
2559 static int32 calc_random_delay(int ch, int note)
2560 {
2561         int nbank, nprog;
2562         ToneBank *bank;
2563         int elm = 0;
2564
2565         if(channel[ch].special_sample > 0) {return 0;}
2566
2567         nbank = channel[ch].bank;
2568
2569         if(ISDRUMCHANNEL(ch)) {
2570                 nprog = note;
2571                 instrument_map(channel[ch].mapID, &nbank, &nprog);
2572                 bank = drumset[nbank];
2573                 if (bank == NULL) {bank = drumset[0];}
2574         } else {
2575                 nprog = channel[ch].program;
2576                 if(nprog == SPECIAL_PROGRAM) {return 0;}
2577                 instrument_map(channel[ch].mapID, &nbank, &nprog);
2578                 bank = tonebank[nbank];
2579                 if(bank == NULL) {bank = tonebank[0];}
2580         }
2581
2582         if (bank->tone[nprog][elm] == NULL) {return 0;}
2583         if (bank->tone[nprog][elm]->rnddelay == 0) {return 0;}
2584         else {return (int32)((double)bank->tone[nprog][elm]->rnddelay * playmode_rate_ms
2585                 * (get_pink_noise_light(&global_pink_noise_light) + 1.0f) * 0.5);}
2586 }
2587
2588 static void recompute_bank_parameter_tone(int ch)
2589 {
2590         int nbank, nprog;
2591         ToneBank *bank;
2592         int elm = 0;
2593
2594         if(channel[ch].special_sample > 0) {return;}
2595         if(ISDRUMCHANNEL(ch)) {return;}
2596         nbank = channel[ch].bank;
2597         nprog = channel[ch].program;
2598         if (nprog == SPECIAL_PROGRAM) {return;}
2599         instrument_map(channel[ch].mapID, &nbank, &nprog);
2600         bank = tonebank[nbank];
2601         if (bank == NULL) {bank = tonebank[0];}
2602
2603         if(bank->tone[nprog][elm]){
2604                 if(channel[ch].legato == -1)
2605                         channel[ch].legato = bank->tone[nprog][elm]->legato;
2606                 channel[ch].damper_mode = bank->tone[nprog][elm]->damper_mode;
2607                 channel[ch].loop_timeout = bank->tone[nprog][elm]->loop_timeout;
2608         }else{
2609                 channel[ch].legato = 0;
2610                 channel[ch].damper_mode = 0;
2611                 channel[ch].loop_timeout = 0;
2612         }
2613 }
2614
2615 static void recompute_bank_parameter_drum(int ch, int note)
2616 {
2617         int nbank, nprog;
2618         ToneBank *bank;
2619         struct DrumParts *drum;
2620         int elm = 0;
2621
2622         if(channel[ch].special_sample > 0) {return;}
2623
2624         nbank = channel[ch].bank;
2625
2626         if(ISDRUMCHANNEL(ch)) {
2627                 nprog = note;
2628                 instrument_map(channel[ch].mapID, &nbank, &nprog);
2629                 bank = drumset[nbank];
2630                 if (bank == NULL) {bank = drumset[0];}
2631                 if (channel[ch].drums[note] == NULL){
2632                         play_midi_setup_drums(ch, note);
2633                 }
2634                 drum = channel[ch].drums[note];
2635                 if(bank->tone[nprog][elm]){
2636                         if(drum->reverb_level == -1 && bank->tone[nprog][elm]->reverb_send != -1)
2637                                 drum->reverb_level = bank->tone[nprog][elm]->reverb_send;
2638                         if(drum->chorus_level == -1 && bank->tone[nprog][elm]->chorus_send != -1)
2639                                 drum->chorus_level = bank->tone[nprog][elm]->chorus_send;
2640                         if(drum->delay_level == -1 && bank->tone[nprog][elm]->delay_send != -1)
2641                                 drum->delay_level = bank->tone[nprog][elm]->delay_send;
2642                         if (drum->rx_note_off == -1)
2643                                 set_rx_drum(drum, RX_NOTE_OFF, bank->tone[nprog][elm]->rx_note_off);
2644                 }
2645         }
2646 }
2647
2648 ///r
2649 Instrument *play_midi_load_instrument(int dr, int bk, int prog, int elm, int *elm_max)
2650 {
2651         ToneBank **bank = (dr) ? drumset : tonebank;
2652         ToneBankElement *tone, *tone0;
2653         Instrument *ip = NULL;
2654         int load_success = 0;
2655         int tmp_num = 0;
2656
2657         if (bank[bk] == NULL)
2658                 alloc_instrument_bank(dr, bk);
2659         
2660         tone = bank[bk]->tone[prog][elm];
2661         /* tone->name is NULL if "soundfont" directive is used, and ip is NULL when not preloaded */
2662         /* dr: not sure but only drumsets are concerned at the moment */
2663         if(tone){
2664                 if (dr && !tone->name && ((ip = tone->instrument) == NULL)
2665                           && (ip = load_instrument(dr, bk, prog, elm)) != NULL) {
2666                         tone->instrument = ip;
2667                         tone->name = safe_strdup(DYNAMIC_INSTRUMENT_NAME);
2668                         load_success = 1;
2669                         tmp_num = bank[bk]->tone[prog][0]->element_num;
2670                         goto end;
2671                 } else if (tone->name) {
2672                         /* Instrument is found. */
2673                         ip = tone->instrument;
2674 #ifndef SUPPRESS_CHANNEL_LAYER
2675                         if (ip == NULL){
2676                                 ip = tone->instrument = load_instrument(dr, bk, prog, elm);
2677                         }
2678 #endif
2679                         if (ip == NULL || IS_MAGIC_INSTRUMENT(ip)) {
2680                                 tone->instrument = MAGIC_ERROR_INSTRUMENT;
2681                         } else {
2682                                 load_success = 1;
2683                                 tmp_num = bank[bk]->tone[prog][0]->element_num;
2684                         }
2685                         goto end;
2686                 }
2687         }
2688         /* Instrument is not found.
2689                 Try to load the instrument from bank 0 */
2690         tone0 = bank[0]->tone[prog][elm];
2691         if(tone0){
2692                 if ((ip = tone0->instrument) == NULL)
2693                         ip = tone0->instrument = load_instrument(dr, 0, prog, elm);
2694                 if (ip == NULL || IS_MAGIC_INSTRUMENT(ip)) {
2695                         tone0->instrument = MAGIC_ERROR_INSTRUMENT;
2696                 } else {        
2697                         if(tone == NULL){       
2698                                 if(alloc_tone_bank_element(&bank[bk]->tone[prog][elm])){
2699                                         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "play_midi_load_instrument ToneBankElement malloc error ");
2700                                         return NULL;
2701                                 }
2702                                 tone = bank[bk]->tone[prog][elm];
2703                         }
2704                         copy_tone_bank_element(tone, tone0);
2705                         tone->instrument = ip;
2706                         load_success = 1;
2707                         tmp_num = bank[0]->tone[prog][0]->element_num;
2708                         goto end;
2709                 }
2710         }
2711 end:
2712         if(elm_max)
2713                 *elm_max = tmp_num;
2714         if (load_success)
2715                 aq_add(NULL, 0);        /* Update software buffer */
2716
2717         if (ip == MAGIC_ERROR_INSTRUMENT)
2718                 return NULL;
2719
2720         return ip;
2721 }
2722
2723
2724 #if 0
2725 /* reduce_voice_CPU() may not have any speed advantage over reduce_voice().
2726  * So this function is not used, now.
2727  */
2728
2729 /* The goal of this routine is to free as much CPU as possible without
2730    loosing too much sound quality.  We would like to know how long a note
2731    has been playing, but since we usually can't calculate this, we guess at
2732    the value instead.  A bad guess is better than nothing.  Notes which
2733    have been playing a short amount of time are killed first.  This causes
2734    decays and notes to be cut earlier, saving more CPU time.  It also causes
2735    notes which are closer to ending not to be cut as often, so it cuts
2736    a different note instead and saves more CPU in the long run.  ON voices
2737    are treated a little differently, since sound quality is more important
2738    than saving CPU at this point.  Duration guesses for loop regions are very
2739    crude, but are still better than nothing, they DO help.  Non-looping ON
2740    notes are cut before looping ON notes.  Since a looping ON note is more
2741    likely to have been playing for a long time, we want to keep it because it
2742    sounds better to keep long notes.
2743 */
2744 static int reduce_voice_CPU(void)
2745 {
2746     int32 lv, v, vr;
2747     int i, j, lowest=-0x7FFFFFFF;
2748     int32 duration;
2749
2750     i = upper_voices;
2751     lv = 0x7FFFFFFF;
2752     
2753     /* Look for the decaying note with the longest remaining decay time */
2754     /* Protect drum decays.  They do not take as much CPU (?) and truncating
2755        them early sounds bad, especially on snares and cymbals */
2756     for(j = 0; j < i; j++)
2757     {
2758         if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
2759             continue;
2760         /* skip notes that don't need resampling (most drums) */
2761         if (voice[j].sample->note_to_use)
2762             continue;
2763         if(voice[j].status & ~(VOICE_ON | VOICE_DIE | VOICE_SUSTAINED))
2764         {
2765             /* Choose note with longest decay time remaining */
2766             /* This frees more CPU than choosing lowest volume */
2767             if (!voice[j].envelope_increment) duration = 0;
2768             else duration =
2769                 (voice[j].envelope_target - voice[j].envelope_volume) /
2770                 voice[j].envelope_increment;
2771             v = -duration;
2772             if(v < lv)
2773             {
2774                 lv = v;
2775                 lowest = j;
2776             }
2777         }
2778     }
2779     if(lowest != -0x7FFFFFFF)
2780     {
2781         /* This can still cause a click, but if we had a free voice to
2782            spare for ramping down this note, we wouldn't need to kill it
2783            in the first place... Still, this needs to be fixed. Perhaps
2784            we could use a reserve of voices to play dying notes only. */
2785
2786         cut_notes++;
2787         return lowest;
2788     }
2789
2790     /* try to remove VOICE_DIE before VOICE_ON */
2791     lv = 0x7FFFFFFF;
2792     lowest = -1;
2793     for(j = 0; j < i; j++)
2794     {
2795       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
2796             continue;
2797       if(voice[j].status & ~(VOICE_ON | VOICE_SUSTAINED))
2798       {
2799         /* continue protecting non-resample decays */
2800         if (voice[j].status & ~(VOICE_DIE) && voice[j].sample->note_to_use)
2801                 continue;
2802
2803         /* choose note which has been on the shortest amount of time */
2804         /* this is a VERY crude estimate... */
2805         if (voice[j].sample->modes & MODES_LOOPING)
2806             duration = voice[j].sample_offset - voice[j].sample->loop_start;
2807         else
2808             duration = voice[j].sample_offset;
2809         if (voice[j].sample_increment > 0)
2810             duration /= voice[j].sample_increment;
2811         v = duration;
2812         if(v < lv)
2813         {
2814             lv = v;
2815             lowest = j;
2816         }
2817       }
2818     }
2819     if(lowest != -1)
2820     {
2821         cut_notes++;
2822         return lowest;
2823     }
2824
2825     /* try to remove VOICE_SUSTAINED before VOICE_ON */
2826     lv = 0x7FFFFFFF;
2827     lowest = -0x7FFFFFFF;
2828     for(j = 0; j < i; j++)
2829     {
2830       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
2831             continue;
2832       if(voice[j].status & VOICE_SUSTAINED)
2833       {
2834         /* choose note which has been on the shortest amount of time */
2835         /* this is a VERY crude estimate... */
2836         if (voice[j].sample->modes & MODES_LOOPING)
2837             duration = voice[j].sample_offset - voice[j].sample->loop_start;
2838         else
2839             duration = voice[j].sample_offset;
2840         if (voice[j].sample_increment > 0)
2841             duration /= voice[j].sample_increment;
2842         v = duration;
2843         if(v < lv)
2844         {
2845             lv = v;
2846             lowest = j;
2847         }
2848       }
2849     }
2850     if(lowest != -0x7FFFFFFF)
2851     {
2852         cut_notes++;
2853         return lowest;
2854     }
2855         
2856     lost_notes++;
2857
2858     /* try to remove non-looping voices first */
2859     lv = 0x7FFFFFFF;
2860     lowest = -0x7FFFFFFF;
2861     for(j = 0; j < i; j++)
2862     {
2863       if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
2864             continue;
2865       if(!(voice[j].sample->modes & MODES_LOOPING))
2866       {
2867         /* score notes based on both volume AND duration */
2868         /* this scoring function needs some more tweaking... */
2869         duration = voice[j].sample_offset;
2870         if (voice[j].sample_increment > 0)
2871             duration /= voice[j].sample_increment;
2872         v = voice[j].left_mix * duration;
2873         vr = voice[j].right_mix * duration;
2874         if(voice[j].panned == PANNED_MYSTERY && vr > v)
2875             v = vr;
2876         if(v < lv)
2877         {
2878             lv = v;
2879             lowest = j;
2880         }
2881       }
2882     }
2883     if(lowest != -0x7FFFFFFF)
2884     {
2885         return lowest;
2886     }
2887
2888     lv = 0x7FFFFFFF;
2889     lowest = 0;
2890     for(j = 0; j < i; j++)
2891     {
2892         if(voice[j].status & VOICE_FREE || voice[j].cache != NULL)
2893             continue;
2894         if (!(voice[j].sample->modes & MODES_LOOPING)) continue;
2895
2896         /* score notes based on both volume AND duration */
2897         /* this scoring function needs some more tweaking... */
2898         duration = voice[j].sample_offset - voice[j].sample->loop_start;
2899         if (voice[j].sample_increment > 0)
2900             duration /= voice[j].sample_increment;
2901         v = voice[j].left_mix * duration;
2902         vr = voice[j].right_mix * duration;
2903         if(voice[j].panned == PANNED_MYSTERY && vr > v)
2904             v = vr;
2905         if(v < lv)
2906         {
2907             lv = v;
2908             lowest = j;
2909         }
2910     }
2911
2912     return lowest;
2913 }
2914 #endif
2915
2916 /* this reduces voices while maintaining sound quality */
2917 static int reduce_voice(void)
2918 {
2919     int32 lv, v;
2920     int i, j, lowest=-0x7FFFFFFF;
2921
2922     i = upper_voices;
2923     lv = 0x7FFFFFFF;
2924     
2925     /* Look for the decaying note with the smallest volume */
2926     /* Protect drum decays.  Truncating them early sounds bad, especially on
2927        snares and cymbals */
2928     for(j = 0; j < i; j++)
2929     {
2930         if(voice[j].status & VOICE_FREE ||
2931            (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
2932             continue;
2933         
2934         if(voice[j].status & ~(VOICE_ON | VOICE_DIE | VOICE_SUSTAINED))
2935         {
2936             /* find lowest volume */
2937             v = voice[j].left_mix;
2938             if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
2939                 v = voice[j].right_mix;
2940             if(v < lv)
2941             {
2942                 lv = v;
2943                 lowest = j;
2944             }
2945         }
2946     }
2947     if(lowest != -0x7FFFFFFF)
2948     {
2949         /* This can still cause a click, but if we had a free voice to
2950            spare for ramping down this note, we wouldn't need to kill it
2951            in the first place... Still, this needs to be fixed. Perhaps
2952            we could use a reserve of voices to play dying notes only. */
2953
2954         cut_notes++;
2955         free_voice(lowest);
2956         if(!prescanning_flag)
2957             ctl_note_event(lowest);
2958         return lowest;
2959     }
2960
2961     /* try to remove VOICE_DIE before VOICE_ON */
2962     lv = 0x7FFFFFFF;
2963     lowest = -1;
2964     for(j = 0; j < i; j++)
2965     {
2966       if(voice[j].status & VOICE_FREE)
2967             continue;
2968       if(voice[j].status & ~(VOICE_ON | VOICE_SUSTAINED))
2969       {
2970         /* continue protecting drum decays */
2971         if (voice[j].status & ~(VOICE_DIE) &&
2972             (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
2973                 continue;
2974         /* find lowest volume */
2975         v = voice[j].left_mix;
2976         if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
2977             v = voice[j].right_mix;
2978         if(v < lv)
2979         {
2980             lv = v;
2981             lowest = j;
2982         }
2983       }
2984     }
2985     if(lowest != -1)
2986     {
2987         cut_notes++;
2988         free_voice(lowest);
2989         if(!prescanning_flag)
2990             ctl_note_event(lowest);
2991         return lowest;
2992     }
2993
2994     /* try to remove VOICE_SUSTAINED before VOICE_ON */
2995     lv = 0x7FFFFFFF;
2996     lowest = -0x7FFFFFFF;
2997     for(j = 0; j < i; j++)
2998     {
2999       if(voice[j].status & VOICE_FREE)
3000             continue;
3001       if(voice[j].status & VOICE_SUSTAINED)
3002       {
3003         /* find lowest volume */
3004         v = voice[j].left_mix;
3005         if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
3006             v = voice[j].right_mix;
3007         if(v < lv)
3008         {
3009             lv = v;
3010             lowest = j;
3011         }
3012       }
3013     }
3014     if(lowest != -0x7FFFFFFF)
3015     {
3016         cut_notes++;
3017         free_voice(lowest);
3018         if(!prescanning_flag)
3019             ctl_note_event(lowest);
3020         return lowest;
3021     }
3022         
3023     lost_notes++;
3024
3025     /* remove non-drum VOICE_ON */
3026     lv = 0x7FFFFFFF;
3027     lowest = -0x7FFFFFFF;
3028     for(j = 0; j < i; j++)
3029     {
3030         if(voice[j].status & VOICE_FREE ||
3031            (voice[j].sample->note_to_use && ISDRUMCHANNEL(voice[j].channel)))
3032                 continue;
3033
3034         /* find lowest volume */
3035         v = voice[j].left_mix;
3036         if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
3037             v = voice[j].right_mix;
3038         if(v < lv)
3039         {
3040             lv = v;
3041             lowest = j;
3042         }
3043     }
3044     if(lowest != -0x7FFFFFFF)
3045     {
3046         free_voice(lowest);
3047         if(!prescanning_flag)
3048             ctl_note_event(lowest);
3049         return lowest;
3050     }
3051
3052     /* remove all other types of notes */
3053     lv = 0x7FFFFFFF;
3054     lowest = 0;
3055     for(j = 0; j < i; j++)
3056     {
3057         if(voice[j].status & VOICE_FREE)
3058             continue;
3059         /* find lowest volume */
3060         v = voice[j].left_mix;
3061         if(voice[j].panned == PANNED_MYSTERY && voice[j].right_mix > v)
3062             v = voice[j].right_mix;
3063         if(v < lv)
3064         {
3065             lv = v;
3066             lowest = j;
3067         }
3068     }
3069
3070     free_voice(lowest);
3071     if(!prescanning_flag)
3072         ctl_note_event(lowest);
3073     return lowest;
3074 }
3075
3076 void free_voice(int v1)
3077 {
3078     voice[v1].status = VOICE_FREE;
3079     voice[v1].temper_instant = 0;
3080 }
3081
3082 static int find_free_voice(void)
3083 {
3084     int i, nv = voices, lowest;
3085     int32 lv, v;
3086
3087     for(i = 0; i < nv; i++)
3088         if(voice[i].status == VOICE_FREE)
3089         {
3090             if(upper_voices <= i)
3091                 upper_voices = i + 1;
3092             return i;
3093         }
3094
3095     upper_voices = voices;
3096
3097     /* Look for the decaying note with the lowest volume */
3098     lv = 0x7FFFFFFF;
3099     lowest = -1;
3100     for(i = 0; i < nv; i++)
3101     {
3102         if(voice[i].status & ~(VOICE_ON | VOICE_DIE) &&
3103            !(voice[i].sample && voice[i].sample->note_to_use && ISDRUMCHANNEL(voice[i].channel)))
3104         {
3105             v = voice[i].left_mix;
3106             if((voice[i].panned==PANNED_MYSTERY) && (voice[i].right_mix>v))
3107                 v = voice[i].right_mix;
3108             if(v<lv)
3109             {
3110                 lv = v;
3111                 lowest = i;
3112             }
3113         }
3114     }
3115     if(lowest != -1 && !prescanning_flag)
3116     {
3117         free_voice(lowest);
3118         ctl_note_event(lowest);
3119     }
3120     return lowest;
3121 }
3122
3123
3124 ///r
3125 static int find_samples(MidiEvent *e, int *vlist)
3126 {
3127         int i, j, ch, bank, prog, note = -1, noteo = -1, nv = 0, nvo = 0, nvt = 0; // nv
3128         SpecialPatch *s;
3129         Instrument *ip;
3130         int elm, elm_max = 0;
3131         
3132         ch = e->channel;
3133         if (channel[ch].special_sample > 0) {
3134                 if ((s = special_patch[channel[ch].special_sample]) == NULL) {
3135                         ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
3136                                         "Strange: Special patch %d is not installed",
3137                                         channel[ch].special_sample);
3138                         return 0;
3139                 }
3140                 note = e->a + channel[ch].key_shift + note_key_offset;
3141                 note = (note < 0) ? 0 : ((note > 127) ? 127 : note);
3142                 return select_play_sample(s->sample, s->samples, &note, vlist, e, nv);
3143         }
3144         bank = channel[ch].bank;
3145         if (ISDRUMCHANNEL(ch)) {
3146                 ip = NULL;
3147                 note = e->a & 0x7f;
3148                 instrument_map(channel[ch].mapID, &bank, &note);
3149                 noteo = note;
3150 //              for(elm = 0; elm < drumset[bank]->tone[note][0].element_num + 1; elm++){
3151 //              for (elm = 0; drumset[bank] && elm < drumset[bank]->tone[note][0].element_num + 1; elm++) {
3152 //              for(elm = 0; elm < MAX_ELEMENT; elm++){
3153                 for(elm = 0; elm <= elm_max; elm++){                    
3154                         ip = NULL;
3155                         if (! (ip = play_midi_load_instrument(1, bank, note, elm, &elm_max))) // change elm_max
3156                                 if(elm == 0)
3157                                         return 0;       /* No instrument? Then we can't play. */        
3158                                 else
3159                                         break;
3160                 /* if (ip->type == INST_GUS && ip->samples != 1)
3161                         ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
3162                                         "Strange: percussion instrument with %d samples!",
3163                                         ip->samples); */
3164                 /* "keynum" of SF2, and patch option "note=" */
3165                         if (ip->sample->note_to_use)
3166                                 note = ip->sample->note_to_use;
3167                         nvo = nv;
3168                         nv = select_play_sample(ip->sample, ip->samples, &note, vlist, e, nv);
3169                         nvt += nv;
3170                         /* Replace the sample if the sample is cached. */
3171                         if (! prescanning_flag) {
3172                                 if (ip->sample->note_to_use)
3173                                         note = MIDI_EVENT_NOTE(e);
3174                                 for (i = nvo; i < nv; i++) { // i = 0
3175                                         j = vlist[i];
3176                                         if (! opt_realtime_playing && allocate_cache_size > 0
3177                                                         && ! channel[ch].portamento) {
3178                                                 voice[j].cache = resamp_cache_fetch(voice[j].sample, note);
3179                                                 if (voice[j].cache)     /* cache hit */
3180                                                         voice[j].sample = voice[j].cache->resampled;
3181                                         } else
3182                                                 voice[j].cache = NULL;
3183                                 }
3184                         }
3185                         note = noteo;
3186                 }
3187 //              if (!ip)
3188 //                      return 0;       /* No instrument? Then we can't play. */
3189         } else if ((prog = channel[ch].program) == SPECIAL_PROGRAM){
3190                 ip = default_instrument;
3191                 note = ((ip->sample->note_to_use) ? ip->sample->note_to_use : e->a) + channel[ch].key_shift + note_key_offset;
3192                 note = (note < 0) ? 0 : ((note > 127) ? 127 : note);
3193                 nv = select_play_sample(ip->sample, ip->samples, &note, vlist, e, nv);
3194                 nvt += nv;
3195         } else {
3196                 instrument_map(channel[ch].mapID, &bank, &prog);
3197 //              for(elm = 0; elm < tonebank[bank]->tone[prog][0].element_num + 1; elm++){
3198 //              for(elm = 0; tonebank[bank] && elm < tonebank[bank]->tone[prog][0].element_num + 1; elm++){
3199 //              for(elm = 0; elm < MAX_ELEMENT; elm++){
3200                 for(elm = 0; elm <= elm_max; elm++){
3201                         ip = NULL;
3202                         if (! (ip = play_midi_load_instrument(0, bank, prog, elm, &elm_max))) // change elm_max
3203                                 if(elm == 0)
3204                                         return 0;       /* No instrument? Then we can't play. */        
3205                                 else
3206                                         break;
3207                         note = ((ip->sample->note_to_use) ? ip->sample->note_to_use : e->a) + channel[ch].key_shift + note_key_offset;
3208                         note = (note < 0) ? 0 : ((note > 127) ? 127 : note);
3209                         nvo = nv;
3210                         nv = select_play_sample(ip->sample, ip->samples, &note, vlist, e, nv);
3211                         nvt += nv;
3212                         /* Replace the sample if the sample is cached. */
3213                         if (! prescanning_flag) {
3214                                 if (ip->sample->note_to_use)
3215                                         note = MIDI_EVENT_NOTE(e);
3216                                 for (i = nvo; i < nv; i++) { // i = 0
3217                                         j = vlist[i];
3218                                         if (! opt_realtime_playing && allocate_cache_size > 0
3219                                                         && ! channel[ch].portamento) {
3220                                                 voice[j].cache = resamp_cache_fetch(voice[j].sample, note);
3221                                                 if (voice[j].cache)     /* cache hit */
3222                                                         voice[j].sample = voice[j].cache->resampled;
3223                                         } else
3224                                                 voice[j].cache = NULL;
3225                                 }
3226                         }
3227                 }
3228 //              if(!nvt)
3229                 if(nvt == 0)
3230                         ctl->cmsg(CMSG_WARNING, VERB_NOISY, "Strange: ch %d note %d can't select play sample.", ch, e->a);
3231 //              if (!ip)
3232 //                      return 0;       /* No instrument? Then we can't play. */
3233         }
3234 /*
3235 for(elm \82ª\92Ç\89Á\82³\82ê\82½\82±\82Æ\82Å ip \82Ì\97L\8cø\94Í\88Í\82Í\83\8b\81[\83v\93à\82É\82È\82Á\82½\82Ì\82Å\83L\83\83\83b\83V\83\85\92u\8a·\82à\92\86\82É\93ü\82ê\82é\95K\97v\82ª\82Å\82«\82½
3236 noteo : note_to_use \82Å\95Ï\8dX\82³\82ê\82½\8fê\8d\87 for(elm \8fð\8c\8f\82É\89e\8b¿\82·\82é\81H
3237 nvo : ip \82Æ\91Î\89\9e\82·\82é vlist \82Ì nv \82Ì\94Í\88Í\82ð\8ew\92è\82·\82é\95K\97v\82ª\82 \82é
3238 elm_max : \96¢\92è\8b`\83o\83\93\83N\82Ì\8fê\8d\87,\91ã\91Ö\90æ\83o\83\93\83N\82Ìelement_num\82ª\95K\97v\82È\82Ì\82Åplay_midi_load_instrument()\93à\82Å\8dX\90V
3239 */
3240 #if 0
3241         /* Replace the sample if the sample is cached. */
3242         if (! prescanning_flag) {
3243                 if (ip->sample->note_to_use)
3244                         note = MIDI_EVENT_NOTE(e);
3245                 for (i = 0; i < nv; i++) {
3246                         j = vlist[i];
3247                         if (! opt_realtime_playing && allocate_cache_size > 0
3248                                         && ! channel[ch].portamento) {
3249                                 voice[j].cache = resamp_cache_fetch(voice[j].sample, note);
3250                                 if (voice[j].cache)     /* cache hit */
3251                                         voice[j].sample = voice[j].cache->resampled;
3252                         } else
3253                                 voice[j].cache = NULL;
3254                 }
3255         }
3256 #endif
3257         return nv;
3258 }
3259 ///r
3260 static int select_play_sample(Sample *splist,
3261                 int nsp, int *note, int *vlist, MidiEvent *e, int nv)
3262 {
3263         int ch = e->channel, kn = e->a & 0x7f, vel = e->b;
3264         int32 f, fs, ft, fst, fc, fr, cdiff, diff, sample_link;
3265         int8 tt = channel[ch].temper_type;
3266         uint8 tp = channel[ch].rpnmap[RPN_ADDR_0003];
3267         Sample *sp, *spc, *spr;
3268         int16 sf, sn;
3269         double ratio;
3270         int i, j, k, nvc, nvo = nv;
3271         
3272         if (ISDRUMCHANNEL(ch)){
3273                 f = freq_table[*note];
3274         //      fs = f;
3275         }else {
3276                 if (opt_pure_intonation) {
3277                         if (current_keysig < 8)
3278                                 f = freq_table_pureint[current_freq_table][*note];
3279                         else
3280                                 f = freq_table_pureint[current_freq_table + 12][*note];
3281                 } else if (opt_temper_control)
3282                         switch (tt) {
3283                         case 0:
3284                                 f = freq_table_tuning[tp][*note];
3285                                 break;
3286                         case 1:
3287                                 if (current_temper_keysig < 8)
3288                                         f = freq_table_pytha[
3289                                                         current_temper_freq_table][*note];
3290                                 else
3291                                         f = freq_table_pytha[
3292                                                         current_temper_freq_table + 12][*note];
3293                                 break;
3294                         case 2:
3295                                 if (current_temper_keysig < 8)
3296                                         f = freq_table_meantone[current_temper_freq_table
3297                                                         + ((temper_adj) ? 36 : 0)][*note];
3298                                 else
3299                                         f = freq_table_meantone[current_temper_freq_table
3300                                                         + ((temper_adj) ? 24 : 12)][*note];
3301                                 break;
3302                         case 3:
3303                                 if (current_temper_keysig < 8)
3304                                         f = freq_table_pureint[current_temper_freq_table
3305                                                         + ((temper_adj) ? 36 : 0)][*note];
3306                                 else
3307                                         f = freq_table_pureint[current_temper_freq_table
3308                                                         + ((temper_adj) ? 24 : 12)][*note];
3309                                 break;
3310                         default:        /* user-defined temperament */
3311                                 if ((tt -= 0x40) >= 0 && tt < 4) {
3312                                         if (current_temper_keysig < 8)
3313                                                 f = freq_table_user[tt][current_temper_freq_table
3314                                                                 + ((temper_adj) ? 36 : 0)][*note];
3315                                         else
3316                                                 f = freq_table_user[tt][current_temper_freq_table
3317                                                                 + ((temper_adj) ? 24 : 12)][*note];
3318                                 } else
3319                                         f = freq_table[*note];
3320                                 break;
3321                         }
3322                 else
3323                         f = freq_table[*note];
3324                 if (! opt_pure_intonation && opt_temper_control
3325                                 && tt == 0 && f != freq_table[*note]) {
3326                         *note = log(f / 440000.0) * DIV_LN2 * 12 + 69.5;
3327                         *note = (*note < 0) ? 0 : ((*note > 127) ? 127 : *note);
3328                 //      fs = freq_table[*note];
3329                 }
3330                 //else
3331                 //      fs = freq_table[*note];
3332         }
3333 #if 0 // random vel
3334         {
3335                 int32 rvel, rnd = rand(), flg = rnd & 0x1000, ofs = rnd & 0x7;
3336                 rvel = flg ? (vel - ofs) : (vel + ofs);
3337                 if(rvel > 127)
3338                         rvel = vel - ofs;
3339                 else if(rvel < 0)
3340                         rvel = vel + ofs;
3341                 vel = rvel;
3342         }
3343 #endif
3344 #if 1
3345 /*
3346 \83T\83\93\83v\83\8b\8ew\92è\82Í \83m\81[\83i\83\93\83o\81[,\83x\83\8d\83V\83e\83\82ª\8ae\83\8c\83\93\83W\93à\82É\82 \82é\82à\82Ì\91S\82Ä
3347 \8e\9f\82É\8ew\92è\82Ì\83T\83\93\83v\83\8b\90Ý\92è(scale_factor)\82ð\8c³\82É\8dÄ\90\8eü\94g\90\94\82ð\8ew\92è
3348 */
3349         for (i = 0, sp = splist; i < nsp; i++, sp++) {
3350                 if (((sp->low_key <= *note && sp->high_key >= *note))
3351                         && sp->low_vel <= vel && sp->high_vel >= vel) { 
3352                         /* GUS/SF2 - Scale Tuning */
3353                         if ((sf = sp->scale_factor) != 1024) {
3354                                 sn = sp->scale_freq;
3355                                 ratio = pow(2.0, (double)((*note - sn) * (sf - 1024)) * DIV_12288);
3356                                 ft = f * ratio + 0.5;
3357                         } else
3358                                 ft = f;
3359                         if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
3360                                 if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
3361                                         ft = ft * ratio + 0.5;
3362                         j = vlist[nv] = find_voice(e);
3363                         voice[j].orig_frequency = ft;
3364                         MYCHECK(voice[j].orig_frequency);
3365                         voice[j].sample = sp;
3366                         voice[j].status = VOICE_ON;
3367                         nv++;
3368                 }
3369         }
3370         // move to find_samples() (for add_elm
3371         //if(nv == 0)
3372         //      ctl->cmsg(CMSG_WARNING, VERB_NOISY, 
3373         //              "Strange: ch %d note %d can't select play sample.", ch, *note);
3374         return nv;
3375 #else
3376 //      nv = 0; 
3377         for (i = 0, sp = splist; i < nsp; i++, sp++) {
3378                 /* GUS/SF2 - Scale Tuning */
3379                 if ((sf = sp->scale_factor) != 1024) {
3380                         sn = sp->scale_freq;
3381                         ratio = pow(2.0, (double)((*note - sn) * (sf - 1024)) * DIV_12288);
3382                         ft = f * ratio + 0.5, fst = fs * ratio + 0.5;
3383                 } else
3384                         ft = f, fst = fs;
3385                 if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
3386                         if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
3387                                 ft = ft * ratio + 0.5, fst = fst * ratio + 0.5;
3388                 if (sp->low_freq <= fst && sp->high_freq >= fst
3389                                 && sp->low_vel <= vel && sp->high_vel >= vel
3390                                 && ! (sp->inst_type == INST_SF2
3391                                 && sp->sample_type == SF_SAMPLETYPE_RIGHT)) {
3392                         j = vlist[nv] = find_voice(e);
3393                         voice[j].orig_frequency = ft;
3394                         MYCHECK(voice[j].orig_frequency);
3395                         voice[j].sample = sp;
3396                         voice[j].status = VOICE_ON;
3397                         nv++;
3398                 }
3399         }
3400         if (nv == 0) {  /* we must select at least one sample. */
3401                 fr = fc = 0;
3402                 spc = spr = NULL;
3403                 cdiff = 0x7fffffff;
3404                 for (i = 0, sp = splist; i < nsp; i++, sp++) {
3405                         /* GUS/SF2 - Scale Tuning */
3406                         if ((sf = sp->scale_factor) != 1024) {
3407                                 sn = sp->scale_freq;
3408                                 ratio = pow(2.0, (double)((*note - sn) * (sf - 1024)) * DIV_12288);
3409                                 ft = f * ratio + 0.5, fst = fs * ratio + 0.5;
3410                         } else
3411                                 ft = f, fst = fs;
3412                         if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
3413                                 if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
3414                                         ft = ft * ratio + 0.5, fst = fst * ratio + 0.5;
3415                         diff = abs(sp->root_freq - fst);
3416                         if (diff < cdiff) {
3417                                 if (sp->inst_type == INST_SF2
3418                                                 && sp->sample_type == SF_SAMPLETYPE_RIGHT) {
3419                                         fr = ft;        /* reserve */
3420                                         spr = sp;       /* reserve */
3421                                 } else {
3422                                         fc = ft;
3423                                         spc = sp;
3424                                         cdiff = diff;
3425                                 }
3426                         }
3427                 }
3428                 /* If spc is not NULL, a makeshift sample is found. */
3429                 /* Otherwise, it's a lonely right sample, but better than nothing. */
3430                 j = vlist[nv] = find_voice(e);
3431                 voice[j].orig_frequency = (spc) ? fc : fr;
3432                 MYCHECK(voice[j].orig_frequency);
3433                 voice[j].sample = (spc) ? spc : spr;
3434                 voice[j].status = VOICE_ON;
3435                 nv++;
3436         }
3437         nvc = nv;
3438         for (i = nvo; i < nvc; i++) { // i = 0
3439                 spc = voice[vlist[i]].sample;
3440                 /* If it's left sample, there must be right sample. */
3441                 if (spc->inst_type == INST_SF2
3442                                 && spc->sample_type == SF_SAMPLETYPE_LEFT) {
3443                         sample_link = spc->sf_sample_link;
3444                         for (j = 0, sp = splist; j < nsp; j++, sp++)
3445                                 if (sp->inst_type == INST_SF2
3446                                                 && sp->sample_type == SF_SAMPLETYPE_RIGHT
3447                                                 && sp->sf_sample_index == sample_link) {
3448                                         /* right sample is found. */
3449                                         /* GUS/SF2 - Scale Tuning */
3450                                         if ((sf = sp->scale_factor) != 1024) {
3451                                                 sn = sp->scale_freq;
3452                                                 ratio = pow(2.0, (double)((*note - sn) * (sf - 1024)) * DIV_12288);
3453                                                 ft = f * ratio + 0.5;
3454                                         } else
3455                                                 ft = f;
3456                                         if (ISDRUMCHANNEL(ch) && channel[ch].drums[kn] != NULL)
3457                                                 if ((ratio = get_play_note_ratio(ch, kn)) != 1.0)
3458                                                         ft = ft * ratio + 0.5;
3459                                         k = vlist[nv] = find_voice(e);
3460                                         voice[k].orig_frequency = ft;
3461                                         MYCHECK(voice[k].orig_frequency);
3462                                         voice[k].sample = sp;
3463                                         voice[k].status = VOICE_ON;
3464                                         nv++;
3465                                         break;
3466                                 }
3467                 }
3468         }
3469         return nv;
3470 #endif
3471 }
3472
3473 static double get_play_note_ratio(int ch, int note)
3474 {
3475         int play_note = channel[ch].drums[note]->play_note;
3476         int bank = channel[ch].bank;
3477         ToneBank *dbank;
3478         int def_play_note;
3479         int elm = 0;
3480         
3481         if (play_note == -1)
3482                 return 1.0;
3483         instrument_map(channel[ch].mapID, &bank, &note);
3484         dbank = (drumset[bank]) ? drumset[bank] : drumset[0];
3485         if(dbank->tone[note][elm] == NULL)
3486                 return 1.0;
3487         if ((def_play_note = dbank->tone[note][elm]->play_note) == -1)
3488                 return 1.0;
3489         if (play_note >= def_play_note)
3490                 return bend_coarse[(play_note - def_play_note) & 0x7f];
3491         else
3492                 return 1 / bend_coarse[(def_play_note - play_note) & 0x7f];
3493 }
3494
3495 ///r
3496 /*
3497 kill_note(i); // cut sustain
3498 finish_note(i); // drop sustain ? NOTE_OFF ?
3499 cut_note(i) // cut short release // altassign,mono
3500 cut_note2(i) // cut short release // overlaped voice
3501 */
3502 static void voice_control(MidiEvent *e)
3503 {
3504         int i;
3505         int ch = e->channel;
3506         int note = MIDI_EVENT_NOTE(e);
3507         int mono_check = channel[ch].mono;
3508         AlternateAssign *altassign = find_altassign(channel[ch].altassign, note);
3509         
3510         for (i = 0; i < upper_voices; i++){
3511                 if (voice[i].status == VOICE_FREE || voice[i].channel != ch)
3512                         continue;
3513 #if 1 // opt_max_channel_voices
3514                 if (voice[i].channel_voice_count > 0)
3515                         voice[i].channel_voice_count--;
3516                 else
3517                         cut_note2(i);
3518 #endif
3519                 if (!opt_overlap_voice_allow) {
3520                         // overlap_voice OFF
3521                         if(voice[i].note == note)
3522                                 kill_note(i);
3523                         else if (altassign && find_altassign(altassign, voice[i].note))
3524                                 kill_note(i);
3525                         else if (mono_check)
3526                                 kill_note(i);
3527                 }
3528                 else if (altassign && find_altassign(altassign, voice[i].note))
3529                         cut_note(i);
3530                 else if (mono_check)
3531                         cut_note(i);
3532                 else if (voice[i].note != note || channel[ch].assign_mode == 2)
3533                         continue;
3534                 else if (channel[ch].assign_mode == 0)
3535                         cut_note(i);
3536                 else if (channel[ch].assign_mode == 1){
3537                         if (voice[i].overlap_count > 0)
3538                                 voice[i].overlap_count--;
3539                         else
3540                                 cut_note2(i);
3541                 }               
3542         }
3543 }
3544
3545 /* Only one instance of a note can be playing on a single channel. */
3546 static int find_voice(MidiEvent *e)
3547 {
3548         int i, lowest = -1;
3549
3550         for (i = 0; i < upper_voices; i++)
3551                 if (voice[i].status == VOICE_FREE) {
3552                         lowest = i;     /* lower volume */
3553                         break;
3554                 }
3555         if (lowest != -1)       /* Found a free voice. */
3556                 return lowest;
3557         if (upper_voices < voices)
3558                 return upper_voices++;
3559         return reduce_voice();
3560 }
3561
3562 ///r
3563 // DIV_12288 = 1.0 / (double)(12 * (1 << 10)); 
3564 int32 get_note_freq(Sample *sp, int note)
3565 {       
3566         /* GUS/SF2 - Scale Tuning */
3567         if (sp->scale_factor != 1024) {
3568                 double ratio = pow(2.0, (double)((note - sp->scale_freq) * (sp->scale_factor - 1024)) * DIV_12288);
3569                 return (int32)((double)freq_table[note] * ratio + 0.5);
3570         }else
3571                 return freq_table[note];
3572 }
3573
3574 #if 0
3575 int32 get_note_freq(Sample *sp, int note)
3576 {
3577         int32 f;
3578         int16 sf, sn;
3579         double ratio;
3580         
3581         f = freq_table[note];
3582         /* GUS/SF2 - Scale Tuning */
3583         if ((sf = sp->scale_factor) != 1024) {
3584                 sn = sp->scale_freq;
3585                 ratio = pow(2.0, (note - sn) * (sf - 1024) / 12288.0);
3586                 f = f * ratio + 0.5;
3587         }
3588         return f;
3589 }
3590 #endif
3591
3592
3593 static void update_modulation_wheel(int ch)
3594 {
3595         recompute_channel_lfo(ch);
3596         recompute_channel_amp(ch);
3597         recompute_channel_filter(ch);
3598         recompute_channel_pitch(ch);
3599 //   int i, uv = upper_voices;
3600 //    for(i = 0; i < uv; i++)
3601 //      if(voice[i].status != VOICE_FREE && voice[i].channel == ch)
3602 //      {
3603 //          /* Set/Reset mod-wheel */
3604 ////            voice[i].vibrato_control_counter = voice[i].vibrato_phase = 0; //elion comment out
3605 //          recompute_amp(i);
3606 //              apply_envelope_to_amp(i);
3607 //          recompute_freq(i);
3608 //              recompute_voice_filter(i);
3609 //      }
3610 }
3611
3612
3613 static void drop_portamento(int ch)
3614 {
3615     int i, uv = upper_voices;
3616
3617     channel[ch].porta_status = 0;
3618     for(i = 0; i < uv; i++)
3619         if(voice[i].status != VOICE_FREE &&
3620            voice[i].channel == ch &&
3621            voice[i].porta_status)
3622         {
3623             voice[i].porta_status = 0;
3624         //    recompute_freq(i);
3625                 recompute_voice_pitch(i);
3626         }
3627         //channel[ch].porta_last_note_fine = -1;
3628 }
3629
3630 static void update_portamento_controls(int ch)
3631 {
3632     if(!channel[ch].portamento && channel[ch].portamento_control == -1){
3633         //      || (channel[ch].portamento_time_msb | channel[ch].portamento_time_lsb) == 0){
3634                 if(channel[ch].porta_status)
3635                         drop_portamento(ch);
3636         } else {
3637 #if 1 // use portament_time_table               
3638                 double st = portament_time_table_xg[channel[ch].portamento_time_msb & 0x7F];
3639                 channel[ch].porta_dpb = st * PORTAMENTO_CONTROL_RATIO * div_playmode_rate;
3640 #else
3641                 const double tuning = PORTAMENTO_TIME_TUNING * 256.0 * 256.0;
3642                 double mt, st;
3643                 mt = midi_time_table[channel[ch].portamento_time_msb & 0x7F] *
3644                         midi_time_table2[channel[ch].portamento_time_lsb & 0x7F] * tuning;
3645                 st = (double)1000.0 / mt; // semitone/sec
3646                 channel[ch].porta_dpb = st * PORTAMENTO_CONTROL_RATIO * div_playmode_rate;
3647 #endif
3648         //      channel[ch].porta_status = 1;
3649     }
3650 }
3651
3652 static void update_portamento_time(int ch)
3653 {
3654     int i, uv = upper_voices;
3655     int dpb;
3656     int32 ratio;
3657
3658     update_portamento_controls(ch);
3659     dpb = channel[ch].porta_dpb;
3660     //ratio = channel[ch].porta_status;
3661
3662     for(i = 0; i < uv; i++)
3663     {
3664         if(voice[i].status != VOICE_FREE &&
3665            voice[i].channel == ch &&
3666            voice[i].porta_status)
3667         {
3668          //   voice[i].porta_status = ratio;
3669             voice[i].porta_dpb = dpb;
3670         //    recompute_freq(i);
3671         //      recompute_voice_pitch(i);
3672         }
3673     }
3674 }
3675
3676 static void drop_legato(int ch)
3677 {
3678     int i, uv = upper_voices;
3679
3680     channel[ch].legato_status = 0;
3681         if(channel[ch].legato_note > 127)
3682                 return;
3683     for(i = 0; i < uv; i++)
3684         if(voice[i].status != VOICE_FREE &&
3685            voice[i].channel == ch &&
3686            voice[i].note == channel[ch].legato_note)
3687         {
3688             voice[i].porta_status = 0;
3689             cut_note(i);
3690         //    recompute_freq(i);
3691         //      recompute_voice_pitch(i);
3692         }
3693         channel[ch].legato_note = 255;
3694         channel[ch].legato_flag = 0;
3695 }
3696
3697 static void update_legato_status(int ch)
3698 {
3699         if(channel[ch].legato <= 0){
3700                 if(channel[ch].legato_status)
3701                         drop_legato(ch);
3702         }else{
3703 #if 1
3704         //      const double ss = 4069.0104166666670; // semitone / sec
3705                 const double ss = 12000.0; // semitone / sec
3706                 channel[ch].porta_dpb = ss * PORTAMENTO_CONTROL_RATIO * div_playmode_rate;
3707 #else
3708                 const double st = 1.0 / 0.06250 * PORTAMENTO_TIME_TUNING * 0.3 * 256.0 * 256;
3709                 double st = (double)1.0 / mt; // semitone / ms
3710                 channel[ch].porta_dpb = st * PORTAMENTO_CONTROL_RATIO * 1000.0 * div_playmode_rate;
3711 #endif
3712                 //channel[ch].porta_status = 1;
3713         }
3714 }
3715
3716 /*! update legato for a voice. */
3717 static void update_voice_legato(int ch)
3718 {
3719         int i;
3720
3721         for(i = 0; i < upper_voices; i++){
3722                 if(voice[i].status != VOICE_FREE &&
3723                         voice[i].channel == ch &&
3724                         voice[i].note == channel[ch].legato_note){
3725                         voice[i].porta_next_pb = channel[ch].porta_next_pb;
3726                         voice[i].porta_dpb = channel[ch].porta_dpb;     
3727                         if(voice[i].porta_pb != voice[i].porta_next_pb)
3728                                 voice[i].porta_status = 1;
3729                 }
3730         }       
3731 }
3732
3733 /*! initialize portamento or legato for a voice. */
3734 static void init_voice_portamento(int v)
3735 {
3736         Voice *vp = &(voice[v]);
3737         int ch = vp->channel;
3738
3739         vp->porta_status = 0;
3740         vp->porta_out = 0;
3741         if(!opt_portamento)
3742                 return;
3743         if(channel[ch].porta_status || channel[ch].legato_flag) {
3744                 vp->porta_note_fine = channel[ch].porta_note_fine;
3745                 vp->porta_next_pb = channel[ch].porta_next_pb;
3746                 vp->porta_dpb = channel[ch].porta_dpb;
3747                 vp->porta_pb = channel[ch].porta_pb;            
3748                 if(vp->porta_pb != vp->porta_next_pb)
3749                         vp->porta_status = 1;
3750         }
3751 }
3752
3753 static int note_off_legato(MidiEvent *e)
3754 {
3755         int i, ch = e->channel, note = MIDI_EVENT_NOTE(e);
3756         int count, max = 0, fnote = -1;
3757         
3758 // -2:return finish_note()\82µ\82È\82¢
3759 // -1:thru finish_note()\82·\82é
3760 // 0<=:change note finish_note()\82·\82é
3761         if(!channel[ch].legato_status){
3762                 channel[ch].legato_flag = 0;
3763                 return -1; // thru
3764         }
3765         count = channel[ch].legato_hist[note];          
3766         if(!count) 
3767                 return -1; // thru
3768         channel[ch].legato_hist[note] = 0; // clear flag        
3769         if(note == channel[ch].legato_note)
3770                 ctl_note_event2(ch, note, VOICE_SUSTAINED, channel[ch].legato_velo); // legato\82Ì\8aî\8f\80\83m\81[\83g\82È\82Ì\82Å\95\\8e¦\8ec\82µ\82Ä\82¨\82­
3771         else
3772                 ctl_note_event2(ch, note, VOICE_FREE, channel[ch].legato_velo);
3773 #if 0 // \8ec\82Á\82Ä\82¢\82é\8dÅ\8bß\82Ì\83m\81[\83g\82Ö\83s\83b\83`\95Ï\8dX
3774         for (i = 0; i < 128; i++){
3775                 if(channel[ch].legato_hist[i] > count) // \8d¡note_off\82µ\82½note\82ªnoteon\82µ\82½\82Æ\82«\82æ\82è\8cã\82Énoteon\82µ\82½note\82ð\92T\82·
3776                         return -2; // finish_note()\82µ\82È\82¢
3777                 if(channel[ch].legato_hist[i] > max){ // \8d¡note_off\82µ\82½note\82ªnoteon\82µ\82½\82Æ\82«\82æ\82è\91O\82Énoteon\82µ\82½\8dÅ\8bß\82Ìnote\82ð\92T\82·
3778                         max = channel[ch].legato_hist[i];
3779                         fnote = i;
3780                 }
3781         }
3782         if(fnote != -1){ // note\82ª\82 \82é\8fê\8d\87              
3783                 uint8 pnote = channel[ch].legato_last_note;
3784                 channel[ch].legato_last_note = fnote;
3785                 channel[ch].porta_next_pb = fnote * 256;
3786                 update_voice_legato(ch);
3787                 ctl->cmsg(CMSG_INFO,VERB_DEBUG, "Legato: change note:%d (CH:%d NOTE:%d noteoff)", 
3788                         fnote, ch, note);
3789                 ctl_note_event2(ch, pnote, VOICE_SUSTAINED, channel[ch].legato_velo);
3790                 ctl_note_event2(ch, note, VOICE_ON, channel[ch].legato_velo); // e->b = velocity
3791                 return -2; // finish_note()\82µ\82È\82¢
3792         }
3793 #else // noteoff\82Å\82Í\83s\83b\83`\95Ï\8dX\82µ\82È\82¢ note\82ª\82 \82é\8aÔ\82Ílegato_note\82ð\8cp\91±\82·\82é
3794         for (i = 0; i < 128; i++){
3795                 if(channel[ch].legato_hist[i]) // noteon\92\86\82Ìnote\82ð\92T\82·
3796                         return -2; // finish_note()\82µ\82È\82¢
3797         }
3798 #endif
3799         // \8dÅ\8bß\82Ìnote\82ª\82È\82¢\8fê\8d\87 (\91S\82Änoteoff\82µ\82½\8fê\8d\87
3800         ctl->cmsg(CMSG_INFO,VERB_DEBUG, "Legato: finish note:%d (CH:%d NOTE:%d noteoff)", 
3801                 channel[ch].legato_note, ch, note);
3802         channel[ch].legato_flag = 0;
3803         channel[ch].legato_status = 0; // legato\8fI\97¹
3804         return channel[ch].legato_note; // last_vidq()\82ð\92Ê\82·\82½\82ß\82É legato\8aJ\8en\8e\9e\82Ìnote\82É\8f\91\82«\8a·\82¦ \8cã\82Ífinish_note()
3805 }
3806
3807 /*! initialize portamento or legato for a channel. */
3808 static int init_channel_portamento(MidiEvent *e)
3809 {
3810 #if 1 // portamento and leagato
3811     int i, ch = e->channel, note = MIDI_EVENT_NOTE(e);
3812         int32 times = 0, fine = note * PORTAMENTO_CONTROL_RATIO;
3813
3814         if(!(channel[ch].portamento_control != -1
3815                 || channel[ch].portamento
3816                 || channel[ch].legato > 0)){
3817                 channel[ch].porta_last_note_fine = fine; // for portamento
3818                 return 0;
3819         }
3820         if(channel[ch].legato > 0 && channel[ch].legato_flag){ // \95¡\90\94\83m\81[\83g\82Ì2\83m\81[\83g\96Ú\88È\8d~
3821                 if(channel[ch].legato_status || channel[ch].porta_status
3822                         && (times = e->time - channel[ch].legato_note_time) > (play_mode->rate >> 2) ) { // legato start
3823                         if(!channel[ch].legato_status){
3824                                 channel[ch].legato_status = 1; // legato start
3825                                 channel[ch].legato_note = channel[ch].legato_last_note; // set\8aî\8f\80\83m\81[\83g
3826                                 memset(channel[ch].legato_hist, 0, sizeof(channel[ch].legato_hist)); // init                                            
3827                                 channel[ch].legato_hist[channel[ch].legato_note] = channel[ch].legato_status;
3828                                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3829                                         "Legato: start legato. base note:%d (CH:%d NOTE:%d) time:%d", 
3830                                         channel[ch].legato_note, ch, note, times);
3831                         }
3832                         if(!(channel[ch].portamento_control != -1 || channel[ch].portamento))
3833                                 update_legato_status(ch);
3834                         channel[ch].legato_hist[note] = (++channel[ch].legato_status);
3835                         channel[ch].porta_next_pb = fine;
3836                         update_voice_legato(ch);
3837                         ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3838                                 "Legato: update legato. change note:%d legato (CH:%d NOTE:%d)", note, ch, note);
3839                         ctl_note_event2(ch, channel[ch].legato_last_note, VOICE_SUSTAINED, channel[ch].legato_velo);
3840                         ctl_note_event2(ch, note, VOICE_ON, channel[ch].legato_velo);
3841                         channel[ch].legato_last_note = note;
3842                         channel[ch].porta_last_note_fine = fine; // for portamento
3843                         return 1; // legato start
3844                 }
3845         }                       
3846         // start note (legato\82Ì\8aî\8f\80\83m\81[\83g\82É\82È\82é\89Â\94\\90«\82ª\82 \82é
3847         if(channel[ch].portamento_control != -1){ // portament_control
3848                 update_portamento_controls(ch); 
3849                 channel[ch].porta_status = 1;
3850                 channel[ch].porta_pb = channel[ch].portamento_control * PORTAMENTO_CONTROL_RATIO;
3851                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3852                         "Portamento Control: start note:%d to base note:%d (CH:%d NOTE:%d)", 
3853                         channel[ch].portamento_control, note, ch, note);        
3854                 channel[ch].portamento_control = -1;
3855                 channel[ch].portamento = 127;
3856                 channel[ch].porta_dpb = (double)(12000 * PORTAMENTO_CONTROL_RATIO) * div_playmode_rate; // 12000st/s instant
3857         }else if(channel[ch].portamento){ // portament
3858                 update_portamento_controls(ch); 
3859                 channel[ch].porta_status = 1;
3860                 if(channel[ch].porta_last_note_fine == -1) // first noteon
3861                         channel[ch].porta_pb = fine;
3862                 else
3863                         channel[ch].porta_pb = channel[ch].porta_last_note_fine;                
3864                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3865                         "Portamento: start note:%d to base note:%d (CH:%d NOTE:%d)", 
3866                         channel[ch].porta_last_note_fine >> PORTAMENTO_CONTROL_BIT, note, ch, note);    
3867         }else{ // if(channel[ch].legato > 0)
3868                 update_legato_status(ch);
3869                 channel[ch].porta_status = 1;
3870                 channel[ch].porta_pb = fine;
3871         }
3872         channel[ch].porta_next_pb = fine;
3873         channel[ch].porta_note_fine = fine;
3874         channel[ch].legato_note = 255; // \96³\8cø\82È\83m\81[\83g\83i\83\93\83o\81[
3875         channel[ch].legato_velo = e->b; // velocity
3876         channel[ch].legato_flag = 1;    
3877         channel[ch].legato_note_time = e->time;
3878         channel[ch].legato_last_note = note;
3879         channel[ch].porta_last_note_fine = fine;
3880         return 0;
3881 #else // portamento or leagato
3882     int i, ch = e->channel, note = MIDI_EVENT_NOTE(e);
3883         int32 times, fine = note * PORTAMENTO_CONTROL_RATIO;
3884
3885         if(channel[ch].portamento_control != -1){ // portament_control
3886                 update_portamento_controls(ch); 
3887                 channel[ch].porta_status = 1;
3888                 channel[ch].porta_last_note_fine = channel[ch].portamento_control * PORTAMENTO_CONTROL_RATIO;
3889                 channel[ch].porta_note_fine = fine;
3890                 channel[ch].porta_pb = channel[ch].porta_last_note_fine;
3891                 channel[ch].porta_next_pb = channel[ch].porta_note_fine;                
3892                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3893                         "Portamento Control: start note:%d to base note:%d (CH:%d NOTE:%d)", 
3894                         channel[ch].portamento_control, note, ch, note);        
3895                 channel[ch].portamento_control = -1;
3896         }else if(channel[ch].portamento){ // portament
3897                 update_portamento_controls(ch); 
3898                 channel[ch].porta_status = 1;
3899                 if(channel[ch].porta_last_note_fine == -1) // first noteon
3900                         channel[ch].porta_last_note_fine = fine;
3901                 channel[ch].porta_note_fine = fine;
3902                 channel[ch].porta_pb = channel[ch].porta_last_note_fine;
3903                 channel[ch].porta_next_pb = channel[ch].porta_note_fine;                
3904                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3905                         "Portamento: start note:%d to base note:%d (CH:%d NOTE:%d)", 
3906                         channel[ch].porta_last_note_fine >> PORTAMENTO_CONTROL_BIT, note, ch, note);    
3907         }else if(channel[ch].legato > 0){ // legato     
3908                 if(channel[ch].legato_flag){ // \95¡\90\94\83m\81[\83g\82Ì2\83m\81[\83g\96Ú\88È\8d~
3909 #if 0
3910 #ifdef _DEBUG
3911 ctl->cmsg(CMSG_INFO,VERB_NORMAL, "Legato: times:%d = now - prev:%d", 
3912 e->time - channel[ch].legato_note_time,  channel[ch].legato_note_time, ch, note);
3913 #endif
3914 #endif
3915                         if(!channel[ch].legato_status
3916                                 && (times = e->time - channel[ch].legato_note_time) < (play_mode->rate >> 2) ){ // legato start
3917 #if 0
3918 #ifdef _DEBUG
3919 ctl->cmsg(CMSG_INFO,VERB_NORMAL,
3920 "Legato: disable legato times:%d (times:%d CH:%d NOTE:%d)", times, ch, note);
3921 #endif
3922 #endif
3923                         }else{  
3924                                 if(!channel[ch].legato_status){
3925                                         channel[ch].legato_status = 1; // legato start
3926                                         channel[ch].legato_note = channel[ch].legato_last_note; // set\8aî\8f\80\83m\81[\83g
3927                                         memset(channel[ch].legato_hist, 0, sizeof(channel[ch].legato_hist)); // init                                            
3928                                         channel[ch].legato_hist[channel[ch].legato_note] = channel[ch].legato_status;
3929                                         ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3930                                                 "Legato: start legato. base note:%d (CH:%d NOTE:%d) time:%d", 
3931                                                 channel[ch].legato_note, ch, note, times);
3932                                 }       
3933                                 update_legato_status(ch);
3934                                 channel[ch].legato_hist[note] = (++channel[ch].legato_status);
3935                                 channel[ch].porta_next_pb = fine;
3936                                 update_voice_legato(ch);
3937                                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,
3938                                         "Legato: update legato. change note:%d legato (CH:%d NOTE:%d)", note, ch, note);
3939                                 ctl_note_event2(ch, channel[ch].legato_last_note, VOICE_SUSTAINED, channel[ch].legato_velo);
3940                                 ctl_note_event2(ch, note, VOICE_ON, channel[ch].legato_velo);
3941                                 channel[ch].legato_last_note = note;
3942                                 channel[ch].porta_last_note_fine = fine; // for portamento
3943                                 return 1; // legato start
3944                         }
3945                 }
3946                 // normal (legato\82Ì\8aî\8f\80\83m\81[\83g\82É\82È\82é\89Â\94\\90«\82ª\82 \82é \82 \82é\92ö\93x\8f\89\8aú\89»\82ª\95K\97v
3947                 channel[ch].legato_note = 255; // \96³\8cø\82È\83m\81[\83g\83i\83\93\83o\81[
3948                 channel[ch].porta_note_fine = fine;
3949                 channel[ch].porta_pb = fine;
3950                 channel[ch].porta_next_pb = fine;
3951                 channel[ch].legato_velo = e->b; // velocity
3952                 channel[ch].legato_flag = 1;    
3953                 channel[ch].legato_note_time = e->time;
3954                 channel[ch].legato_last_note = note;
3955         }
3956         channel[ch].porta_last_note_fine = fine; // for portamento
3957         return 0;
3958 #endif
3959 }
3960
3961
3962
3963 ///r
3964 static void recompute_amp_envelope_follow(int v, int ch)
3965 {
3966         Voice *vp = voice + v; 
3967         Channel *cp = channel + ch;
3968         int i, note = vp->note, dr = ISDRUMCHANNEL(ch);
3969         double notesub = (double)(vp->note - vp->sample->envelope_keyf_bpo); 
3970         double amp_velsub = (double)(vp->velocity - vp->sample->envelope_velf_bpo);
3971         struct DrumParts *dp = NULL;
3972         int add_param[6];
3973
3974         for(i = 0; i < ENV0_STAGE_LIST_MAX; i++)
3975                 vp->amp_env.follow[i] = 1.0;    
3976         for(i = 0; i < 6; i++)
3977                 add_param[i] = 0;
3978         
3979         if (dr){
3980                 if(cp->drums[note] != NULL){
3981                         dp = cp->drums[note];
3982                         // amp
3983                         if(dp->drum_envelope_rate[EG_GUS_ATTACK] != -1)
3984                                 add_param[EG_GUS_ATTACK] = (dp->drum_envelope_rate[EG_GUS_ATTACK] - 0x40);
3985                         if(dp->drum_envelope_rate[EG_GUS_DECAY] != -1)
3986                                 add_param[EG_GUS_DECAY] = (dp->drum_envelope_rate[EG_GUS_DECAY] - 0x40);
3987                         if(dp->drum_envelope_rate[EG_GUS_SUSTAIN] != -1)
3988                                 add_param[EG_GUS_SUSTAIN] = (dp->drum_envelope_rate[EG_GUS_SUSTAIN] - 0x40);
3989                         if(dp->drum_envelope_rate[EG_GUS_RELEASE1] != -1)
3990                                 add_param[EG_GUS_RELEASE1] = (dp->drum_envelope_rate[EG_GUS_RELEASE1] - 0x40);
3991                 }
3992         }else{
3993                 if(cp->envelope_rate[EG_GUS_ATTACK] != -1)
3994                         add_param[EG_GUS_ATTACK] = (cp->envelope_rate[EG_GUS_ATTACK] - 0x40);
3995                 if(cp->envelope_rate[EG_GUS_DECAY] != -1)
3996                         add_param[EG_GUS_DECAY] = (cp->envelope_rate[EG_GUS_DECAY] - 0x40);
3997                 if(cp->envelope_rate[EG_GUS_SUSTAIN] != -1)
3998                         add_param[EG_GUS_SUSTAIN] = (cp->envelope_rate[EG_GUS_SUSTAIN] - 0x40);
3999                 if(cp->envelope_rate[EG_GUS_RELEASE1] != -1)
4000                         add_param[EG_GUS_RELEASE1] = (cp->envelope_rate[EG_GUS_RELEASE1] - 0x40);
4001                 /* envelope key-follow */       
4002                 if (vp->sample->envelope_keyf[EG_GUS_ATTACK])
4003                         vp->amp_env.follow[ENV0_ATTACK_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_ATTACK] * DIV_1200);
4004                 if (vp->sample->envelope_keyf[EG_GUS_DECAY])
4005                         vp->amp_env.follow[ENV0_HOLD_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_DECAY] * DIV_1200);
4006                 if (vp->sample->envelope_keyf[EG_GUS_SUSTAIN])
4007                         vp->amp_env.follow[ENV0_DECAY_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_SUSTAIN] * DIV_1200);
4008                 if (vp->sample->envelope_keyf[EG_GUS_RELEASE1])
4009                         vp->amp_env.follow[ENV0_RELEASE1_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_RELEASE1] * DIV_1200);
4010                 if (vp->sample->envelope_keyf[EG_GUS_RELEASE2])
4011                         vp->amp_env.follow[ENV0_RELEASE2_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_RELEASE2] * DIV_1200);
4012                 if (vp->sample->envelope_keyf[EG_GUS_RELEASE3])
4013                         vp->amp_env.follow[ENV0_RELEASE3_STAGE] *= POW2(notesub * (double)vp->sample->envelope_keyf[EG_GUS_RELEASE3] * DIV_1200);
4014         }       
4015         /* envelope velocity-follow */
4016         if (vp->sample->envelope_velf[EG_GUS_ATTACK])
4017                 vp->amp_env.follow[ENV0_ATTACK_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_ATTACK] * DIV_1200);
4018         if (vp->sample->envelope_velf[EG_GUS_DECAY])
4019                 vp->amp_env.follow[ENV0_HOLD_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_DECAY] * DIV_1200);
4020         if (vp->sample->envelope_velf[EG_GUS_SUSTAIN])
4021                 vp->amp_env.follow[ENV0_DECAY_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_SUSTAIN] * DIV_1200);
4022         if (vp->sample->envelope_velf[EG_GUS_RELEASE1])
4023                 vp->amp_env.follow[ENV0_RELEASE1_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_RELEASE1] * DIV_1200);
4024         if (vp->sample->envelope_velf[EG_GUS_RELEASE2])
4025                 vp->amp_env.follow[ENV0_RELEASE2_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_RELEASE2] * DIV_1200);
4026         if (vp->sample->envelope_velf[EG_GUS_RELEASE3])
4027                 vp->amp_env.follow[ENV0_RELEASE3_STAGE] *= POW2(amp_velsub * (double)vp->sample->envelope_velf[EG_GUS_RELEASE3] * DIV_1200);
4028         /* NRPN */
4029         if(add_param[EG_GUS_ATTACK]){
4030                 FLOAT_T sub_ofs_div_cr = fabs(0.0 - vp->amp_env.offset[ENV0_ATTACK_STAGE]) * div_playmode_rate * 1000.0;
4031                 FLOAT_T time_ms = sub_ofs_div_cr / vp->amp_env.rate[ENV0_ATTACK_STAGE];
4032                 time_ms = calc_nrpn_param(time_ms, (double)add_param[EG_GUS_ATTACK] * env_attack_calc, nrpn_env_attack_mode);
4033                 if(time_ms <= 0.0) 
4034                         vp->amp_env.rate[ENV0_ATTACK_STAGE] = ENV0_OFFSET_MAX;
4035                 else
4036                         vp->amp_env.rate[ENV0_ATTACK_STAGE] = sub_ofs_div_cr / time_ms;
4037         }
4038         if(add_param[EG_GUS_DECAY]){
4039                 FLOAT_T sub_ofs_div_cr = fabs(vp->amp_env.offset[ENV0_ATTACK_STAGE] - vp->amp_env.offset[ENV0_HOLD_STAGE]) * div_playmode_rate * 1000.0;
4040                 FLOAT_T time_ms = sub_ofs_div_cr / vp->amp_env.rate[ENV0_HOLD_STAGE];
4041                 time_ms *= lookup_nrpn_param(64.0 + (double)add_param[EG_GUS_DECAY] * env_decay_calc, nrpn_env_decay_mode);
4042                 if(time_ms < 5.0) time_ms = 5.0;
4043                 vp->amp_env.rate[ENV0_HOLD_STAGE] = sub_ofs_div_cr / time_ms;
4044         }
4045         if(add_param[EG_GUS_SUSTAIN]){
4046                 FLOAT_T sub_ofs_div_cr = fabs(vp->amp_env.offset[ENV0_HOLD_STAGE] - vp->amp_env.offset[ENV0_DECAY_STAGE]) * div_playmode_rate * 1000.0;
4047                 FLOAT_T time_ms = sub_ofs_div_cr / vp->amp_env.rate[ENV0_DECAY_STAGE];
4048                 time_ms *= lookup_nrpn_param(64.0 + (double)add_param[EG_GUS_SUSTAIN] * env_decay_calc, nrpn_env_decay_mode);
4049                 if(time_ms < 5.0) time_ms = 5.0;
4050                 vp->amp_env.rate[ENV0_DECAY_STAGE] = sub_ofs_div_cr / time_ms;
4051         }
4052         if(add_param[EG_GUS_RELEASE1]){
4053                 FLOAT_T sub_ofs_div_cr = fabs(ENV0_OFFSET_MAX - vp->amp_env.offset[ENV0_RELEASE1_STAGE]) * div_playmode_rate * 1000.0;
4054                 FLOAT_T time_ms = sub_ofs_div_cr / vp->amp_env.rate[ENV0_RELEASE1_STAGE];
4055                 time_ms = calc_nrpn_param(time_ms, (double)add_param[EG_GUS_RELEASE1] * env_release_calc, nrpn_env_release_mode);
4056                 if(time_ms < 5.0) time_ms = 5.0;
4057                 vp->amp_env.rate[ENV0_RELEASE1_STAGE] = sub_ofs_div_cr / time_ms;
4058         }
4059 }
4060
4061 static void recompute_mod_envelope_follow(int v, int ch)
4062 {
4063         Voice *vp = voice + v; 
4064         Channel *cp = channel + ch;
4065         int i, note = vp->note, dr = ISDRUMCHANNEL(ch);
4066         double notesub = (double)(vp->note - vp->sample->modenv_keyf_bpo);
4067         double mod_velsub = (double)(vp->velocity - vp->sample->modenv_velf_bpo);
4068         struct DrumParts *dp = NULL;
4069         int add_param[6];
4070
4071                 
4072         for(i = 0; i < ENV0_STAGE_LIST_MAX; i++)
4073                 vp->mod_env.follow[i] = 1.0;    
4074         for(i = 0; i < 6; i++)
4075                 add_param[i] = 0;
4076
4077         if (dr){
4078                 if(cp->drums[note] != NULL){
4079                         dp = cp->drums[note];
4080                         if(dp->drum_envelope_rate[EG_GUS_ATTACK] != -1)
4081                                 add_param[EG_GUS_ATTACK] = (dp->drum_envelope_rate[EG_GUS_ATTACK] - 0x40);
4082                         if(dp->drum_envelope_rate[EG_GUS_DECAY] != -1)
4083                                 add_param[EG_GUS_DECAY] = (dp->drum_envelope_rate[EG_GUS_DECAY] - 0x40);
4084                         if(dp->drum_envelope_rate[EG_GUS_SUSTAIN] != -1)
4085                                 add_param[EG_GUS_SUSTAIN] = (dp->drum_envelope_rate[EG_GUS_SUSTAIN] - 0x40);
4086                         if(dp->drum_envelope_rate[EG_GUS_RELEASE1] != -1)
4087                                 add_param[EG_GUS_RELEASE1] = (dp->drum_envelope_rate[EG_GUS_RELEASE1] - 0x40);
4088                 }
4089         }else{
4090                 if(cp->envelope_rate[EG_GUS_ATTACK] != -1)
4091                         add_param[EG_GUS_ATTACK] = (cp->envelope_rate[EG_GUS_ATTACK] - 0x40);
4092                 if(cp->envelope_rate[EG_GUS_DECAY] != -1)
4093                         add_param[EG_GUS_DECAY] = (cp->envelope_rate[EG_GUS_DECAY] - 0x40);
4094                 if(cp->envelope_rate[EG_GUS_SUSTAIN] != -1)
4095                         add_param[EG_GUS_SUSTAIN] = (cp->envelope_rate[EG_GUS_SUSTAIN] - 0x40);
4096                 if(cp->envelope_rate[EG_GUS_RELEASE1] != -1)
4097                         add_param[EG_GUS_RELEASE1] = (cp->envelope_rate[EG_GUS_RELEASE1] - 0x40);
4098                 /* envelope key-follow */       
4099                 if (vp->sample->modenv_keyf[EG_GUS_ATTACK])
4100                         vp->mod_env.follow[ENV0_ATTACK_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_ATTACK] * DIV_1200);
4101                 if (vp->sample->modenv_keyf[EG_GUS_DECAY])
4102                         vp->mod_env.follow[ENV0_HOLD_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_DECAY] * DIV_1200);
4103                 if (vp->sample->modenv_keyf[EG_GUS_SUSTAIN])
4104                         vp->mod_env.follow[ENV0_DECAY_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_SUSTAIN] * DIV_1200);
4105                 if (vp->sample->modenv_keyf[EG_GUS_RELEASE1])
4106                         vp->mod_env.follow[ENV0_RELEASE1_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_RELEASE1] * DIV_1200);
4107                 if (vp->sample->modenv_keyf[EG_GUS_RELEASE2])
4108                         vp->mod_env.follow[ENV0_RELEASE2_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_RELEASE2] * DIV_1200);
4109                 if (vp->sample->modenv_keyf[EG_GUS_RELEASE3])
4110                         vp->mod_env.follow[ENV0_RELEASE3_STAGE] *= POW2(notesub * (double)vp->sample->modenv_keyf[EG_GUS_RELEASE3] * DIV_1200);
4111         }       
4112         /* envelope velocity-follow */
4113         if (vp->sample->modenv_velf[EG_GUS_ATTACK])
4114                 vp->mod_env.follow[ENV0_ATTACK_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_ATTACK] * DIV_1200);
4115         if (vp->sample->modenv_velf[EG_GUS_DECAY])
4116                 vp->mod_env.follow[ENV0_HOLD_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_DECAY] * DIV_1200);
4117         if (vp->sample->modenv_velf[EG_GUS_SUSTAIN])
4118                 vp->mod_env.follow[ENV0_DECAY_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_SUSTAIN] * DIV_1200);
4119         if (vp->sample->modenv_velf[EG_GUS_RELEASE1])
4120                 vp->mod_env.follow[ENV0_RELEASE1_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_RELEASE1] * DIV_1200);
4121         if (vp->sample->modenv_velf[EG_GUS_RELEASE2])
4122                 vp->mod_env.follow[ENV0_RELEASE2_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_RELEASE2] * DIV_1200);
4123         if (vp->sample->modenv_velf[EG_GUS_RELEASE3])
4124                 vp->mod_env.follow[ENV0_RELEASE3_STAGE] *= POW2(mod_velsub * (double)vp->sample->modenv_velf[EG_GUS_RELEASE3] * DIV_1200);
4125         /* NRPN */
4126         if(add_param[EG_GUS_ATTACK]){
4127                 FLOAT_T sub_ofs_div_cr = fabs(0.0 - vp->mod_env.offset[ENV0_ATTACK_STAGE]) * div_playmode_rate * 1000.0;
4128                 FLOAT_T time_ms = sub_ofs_div_cr / vp->mod_env.rate[ENV0_ATTACK_STAGE];
4129                 time_ms = calc_nrpn_param(time_ms, (double)add_param[EG_GUS_ATTACK] * env_attack_calc, nrpn_env_attack_mode);
4130                 if(time_ms <= 0.0) 
4131                         vp->mod_env.rate[ENV0_ATTACK_STAGE] = ENV0_OFFSET_MAX;
4132                 vp->mod_env.rate[ENV0_ATTACK_STAGE] = sub_ofs_div_cr / time_ms;
4133         }
4134         if(add_param[EG_GUS_DECAY]){
4135                 FLOAT_T sub_ofs_div_cr = fabs(vp->mod_env.offset[ENV0_ATTACK_STAGE] - vp->mod_env.offset[ENV0_HOLD_STAGE]) * div_playmode_rate * 1000.0;
4136                 FLOAT_T time_ms = sub_ofs_div_cr / vp->mod_env.rate[ENV0_HOLD_STAGE];
4137                 time_ms *= lookup_nrpn_param(64.0 + (double)add_param[EG_GUS_DECAY] * env_decay_calc, nrpn_env_decay_mode);
4138                 if(time_ms < 5.0) time_ms = 5.0;
4139                 vp->mod_env.rate[ENV0_HOLD_STAGE] = sub_ofs_div_cr / time_ms;
4140         }
4141         if(add_param[EG_GUS_SUSTAIN]){
4142                 FLOAT_T sub_ofs_div_cr = fabs(vp->mod_env.offset[ENV0_HOLD_STAGE] - vp->mod_env.offset[ENV0_DECAY_STAGE]) * div_playmode_rate * 1000.0;
4143                 FLOAT_T time_ms = sub_ofs_div_cr / vp->mod_env.rate[ENV0_DECAY_STAGE];
4144                 time_ms *= lookup_nrpn_param(64.0 + (double)add_param[EG_GUS_SUSTAIN] * env_decay_calc, nrpn_env_decay_mode);
4145                 if(time_ms < 5.0) time_ms = 5.0;
4146                 vp->mod_env.rate[ENV0_DECAY_STAGE] = sub_ofs_div_cr / time_ms;
4147         }
4148         if(add_param[EG_GUS_RELEASE1]){
4149                 FLOAT_T sub_ofs_div_cr = fabs(ENV0_OFFSET_MAX - vp->mod_env.offset[ENV0_RELEASE1_STAGE]) * div_playmode_rate * 1000.0;
4150                 FLOAT_T time_ms = sub_ofs_div_cr / vp->mod_env.rate[ENV0_RELEASE1_STAGE];
4151                 time_ms = calc_nrpn_param(time_ms, (double)add_param[EG_GUS_RELEASE1] * env_release_calc, nrpn_env_release_mode);
4152                 if(time_ms < 5.0) time_ms = 5.0;
4153                 vp->mod_env.rate[ENV0_RELEASE1_STAGE] = sub_ofs_div_cr / time_ms;
4154         }
4155 }
4156
4157 static void set_amp_envelope_param(int v)
4158 {
4159         int i;
4160         Voice *vp = voice + v;
4161
4162         for(i = 0; i < ENV0_STAGE_LIST_MAX; i++){
4163                 if(i == ENV0_END_STAGE)
4164                         continue;               
4165                 if(i == ENV0_SUSTAIN_STAGE){
4166                         vp->amp_env.rate[i] = div_control_ratio;
4167                         vp->amp_env.offset[i] = 0;
4168                 }else if(i == ENV0_RELEASE4_STAGE){
4169                         vp->amp_env.rate[i] = (double)OFFSET_MAX * DIV_RELEASE4_TIME * div_playmode_rate;
4170                         vp->amp_env.offset[i] = 0;
4171                 }else if(i < ENV0_RELEASE1_STAGE){
4172                         vp->amp_env.rate[i] = (double)vp->sample->envelope_rate[i - 1] * div_control_ratio;
4173                         vp->amp_env.offset[i] = (double)vp->sample->envelope_offset[i - 1];
4174                 }else{
4175                         vp->amp_env.rate[i] = (double)vp->sample->envelope_rate[i - 2] * div_control_ratio;
4176                         vp->amp_env.offset[i] = (double)vp->sample->envelope_offset[i - 2];
4177                 }
4178         }
4179         vp->amp_env.curve[ENV0_ATTACK_STAGE] = LINEAR_CURVE;
4180         if(vp->sample->inst_type == INST_SF2){
4181                 for(i = ENV0_ATTACK_STAGE + 1; i < ENV0_STAGE_LIST_MAX; i++)
4182                         vp->amp_env.curve[i] = SF2_VOL_CURVE;
4183         }else switch(play_system_mode){
4184         case GS_SYSTEM_MODE:
4185                 for(i = ENV0_ATTACK_STAGE + 1; i < ENV0_STAGE_LIST_MAX; i++)
4186                         vp->amp_env.curve[i] = GS_VOL_CURVE;
4187                 break;
4188         case XG_SYSTEM_MODE:
4189                 for(i = ENV0_ATTACK_STAGE + 1; i < ENV0_STAGE_LIST_MAX; i++)
4190                         vp->amp_env.curve[i] = XG_VOL_CURVE;
4191                 break;
4192         case GM2_SYSTEM_MODE:
4193         case GM_SYSTEM_MODE:
4194         default:
4195                 for(i = ENV0_ATTACK_STAGE + 1; i < ENV0_STAGE_LIST_MAX; i++)
4196                         vp->amp_env.curve[i] = DEF_VOL_CURVE;
4197                 break;
4198         }
4199 }
4200
4201 static void set_mod_envelope_param(int v)
4202 {
4203         int i;
4204         Voice *vp = voice + v;
4205
4206         for(i = 0; i < ENV0_STAGE_LIST_MAX; i++){
4207                 if(i == ENV0_END_STAGE)
4208                         continue;
4209                 if(i == ENV0_SUSTAIN_STAGE){
4210                         vp->mod_env.rate[i] = div_control_ratio;
4211                         vp->mod_env.offset[i] = 0;
4212                 }else if(i == ENV0_RELEASE4_STAGE){
4213                         vp->mod_env.rate[i] = (double)OFFSET_MAX * DIV_RELEASE4_TIME * div_playmode_rate;
4214                         vp->mod_env.offset[i] = 0;
4215                 }else if(i < ENV0_RELEASE1_STAGE){
4216                         vp->mod_env.rate[i] = (double)vp->sample->modenv_rate[i - 1] * div_control_ratio;
4217                         vp->mod_env.offset[i] = (double)vp->sample->modenv_offset[i - 1];
4218                 }else{
4219                         vp->mod_env.rate[i] = (double)vp->sample->modenv_rate[i - 2] * div_control_ratio;
4220                         vp->mod_env.offset[i] = (double)vp->sample->modenv_offset[i - 2];
4221                 }
4222         }
4223         for(i = 0; i < ENV0_STAGE_LIST_MAX; i++){
4224                 if(i == ENV0_ATTACK_STAGE)
4225                         vp->mod_env.curve[i] = SF2_CONVEX;
4226                 else
4227                         vp->mod_env.curve[i] = SF2_CONCAVE;
4228         }
4229
4230 }
4231
4232 /* initialize amp/mod/pitch envelope */
4233 static void init_voice_envelope(int i)
4234 {
4235         Voice *vp = voice + i;
4236         int ch = vp->channel;
4237         int note = vp->note;
4238         int add_delay_cnt = vp->add_delay_cnt;
4239         
4240         /* initialize amp envelope */
4241         if(vp->sample->modes & MODES_ENVELOPE){         
4242                 init_envelope0(&vp->amp_env);
4243                 set_amp_envelope_param(i);
4244                 recompute_amp_envelope_follow(i, ch);
4245                 vp->amp_env.offdelay = vp->amp_env.delay = vp->sample->envelope_delay + add_delay_cnt;
4246                 vp->amp_env.offdelay += env_add_offdelay_count;
4247                 if(min_sustain_time == 1)
4248                         vp->amp_env.count[ENV0_SUSTAIN_STAGE] = 1; /* The sustain stage is ignored. */
4249                 else if(channel[ch].loop_timeout > 0 && channel[ch].loop_timeout * 1000 < min_sustain_time)
4250                         vp->amp_env.count[ENV0_SUSTAIN_STAGE] = channel[ch].loop_timeout * play_mode->rate; /* timeout (See also "#extension timeout" line in *.cfg file */
4251                 else if(min_sustain_time <= 0)
4252                         vp->amp_env.count[ENV0_SUSTAIN_STAGE] = 0;
4253                 else
4254                         vp->amp_env.count[ENV0_SUSTAIN_STAGE] = playmode_rate_ms * min_sustain_time;
4255                 apply_envelope0_param(&vp->amp_env);
4256         }else{  
4257                 init_envelope0(&vp->amp_env);
4258                 vp->amp_env.offdelay = vp->amp_env.delay = vp->sample->envelope_delay + add_delay_cnt;
4259                 vp->amp_env.volume = 1.0;
4260         }
4261         /* initialize modulation envelope */
4262         if (opt_modulation_envelope && vp->sample->modes & MODES_ENVELOPE){
4263                 init_envelope0(&vp->mod_env);   
4264                 set_mod_envelope_param(i);      
4265                 recompute_mod_envelope_follow(i, ch);
4266                 vp->mod_env.delay = vp->sample->modenv_delay;
4267                 vp->mod_env.offdelay = vp->sample->modenv_delay + env_add_offdelay_count;
4268                 apply_envelope0_param(&vp->mod_env);
4269         }else{
4270                 init_envelope0(&vp->mod_env);
4271                 vp->mod_env.delay = vp->sample->modenv_delay;
4272                 vp->mod_env.offdelay = vp->sample->modenv_delay + env_add_offdelay_count;
4273                 vp->mod_env.volume = 1.0;
4274         }
4275         /* initialize pitch envelope */
4276         if (opt_modulation_envelope && vp->sample->modes & MODES_ENVELOPE){
4277                 FLOAT_T ini_lv = vp->sample->pitch_envelope[0]; // cent init lv
4278                 FLOAT_T atk_lv = vp->sample->pitch_envelope[1]; // cent attack lv
4279                 FLOAT_T atk_tm = vp->sample->pitch_envelope[2]; // ms   attacl time
4280                 FLOAT_T dcy_lv = vp->sample->pitch_envelope[3]; // cent decay1 lv
4281                 FLOAT_T dcy_tm = vp->sample->pitch_envelope[4]; // ms   decay1 time
4282                 FLOAT_T sus_lv = vp->sample->pitch_envelope[5]; // cent decay2 lv
4283                 FLOAT_T sus_tm = vp->sample->pitch_envelope[6]; // ms   decay2 time
4284                 FLOAT_T rls_lv = vp->sample->pitch_envelope[7]; // cent release lv
4285                 FLOAT_T rls_tm = vp->sample->pitch_envelope[8]; // ms   release time
4286                 if(channel[ch].pit_env_level[0] != 0x40)
4287                         ini_lv += (double)(channel[ch].pit_env_level[0] - 64) * DIV_64 * 1280.0; // cent
4288                 if(channel[ch].pit_env_level[1] != 0x40)
4289                         atk_lv += (double)(channel[ch].pit_env_level[1] - 64) * DIV_64 * 1280.0; // cent
4290                 if(channel[ch].pit_env_level[2] != 0x40)
4291                         dcy_lv += (double)(channel[ch].pit_env_level[2] - 64) * DIV_64 * 1280.0; // cent
4292                 if(channel[ch].pit_env_level[3] != 0x40)
4293                         sus_lv += (double)(channel[ch].pit_env_level[3] - 64) * DIV_64 * 1280.0; // cent
4294                 if(channel[ch].pit_env_level[4] != 0x40)
4295                         rls_lv += (double)(channel[ch].pit_env_level[4] - 64) * DIV_64 * 1280.0; // cent
4296                 if(channel[ch].pit_env_time[0] != 0x40)
4297                         atk_tm *= POW2((double)(channel[ch].pit_env_time[0] - 64) * DIV_32); // mul 0.5~2.0
4298                 if(channel[ch].pit_env_time[1] != 0x40)
4299                         dcy_tm *= POW2((double)(channel[ch].pit_env_time[1] - 64) * DIV_32); // mul 0.5~2.0
4300                 if(channel[ch].pit_env_time[2] != 0x40)
4301                         sus_tm *= POW2((double)(channel[ch].pit_env_time[2] - 64) * DIV_32); // mul 0.5~2.0
4302                 if(channel[ch].pit_env_time[3] != 0x40)
4303                         rls_tm *= POW2((double)(channel[ch].pit_env_time[3] - 64) * DIV_32); // mul 0.5~2.0
4304                 init_envelope4(&vp->pit_env, 0, env_add_offdelay_count, 
4305                         ini_lv, 
4306                         atk_lv, atk_tm * playmode_rate_ms, 
4307                         dcy_lv, dcy_tm * playmode_rate_ms, 
4308                         sus_lv, sus_tm * playmode_rate_ms,  
4309                         rls_lv, rls_tm * playmode_rate_ms );
4310         }else{
4311                 init_envelope4(&vp->pit_env, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
4312         }
4313 }
4314
4315 // called mix.c mix_voice() , thread_mix.c mix_voice_thread()
4316 void update_voice(int i)
4317 {
4318         Voice *vp = voice + i;
4319
4320         // \93¯\8e\9e\8f\88\97\9d\82ª\95K\97v\82É\82È\82Á\82½\82ç\83r\83b\83g\83t\83\89\83O\95ª\8aò\82É\95Ï\8dX\82·\82é\89Â\94\\90«\82ª\82 \82é\82Ì\82Å \92è\90\94\82Í2^n\82É\82µ\82Ä\82¨\82­
4321         // playmidi.h /* update_voice options: */
4322         switch(vp->update_voice){
4323         case UPDATE_VOICE_FINISH_NOTE: // finish note
4324                 reset_envelope0_release(&vp->amp_env, ENV0_KEEP);
4325                 reset_envelope0_release(&vp->mod_env, ENV0_KEEP);
4326                 reset_envelope4_noteoff(&vp->pit_env);
4327 #ifdef INT_SYNTH
4328                 if(vp->sample->inst_type == INST_MMS)
4329                         noteoff_int_synth_mms(i);
4330                 else if(vp->sample->inst_type == INST_SCC)
4331                         noteoff_int_synth_scc(i);
4332 #endif
4333 #ifdef VOICE_EFFECT
4334                 noteoff_voice_effect(i);            /* voice effect */
4335 #endif
4336                 break;
4337         case UPDATE_VOICE_CUT_NOTE: // cut_note
4338                 reset_envelope0_release(&vp->amp_env, cut_short_rate);
4339                 break;
4340         case UPDATE_VOICE_CUT_NOTE2: // cut_note2
4341                 reset_envelope0_release(&vp->amp_env, cut_short_rate2);
4342                 break;          
4343         case UPDATE_VOICE_KILL_NOTE: // kill_note
4344                 reset_envelope0_release(&vp->amp_env, ramp_out_rate);
4345                 break;          
4346         }
4347         vp->update_voice = 0; // flag clear
4348 }
4349
4350 // called mix.c mix_voice() , thread_mix.c mix_voice_thread()
4351 void init_voice(int i)
4352 {
4353         Voice *vp = voice + i;
4354         int ch = vp->channel;
4355         
4356         vp->init_voice = 1; // init flag
4357         /* pan */
4358         vp->panned = (play_mode->encoding & PE_MONO) ? PANNED_CENTER : PANNED_MYSTERY;
4359         vp->pan_ctrl = 1; // pan update recompute_voice_amp()   
4360         init_voice_resample(i);
4361 #ifdef INT_SYNTH
4362         if(vp->sample->inst_type == INST_MMS)
4363                 init_int_synth_mms(i);
4364         else if(vp->sample->inst_type == INST_SCC)
4365                 init_int_synth_scc(i);
4366 #endif
4367         init_voice_portamento(i); /* portamento or legato */
4368         init_voice_envelope(i);   /* amp/mod/pitch envelope */
4369         init_voice_lfo(i);        /* lfo1,lfo2 */
4370         init_voice_filter(i);     /* resonant lowpass filter */
4371         init_voice_filter2(i);    /* resonant highpass filter */        
4372         init_voice_pitch(i);      /* pitch */
4373         init_voice_amp(i);        /* after init_resample_filter() */    
4374         recompute_voice_lfo(i);
4375         recompute_voice_filter(i); 
4376         recompute_voice_pitch(i); 
4377         recompute_voice_amp(i); 
4378         init_resample_filter(i);  /* resample filter , after voice recomp */
4379         recompute_resample_filter(i); /* after voice recomp */
4380         /* initialize volume envelope */
4381         init_envelope2(&vp->vol_env , vp->left_amp, vp->right_amp, vol_env_count);
4382         /* initialize mix envelope */
4383         apply_envelope_to_amp(i);
4384         if(opt_mix_envelope)
4385                 init_envelope2(&vp->mix_env , vp->left_mix, vp->right_mix, mix_env_count);  
4386 #ifdef VOICE_EFFECT
4387         init_voice_effect(i);       /* voice effect */
4388 #endif  
4389 }
4390
4391 ///r
4392 static void start_note(MidiEvent *e, int i, int vid, int cnt, int add_delay_cnt)
4393 {
4394         Voice *vp = voice + i;
4395         int ch = e->channel;
4396         int note = MIDI_EVENT_NOTE(e);
4397         int j;
4398
4399         /* status , control */
4400         vp->status = VOICE_ON;
4401         vp->channel = ch;
4402         vp->note = note;
4403         vp->velocity = e->b;
4404         vp->vid = vid;  
4405         vp->sostenuto = 0;
4406         vp->paf_ctrl = 0;
4407         vp->overlap_count = opt_overlap_voice_count;
4408         vp->channel_voice_count = opt_max_channel_voices;
4409         vp->mod_update_count = -1;
4410         vp->init_voice = 0; // flag clear
4411         vp->update_voice = 0; // flag clear
4412         vp->finish_voice = 0; // flag clear
4413         vp->add_delay_cnt = add_delay_cnt;
4414         /* for pitch ctrl */
4415         vp->prev_tuning = 0;
4416         vp->pitchfactor = 0;
4417         vp->orig_pitchfactor = 1.0;
4418         /* for resample */
4419         j = channel[ch].special_sample;  
4420         if(!j){
4421                 vp->reserve_offset = 0;
4422         }else{ // special_patch
4423                 if(!special_patch[j]){
4424                         vp->reserve_offset = 0;
4425                 }else{
4426                         vp->reserve_offset = (splen_t)special_patch[j]->sample_offset << FRACTION_BITS;
4427                         if(vp->sample->modes & MODES_LOOPING)  {
4428                                 if(vp->reserve_offset > vp->sample->loop_end)
4429                                         vp->reserve_offset = vp->sample->loop_start;
4430                         } else if(vp->reserve_offset > vp->sample->data_length){
4431                                 free_voice(i);
4432                                 return;
4433                         }
4434                 }  
4435         }
4436         /* update ctl */
4437         if(!prescanning_flag)
4438                 ctl_note_event(i);
4439 }
4440
4441
4442
4443 static void finish_note(int i)
4444 {
4445     if (voice[i].sample->modes & MODES_ENVELOPE)
4446     {
4447                 /* We need to get the envelope out of Sustain stage. */
4448                 /* Note that voice[i].envelope_stage < EG_GUS_RELEASE1 */
4449 //              voice[i].status = VOICE_OFF;            
4450 ///r
4451                 
4452                 if(voice[i].status & (VOICE_FREE | VOICE_DIE | VOICE_OFF))
4453                         return;
4454                 voice[i].status = VOICE_OFF;
4455                 voice[i].update_voice = UPDATE_VOICE_FINISH_NOTE ; // finish note
4456                 ctl_note_event(i);
4457         }
4458     else
4459     {
4460                 if(current_file_info->pcm_mode != PCM_MODE_NON)
4461                 {
4462                         free_voice(i);
4463                         ctl_note_event(i);
4464                 }
4465                 else
4466                 {
4467                         /* Set status to OFF so resample_voice() will let this voice out
4468                         of its loop, if any. In any case, this voice dies when it
4469                                 hits the end of its data (ofs>=data_length). */
4470                         if(voice[i].status != VOICE_OFF)
4471                         {
4472                         voice[i].status = VOICE_OFF;
4473                         ctl_note_event(i);
4474                         }
4475                 }
4476     }
4477 }
4478
4479
4480 static void set_envelope_time(int ch, int val, int stage)
4481 {
4482         val = val & 0x7F;
4483         switch(stage) {
4484         case EG_ATTACK: /* Attack */
4485                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Attack Time (CH:%d VALUE:%d)", ch, val);
4486                 break;
4487         case EG_DECAY: /* Decay */
4488                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Decay Time (CH:%d VALUE:%d)", ch, val);
4489                 break;
4490         case EG_RELEASE:        /* Release */
4491                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Release Time (CH:%d VALUE:%d)", ch, val);
4492                 break;
4493         default:
4494                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"? Time (CH:%d VALUE:%d)", ch, val);
4495         }
4496         channel[ch].envelope_rate[stage] = val;
4497 }
4498
4499
4500
4501 ///r
4502
4503 /*! note_on() (prescanning) */
4504 static void note_on_prescan(MidiEvent *ev)
4505 {
4506         int i, ch = ev->channel, note = MIDI_EVENT_NOTE(ev);
4507         int32 random_delay = 0;
4508
4509         if(ISDRUMCHANNEL(ch) &&
4510            channel[ch].drums[note] != NULL &&
4511            !get_rx_drum(channel[ch].drums[note], RX_NOTE_ON)) { /* Rx. Note On */
4512                 return;
4513         }
4514         if(channel[ch].note_limit_low > note ||
4515                 channel[ch].note_limit_high < note ||
4516                 channel[ch].vel_limit_low > ev->b ||
4517                 channel[ch].vel_limit_high < ev->b) {
4518                 return;
4519         }
4520
4521   //  if(!channel[ch].portamento && channel[ch].portamento_control != -1)
4522         {
4523                 int nv;
4524                 int vlist[32];
4525                 Voice *vp;
4526
4527                 nv = find_samples(ev, vlist);
4528
4529                 if((allocate_cache_size > 0) &&
4530                         ISDRUMCHANNEL(ch) ||
4531                         (!channel[ch].portamento && channel[ch].portamento_control != -1) ){
4532                         for(i = 0; i < nv; i++)
4533                         {
4534                                 vp = voice + vlist[i];
4535                                 start_note(ev, vlist[i], 0, nv - i - 1, random_delay);
4536                                 resamp_cache_refer_on(vp, ev->time);
4537                                 vp->status = VOICE_FREE;
4538                                 vp->temper_instant = 0;
4539                         }
4540                 }
4541         }
4542 }
4543
4544 static void note_on(MidiEvent *e)
4545 {
4546     int i, nv, v, ch = e->channel, note = MIDI_EVENT_NOTE(e);
4547     int vlist[32];
4548     int vid;
4549         int32 random_delay = 0;
4550         int porta_flg = 0;
4551         int dr = ISDRUMCHANNEL(ch);
4552                 
4553         ch = e->channel;
4554         note = MIDI_EVENT_NOTE(e);
4555         
4556         if(dr &&  channel[ch].drums[note] != NULL &&
4557            !get_rx_drum(channel[ch].drums[note], RX_NOTE_ON)) { /* Rx. Note On */
4558                 return;
4559         }
4560         if(channel[ch].note_limit_low > note ||
4561                 channel[ch].note_limit_high < note ||
4562                 channel[ch].vel_limit_low > e->b ||
4563                 channel[ch].vel_limit_high < e->b) {
4564                 return;
4565         }
4566         voice_control(e);
4567     if((nv = find_samples(e, vlist)) == 0)
4568         return;
4569         
4570         if(dr){
4571                 recompute_bank_parameter_drum(ch, note);        
4572         }else{
4573                 if(!channel[ch].program_flag) // PC\82ª\82È\82©\82Á\82½\8fê\8d\87(recompute_bank_param\82µ\82Ä\82È\82¢\8fê\8d\87
4574                         recompute_bank_parameter_tone(ch);
4575                 /* portamento , legato */
4576                 if(opt_portamento)
4577                         if(init_channel_portamento(e)) /* portamento , legato */
4578                                 return;
4579         }
4580
4581         if(! opt_realtime_playing && emu_delay_time > 0)
4582                 random_delay = calc_random_delay(ch, note) + calc_emu_delay(e);
4583         else
4584                 random_delay = calc_random_delay(ch, note);
4585         
4586     vid = new_vidq(e->channel, note);
4587     for(i = 0; i < nv; i++) {
4588                 v = vlist[i];
4589                 if(ISDRUMCHANNEL(ch) &&
4590                    channel[ch].drums[note] != NULL &&
4591                    channel[ch].drums[note]->pan_random){
4592                         channel[ch].drums[note]->drum_panning = int_rand(128);
4593                 }else if(channel[ch].pan_random)        {
4594                         channel[ch].panning = int_rand(128);
4595                         ctl_mode_event(CTLE_PANNING, 1, ch, channel[ch].panning);
4596                 }
4597                 start_note(e, v, vid, nv - i - 1, random_delay);
4598     }   
4599 }
4600 ///r
4601 /*! sostenuto is now implemented as an instant sustain */
4602 static void update_sostenuto_controls(int ch)
4603 {
4604   int uv = upper_voices, i;
4605
4606   if(ISDRUMCHANNEL(ch)) {return;}
4607
4608         for(i = 0; i < uv; i++)
4609                 if ((voice[i].status & VOICE_ON) && voice[i].channel == ch)
4610                 {
4611                         voice[i].sostenuto = channel[ch].sostenuto;
4612                         ctl_note_event(i);
4613                 }
4614
4615 }
4616 ///r
4617 /*! redamper / half damper effect for piano instruments */
4618 static void update_redamper_controls(int ch)
4619 {
4620   int uv = upper_voices, i;
4621   
4622   if(ISDRUMCHANNEL(ch) || channel[ch].damper_mode == 0 || channel[ch].sustain == 0) {return;}
4623
4624         for(i = 0; i < uv; i++)
4625                 if ((voice[i].status & (VOICE_OFF | VOICE_SUSTAINED)) && voice[i].channel == ch)
4626                 {
4627                         voice[i].status = VOICE_SUSTAINED;
4628                         reset_envelope0_damper(&voice[i].amp_env, channel[ch].sustain);
4629                         reset_envelope0_damper(&voice[i].mod_env, channel[ch].sustain);
4630                         ctl_note_event(i);
4631 #ifdef INT_SYNTH
4632                 if(voice[i].sample->inst_type == INST_MMS)
4633                         damper_int_synth_mms(i, channel[ch].sustain);
4634                 else if(voice[i].sample->inst_type == INST_SCC)
4635                         damper_int_synth_scc(i, channel[ch].sustain);
4636 #endif
4637
4638 #ifdef VOICE_EFFECT
4639                         damper_voice_effect(i, channel[ch].sustain);
4640 #endif
4641                 }
4642 }
4643 ///r
4644 static void note_off(MidiEvent *e)
4645 {
4646   int uv = upper_voices, i;
4647   int ch, note, vid;
4648   int elm = 0;
4649
4650   ch = e->channel;
4651   note = MIDI_EVENT_NOTE(e);
4652
4653   if(ISDRUMCHANNEL(ch))
4654   {
4655       int nbank, nprog;
4656
4657       nbank = channel[ch].bank;
4658       nprog = note;
4659       instrument_map(channel[ch].mapID, &nbank, &nprog);
4660       
4661       if (channel[ch].drums[nprog] != NULL){
4662                   if(!get_rx_drum(channel[ch].drums[nprog], RX_NOTE_OFF)){ // disable NOTE_OFF
4663                           return;
4664                   }else{
4665                           ToneBank *bank;
4666                           bank = drumset[nbank];
4667                           if(bank == NULL) bank = drumset[0];          
4668                           if (bank->tone[nprog][elm]){
4669                                   /* uh oh, this drum doesn't have an instrument loaded yet */
4670                                   if (bank->tone[nprog][elm]->instrument == NULL)
4671                                           return;
4672                                   /* this drum is not loaded for some reason (error occured?) */
4673                                   if (IS_MAGIC_INSTRUMENT(bank->tone[nprog][elm]->instrument))
4674                                           return;
4675                                   /* only disallow Note Off if the drum sample is not looped */
4676                                   //if (!(bank->tone[nprog][elm].instrument->sample->modes & MODES_LOOPING))
4677                                          // return;     /* Note Off is not allowed. */
4678                           }
4679                   }
4680           }
4681   }
4682   /* legato */
4683   if(opt_portamento){
4684           int tmp = note_off_legato(e); // -2:return -1:thru 0<=:change note
4685           if(tmp < -1)
4686                   return;
4687           else if(tmp >= 0)
4688                   note = tmp;
4689   }
4690
4691   if ((vid = last_vidq(ch, note)) == -1)
4692       return;
4693   for (i = 0; i < uv; i++)
4694   {       
4695       if(voice[i].status == VOICE_ON && voice[i].channel == ch && voice[i].note == note && voice[i].vid == vid)
4696       {
4697                   if(voice[i].sostenuto){
4698                           voice[i].status = VOICE_SUSTAINED;
4699                           ctl_note_event(i);
4700                   }else if(channel[ch].sustain){
4701                           voice[i].status = VOICE_SUSTAINED;
4702                           if(channel[ch].damper_mode){
4703                                 reset_envelope0_damper(&voice[i].amp_env, channel[ch].sustain);
4704                                 reset_envelope0_damper(&voice[i].mod_env, channel[ch].sustain);
4705                           }
4706                           ctl_note_event(i);
4707                   }else{
4708                           finish_note(i);
4709                   }
4710       }
4711   }
4712 }
4713
4714
4715 /* Process the All Notes Off event */
4716 static void all_notes_off(int c)
4717 {
4718   int i, uv = upper_voices;
4719   ctl->cmsg(CMSG_INFO, VERB_DEBUG, "All notes off on channel %d", c);
4720   for(i = 0; i < uv; i++)
4721     if (voice[i].status==VOICE_ON &&
4722         voice[i].channel==c)
4723       {
4724         if (channel[c].sustain)
4725           {
4726             voice[i].status=VOICE_SUSTAINED;
4727             ctl_note_event(i);
4728           }
4729         else
4730           finish_note(i);
4731       }
4732   for(i = 0; i < 128; i++)
4733       vidq_head[c * 128 + i] = vidq_tail[c * 128 + i] = 0;
4734 }
4735
4736 /* Process the All Sounds Off event */
4737 static void all_sounds_off(int c)
4738 {
4739   int i, uv = upper_voices;
4740   for(i = 0; i < uv; i++)
4741     if (voice[i].channel==c &&
4742         (voice[i].status & ~(VOICE_FREE | VOICE_DIE)))
4743       {
4744         kill_note(i);
4745       }
4746   for(i = 0; i < 128; i++)
4747       vidq_head[c * 128 + i] = vidq_tail[c * 128 + i] = 0;
4748 }
4749
4750 /*! adjust polyphonic key pressure (PAf, PAT) */
4751 static void adjust_pressure(MidiEvent *e)
4752 {
4753     int i, uv = upper_voices;
4754     int note, ch;
4755
4756     if(opt_channel_pressure)
4757     {
4758         ch = e->channel;
4759     note = MIDI_EVENT_NOTE(e);
4760         channel[ch].paf.val = e->b;
4761         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf (CH:%d NOTE:%d VAL:%d)", ch, note, channel[ch].paf.val);
4762     for(i = 0; i < uv; i++)
4763                 if(voice[i].status == VOICE_ON &&
4764                    voice[i].channel == ch &&
4765                    voice[i].note == note)
4766                 {
4767                         voice[i].paf_ctrl = 1;
4768                         //recompute_amp(i);
4769                         //apply_envelope_to_amp(i);
4770                         //recompute_freq(i);
4771                         //recompute_voice_filter(i);
4772                 }
4773         }
4774 }
4775
4776 /*! adjust channel pressure (channel aftertouch, CAf, CAT) */
4777 static void adjust_channel_pressure(MidiEvent *e)
4778 {
4779     if(opt_channel_pressure)
4780     {
4781         int i, uv = upper_voices;
4782         int ch;
4783
4784         ch = e->channel;
4785         channel[ch].caf.val = e->a;
4786         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf (CH:%d VAL:%d)", ch, channel[ch].caf.val);
4787         recompute_channel_lfo(ch);
4788         recompute_channel_amp(ch);
4789         recompute_channel_filter(ch);
4790         recompute_channel_pitch(ch);
4791           
4792         //for(i = 0; i < uv; i++)
4793         //{
4794         //    if(voice[i].status == VOICE_ON && voice[i].channel == ch)
4795         //    {
4796         //              recompute_amp(i);
4797         //              apply_envelope_to_amp(i);
4798         //              recompute_freq(i);
4799         //              recompute_voice_filter(i);
4800         //      }
4801         //}
4802     }
4803 }
4804
4805 static void adjust_panning(int c)
4806 {
4807     int i, uv = upper_voices;
4808         
4809         recompute_channel_amp(c);
4810         if(!adjust_panning_immediately)
4811                 return;
4812     for(i = 0; i < uv; i++) {
4813                 if ((voice[i].channel==c) &&
4814                         (voice[i].status & (VOICE_ON | VOICE_SUSTAINED))){
4815                         voice[i].pan_ctrl = 1;
4816                 }
4817     }
4818 }
4819
4820 void play_midi_setup_drums(int ch, int note)
4821 {       
4822     channel[ch].drums[note] = (struct DrumParts *)new_segment(&playmidi_pool, sizeof(struct DrumParts));
4823     reset_drum_controllers(channel[ch].drums, note);
4824         channel[ch].drum_effect_flag |= 0x2; // add note
4825 }
4826
4827 static void adjust_drum_panning(int ch, int note)
4828 {
4829  //   int i, uv = upper_voices;
4830
4831  //   for(i = 0; i < uv; i++) {
4832         //      if(voice[i].channel == ch &&
4833         //         voice[i].note == note &&
4834         //         (voice[i].status & (VOICE_ON | VOICE_SUSTAINED)))
4835         //      {
4836         //              recompute_amp(i);
4837         //              apply_envelope_to_amp(i);
4838         //      }
4839         //}
4840 }
4841
4842 static void drop_sustain(int c)
4843 {
4844   int i, uv = upper_voices;
4845   for(i = 0; i < uv; i++)
4846     if (voice[i].status == VOICE_SUSTAINED && voice[i].channel == c)
4847       finish_note(i);
4848 }
4849
4850 static void adjust_all_pitch(void)
4851 {
4852         int ch, i, uv = upper_voices;
4853         
4854         for (ch = 0; ch < MAX_CHANNELS; ch++){
4855                 recompute_channel_pitch(ch);
4856         }
4857         //for (i = 0; i < uv; i++)
4858         //      if (voice[i].status != VOICE_FREE)
4859         //              recompute_freq(i);
4860 }
4861
4862 static void adjust_pitch(int c)
4863 {
4864         recompute_channel_lfo(c);
4865         recompute_channel_amp(c);
4866         recompute_channel_filter(c);
4867         recompute_channel_pitch(c);
4868  // int i, uv = upper_voices;
4869  // for(i = 0; i < uv; i++)
4870  //   if (voice[i].status != VOICE_FREE && voice[i].channel == c)
4871         //recompute_freq(i);
4872 }
4873
4874 static void adjust_volume(int c)
4875 {
4876         recompute_channel_amp(c);
4877  // int i, uv = upper_voices;
4878  // for(i = 0; i < uv; i++)
4879  //   if (voice[i].channel == c &&
4880         //(voice[i].status & (VOICE_ON | VOICE_SUSTAINED)))
4881  //     {
4882         //recompute_amp(i);
4883         //apply_envelope_to_amp(i);
4884  //     }
4885 }
4886
4887 int get_reverb_level(int ch)
4888 {
4889         if (channel[ch].reverb_level == -1)
4890                 return (opt_reverb_control < 0) ? -opt_reverb_control & 0x7f : DEFAULT_REVERB_SEND_LEVEL;
4891         return channel[ch].reverb_level;
4892 }
4893
4894 static void set_reverb_level(int ch, int level)
4895 {
4896         if (level == -1) {
4897                 channel[ch].reverb_level = (opt_reverb_control < 0)     ? -opt_reverb_control & 0x7f : DEFAULT_REVERB_SEND_LEVEL;
4898         }else{
4899                 channel[ch].reverb_level = level;
4900         }
4901 }
4902
4903 int get_chorus_level(int ch)
4904 {
4905 #ifdef DISALLOW_DRUM_BENDS
4906     if(ISDRUMCHANNEL(ch))
4907         return 0; /* Not supported drum channel chorus */
4908 #endif
4909         if(channel[ch].chorus_level == -1)
4910                 return (opt_chorus_control<0) ? -opt_chorus_control : 0;
4911   if(opt_chorus_control == 1)
4912                 return channel[ch].chorus_level;
4913   return -opt_chorus_control;
4914 }
4915
4916
4917 void free_drum_effect(int ch)
4918 {
4919         int i, j;
4920         struct DrumPartEffect *de;
4921         if (channel[ch].drum_effect != NULL) {
4922                 for (i = 0; i < channel[ch].drum_effect_num; i++) {     
4923                         de = &(channel[ch].drum_effect[i]);     
4924
4925 #ifdef MULTI_THREAD_COMPUTE     
4926
4927                         for (j = 0; j < 4; j++) {
4928 #ifdef ALIGN_SIZE
4929                                 aligned_free(de->buf_ptr[j]);
4930 #else   
4931                                 safe_free(de->buf_ptr[j]);
4932 #endif
4933                                 de->buf_ptr[j] = NULL;
4934                         }
4935                         de->buf = NULL;
4936
4937 #else  // ! MULTI_THREAD_COMPUTE
4938                         
4939 #ifdef ALIGN_SIZE
4940                         aligned_free(de->buf);
4941 #else
4942                         safe_free(de->buf);
4943 #endif
4944                         de->buf = NULL; 
4945
4946 #endif // MULTI_THREAD_COMPUTE  
4947
4948                 }
4949                 safe_free(channel[ch].drum_effect);
4950                 channel[ch].drum_effect = NULL;
4951         }
4952         channel[ch].drum_effect_num = 0;
4953         channel[ch].drum_effect_flag = 0;
4954 }
4955
4956 ///r
4957 static void make_drum_effect(int ch)
4958 {
4959         int i, j, note, num = 0, size;
4960         int8 note_table[128];
4961         struct DrumParts *drum;
4962         struct DrumPartEffect *de;
4963
4964         if (!opt_drum_effect) {return;}
4965         if (channel[ch].drums == NULL) {return;}
4966
4967         // init
4968         if(!(channel[ch].drum_effect_flag & 0x1)){ 
4969                 free_drum_effect(ch);
4970                 memset(note_table, 0, sizeof(int8) * 128);
4971                 for(i = 0; i < 128; i++) {
4972                         if ((drum = channel[ch].drums[i]) == NULL)
4973                                 continue;       
4974                         if (drum->reverb_level != -1 || drum->chorus_level != -1 || drum->delay_level != -1 
4975                                 || (opt_eq_control && drum->eq_xg.valid)) {
4976                                 note_table[num++] = i;
4977                         }
4978                 }
4979                 channel[ch].drum_effect = (struct DrumPartEffect *)safe_malloc(sizeof(struct DrumPartEffect) * 128); // 128=all ,  def: num
4980                 size = AUDIO_BUFFER_SIZE * 2 * sizeof(DATA_T);
4981
4982                 for(i = 0; i < num; i++) {
4983                         de = &(channel[ch].drum_effect[i]);
4984                         de->note = note_table[i];
4985                         drum = channel[ch].drums[de->note];
4986                         de->reverb_send = (int32)drum->reverb_level * (int32)get_reverb_level(ch) / 127;
4987         //      ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "dfx init reverb send: ch:%d note:%d : level:%d", ch, de->note, drum->reverb_level); // test
4988                         de->chorus_send = (int32)drum->chorus_level * (int32)channel[ch].chorus_level / 127;
4989                         de->delay_send = (int32)drum->delay_level * (int32)channel[ch].delay_level / 127;
4990                         de->eq_xg = &drum->eq_xg;               
4991 #ifdef MULTI_THREAD_COMPUTE     
4992                         for (j = 0; j < 4; j++) {
4993 #ifdef ALIGN_SIZE
4994                                 de->buf_ptr[j] = (DATA_T *)aligned_malloc(size, ALIGN_SIZE);
4995 #else   
4996                                 de->buf_ptr[j] = (DATA_T *)safe_malloc(size);
4997 #endif
4998                                 memset(de->buf_ptr[j], 0, size);
4999                         }
5000                         de->buf = de->buf_ptr[0];
5001 #else  // ! MULTI_THREAD_COMPUTE
5002 #ifdef ALIGN_SIZE
5003                         de->buf = (DATA_T *)aligned_malloc(size, ALIGN_SIZE);
5004 #else
5005                         de->buf = (DATA_T *)safe_malloc(size);
5006 #endif
5007                         memset(de->buf, 0, size);       
5008 #endif // MULTI_THREAD_COMPUTE  
5009                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Drum Effect : init note (CH:%d note:%d)", ch, de->note);
5010                 }
5011                 channel[ch].drum_effect_num = num;
5012                 channel[ch].drum_effect_flag = 0x1;
5013                 return;
5014         }       
5015
5016         // add note
5017         if (channel[ch].drum_effect_flag & 0x2) { 
5018                 memset(note_table, 0, sizeof(int8) * 128);              
5019                 for(i = 0; i < 128; i++) {
5020                         if ((drum = channel[ch].drums[i]) == NULL)
5021                                 continue;       
5022                         if (drum->reverb_level != -1 || drum->chorus_level != -1 || drum->delay_level != -1 || (opt_eq_control && drum->eq_xg.valid)) {
5023                                 int dup = 0;
5024                                 for (j = 0; j < channel[ch].drum_effect_num; j++) {
5025                                         de = &(channel[ch].drum_effect[j]);
5026                                         if(i == de->note){
5027                                                 dup = 1;
5028                                                 break;
5029                                         }
5030                                 }
5031                                 if(dup) continue;
5032                                 note_table[num++] = i;
5033                         }
5034                 }       
5035                 size = AUDIO_BUFFER_SIZE * 2 * sizeof(DATA_T);
5036                 for(i = 0; i < num; i++) {
5037                         int newnum = channel[ch].drum_effect_num + i;
5038                         if(newnum >= 128){
5039                                 ctl->cmsg(CMSG_INFO, VERB_NORMAL, "ERROR! Drum Effect : over 128 note (CH:%d)", ch);
5040                                 channel[ch].drum_effect_flag = 0; // reset
5041                                 make_drum_effect(ch); // reinit
5042                                 return;
5043                         }
5044                         de = &(channel[ch].drum_effect[newnum]);
5045                         de->note = note_table[i];
5046                         drum = channel[ch].drums[de->note];
5047                         de->reverb_send = (int32)drum->reverb_level * (int32)get_reverb_level(ch) / 127;
5048         //      ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "dfx add reverb send: ch:%d note:%d : level:%d", ch, de->note, drum->reverb_level); // test
5049                         de->chorus_send = (int32)drum->chorus_level * (int32)channel[ch].chorus_level / 127;
5050                         de->delay_send = (int32)drum->delay_level * (int32)channel[ch].delay_level / 127;
5051                         de->eq_xg = &drum->eq_xg;               
5052 #ifdef MULTI_THREAD_COMPUTE     
5053                         for (j = 0; j < 4; j++) {
5054 #ifdef ALIGN_SIZE
5055                                 de->buf_ptr[j] = (DATA_T *)aligned_malloc(size, ALIGN_SIZE);
5056 #else   
5057                                 de->buf_ptr[j] = (DATA_T *)safe_malloc(size);
5058 #endif
5059                                 memset(de->buf_ptr[j], 0, size);
5060                         }
5061                         de->buf = de->buf_ptr[0];
5062 #else  // ! MULTI_THREAD_COMPUTE
5063 #ifdef ALIGN_SIZE
5064                         de->buf = (DATA_T *)aligned_malloc(size, ALIGN_SIZE);
5065 #else
5066                         de->buf = (DATA_T *)safe_malloc(size);
5067 #endif
5068                         memset(de->buf, 0, size);       
5069 #endif // MULTI_THREAD_COMPUTE                          
5070                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Drum Effect : add note (CH:%d note:%d)", ch, de->note);
5071                 }
5072                 channel[ch].drum_effect_num += num;
5073                 channel[ch].drum_effect_flag = 0x1;
5074                 return;
5075         }
5076
5077         // update effect
5078         if (channel[ch].drum_effect_flag & 0x4) {
5079                 if (! channel[ch].drum_effect_num) return;                      
5080                 for (i = 0; i < channel[ch].drum_effect_num; i++) {
5081                         de = &(channel[ch].drum_effect[i]);
5082                         drum = channel[ch].drums[de->note];
5083                         de->reverb_send = (int32)drum->reverb_level * (int32)get_reverb_level(ch) / 127;
5084         //      ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "dfx update reverb send: ch:%d note:%d : level:%d", ch, de->note, drum->reverb_level); // test
5085                         de->chorus_send = (int32)drum->chorus_level * (int32)channel[ch].chorus_level / 127;
5086                         de->delay_send = (int32)drum->delay_level * (int32)channel[ch].delay_level / 127;
5087                 }
5088                 channel[ch].drum_effect_flag = 0x1;
5089                 return;
5090         }
5091 }
5092
5093
5094 static void adjust_master_volume(void)
5095 {
5096   //int i, uv = upper_voices;
5097   adjust_amplification();
5098   //for(i = 0; i < uv; i++)
5099   //    if(voice[i].status & (VOICE_ON | VOICE_SUSTAINED))
5100   //    {
5101          // recompute_amp(i);
5102          // apply_envelope_to_amp(i);
5103   //    }
5104 }
5105
5106 int midi_drumpart_change(int ch, int isdrum)
5107 {
5108         if (IS_SET_CHANNELMASK(drumchannel_mask, ch))
5109                 return 0;
5110         if (isdrum) {
5111                 SET_CHANNELMASK(drumchannels, ch);
5112                 //SET_CHANNELMASK(current_file_info->drumchannels, ch);
5113         } else {
5114                 UNSET_CHANNELMASK(drumchannels, ch);
5115                 //UNSET_CHANNELMASK(current_file_info->drumchannels, ch);
5116         }
5117         return 1;
5118 }
5119
5120
5121 int16 sd_mfx_patch_param[13][9][128][33];
5122
5123 static void sd_mfx_patch_change(int ch, int map, int bank, int prog)
5124 {
5125         int i, num, mfx;
5126         if(channel[ch].sd_output_assign != 2)
5127                 return;
5128         switch (map) {
5129         case 80: num = 0; break; /* Special 1 */
5130         case 81: num = 1; break; /* Special 2 */
5131         case 87: num = 2; break; /* Usr Inst*/
5132         case 96: num = 3; break; /* Clsc Inst */
5133         case 97: num = 4; break; /* Cntn Inst */
5134         case 98: num = 5; break; /* Solo Inst */
5135         case 99: num = 6; break; /* Ehnc Inst */
5136         case 86: num = 7; break; /* Usr Drum */
5137         case 104: num = 8; break; /* Clsc Drum */
5138         case 105: num = 9; break; /* Cntn Drum */
5139         case 106: num = 10; break; /* Solo Drum */
5140         case 107: num = 11; break; /* Ehnc Drum */
5141         //case 121: num = 12; break; /* GM2 tone */ // test
5142         default: num = -1; break;
5143         }
5144         if(num < 0) // error
5145                 return;
5146         channel[ch].mfx_part_type = sd_mfx_patch_param[num][bank][prog][0];
5147         for(i = 0; i < 32; i++)
5148                 channel[ch].mfx_part_param[i] = sd_mfx_patch_param[num][bank][prog][i + 1];
5149         if(channel[ch].mfx_part_type <= 0){
5150                 ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 0);
5151                 return;
5152         }
5153         mfx = channel[ch].sd_output_mfx_select;
5154         realloc_mfx_effect_sd(&mfx_effect_sd[mfx], 3);
5155         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 1);
5156 }
5157
5158 void midi_program_change(int ch, int prog)
5159 {
5160         int dr = ISDRUMCHANNEL(ch);
5161         int newbank, b, p, map;
5162         int elm = 0;
5163         
5164 ///r
5165         channel[ch].program_flag = 1;
5166
5167         switch (play_system_mode) {
5168         case GS_SYSTEM_MODE:    /* GS */
5169 ///r 
5170                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog GS");
5171
5172                 if ((map = channel[ch].bank_lsb) == 0) {
5173                         map = channel[ch].tone_map0_number;
5174                 }
5175                 switch (map) {
5176                 case 0:         /* No change */
5177                         break;
5178                 case 1:
5179                         channel[ch].mapID = (dr) ? SC_55_DRUM_MAP : SC_55_TONE_MAP;
5180                         break;
5181                 case 2:
5182                         channel[ch].mapID = (dr) ? SC_88_DRUM_MAP : SC_88_TONE_MAP;
5183                         break;
5184                 case 3:
5185                         channel[ch].mapID = (dr) ? SC_88PRO_DRUM_MAP : SC_88PRO_TONE_MAP;
5186                         break;
5187                 case 4:
5188                         channel[ch].mapID = (dr) ? SC_8850_DRUM_MAP : SC_8850_TONE_MAP;
5189                         break;
5190                 default:
5191                         break;
5192                 }
5193                 newbank = channel[ch].bank_msb;
5194                 break;
5195 ///r
5196 /*
5197 //elion add
5198                 }
5199                 if (map == MODULE_SDMODE){
5200                         if (channel[ch].bank_msb >= 104 && channel[ch].bank_msb <= 107){
5201                                 midi_drumpart_change(ch, 1);
5202                                 channel[ch].mapID = SDXX_DRUM1_MAP + (channel[ch].bank_msb - 104);
5203                                 channel[ch].bank_msb = 0;
5204                                 newbank = channel[ch].bank_msb;
5205                         }else{
5206                                 if (channel[ch].bank_msb == 120) { // gm2 drum
5207                                         midi_drumpart_change(ch, 1);
5208                                         channel[ch].mapID = GM2_DRUM_MAP;
5209                                         channel[ch].bank_msb = 0x78;
5210                                         newbank = channel[ch].bank_lsb;
5211                                 }else if (channel[ch].bank_msb == 121) { // gm2 inst
5212                                         midi_drumpart_change(ch, 0);
5213                                         channel[ch].mapID = GM2_TONE_MAP;
5214                                         channel[ch].bank_msb = 0;
5215                                         newbank = channel[ch].bank_lsb;
5216                                 }else if (channel[ch].bank_msb >= 96 && channel[ch].bank_msb <= 99) {// sd map
5217                                         channel[ch].mapID = SDXX_TONE_MAP;
5218                                         midi_drumpart_change(ch, 0); 
5219                                         channel[ch].bank_msb = 0;
5220                                         newbank = channel[ch].bank_msb;
5221                                 }else if (channel[ch].bank_msb == 80 || channel[ch].bank_msb == 81 || channel[ch].bank_msb == 87){
5222                                         channel[ch].mapID = INST_NO_MAP; // spacial
5223                                 }else if (channel[ch].bank_msb == 127)
5224                                         channel[ch].mapID = INST_NO_MAP; // mt/cm
5225                                 else
5226                                         channel[ch].mapID = (dr) ? SC_8850_DRUM_MAP : SC_8850_TONE_MAP;
5227                         }
5228                         dr = ISDRUMCHANNEL(ch);
5229                         break;
5230                 }
5231                 break;
5232 */
5233         case XG_SYSTEM_MODE:    /* XG */
5234 ///r 
5235                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog XG");
5236                 switch (channel[ch].bank_msb) {
5237                 case 0:         /* Normal */
5238 #if 0
5239                         if (ch == 9 && channel[ch].bank_lsb == 127
5240                                         && channel[ch].mapID == XG_DRUM_KIT_MAP)
5241                                 /* FIXME: Why this part is drum?  Is this correct? */
5242                                 break;
5243 #endif
5244 /* Eric's explanation for the FIXME (March 2004):
5245  *
5246  * I don't have the original email from my archived inbox, but I found a
5247  * reply I made in my archived sent-mail from 1999.  A September 5th message
5248  * to Masanao Izumo is discussing a problem with a "reapxg.mid", a file which
5249  * I still have, and how it issues an MSB=0 with a program change on ch 9, 
5250  * thus turning it into a melodic channel.  The strange thing is, this doesn't
5251  * happen on XG hardware, nor on the XG softsynth.  It continues to play as a
5252  * normal drum.  The author of the midi file obviously intended it to be
5253  * drumset 16 too.  The original fix was to detect LSB == -1, then break so
5254  * as to not set it to a melodic channel.  I'm guessing that this somehow got
5255  * mutated into checking for 127 instead, and the current FIXME is related to
5256  * the original hack from Sept 1999.  The Sept 5th email discusses patches
5257  * being applied to version 2.5.1 to get XG drums to work properly, and a
5258  * Sept 7th email to someone else discusses the fixes being part of the
5259  * latest 2.6.0-beta3.  A September 23rd email to Masanao Izumo specifically
5260  * mentions the LSB == -1 hack (and reapxg.mid not playing "correctly"
5261  * anymore), as well as new changes in 2.6.0 that broke a lot of other XG
5262  * files (XG drum support was extremely buggy in 1999 and we were still trying
5263  * to figure out how to initialize things to reproduce hardware behavior).  An
5264  * October 5th email says that 2.5.1 was correct, 2.6.0 had very broken XG
5265  * drum changes, and 2.6.1 still has problems.  Further discussions ensued
5266  * over what was "correct": to follow the XG spec, or to reproduce
5267  * "features" / bugs in the hardware.  I can't find the rest of the
5268  * discussions, but I think it ended with us agreeing to just follow the spec
5269  * and not try to reproduce the hardware strangeness.  I don't know how the
5270  * current FIXME wound up the way it is now.  I'm still going to guess it is
5271  * related to the old reapxg.mid hack.
5272  *
5273  * Now that reset_midi() initializes channel[ch].bank_lsb to 0 instead of -1,
5274  * checking for LSB == -1 won't do anything anymore, so changing the above
5275  * FIXME to the original == -1 won't do any good.  It is best to just #if 0
5276  * it out and leave it here as a reminder that there is at least one XG
5277  * hardware / softsynth "bug" that is not reproduced by timidity at the
5278  * moment.
5279  *
5280  * If the current FIXME actually reproduces some other XG hadware bug that
5281  * I don't know about, then it may have a valid purpose.  I just don't know
5282  * what that purpose is at the moment.  Perhaps someone else does?  I still
5283  * have src going back to 2.10.4, and the FIXME comment was already there by
5284  * then.  I don't see any entries in the Changelog that could explain it
5285  * either.  If someone has src from 2.5.1 through 2.10.3 and wants to
5286  * investigate this further, go for it :)
5287  */
5288                         midi_drumpart_change(ch, 0);
5289                         channel[ch].mapID = XG_NORMAL_MAP;
5290                         dr = ISDRUMCHANNEL(ch);
5291                         break;
5292 ///r
5293                 case 126:       /* SFX kit & MU2000 sampling kit*/
5294                         if(113 <= prog && prog <= 116){ // MU2000 sampling kit
5295                                 midi_drumpart_change(ch, 1);
5296                                 channel[ch].mapID = XG_SAMPLING126_MAP;
5297                                 dr = ISDRUMCHANNEL(ch);
5298                         }else{ // SFX kit
5299                                 midi_drumpart_change(ch, 1);
5300                                 channel[ch].mapID = XG_SFX_KIT_MAP;
5301                                 dr = ISDRUMCHANNEL(ch);
5302                         }
5303                 case 127:       /* Drum kit */
5304                         midi_drumpart_change(ch, 1);
5305                         channel[ch].mapID = XG_DRUM_KIT_MAP;
5306                         dr = ISDRUMCHANNEL(ch);
5307                         break;
5308                 case 63:        /* FREE voice */
5309                         midi_drumpart_change(ch, 0);
5310                         channel[ch].mapID = XG_FREE_MAP;
5311                         dr = ISDRUMCHANNEL(ch);
5312                         break;
5313                 case 48:        /* MU100 exclusive voice */
5314                         midi_drumpart_change(ch, 0);
5315                         channel[ch].mapID = XG_MU100EXC_MAP;
5316                         dr = ISDRUMCHANNEL(ch);
5317                         break;
5318                 case 16:        /* MU2000 sampling voice */
5319                         midi_drumpart_change(ch, 0);
5320                         channel[ch].mapID = XG_SAMPLING16_MAP;
5321                         dr = ISDRUMCHANNEL(ch);
5322                         break;
5323                 case 32:        /* PCM-USER voice */
5324                         midi_drumpart_change(ch, 0);
5325                         channel[ch].mapID = XG_PCM_USER_MAP;
5326                         dr = ISDRUMCHANNEL(ch);
5327                         break;
5328                 case 64:        /* PCM-SFX voice */
5329                         midi_drumpart_change(ch, 0);
5330                         channel[ch].mapID = XG_PCM_SFX_MAP;
5331                         dr = ISDRUMCHANNEL(ch);
5332                         break;
5333                 case 80:        /* PCM-A voice */
5334                         midi_drumpart_change(ch, 0);
5335                         channel[ch].mapID = XG_PCM_A_MAP;
5336                         dr = ISDRUMCHANNEL(ch);
5337                         break;
5338                 case 96:        /* PCM-B voice */
5339                         midi_drumpart_change(ch, 0);
5340                         channel[ch].mapID = XG_PCM_B_MAP;
5341                         dr = ISDRUMCHANNEL(ch);
5342                         break;
5343                 case 33:        /* VA-USER voice */
5344                         midi_drumpart_change(ch, 0);
5345                         channel[ch].mapID = XG_VA_USER_MAP;
5346                         dr = ISDRUMCHANNEL(ch);
5347                         break;
5348                 case 65:        /* VA-SFX voice */
5349                         midi_drumpart_change(ch, 0);
5350                         channel[ch].mapID = XG_VA_SFX_MAP;
5351                         dr = ISDRUMCHANNEL(ch);
5352                         break;
5353                 case 81:        /* VA-A voice */
5354                         midi_drumpart_change(ch, 0);
5355                         channel[ch].mapID = XG_VA_A_MAP;
5356                         dr = ISDRUMCHANNEL(ch);
5357                         break;
5358                 case 97:        /* VA-B voice */
5359                         midi_drumpart_change(ch, 0);
5360                         channel[ch].mapID = XG_VA_B_MAP;
5361                         dr = ISDRUMCHANNEL(ch);
5362                         break;
5363                 case 34:        /* SG-USER voice */
5364                         midi_drumpart_change(ch, 0);
5365                         channel[ch].mapID = XG_SG_USER_MAP;
5366                         dr = ISDRUMCHANNEL(ch);
5367                         break;
5368                 case 66:        /* SG-SFX voice */
5369                         midi_drumpart_change(ch, 0);
5370                         channel[ch].mapID = XG_SG_SFX_MAP;
5371                         dr = ISDRUMCHANNEL(ch);
5372                         break;
5373                 case 82:        /* SG-A voice */
5374                         midi_drumpart_change(ch, 0);
5375                         channel[ch].mapID = XG_SG_A_MAP;
5376                         dr = ISDRUMCHANNEL(ch);
5377                         break;
5378                 case 98:        /* SG-B voice */
5379                         midi_drumpart_change(ch, 0);
5380                         channel[ch].mapID = XG_SG_B_MAP;
5381                         dr = ISDRUMCHANNEL(ch);
5382                         break;
5383                 case 35:        /* FM-USER voice */
5384                         midi_drumpart_change(ch, 0);
5385                         channel[ch].mapID = XG_FM_USER_MAP;
5386                         dr = ISDRUMCHANNEL(ch);
5387                         break;
5388                 case 67:        /* FM-SFX voice */
5389                         midi_drumpart_change(ch, 0);
5390                         channel[ch].mapID = XG_FM_SFX_MAP;
5391                         dr = ISDRUMCHANNEL(ch);
5392                         break;
5393                 case 83:        /* FM-A voice */
5394                         midi_drumpart_change(ch, 0);
5395                         channel[ch].mapID = XG_FM_A_MAP;
5396                         dr = ISDRUMCHANNEL(ch);
5397                         break;
5398                 case 99:        /* FM-B voice */
5399                         midi_drumpart_change(ch, 0);
5400                         channel[ch].mapID = XG_FM_B_MAP;
5401                         dr = ISDRUMCHANNEL(ch);
5402                         break;
5403                 default:
5404                         break;
5405                 }
5406                 newbank = channel[ch].bank_lsb;
5407                 break;
5408 ///r
5409         case SD_SYSTEM_MODE:    /* SD */
5410         case GM2_SYSTEM_MODE:   /* GM2 */
5411                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog GM2/SD");
5412                 switch (channel[ch].bank_msb) {
5413                 case 80:        /* Special 1 */
5414                         midi_drumpart_change(ch, 0);
5415                         channel[ch].mapID = SDXX_TONE80_MAP;
5416                         dr = ISDRUMCHANNEL(ch);
5417                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5418                         break;
5419                 case 81:        /* Special 2 */
5420                         midi_drumpart_change(ch, 0);
5421                         channel[ch].mapID = SDXX_TONE81_MAP;
5422                         dr = ISDRUMCHANNEL(ch);
5423                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5424                         break;
5425                 case 87:        /* Usr Inst */ /* SD-50 Preset Inst */
5426                         midi_drumpart_change(ch, 0);
5427                         channel[ch].mapID = SDXX_TONE87_MAP;
5428                         dr = ISDRUMCHANNEL(ch);
5429                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5430                         break;
5431                 case 89:        /* SD-50 Solo Inst */
5432                         midi_drumpart_change(ch, 0);
5433                         channel[ch].mapID = SDXX_TONE89_MAP;
5434                         dr = ISDRUMCHANNEL(ch);
5435                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5436                         break;
5437                 case 96:        /* Clsc Inst */
5438                         midi_drumpart_change(ch, 0);
5439                         channel[ch].mapID = SDXX_TONE96_MAP;
5440                         dr = ISDRUMCHANNEL(ch);
5441                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5442                         break;
5443                 case 97:        /* Cntn Inst */
5444                         midi_drumpart_change(ch, 0);
5445                         channel[ch].mapID = SDXX_TONE97_MAP;
5446                         dr = ISDRUMCHANNEL(ch);
5447                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5448                         break;
5449                 case 98:        /* Solo Inst */
5450                         midi_drumpart_change(ch, 0);
5451                         channel[ch].mapID = SDXX_TONE98_MAP;
5452                         dr = ISDRUMCHANNEL(ch);
5453                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5454                         break;
5455                 case 99:        /* Ehnc Inst */
5456                         midi_drumpart_change(ch, 0);
5457                         channel[ch].mapID = SDXX_TONE99_MAP;
5458                         dr = ISDRUMCHANNEL(ch);
5459                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5460                         break;
5461                 case 86:        /* Usr Drum */ /* SD-50 Preset Rhythm */
5462                         midi_drumpart_change(ch, 1);
5463                         channel[ch].mapID = SDXX_DRUM86_MAP;
5464                         dr = ISDRUMCHANNEL(ch);
5465                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5466                         break;
5467                 case 104:       /* Clsc Drum */
5468                         midi_drumpart_change(ch, 1);
5469                         channel[ch].mapID = SDXX_DRUM104_MAP;
5470                         dr = ISDRUMCHANNEL(ch);
5471                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5472                         break;
5473                 case 105:       /* Cntn Drum */
5474                         midi_drumpart_change(ch, 1);
5475                         channel[ch].mapID = SDXX_DRUM105_MAP;
5476                         dr = ISDRUMCHANNEL(ch);
5477                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5478                         break;
5479                 case 106:       /* Solo Drum */
5480                         midi_drumpart_change(ch, 1);
5481                         channel[ch].mapID = SDXX_DRUM106_MAP;
5482                         dr = ISDRUMCHANNEL(ch);
5483                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5484                         break;
5485                 case 107:       /* Ehnc Drum */
5486                         midi_drumpart_change(ch, 1);
5487                         channel[ch].mapID = SDXX_DRUM107_MAP;
5488                         dr = ISDRUMCHANNEL(ch);
5489                         sd_mfx_patch_change(ch, channel[ch].bank_msb, channel[ch].bank_lsb, prog);
5490                         break;
5491                 case 120:       /* GM2 Drum */
5492                         midi_drumpart_change(ch, 1);                    
5493                         if(play_system_mode == SD_SYSTEM_MODE || is_sd_module()){
5494                                 switch(channel[ch].gm2_inst){
5495                                 case 0: // classic set
5496                                         channel[ch].mapID = SDXX_DRUM104_MAP;
5497                                         break;
5498                                 default:
5499                                 case 1: // contemp set
5500                                         channel[ch].mapID = SDXX_DRUM105_MAP;
5501                                         break;
5502                                 case 2: // solo set
5503                                         channel[ch].mapID = SDXX_DRUM106_MAP;
5504                                         break;
5505                                 case 3: // enhance set
5506                                         channel[ch].mapID = SDXX_DRUM107_MAP;
5507                                         break;
5508                                 }
5509                         }else
5510                                 channel[ch].mapID = GM2_DRUM_MAP;
5511                         dr = ISDRUMCHANNEL(ch);
5512                         break;
5513                 case 121:       /* GM2 Inst */
5514                         midi_drumpart_change(ch, 0);
5515                         if(play_system_mode == SD_SYSTEM_MODE || is_sd_module()){
5516                                 switch(channel[ch].gm2_inst){
5517                                 case 0: // classic set
5518                                         channel[ch].mapID = SDXX_TONE96_MAP;
5519                                         break;
5520                                 default:
5521                                 case 1: // contemp set
5522                                         channel[ch].mapID = SDXX_TONE97_MAP;
5523                                         break;
5524                                 case 2: // solo set
5525                                         channel[ch].mapID = SDXX_TONE98_MAP;
5526                                         break;
5527                                 case 3: // enhance set
5528                                         channel[ch].mapID = SDXX_TONE99_MAP;
5529                                         break;
5530                                 }
5531                         }else
5532                                 channel[ch].mapID = GM2_TONE_MAP;
5533                         dr = ISDRUMCHANNEL(ch);
5534                         break;
5535                 default:
5536                         break;
5537                 }
5538                 newbank = channel[ch].bank_lsb;
5539                 break;
5540         case KG_SYSTEM_MODE:    /* AG */ /* NX */
5541                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog KG");
5542
5543                 switch (channel[ch].bank_msb) {
5544                 case 0:         /* GMa/y */
5545                         midi_drumpart_change(ch, 0);
5546                         if(opt_default_module == MODULE_AG10)
5547                                 channel[ch].mapID = NX5R_TONE0_MAP;
5548                         else if(opt_default_module == MODULE_05RW)
5549                                 channel[ch].mapID = K05RW_TONE0_MAP;
5550                         else if(opt_default_module == MODULE_NX5R)
5551                                 channel[ch].mapID = NX5R_TONE0_MAP;
5552                         dr = ISDRUMCHANNEL(ch);
5553                         break;
5554                 case 1:         /* r1 */
5555                         midi_drumpart_change(ch, 0);
5556                         channel[ch].mapID = NX5R_TONE1_MAP;
5557                         dr = ISDRUMCHANNEL(ch);
5558                         break;
5559                 case 2:         /* r1 */
5560                         midi_drumpart_change(ch, 0);
5561                         channel[ch].mapID = NX5R_TONE2_MAP;
5562                         dr = ISDRUMCHANNEL(ch);
5563                         break;
5564                 case 3:         /* r1 */
5565                         midi_drumpart_change(ch, 0);
5566                         channel[ch].mapID = NX5R_TONE3_MAP;
5567                         dr = ISDRUMCHANNEL(ch);
5568                         break;
5569                 case 4:         /* r1 */
5570                         midi_drumpart_change(ch, 0);
5571                         channel[ch].mapID = NX5R_TONE4_MAP;
5572                         dr = ISDRUMCHANNEL(ch);
5573                         break;
5574                 case 5:         /* r1 */
5575                         midi_drumpart_change(ch, 0);
5576                         channel[ch].mapID = NX5R_TONE5_MAP;
5577                         dr = ISDRUMCHANNEL(ch);
5578                         break;
5579                 case 6:         /* r1 */
5580                         midi_drumpart_change(ch, 0);
5581                         channel[ch].mapID = NX5R_TONE6_MAP;
5582                         dr = ISDRUMCHANNEL(ch);
5583                         break;
5584                 case 7:         /* r1 */
5585                         midi_drumpart_change(ch, 0);
5586                         channel[ch].mapID = NX5R_TONE7_MAP;
5587                         dr = ISDRUMCHANNEL(ch);
5588                         break;
5589                 case 8:         /* r1 */
5590                         midi_drumpart_change(ch, 0);
5591                         channel[ch].mapID = NX5R_TONE8_MAP;
5592                         dr = ISDRUMCHANNEL(ch);
5593                         break;
5594                 case 9:         /* r1 */
5595                         midi_drumpart_change(ch, 0);
5596                         channel[ch].mapID = NX5R_TONE9_MAP;
5597                         dr = ISDRUMCHANNEL(ch);
5598                         break;
5599                 case 10:                /* r1 */
5600                         midi_drumpart_change(ch, 0);
5601                         channel[ch].mapID = NX5R_TONE10_MAP;
5602                         dr = ISDRUMCHANNEL(ch);
5603                         break;
5604                 case 11:                /* r1 */
5605                         midi_drumpart_change(ch, 0);
5606                         channel[ch].mapID = NX5R_TONE11_MAP;
5607                         dr = ISDRUMCHANNEL(ch);
5608                         break;
5609                 case 16:                /* r1 */
5610                         midi_drumpart_change(ch, 0);
5611                         channel[ch].mapID = NX5R_TONE16_MAP;
5612                         dr = ISDRUMCHANNEL(ch);
5613                         break;
5614                 case 17:                /* r1 */
5615                         midi_drumpart_change(ch, 0);
5616                         channel[ch].mapID = NX5R_TONE17_MAP;
5617                         dr = ISDRUMCHANNEL(ch);
5618                         break;
5619                 case 18:                /* r1 */
5620                         midi_drumpart_change(ch, 0);
5621                         channel[ch].mapID = NX5R_TONE18_MAP;
5622                         dr = ISDRUMCHANNEL(ch);
5623                         break;
5624                 case 19:                /* r1 */
5625                         midi_drumpart_change(ch, 0);
5626                         channel[ch].mapID = NX5R_TONE19_MAP;
5627                         dr = ISDRUMCHANNEL(ch);
5628                         break;
5629                 case 24:                /* r1 */
5630                         midi_drumpart_change(ch, 0);
5631                         channel[ch].mapID = NX5R_TONE24_MAP;
5632                         dr = ISDRUMCHANNEL(ch);
5633                         break;
5634                 case 25:                /* r1 */
5635                         midi_drumpart_change(ch, 0);
5636                         channel[ch].mapID = NX5R_TONE25_MAP;
5637                         dr = ISDRUMCHANNEL(ch);
5638                         break;
5639                 case 26:                /* r1 */
5640                         midi_drumpart_change(ch, 0);
5641                         channel[ch].mapID = NX5R_TONE26_MAP;
5642                         dr = ISDRUMCHANNEL(ch);
5643                         break;
5644                 case 32:                /* r1 */
5645                         midi_drumpart_change(ch, 0);
5646                         channel[ch].mapID = NX5R_TONE32_MAP;
5647                         dr = ISDRUMCHANNEL(ch);
5648                         break;
5649                 case 33:                /* r1 */
5650                         midi_drumpart_change(ch, 0);
5651                         channel[ch].mapID = NX5R_TONE33_MAP;
5652                         dr = ISDRUMCHANNEL(ch);
5653                         break;
5654                 case 40:                /* r1 */
5655                         midi_drumpart_change(ch, 0);
5656                         channel[ch].mapID = NX5R_TONE40_MAP;
5657                         dr = ISDRUMCHANNEL(ch);
5658                         break;
5659                 case 56:                /* GMb */
5660                         midi_drumpart_change(ch, 0);
5661                         channel[ch].mapID = K05RW_TONE56_MAP;
5662                         dr = ISDRUMCHANNEL(ch);
5663                         break;
5664                 case 57:                /* GMb */
5665                         midi_drumpart_change(ch, 0);
5666                         channel[ch].mapID = K05RW_TONE57_MAP;
5667                         dr = ISDRUMCHANNEL(ch);
5668                         break;
5669                 case 61:        /* rDrm */
5670                         midi_drumpart_change(ch, 1);
5671                         channel[ch].mapID = NX5R_DRUM61_MAP;
5672                         dr = ISDRUMCHANNEL(ch);
5673                         break;
5674                 case 62:        /* kDrum */
5675                         midi_drumpart_change(ch, 1);
5676                         channel[ch].mapID = K05RW_DRUM62_MAP;
5677                         dr = ISDRUMCHANNEL(ch);
5678                         break;
5679                 case 64:        /* ySFX voice */
5680                         midi_drumpart_change(ch, 0);
5681                         channel[ch].mapID = NX5R_TONE64_MAP;
5682                         dr = ISDRUMCHANNEL(ch);
5683                         break;
5684                 case 80:                /* r1 */
5685                         midi_drumpart_change(ch, 0);
5686                         channel[ch].mapID = NX5R_TONE80_MAP;
5687                         dr = ISDRUMCHANNEL(ch);
5688                         break;
5689                 case 81:                /* r1 */
5690                         midi_drumpart_change(ch, 0);
5691                         channel[ch].mapID = NX5R_TONE81_MAP;
5692                         dr = ISDRUMCHANNEL(ch);
5693                         break;
5694                 case 82:                /* r1 */
5695                         midi_drumpart_change(ch, 0);
5696                         channel[ch].mapID = NX5R_TONE82_MAP;
5697                         dr = ISDRUMCHANNEL(ch);
5698                         break;
5699                 case 83:                /* r1 */
5700                         midi_drumpart_change(ch, 0);
5701                         channel[ch].mapID = NX5R_TONE83_MAP;
5702                         dr = ISDRUMCHANNEL(ch);
5703                         break;
5704                 case 88:                /* r1 */
5705                         midi_drumpart_change(ch, 0);
5706                         channel[ch].mapID = NX5R_TONE88_MAP;
5707                         dr = ISDRUMCHANNEL(ch);
5708                         break;
5709                 case 89:                /* r1 */
5710                         midi_drumpart_change(ch, 0);
5711                         channel[ch].mapID = NX5R_TONE89_MAP;
5712                         dr = ISDRUMCHANNEL(ch);
5713                         break;
5714                 case 90:                /* r1 */
5715                         midi_drumpart_change(ch, 0);
5716                         channel[ch].mapID = NX5R_TONE90_MAP;
5717                         dr = ISDRUMCHANNEL(ch);
5718                         break;
5719                 case 91:                /* r1 */
5720                         midi_drumpart_change(ch, 0);
5721                         channel[ch].mapID = NX5R_TONE91_MAP;
5722                         dr = ISDRUMCHANNEL(ch);
5723                         break;
5724                 case 125:               /* CM */
5725                         midi_drumpart_change(ch, 0);
5726                         channel[ch].mapID = NX5R_TONE125_MAP;
5727                         dr = ISDRUMCHANNEL(ch);
5728                         break;
5729                 case 126:       /* yDrm1 */
5730                         midi_drumpart_change(ch, 1);
5731                         channel[ch].mapID = NX5R_DRUM126_MAP;
5732                         dr = ISDRUMCHANNEL(ch);
5733                         break;
5734                 case 127:       /* yDrm2 */
5735                         midi_drumpart_change(ch, 1);
5736                         channel[ch].mapID = NX5R_DRUM127_MAP;
5737                         dr = ISDRUMCHANNEL(ch);
5738                         break;
5739                 default:
5740                         break;
5741                 }
5742                 newbank = channel[ch].bank_lsb;
5743                 break;
5744         case CM_SYSTEM_MODE:    /* MT32 CMxx */
5745                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog CM");
5746                 if(opt_default_module == MODULE_CM500D){ // CM500D 1-9GS 10-15LA 
5747                         if(ch < 10)
5748                                 channel[ch].mapID = (dr) ? SC_55_DRUM_MAP : SC_55_TONE_MAP;
5749                         else
5750                                 channel[ch].mapID = CM32L_TONE_MAP;
5751                 }else if(ch > 15){ // other CM
5752                         channel[ch].mapID = (dr) ? SC_88PRO_DRUM_MAP : SC_88PRO_TONE_MAP;
5753                 }else if((ch & (16 - 1)) == 9){
5754                         midi_drumpart_change(ch, 1);
5755                         channel[ch].mapID = CM32_DRUM_MAP;
5756         //              channel[ch].mapID = (opt_default_module == MODULE_MT32) ? MT32_DRUM_MAP : CM32_DRUM_MAP;
5757                         dr = ISDRUMCHANNEL(ch);
5758                 }else if((ch & (16 - 1)) < 9){
5759                         midi_drumpart_change(ch, 0);
5760                         channel[ch].mapID = CM32L_TONE_MAP;
5761         //              channel[ch].mapID = (opt_default_module == MODULE_MT32) ? MT32_TONE_MAP : CM32L_TONE_MAP;
5762                         dr = ISDRUMCHANNEL(ch);
5763                 }else if(prog < 64){
5764                         midi_drumpart_change(ch, 0);
5765                         channel[ch].mapID = CM32P_TONE_MAP;
5766                         dr = ISDRUMCHANNEL(ch);
5767                 }else switch (opt_default_module) {
5768                 case MODULE_CM64_SN01:
5769                         midi_drumpart_change(ch, 0);
5770                         channel[ch].mapID = SN01_TONE_MAP;
5771                         dr = ISDRUMCHANNEL(ch);
5772                 case MODULE_CM64_SN02:
5773                         if(prog < 71){
5774                                 midi_drumpart_change(ch, 1);
5775                                 channel[ch].mapID = SN02_DRUM_MAP;
5776                                 dr = ISDRUMCHANNEL(ch);
5777                         }else{
5778                                 midi_drumpart_change(ch, 0);
5779                                 channel[ch].mapID = SN02_TONE_MAP;
5780                                 dr = ISDRUMCHANNEL(ch);
5781                         }
5782                         break;
5783                 case MODULE_CM64_SN03:
5784                         midi_drumpart_change(ch, 0);
5785                         channel[ch].mapID = SN03_TONE_MAP;
5786                         dr = ISDRUMCHANNEL(ch);
5787                         break;
5788                 case MODULE_CM64_SN04:
5789                         midi_drumpart_change(ch, 0);
5790                         channel[ch].mapID = SN04_TONE_MAP;
5791                         dr = ISDRUMCHANNEL(ch);
5792                         break;
5793                 case MODULE_CM64_SN05:
5794                         midi_drumpart_change(ch, 0);
5795                         channel[ch].mapID = SN05_TONE_MAP;
5796                         dr = ISDRUMCHANNEL(ch);
5797                         break;
5798                 case MODULE_CM64_SN06:
5799                         midi_drumpart_change(ch, 0);
5800                         channel[ch].mapID = SN06_TONE_MAP;
5801                         dr = ISDRUMCHANNEL(ch);
5802                         break;
5803                 case MODULE_CM64_SN07:
5804                         midi_drumpart_change(ch, 0);
5805                         channel[ch].mapID = SN07_TONE_MAP;
5806                         dr = ISDRUMCHANNEL(ch);
5807                         break;
5808                 case MODULE_CM64_SN08:
5809                         midi_drumpart_change(ch, 0);
5810                         channel[ch].mapID = SN08_TONE_MAP;
5811                         dr = ISDRUMCHANNEL(ch);
5812                         break;
5813                 case MODULE_CM64_SN09:
5814                         midi_drumpart_change(ch, 0);
5815                         channel[ch].mapID = SN09_TONE_MAP;
5816                         dr = ISDRUMCHANNEL(ch);
5817                         break;
5818                 case MODULE_CM64_SN10:
5819                         midi_drumpart_change(ch, 1);
5820                         channel[ch].mapID = SN10_DRUM_MAP;
5821                         dr = ISDRUMCHANNEL(ch);
5822                         break;
5823                 case MODULE_CM64_SN11:
5824                         midi_drumpart_change(ch, 0);
5825                         channel[ch].mapID = SN11_TONE_MAP;
5826                         dr = ISDRUMCHANNEL(ch);
5827                         break;
5828                 case MODULE_CM64_SN12:
5829                         midi_drumpart_change(ch, 0);
5830                         channel[ch].mapID = SN12_TONE_MAP;
5831                         dr = ISDRUMCHANNEL(ch);
5832                         break;
5833                 case MODULE_CM64_SN13:
5834                         midi_drumpart_change(ch, 0);
5835                         channel[ch].mapID = SN13_TONE_MAP;
5836                         dr = ISDRUMCHANNEL(ch);
5837                         break;
5838                 case MODULE_CM64_SN14:
5839                         midi_drumpart_change(ch, 0);
5840                         channel[ch].mapID = SN14_TONE_MAP;
5841                         dr = ISDRUMCHANNEL(ch);
5842                         break;
5843                 case MODULE_CM64_SN15:
5844                         midi_drumpart_change(ch, 0);
5845                         channel[ch].mapID = SN15_TONE_MAP;
5846                         dr = ISDRUMCHANNEL(ch);
5847                         break;
5848                 default:
5849                         break;
5850                 }
5851                 newbank = channel[ch].bank_msb;
5852                 break;
5853         default:
5854                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Prog Def");
5855                 newbank = channel[ch].bank_msb;
5856                 break;
5857         }
5858         if (dr) {
5859                 channel[ch].bank = prog;        // newbank is ignored
5860                 channel[ch].program = prog;
5861                 if (drumset[prog] == NULL || drumset[prog]->alt == NULL)
5862                         channel[ch].altassign = drumset[0]->alt;
5863                 else
5864                         channel[ch].altassign = drumset[prog]->alt;
5865                 ctl_mode_event(CTLE_DRUMPART, 1, ch, 1);
5866         } else {
5867                 channel[ch].bank = (special_tonebank >= 0)
5868                                 ? special_tonebank : newbank;
5869                 channel[ch].program = (default_program[ch] == SPECIAL_PROGRAM)
5870                                 ? SPECIAL_PROGRAM : prog;
5871                 channel[ch].altassign = NULL;
5872                 ctl_mode_event(CTLE_DRUMPART, 1, ch, 0);
5873 ///r
5874                 recompute_bank_parameter_tone(ch);
5875                 if (opt_realtime_playing && (play_mode->flag & PF_PCM_STREAM)) {
5876                         int elm_max = 0;
5877                         b = channel[ch].bank, p = prog;
5878                         instrument_map(channel[ch].mapID, &b, &p);
5879                 //      for(elm = 0; elm < tonebank[b]->tone[p][elm].element_num + 1; elm++)
5880                 //      for(elm = 0; tonebank[b] && elm < tonebank[b]->tone[p][elm].element_num + 1; elm++)
5881                         for(elm = 0; elm <= elm_max; elm++)
5882                                 play_midi_load_instrument(0, b, p, elm, &elm_max); // change elm_max
5883                 }
5884         }
5885 }
5886
5887
5888 static int32 conv_pitch_control(int val)
5889 {
5890         if(val > 0x58) {val = 0x58;}
5891         else if(val < 0x28) {val = 0x28;}
5892         return (val - 0x40); // max +-24semitone
5893 }
5894
5895 static float conv_cutoff_control(int val)
5896 {
5897         return (double)(val - 0x40) * DIV_64 * 9600.0; // max +-9600cent
5898 }
5899
5900 static float conv_amp_control(int val)
5901 {
5902         return (double)(val - 0x40) * DIV_64; // max +-100%
5903 }
5904
5905 static float conv_lfo_rate(int val)
5906 {
5907 //      return (int16)(0.0318f * val * val + 0.6858f * val + 0.5f);
5908         return (double)(val - 0x40) * DIV_64 * 10.0; // max +-10Hz
5909 }
5910
5911 static float conv_lfo_amp_depth(int val)
5912 {
5913         return (double)val * DIV_128; // max 100%
5914 }
5915
5916 static float conv_lfo_pitch_depth(int val)
5917 {
5918 //      return (int16)(0.0318f * val * val + 0.6858f * val + 0.5f);
5919         return (double)val * DIV_127 * 600.0; // max 600cent
5920 }
5921
5922 static float conv_lfo_filter_depth(int val)
5923 {
5924 //      return (int16)((0.0318f * val * val + 0.6858f * val) * 4.0f + 0.5f);
5925         return (double)val * DIV_127 * 2400.0; // max 2400cent
5926 }
5927
5928 static float conv_modenv_depth(int val)
5929 {
5930         return (double)(val - 0x40) * DIV_64 * 9600.0; // max +-9600cent
5931 }
5932
5933 /*! process system exclusive sent from parse_sysex_event_multi(). */
5934 static void process_sysex_event(int ev, int ch, int val, int b)
5935 {
5936         int temp, msb, note;
5937
5938         if (ch >= MAX_CHANNELS)
5939                 return;
5940         if (ev == ME_SYSEX_MSB) {
5941                 channel[ch].sysex_msb_addr = b;
5942                 channel[ch].sysex_msb_val = val;
5943         } else if(ev == ME_SYSEX_GS_MSB) {
5944                 channel[ch].sysex_gs_msb_addr = b;
5945                 channel[ch].sysex_gs_msb_val = val;
5946         } else if(ev == ME_SYSEX_XG_MSB) {
5947                 channel[ch].sysex_xg_msb_addr = b;
5948                 channel[ch].sysex_xg_msb_val = val;
5949         } else if(ev == ME_SYSEX_SD_MSB) {
5950                 channel[ch].sysex_sd_msb_addr = b;
5951                 channel[ch].sysex_sd_msb_val = val;
5952         } else if(ev == ME_SYSEX_SD_HSB) {
5953                 channel[ch].sysex_sd_hsb_addr = b;
5954                 channel[ch].sysex_sd_hsb_val = val;
5955         } else if(ev == ME_SYSEX_LSB) { /* Universal system exclusive message */
5956                 msb = channel[ch].sysex_msb_addr;
5957                 note = channel[ch].sysex_msb_val;
5958                 channel[ch].sysex_msb_addr = channel[ch].sysex_msb_val = 0;
5959                 switch(b)
5960                 {
5961                 case 0x00:      /* CAf Pitch Control */
5962                         channel[ch].caf.pitch = conv_pitch_control(val);
5963                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Pitch Control (CH:%d %d semitones)", ch, channel[ch].caf.pitch);
5964                         break;
5965                 case 0x01:      /* CAf Filter Cutoff Control */
5966                         channel[ch].caf.cutoff = conv_cutoff_control(val);
5967                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].caf.cutoff);
5968                         break;
5969                 case 0x02:      /* CAf Amplitude Control */
5970                         channel[ch].caf.amp = conv_amp_control(val);
5971                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf Amplitude Control (CH:%d %.2f)", ch, channel[ch].caf.amp);
5972                         break;
5973                 case 0x03:      /* CAf LFO1 Rate Control */
5974                         channel[ch].caf.lfo1_rate = conv_lfo_rate(val);
5975                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].caf.lfo1_rate);
5976                         break;
5977                 case 0x04:      /* CAf LFO1 Pitch Depth */
5978                         channel[ch].caf.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
5979                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].caf.lfo1_pitch_depth); 
5980                         break;
5981                 case 0x05:      /* CAf LFO1 Filter Depth */
5982                         channel[ch].caf.lfo1_tvf_depth = conv_lfo_filter_depth(val);
5983                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].caf.lfo1_tvf_depth); 
5984                         break;
5985                 case 0x06:      /* CAf LFO1 Amplitude Depth */
5986                         channel[ch].caf.lfo1_tva_depth = conv_lfo_amp_depth(val);
5987                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].caf.lfo1_tva_depth); 
5988                         break;
5989                 case 0x07:      /* CAf LFO2 Rate Control */
5990                         channel[ch].caf.lfo2_rate = conv_lfo_rate(val);
5991                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Rate Control (CH:%d %.2f Hz)", ch, channel[ch].caf.lfo2_rate);
5992                         break;
5993                 case 0x08:      /* CAf LFO2 Pitch Depth */
5994                         channel[ch].caf.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
5995                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].caf.lfo2_pitch_depth); 
5996                         break;
5997                 case 0x09:      /* CAf LFO2 Filter Depth */
5998                         channel[ch].caf.lfo2_tvf_depth = conv_lfo_filter_depth(val);
5999                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].caf.lfo2_tvf_depth); 
6000                         break;
6001                 case 0x0A:      /* CAf LFO2 Amplitude Depth */
6002                         channel[ch].caf.lfo2_tva_depth = conv_lfo_amp_depth(val);
6003                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAf LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].caf.lfo2_tva_depth); 
6004                         break;
6005                 case 0x0B:      /* PAf Pitch Control */
6006                         channel[ch].paf.pitch = conv_pitch_control(val);
6007                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Pitch Control (CH:%d %d semitones)", ch, channel[ch].paf.pitch);
6008                         break;
6009                 case 0x0C:      /* PAf Filter Cutoff Control */
6010                         channel[ch].paf.cutoff = conv_cutoff_control(val);
6011                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].paf.cutoff);
6012                         break;
6013                 case 0x0D:      /* PAf Amplitude Control */
6014                         channel[ch].paf.amp = conv_amp_control(val);
6015                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf Amplitude Control (CH:%d %.2f)", ch, channel[ch].paf.amp);
6016                         break;
6017                 case 0x0E:      /* PAf LFO1 Rate Control */
6018                         channel[ch].paf.lfo1_rate = conv_lfo_rate(val);
6019                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].paf.lfo1_rate);
6020                         break;
6021                 case 0x0F:      /* PAf LFO1 Pitch Depth */
6022                         channel[ch].paf.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6023                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].paf.lfo1_pitch_depth); 
6024                         break;
6025                 case 0x10:      /* PAf LFO1 Filter Depth */
6026                         channel[ch].paf.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6027                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].paf.lfo1_tvf_depth); 
6028                         break;
6029                 case 0x11:      /* PAf LFO1 Amplitude Depth */
6030                         channel[ch].paf.lfo1_tva_depth = conv_lfo_amp_depth(val);
6031                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].paf.lfo1_tva_depth); 
6032                         break;
6033                 case 0x12:      /* PAf LFO2 Rate Control */
6034                         channel[ch].paf.lfo2_rate = conv_lfo_rate(val);
6035                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].paf.lfo2_rate);
6036                         break;
6037                 case 0x13:      /* PAf LFO2 Pitch Depth */
6038                         channel[ch].paf.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6039                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].paf.lfo2_pitch_depth); 
6040                         break;
6041                 case 0x14:      /* PAf LFO2 Filter Depth */
6042                         channel[ch].paf.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6043                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].paf.lfo2_tvf_depth); 
6044                         break;
6045                 case 0x15:      /* PAf LFO2 Amplitude Depth */
6046                         channel[ch].paf.lfo2_tva_depth = conv_lfo_amp_depth(val);
6047                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "PAf LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].paf.lfo2_tva_depth); 
6048                         break;
6049                 case 0x16:      /* MOD Pitch Control */
6050                         channel[ch].mod.pitch = conv_pitch_control(val);
6051                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Pitch Control (CH:%d %d semitones)", ch, channel[ch].mod.pitch);
6052                         break;
6053                 case 0x17:      /* MOD Filter Cutoff Control */
6054                         channel[ch].mod.cutoff = conv_cutoff_control(val);
6055                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].mod.cutoff);
6056                         break;
6057                 case 0x18:      /* MOD Amplitude Control */
6058                         channel[ch].mod.amp = conv_amp_control(val);
6059                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD Amplitude Control (CH:%d %.2f)", ch, channel[ch].mod.amp);
6060                         break;
6061                 case 0x19:      /* MOD LFO1 Rate Control */
6062                         channel[ch].mod.lfo1_rate = conv_lfo_rate(val);
6063                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].mod.lfo1_rate);
6064                         break;
6065                 case 0x1A:      /* MOD LFO1 Pitch Depth */
6066                         channel[ch].mod.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6067                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].mod.lfo1_pitch_depth); 
6068                         break;
6069                 case 0x1B:      /* MOD LFO1 Filter Depth */
6070                         channel[ch].mod.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6071                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].mod.lfo1_tvf_depth); 
6072                         break;
6073                 case 0x1C:      /* MOD LFO1 Amplitude Depth */
6074                         channel[ch].mod.lfo1_tva_depth = conv_lfo_amp_depth(val);
6075                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].mod.lfo1_tva_depth); 
6076                         break;
6077                 case 0x1D:      /* MOD LFO2 Rate Control */
6078                         channel[ch].mod.lfo2_rate = conv_lfo_rate(val);
6079                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].mod.lfo2_rate);
6080                         break;
6081                 case 0x1E:      /* MOD LFO2 Pitch Depth */
6082                         channel[ch].mod.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6083                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].mod.lfo2_pitch_depth); 
6084                         break;
6085                 case 0x1F:      /* MOD LFO2 Filter Depth */
6086                         channel[ch].mod.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6087                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].mod.lfo2_tvf_depth); 
6088                         break;
6089                 case 0x20:      /* MOD LFO2 Amplitude Depth */
6090                         channel[ch].mod.lfo2_tva_depth = conv_lfo_amp_depth(val);
6091                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "MOD LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].mod.lfo2_tva_depth); 
6092                         break;
6093                 case 0x21:      /* BEND Pitch Control */
6094                         channel[ch].bend.pitch = conv_pitch_control(val);
6095                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Pitch Control (CH:%d %d semitones)", ch, channel[ch].bend.pitch);
6096                         break;
6097                 case 0x22:      /* BEND Filter Cutoff Control */
6098                         channel[ch].bend.cutoff = conv_cutoff_control(val);
6099                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].bend.cutoff);
6100                         break;
6101                 case 0x23:      /* BEND Amplitude Control */
6102                         channel[ch].bend.amp = conv_amp_control(val);
6103                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND Amplitude Control (CH:%d %.2f)", ch, channel[ch].bend.amp);
6104                         break;
6105                 case 0x24:      /* BEND LFO1 Rate Control */
6106                         channel[ch].bend.lfo1_rate = conv_lfo_rate(val);
6107                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].bend.lfo1_rate);
6108                         break;
6109                 case 0x25:      /* BEND LFO1 Pitch Depth */
6110                         channel[ch].bend.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6111                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].bend.lfo1_pitch_depth); 
6112                         break;
6113                 case 0x26:      /* BEND LFO1 Filter Depth */
6114                         channel[ch].bend.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6115                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].bend.lfo1_tvf_depth); 
6116                         break;
6117                 case 0x27:      /* BEND LFO1 Amplitude Depth */
6118                         channel[ch].bend.lfo1_tva_depth = conv_lfo_amp_depth(val);
6119                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].bend.lfo1_tva_depth); 
6120                         break;
6121                 case 0x28:      /* BEND LFO2 Rate Control */
6122                         channel[ch].bend.lfo2_rate = conv_lfo_rate(val);
6123                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].bend.lfo2_rate);
6124                         break;
6125                 case 0x29:      /* BEND LFO2 Pitch Depth */
6126                         channel[ch].bend.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6127                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].bend.lfo2_pitch_depth); 
6128                         break;
6129                 case 0x2A:      /* BEND LFO2 Filter Depth */
6130                         channel[ch].bend.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6131                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].bend.lfo2_tvf_depth); 
6132                         break;
6133                 case 0x2B:      /* BEND LFO2 Amplitude Depth */
6134                         channel[ch].bend.lfo2_tva_depth = conv_lfo_amp_depth(val);
6135                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].bend.lfo2_tva_depth); 
6136                         break;
6137                 case 0x2C:      /* CC1 Pitch Control */
6138                         channel[ch].cc1.pitch = conv_pitch_control(val);
6139                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc1.pitch);
6140                         break;
6141                 case 0x2D:      /* CC1 Filter Cutoff Control */
6142                         channel[ch].cc1.cutoff = conv_cutoff_control(val);
6143                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc1.cutoff);
6144                         break;
6145                 case 0x2E:      /* CC1 Amplitude Control */
6146                         channel[ch].cc1.amp = conv_amp_control(val);
6147                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc1.amp);
6148                         break;
6149                 case 0x2F:      /* CC1 LFO1 Rate Control */
6150                         channel[ch].cc1.lfo1_rate = conv_lfo_rate(val);
6151                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc1.lfo1_rate);
6152                         break;
6153                 case 0x30:      /* CC1 LFO1 Pitch Depth */
6154                         channel[ch].cc1.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6155                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc1.lfo1_pitch_depth); 
6156                         break;
6157                 case 0x31:      /* CC1 LFO1 Filter Depth */
6158                         channel[ch].cc1.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6159                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc1.lfo1_tvf_depth); 
6160                         break;
6161                 case 0x32:      /* CC1 LFO1 Amplitude Depth */
6162                         channel[ch].cc1.lfo1_tva_depth = conv_lfo_amp_depth(val);
6163                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc1.lfo1_tva_depth); 
6164                         break;
6165                 case 0x33:      /* CC1 LFO2 Rate Control */
6166                         channel[ch].cc1.lfo2_rate = conv_lfo_rate(val);
6167                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc1.lfo2_rate);
6168                         break;
6169                 case 0x34:      /* CC1 LFO2 Pitch Depth */
6170                         channel[ch].cc1.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6171                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc1.lfo2_pitch_depth); 
6172                         break;
6173                 case 0x35:      /* CC1 LFO2 Filter Depth */
6174                         channel[ch].cc1.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6175                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc1.lfo2_tvf_depth); 
6176                         break;
6177                 case 0x36:      /* CC1 LFO2 Amplitude Depth */
6178                         channel[ch].cc1.lfo2_tva_depth = conv_lfo_amp_depth(val);
6179                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc1.lfo2_tva_depth); 
6180                         break;
6181                 case 0x37:      /* CC2 Pitch Control */
6182                         channel[ch].cc2.pitch = conv_pitch_control(val);
6183                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc2.pitch);
6184                         break;
6185                 case 0x38:      /* CC2 Filter Cutoff Control */
6186                         channel[ch].cc2.cutoff = conv_cutoff_control(val);
6187                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc2.cutoff);
6188                         break;
6189                 case 0x39:      /* CC2 Amplitude Control */
6190                         channel[ch].cc2.amp = conv_amp_control(val);
6191                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc2.amp);
6192                         break;
6193                 case 0x3A:      /* CC2 LFO1 Rate Control */
6194                         channel[ch].cc2.lfo1_rate = conv_lfo_rate(val);
6195                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc2.lfo1_rate);
6196                         break;
6197                 case 0x3B:      /* CC2 LFO1 Pitch Depth */
6198                         channel[ch].cc2.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6199                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc2.lfo1_pitch_depth); 
6200                         break;
6201                 case 0x3C:      /* CC2 LFO1 Filter Depth */
6202                         channel[ch].cc2.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6203                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc2.lfo1_tvf_depth); 
6204                         break;
6205                 case 0x3D:      /* CC2 LFO1 Amplitude Depth */
6206                         channel[ch].cc2.lfo1_tva_depth = conv_lfo_amp_depth(val);
6207                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc2.lfo1_tva_depth); 
6208                         break;
6209                 case 0x3E:      /* CC2 LFO2 Rate Control */
6210                         channel[ch].cc2.lfo2_rate = conv_lfo_rate(val);
6211                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc2.lfo2_rate);
6212                         break;
6213                 case 0x3F:      /* CC2 LFO2 Pitch Depth */
6214                         channel[ch].cc2.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6215                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc2.lfo2_pitch_depth); 
6216                         break;
6217                 case 0x40:      /* CC2 LFO2 Filter Depth */
6218                         channel[ch].cc2.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6219                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc2.lfo2_tvf_depth); 
6220                         break;
6221                 case 0x41:      /* CC2 LFO2 Amplitude Depth */
6222                         channel[ch].cc2.lfo2_tva_depth = conv_lfo_amp_depth(val);
6223                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc2.lfo2_tva_depth); 
6224                         break;
6225                 case 0x42:      /* Note Limit Low */
6226                         channel[ch].note_limit_low = val;
6227                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Note Limit Low (CH:%d VAL:%d)", ch, val); 
6228                         break;
6229                 case 0x43:      /* Note Limit High */
6230                         channel[ch].note_limit_high = val;
6231                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Note Limit High (CH:%d VAL:%d)", ch, val); 
6232                         break;
6233                 case 0x44:      /* Velocity Limit Low */
6234                         channel[ch].vel_limit_low = val;
6235                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Velocity Limit Low (CH:%d VAL:%d)", ch, val); 
6236                         break;
6237                 case 0x45:      /* Velocity Limit High */
6238                         channel[ch].vel_limit_high = val;
6239                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Velocity Limit High (CH:%d VAL:%d)", ch, val); 
6240                         break;
6241                 case 0x46:      /* Rx. Note Off */
6242                         if (channel[ch].drums[note] == NULL)
6243                                 play_midi_setup_drums(ch, note);
6244                         set_rx_drum(channel[ch].drums[note], RX_NOTE_OFF, val);
6245                         channel[ch].drums[note]->rx_note_off = 1;
6246                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
6247                                 "Drum Instrument Rx. Note Off (CH:%d NOTE:%d VAL:%d)",
6248                                 ch, note, val);
6249                         break;
6250                 case 0x47:      /* Rx. Note On */
6251                         if (channel[ch].drums[note] == NULL)
6252                                 play_midi_setup_drums(ch, note);
6253                         set_rx_drum(channel[ch].drums[note], RX_NOTE_ON, val);
6254                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
6255                                 "Drum Instrument Rx. Note On (CH:%d NOTE:%d VAL:%d)",
6256                                 ch, note, val);
6257                         break;
6258                 case 0x48:      /* Rx. Pitch Bend */
6259                         set_rx(ch, RX_PITCH_BEND, val);
6260                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Pitch Bend (CH:%d VAL:%d)", ch, val); 
6261                         break;
6262                 case 0x49:      /* Rx. Channel Pressure */
6263                         set_rx(ch, RX_CH_PRESSURE, val);
6264                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Channel Pressure (CH:%d VAL:%d)", ch, val); 
6265                         break;
6266                 case 0x4A:      /* Rx. Program Change */
6267                         set_rx(ch, RX_PROGRAM_CHANGE, val);
6268                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Program Change (CH:%d VAL:%d)", ch, val); 
6269                         break;
6270                 case 0x4B:      /* Rx. Control Change */
6271                         set_rx(ch, RX_CONTROL_CHANGE, val);
6272                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Control Change (CH:%d VAL:%d)", ch, val); 
6273                         break;
6274                 case 0x4C:      /* Rx. Poly Pressure */
6275                         set_rx(ch, RX_POLY_PRESSURE, val);
6276                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Poly Pressure (CH:%d VAL:%d)", ch, val); 
6277                         break;
6278                 case 0x4D:      /* Rx. Note Message */
6279                         set_rx(ch, RX_NOTE_MESSAGE, val);
6280                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Note Message (CH:%d VAL:%d)", ch, val); 
6281                         break;
6282                 case 0x4E:      /* Rx. RPN */
6283                         set_rx(ch, RX_RPN, val);
6284                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. RPN (CH:%d VAL:%d)", ch, val); 
6285                         break;
6286                 case 0x4F:      /* Rx. NRPN */
6287                         set_rx(ch, RX_NRPN, val);
6288                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. NRPN (CH:%d VAL:%d)", ch, val); 
6289                         break;
6290                 case 0x50:      /* Rx. Modulation */
6291                         set_rx(ch, RX_MODULATION, val);
6292                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Modulation (CH:%d VAL:%d)", ch, val); 
6293                         break;
6294                 case 0x51:      /* Rx. Volume */
6295                         set_rx(ch, RX_VOLUME, val);
6296                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Volume (CH:%d VAL:%d)", ch, val); 
6297                         break;
6298                 case 0x52:      /* Rx. Panpot */
6299                         set_rx(ch, RX_PANPOT, val);
6300                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Panpot (CH:%d VAL:%d)", ch, val); 
6301                         break;
6302                 case 0x53:      /* Rx. Expression */
6303                         set_rx(ch, RX_EXPRESSION, val);
6304                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Expression (CH:%d VAL:%d)", ch, val); 
6305                         break;
6306                 case 0x54:      /* Rx. Hold1 */
6307                         set_rx(ch, RX_HOLD1, val);
6308                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Hold1 (CH:%d VAL:%d)", ch, val); 
6309                         break;
6310                 case 0x55:      /* Rx. Portamento */
6311                         set_rx(ch, RX_PORTAMENTO, val);
6312                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Portamento (CH:%d VAL:%d)", ch, val); 
6313                         break;
6314                 case 0x56:      /* Rx. Sostenuto */
6315                         set_rx(ch, RX_SOSTENUTO, val);
6316                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Sostenuto (CH:%d VAL:%d)", ch, val); 
6317                         break;
6318                 case 0x57:      /* Rx. Soft */
6319                         set_rx(ch, RX_SOFT, val);
6320                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Soft (CH:%d VAL:%d)", ch, val); 
6321                         break;
6322                 case 0x58:      /* Rx. Bank Select */
6323                         set_rx(ch, RX_BANK_SELECT, val);
6324                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Bank Select (CH:%d VAL:%d)", ch, val); 
6325                         break;
6326                 case 0x59:      /* Rx. Bank Select LSB */
6327                         set_rx(ch, RX_BANK_SELECT_LSB, val);
6328                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Rx. Bank Select LSB (CH:%d VAL:%d)", ch, val); 
6329                         break;
6330                 case 0x60:      /* Reverb Type (GM2) */
6331                         if (val > 8) {val = 8;}
6332                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type (%d)", val);
6333                         set_reverb_macro_gm2(val);
6334                         recompute_reverb_status_gs();
6335                         init_ch_reverb();
6336                         break;
6337                 case 0x61:      /* Chorus Type (GM2) */
6338                         if (val > 5) {val = 5;}
6339                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type (%d)", val);
6340                         set_chorus_macro_gm2(val);
6341                         recompute_chorus_status_gs();
6342                         init_ch_chorus();
6343                         break;
6344 ///r
6345                 case 0x62: /* Pitch EG Initial Level*/
6346                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Initial Level (CH:%d VAL:%d)", ch, val);
6347                         channel[ch].pit_env_level[0] = val;                     
6348                         break;
6349                 case 0x63:      /* Pitch EG Attack Level */
6350                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Attack Time (CH:%d VAL:%d)", ch, val);
6351                         channel[ch].pit_env_level[1] = val;     
6352                         break;
6353                 case 0x64:      /* Pitch EG Attack Time */
6354                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Attack Time (CH:%d VAL:%d)", ch, val);
6355                         channel[ch].pit_env_time[0] = val;                      
6356                     break;
6357                 case 0x65:      /* Pitch EG Decay Level */
6358                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Decay Time (CH:%d VAL:%d)", ch, val);
6359                         channel[ch].pit_env_level[2] = val;     
6360                         break;
6361                 case 0x66:      /* Pitch EG Decay Time */
6362                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Decay Time (CH:%d VAL:%d)", ch, val);
6363                         channel[ch].pit_env_time[1] = val;                      
6364                     break;
6365                 case 0x67:      /* Pitch EG Sustain Level */
6366                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Sustain Time (CH:%d VAL:%d)", ch, val);
6367                         channel[ch].pit_env_level[3] = val;     
6368                         break;
6369                 case 0x68:      /* Pitch EG Sustain Time */
6370                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Sustain Time (CH:%d VAL:%d)", ch, val);
6371                         channel[ch].pit_env_time[2] = val;                      
6372                     break;
6373                 case 0x69:      /* Pitch EG Release Level */
6374                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Release Level (CH:%d VAL:%d)", ch, val);
6375                         channel[ch].pit_env_level[4] = val;                     
6376                     break;
6377                 case 0x6A:      /* Pitch EG Release Time */
6378                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Pitch EG Release Time (CH:%d VAL:%d)", ch, val);
6379                         channel[ch].pit_env_time[3] = val;                      
6380                     break;      
6381                 case 0x6B:      /* Filter EG Depth */
6382                         channel[ch].modenv_depth = conv_modenv_depth(val);                      
6383                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Filter EG Depth (CH:%d VAL:%d)", ch, val - 0x40);
6384                     break;                              
6385                 case 0x6C:      /* GM2 Instrument Select */
6386                         if(ch == 0xFF){
6387                                 int i;
6388                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "GM2 Instrument Select (CH:all VAL:%d)", ch, val);
6389                                 for(i = 0; i < MAX_CHANNELS; i++)
6390                                         channel[i].gm2_inst = val;
6391                         }else{
6392                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "GM2 Instrument Select (CH:%d VAL:%d)", ch, val);
6393                                 channel[ch].gm2_inst = val;
6394                         }
6395                         break;
6396                 case 0x6D:      /* CC1 number */                
6397                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC1 number (CH:%d NUM:%d)", ch, val);
6398                         channel[ch].cc1.num = val;      
6399                     break;              
6400                 case 0x6E:      /* CC2 number */                
6401                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC2 number (CH:%d NUM:%d)", ch, val);
6402                         channel[ch].cc2.num = val;      
6403                     break;              
6404                 case 0x6F:      /* CC3 number */                
6405                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 number (CH:%d NUM:%d)", ch, val);
6406                         channel[ch].cc3.num = val;      
6407                     break;              
6408                 case 0x70:      /* CC4 number */                
6409                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 number (CH:%d NUM:%d)", ch, val);
6410                         channel[ch].cc4.num = val;      
6411                     break;
6412                         
6413                 case 0x80:      /* CC3 Pitch Control */
6414                         channel[ch].cc3.pitch = conv_pitch_control(val);
6415                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc3.pitch);
6416                         break;
6417                 case 0x81:      /* CC3 Filter Cutoff Control */
6418                         channel[ch].cc3.cutoff = conv_cutoff_control(val);
6419                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc3.cutoff);
6420                         break;
6421                 case 0x82:      /* CC3 Amplitude Control */
6422                         channel[ch].cc3.amp = conv_amp_control(val);
6423                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc3.amp);
6424                         break;
6425                 case 0x83:      /* CC3 LFO1 Rate Control */
6426                         channel[ch].cc3.lfo1_rate = conv_lfo_rate(val);
6427                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc3.lfo1_rate);
6428                         break;
6429                 case 0x84:      /* CC3 LFO1 Pitch Depth */
6430                         channel[ch].cc3.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6431                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc3.lfo1_pitch_depth); 
6432                         break;
6433                 case 0x85:      /* CC3 LFO1 Filter Depth */
6434                         channel[ch].cc3.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6435                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc3.lfo1_tvf_depth); 
6436                         break;
6437                 case 0x86:      /* CC3 LFO1 Amplitude Depth */
6438                         channel[ch].cc3.lfo1_tva_depth = conv_lfo_amp_depth(val);
6439                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc3.lfo1_tva_depth); 
6440                         break;
6441                 case 0x87:      /* CC3 LFO2 Rate Control */
6442                         channel[ch].cc3.lfo2_rate = conv_lfo_rate(val);
6443                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc3.lfo2_rate);
6444                         break;
6445                 case 0x88:      /* CC3 LFO2 Pitch Depth */
6446                         channel[ch].cc3.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6447                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc3.lfo2_pitch_depth); 
6448                         break;
6449                 case 0x89:      /* CC3 LFO2 Filter Depth */
6450                         channel[ch].cc3.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6451                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc3.lfo2_tvf_depth); 
6452                         break;
6453                 case 0x8A:      /* CC3 LFO2 Amplitude Depth */
6454                         channel[ch].cc3.lfo2_tva_depth = conv_lfo_amp_depth(val);
6455                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC3 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc3.lfo2_tva_depth); 
6456                         break;
6457
6458                 case 0x90:      /* CC4 Pitch Control */
6459                         channel[ch].cc4.pitch = conv_pitch_control(val);
6460                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 Pitch Control (CH:%d %d semitones)", ch, channel[ch].cc4.pitch);
6461                         break;
6462                 case 0x91:      /* CC4 Filter Cutoff Control */
6463                         channel[ch].cc4.cutoff = conv_cutoff_control(val);
6464                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 Filter Cutoff Control (CH:%d %d cents)", ch, channel[ch].cc4.cutoff);
6465                         break;
6466                 case 0x92:      /* CC4 Amplitude Control */
6467                         channel[ch].cc4.amp = conv_amp_control(val);
6468                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 Amplitude Control (CH:%d %.2f)", ch, channel[ch].cc4.amp);
6469                         break;
6470                 case 0x93:      /* CC4 LFO1 Rate Control */
6471                         channel[ch].cc4.lfo1_rate = conv_lfo_rate(val);
6472                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO1 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc4.lfo1_rate);
6473                         break;
6474                 case 0x94:      /* CC4 LFO1 Pitch Depth */
6475                         channel[ch].cc4.lfo1_pitch_depth = conv_lfo_pitch_depth(val);
6476                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO1 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc4.lfo1_pitch_depth); 
6477                         break;
6478                 case 0x95:      /* CC4 LFO1 Filter Depth */
6479                         channel[ch].cc4.lfo1_tvf_depth = conv_lfo_filter_depth(val);
6480                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO1 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc4.lfo1_tvf_depth); 
6481                         break;
6482                 case 0x96:      /* CC4 LFO1 Amplitude Depth */
6483                         channel[ch].cc4.lfo1_tva_depth = conv_lfo_amp_depth(val);
6484                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO1 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc4.lfo1_tva_depth); 
6485                         break;
6486                 case 0x97:      /* CC4 LFO2 Rate Control */
6487                         channel[ch].cc4.lfo2_rate = conv_lfo_rate(val);
6488                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO2 Rate Control (CH:%d %.1f Hz)", ch, channel[ch].cc4.lfo2_rate);
6489                         break;
6490                 case 0x98:      /* CC4 LFO2 Pitch Depth */
6491                         channel[ch].cc4.lfo2_pitch_depth = conv_lfo_pitch_depth(val);
6492                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO2 Pitch Depth (CH:%d %.2f cents)", ch, channel[ch].cc4.lfo2_pitch_depth); 
6493                         break;
6494                 case 0x99:      /* CC4 LFO2 Filter Depth */
6495                         channel[ch].cc4.lfo2_tvf_depth = conv_lfo_filter_depth(val);
6496                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO2 Filter Depth (CH:%d %.2f cents)", ch, channel[ch].cc4.lfo2_tvf_depth); 
6497                         break;
6498                 case 0x9A:      /* CC4 LFO2 Amplitude Depth */
6499                         channel[ch].cc4.lfo2_tva_depth = conv_lfo_amp_depth(val);
6500                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "CC4 LFO2 Amplitude Depth (CH:%d %.2f)", ch, channel[ch].cc4.lfo2_tva_depth); 
6501                         break;
6502                 default:
6503                         break;
6504                 }
6505                 return;
6506         } else if(ev == ME_SYSEX_GS_LSB) {      /* GS system exclusive message */
6507                 msb = channel[ch].sysex_gs_msb_addr;
6508                 note = channel[ch].sysex_gs_msb_val;
6509                 channel[ch].sysex_gs_msb_addr = channel[ch].sysex_gs_msb_val = 0;
6510                 switch(b)
6511                 {
6512                 case 0x00:      /* EQ ON/OFF */
6513                         if(!opt_eq_control) {break;}
6514                         if(channel[ch].eq_gs != val) {
6515                                 if(val) {
6516                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ ON (CH:%d)",ch);
6517                                 } else {
6518                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ OFF (CH:%d)",ch);
6519                                 }
6520                         }
6521                         channel[ch].eq_gs = val;
6522                         break;
6523                 case 0x01:      /* EQ LOW FREQ */
6524                         if(!opt_eq_control) {break;}
6525                         eq_status_gs.low_freq = val;
6526                         recompute_eq_status_gs();
6527                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ LOW FREQ (%d)",val);
6528                         break;
6529                 case 0x02:      /* EQ LOW GAIN */
6530                         if(!opt_eq_control) {break;}
6531                         eq_status_gs.low_gain = val;
6532                         recompute_eq_status_gs();
6533                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ LOW GAIN (%d dB)",val - 0x40);
6534                         break;
6535                 case 0x03:      /* EQ HIGH FREQ */
6536                         if(!opt_eq_control) {break;}
6537                         eq_status_gs.high_freq = val;
6538                         recompute_eq_status_gs();
6539                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ HIGH FREQ (%d)",val);
6540                         break;
6541                 case 0x04:      /* EQ HIGH GAIN */
6542                         if(!opt_eq_control) {break;}
6543                         eq_status_gs.high_gain = val;
6544                         recompute_eq_status_gs();
6545                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS EQ HIGH GAIN (%d dB)",val - 0x40);
6546                         break;
6547                 case 0x05:      /* Reverb Macro */
6548                         if (val > 7) {val = 7;}
6549                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Macro (%d)",val);
6550                         set_reverb_macro_gs(val);
6551                         recompute_reverb_status_gs();
6552                         init_ch_reverb();
6553                         break;
6554                 case 0x06:      /* Reverb Character */
6555                         if (val > 7) {val = 7;}
6556                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Character (%d)",val);
6557                         if (reverb_status_gs.character != val) {
6558                                 reverb_status_gs.character = val;
6559                                 recompute_reverb_status_gs();
6560                                 init_ch_reverb();
6561                         }
6562                         break;
6563                 case 0x07:      /* Reverb Pre-LPF */
6564                         if (val > 7) {val = 7;}
6565                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Pre-LPF (%d)",val);
6566                         if(reverb_status_gs.pre_lpf != val) {
6567                                 reverb_status_gs.pre_lpf = val;
6568                                 recompute_reverb_status_gs();
6569                         }
6570                         break;
6571                 case 0x08:      /* Reverb Level */
6572                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Level (%d)",val);
6573                         if(reverb_status_gs.level != val) {
6574                                 reverb_status_gs.level = val;
6575                                 recompute_reverb_status_gs();
6576                                 init_ch_reverb();
6577                         }
6578                         break;
6579                 case 0x09:      /* Reverb Time */
6580                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Time (%d)",val);
6581                         if(reverb_status_gs.time != val) {
6582                                 reverb_status_gs.time = val;
6583                                 recompute_reverb_status_gs();
6584                                 init_ch_reverb();
6585                         }
6586                         break;
6587                 case 0x0A:      /* Reverb Delay Feedback */
6588                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Delay Feedback (%d)",val);
6589                         if(reverb_status_gs.delay_feedback != val) {
6590                                 reverb_status_gs.delay_feedback = val;
6591                                 recompute_reverb_status_gs();
6592                                 init_ch_reverb();
6593                         }
6594                         break;
6595                 case 0x0C:      /* Reverb Predelay Time */
6596                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Predelay Time (%d)",val);
6597                         if(reverb_status_gs.pre_delay_time != val) {
6598                                 reverb_status_gs.pre_delay_time = val;
6599                                 recompute_reverb_status_gs();
6600                                 init_ch_reverb();
6601                         }
6602                         break;
6603                 case 0x0D:      /* Chorus Macro */
6604                         if (val > 7) {val = 7;}
6605                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Macro (%d)",val);
6606                         set_chorus_macro_gs(val);
6607                         recompute_chorus_status_gs();
6608                         init_ch_chorus();
6609                         break;
6610                 case 0x0E:      /* Chorus Pre-LPF */
6611                         if (val > 7) {val = 7;}
6612                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Pre-LPF (%d)",val);
6613                         if (chorus_status_gs.pre_lpf != val) {
6614                                 chorus_status_gs.pre_lpf = val;
6615                                 recompute_chorus_status_gs();
6616                         }
6617                         break;
6618                 case 0x0F:      /* Chorus Level */
6619                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Level (%d)",val);
6620                         if (chorus_status_gs.level != val) {
6621                                 chorus_status_gs.level = val;
6622                                 recompute_chorus_status_gs();
6623                                 init_ch_chorus();
6624                         }
6625                         break;
6626                 case 0x10:      /* Chorus Feedback */
6627                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Feedback (%d)",val);
6628                         if (chorus_status_gs.feedback != val) {
6629                                 chorus_status_gs.feedback = val;
6630                                 recompute_chorus_status_gs();
6631                                 init_ch_chorus();
6632                         }
6633                         break;
6634                 case 0x11:      /* Chorus Delay */
6635                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Delay (%d)",val);
6636                         if (chorus_status_gs.delay != val) {
6637                                 chorus_status_gs.delay = val;
6638                                 recompute_chorus_status_gs();
6639                                 init_ch_chorus();
6640                         }
6641                         break;
6642                 case 0x12:      /* Chorus Rate */
6643                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Rate (%d)",val);
6644                         if (chorus_status_gs.rate != val) {
6645                                 chorus_status_gs.rate = val;
6646                                 recompute_chorus_status_gs();
6647                                 init_ch_chorus();
6648                         }
6649                         break;
6650                 case 0x13:      /* Chorus Depth */
6651                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Depth (%d)",val);
6652                         if (chorus_status_gs.depth != val) {
6653                                 chorus_status_gs.depth = val;
6654                                 recompute_chorus_status_gs();
6655                                 init_ch_chorus();
6656                         }
6657                         break;
6658                 case 0x14:      /* Chorus Send Level to Reverb */
6659                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send Level to Reverb (%d)",val);
6660                         if (chorus_status_gs.send_reverb != val) {
6661                                 chorus_status_gs.send_reverb = val;
6662                                 recompute_chorus_status_gs();
6663                                 init_ch_chorus();
6664                         }
6665                         break;
6666                 case 0x15:      /* Chorus Send Level to Delay */
6667                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send Level to Delay (%d)",val);
6668                         if (chorus_status_gs.send_delay != val) {
6669                                 chorus_status_gs.send_delay = val;
6670                                 recompute_chorus_status_gs();
6671                                 init_ch_chorus();
6672                         }
6673                         break;
6674                 case 0x16:      /* Delay Macro */
6675                         if (val > 7) {val = 7;}
6676                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Macro (%d)",val);
6677                         set_delay_macro_gs(val);
6678                         recompute_delay_status_gs();
6679                         init_ch_delay();
6680                         break;
6681                 case 0x17:      /* Delay Pre-LPF */
6682                         if (val > 7) {val = 7;}
6683                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Pre-LPF (%d)",val);
6684                         val &= 0x7;
6685                         if (delay_status_gs.pre_lpf != val) {
6686                                 delay_status_gs.pre_lpf = val;
6687                                 recompute_delay_status_gs();
6688                         }
6689                         break;
6690                 case 0x18:      /* Delay Time Center */
6691                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Center (%d)",val);
6692                         if (delay_status_gs.time_c != val) {
6693                                 delay_status_gs.time_c = val;
6694                                 recompute_delay_status_gs();
6695                                 init_ch_delay();
6696                         }
6697                         break;
6698                 case 0x19:      /* Delay Time Ratio Left */
6699                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Ratio Left (%d)",val);
6700                         if (val == 0) {val = 1;}
6701                         if (delay_status_gs.time_l != val) {
6702                                 delay_status_gs.time_l = val;
6703                                 recompute_delay_status_gs();
6704                                 init_ch_delay();
6705                         }
6706                         break;
6707                 case 0x1A:      /* Delay Time Ratio Right */
6708                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Time Ratio Right (%d)",val);
6709                         if (val == 0) {val = 1;}
6710                         if (delay_status_gs.time_r != val) {
6711                                 delay_status_gs.time_r = val;
6712                                 recompute_delay_status_gs();
6713                                 init_ch_delay();
6714                         }
6715                         break;
6716                 case 0x1B:      /* Delay Level Center */
6717                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Center (%d)",val);
6718                         if (delay_status_gs.level_center != val) {
6719                                 delay_status_gs.level_center = val;
6720                                 recompute_delay_status_gs();
6721                                 init_ch_delay();
6722                         }
6723                         break;
6724                 case 0x1C:      /* Delay Level Left */
6725                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Left (%d)",val);
6726                         if (delay_status_gs.level_left != val) {
6727                                 delay_status_gs.level_left = val;
6728                                 recompute_delay_status_gs();
6729                                 init_ch_delay();
6730                         }
6731                         break;
6732                 case 0x1D:      /* Delay Level Right */
6733                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level Right (%d)",val);
6734                         if (delay_status_gs.level_right != val) {
6735                                 delay_status_gs.level_right = val;
6736                                 recompute_delay_status_gs();
6737                                 init_ch_delay();
6738                         }
6739                         break;
6740                 case 0x1E:      /* Delay Level */
6741                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Level (%d)",val);
6742                         if (delay_status_gs.level != val) {
6743                                 delay_status_gs.level = val;
6744                                 recompute_delay_status_gs();
6745                                 init_ch_delay();
6746                         }
6747                         break;
6748                 case 0x1F:      /* Delay Feedback */
6749                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Feedback (%d)",val);
6750                         if (delay_status_gs.feedback != val) {
6751                                 delay_status_gs.feedback = val;
6752                                 recompute_delay_status_gs();
6753                                 init_ch_delay();
6754                         }
6755                         break;
6756                 case 0x20:      /* Delay Send Level to Reverb */
6757                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send Level to Reverb (%d)",val);
6758                         if (delay_status_gs.send_reverb != val) {
6759                                 delay_status_gs.send_reverb = val;
6760                                 recompute_delay_status_gs();
6761                                 init_ch_delay();
6762                         }
6763                         break;
6764                 case 0x21:      /* Velocity Sense Depth */
6765                         channel[ch].velocity_sense_depth = val;
6766                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Velocity Sense Depth (CH:%d VAL:%d)",ch,val);
6767                         break;
6768                 case 0x22:      /* Velocity Sense Offset */
6769                         channel[ch].velocity_sense_offset = val;
6770                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Velocity Sense Offset (CH:%d VAL:%d)",ch,val);
6771                         break;
6772                 case 0x23:      /* Insertion Effect ON/OFF */
6773                         if(!opt_insertion_effect) {break;}
6774                         if(channel[ch].insertion_effect != val) {
6775                                 if(val) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS Insertion Effect ON (CH:%d)",ch);}
6776                                 else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"GS Insertion Effect OFF (CH:%d)",ch);}
6777                         }
6778                         channel[ch].insertion_effect = val;
6779                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, channel[ch].insertion_effect);
6780                         break;
6781                 case 0x24:      /* Assign Mode */
6782                         channel[ch].assign_mode = val;
6783                         if(val == 0) {
6784                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Single (CH:%d)",ch);
6785                         } else if(val == 1) {
6786                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Limited-Multi (CH:%d)",ch);
6787                         } else if(val == 2) {
6788                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Assign Mode: Full-Multi (CH:%d)",ch);
6789                         }
6790                         break;
6791                 case 0x25:      /* TONE MAP-0 NUMBER */
6792                         channel[ch].tone_map0_number = val;
6793                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tone Map-0 Number (CH:%d VAL:%d)",ch,val);
6794                         break;
6795                 case 0x26:      /* Pitch Offset Fine */
6796                         {
6797                                 if(val != 0x80)
6798                                         channel[ch].pitch_offset_fine = (FLOAT_T)((int)val - 0x80) * DIV_10;
6799                                 else
6800                                         channel[ch].pitch_offset_fine = 0.0;
6801                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Pitch Offset Fine (CH:%d %3fHz)",ch,channel[ch].pitch_offset_fine);
6802                         }
6803                         break;
6804                 case 0x27:      /* Insertion Effect Type MSB */
6805                         if(!opt_insertion_effect) {break;}
6806                         insertion_effect_gs.type_msb = val;
6807                         //temp = insertion_effect_gs.type;
6808                         //if(temp == insertion_effect_gs.type) {
6809                         //      recompute_insertion_effect_gs(1);
6810                         //} else {
6811                         //      realloc_insertion_effect_gs();
6812                         //}
6813                         break;
6814                 case 0x28:      /* Insertion Effect Type LSB */
6815                         if(!opt_insertion_effect) {break;}
6816                         temp = insertion_effect_gs.type;
6817                         insertion_effect_gs.type_lsb = val;
6818                         insertion_effect_gs.type = ((int32)insertion_effect_gs.type_msb << 8) | (int32)insertion_effect_gs.type_lsb;
6819                         if(temp == insertion_effect_gs.type) {
6820                                 recompute_insertion_effect_gs(1);
6821                         } else {
6822                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "GS Insertion Effect TYPE (%02X %02X)", 
6823                                         insertion_effect_gs.type_msb, insertion_effect_gs.type_lsb);
6824                                 realloc_insertion_effect_gs();
6825                         }
6826                         break;
6827                 case 0x29: /* Insertion Effect Parameter */
6828                 case 0x2A:
6829                 case 0x2B:
6830                 case 0x2C:
6831                 case 0x2D:
6832                 case 0x2E:
6833                 case 0x2F:
6834                 case 0x30:
6835                 case 0x31:
6836                 case 0x32:
6837                 case 0x33:
6838                 case 0x34:
6839                 case 0x35:
6840                 case 0x36:
6841                 case 0x37:
6842                 case 0x38:
6843                 case 0x39:
6844                 case 0x3A:
6845                 case 0x3B:
6846                 case 0x3C:
6847                         if(!opt_insertion_effect) {break;}
6848                         temp = b - 0x29;
6849                         if(val >= 0 && val <= 127){
6850                                 insertion_effect_gs.set_param[temp] = val;
6851                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Parameter %d (VAL:%d)", temp + 1, val);
6852                                 recompute_insertion_effect_gs(1);
6853                         }else{
6854                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "ERROR! GS Insertion Parameter %d (VAL:%d)", temp + 1, val);
6855                         }
6856                         break;
6857                 case 0x3D:
6858                         if(!opt_insertion_effect) {break;}
6859                         insertion_effect_gs.send_reverb = val;
6860                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Send Reverb Level (VAL:%d)",val);
6861                         recompute_insertion_effect_gs(1);
6862                         break;
6863                 case 0x3E:
6864                         if(!opt_insertion_effect) {break;}
6865                         insertion_effect_gs.send_chorus = val;
6866                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Send Chorus Level (VAL:%d)",val);
6867                         recompute_insertion_effect_gs(1);
6868                         break;
6869                 case 0x3F:
6870                         if(!opt_insertion_effect) {break;}
6871                         insertion_effect_gs.send_delay = val;
6872                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Send Delay Level (VAL:%d)",val);
6873                         recompute_insertion_effect_gs(1);
6874                         break;
6875                 case 0x40:
6876                         if(!opt_insertion_effect) {break;}
6877                         insertion_effect_gs.control_source1 = val;
6878                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Control Source 1 (VAL:%d)",val);
6879                         recompute_insertion_effect_gs(1);
6880                         break;
6881                 case 0x41:
6882                         if(!opt_insertion_effect) {break;}
6883                         insertion_effect_gs.control_depth1 = val;
6884                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Control Depth 1 (VAL:%d)",val);
6885                         recompute_insertion_effect_gs(1);
6886                         break;
6887                 case 0x42:
6888                         if(!opt_insertion_effect) {break;}
6889                         insertion_effect_gs.control_source2 = val;
6890                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Control Source 2 (VAL:%d)",val);
6891                         recompute_insertion_effect_gs(1);
6892                         break;
6893                 case 0x43:
6894                         if(!opt_insertion_effect) {break;}
6895                         insertion_effect_gs.control_depth2 = val;
6896                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion Control Depth 2 (VAL:%d)",val);
6897                         recompute_insertion_effect_gs(1);
6898                         break;
6899                 case 0x44:
6900                         if(!opt_insertion_effect) {break;}
6901                         insertion_effect_gs.send_eq_switch = val;
6902                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "GS Insertion EQ Switch (VAL:%d)",val);
6903                         recompute_insertion_effect_gs(1);
6904                         break;
6905                 case 0x45:      /* Rx. Channel */
6906                         reset_controllers(ch);
6907                         redraw_controllers(ch);
6908                         all_notes_off(ch);
6909                         if (val == 0x80)
6910                                 remove_channel_layer(ch);
6911                         else
6912                                 add_channel_layer(ch, val);
6913                         break;
6914                 case 0x46:      /* Channel Msg Rx Port */
6915                         reset_controllers(ch);
6916                         redraw_controllers(ch);
6917                         all_notes_off(ch);
6918                         channel[ch].port_select = val;
6919                         break;
6920                 case 0x47:      /* Play Note Number */
6921                         if (channel[ch].drums[note] == NULL)
6922                                 play_midi_setup_drums(ch, note);
6923                         channel[ch].drums[note]->play_note = val;
6924                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
6925                                 "Drum Instrument Play Note (CH:%d NOTE:%d VAL:%d)",
6926                                 ch, note, channel[ch].drums[note]->play_note);
6927                         break;
6928                 default:
6929                         break;
6930                 }
6931                 return;
6932         } else if(ev == ME_SYSEX_XG_LSB) {      /* XG system exclusive message */
6933                 msb = channel[ch].sysex_xg_msb_addr;
6934                 note = channel[ch].sysex_xg_msb_val;
6935 ///r
6936                 if (note == 2 && msb >= 0 && msb < 0x40) {      /* Effect 1 */
6937                         note = 0;       /* not use */
6938                         if(b >= 0x40){ /* variation effect */
6939                                 msb -= 1;       /* variation effect num start 1 , dim 0*/
6940                                 /* msb=0 variation 1 */ 
6941                                 /* msb=n variation n+1 */ 
6942                                 if(msb < 0 || msb >= XG_VARIATION_EFFECT_NUM){
6943                                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "ERROR! XG Variation Effect Number (%d)", msb);
6944                                         return;
6945                                 }
6946                         }
6947                         switch(b)
6948                         {
6949                         case 0x00:      /* Reverb Type MSB */
6950                                 reverb_status_xg.type_msb = val;
6951                                 //if (reverb_status_xg.type_msb != val) {
6952                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type MSB (%02X)", val);
6953                                 //      reverb_status_xg.type_msb = val;
6954                                 //      realloc_effect_xg(&reverb_status_xg);
6955                                 //}
6956                                 break;
6957                         case 0x01:      /* Reverb Type LSB */
6958                                 temp = reverb_status_xg.type;
6959                                 reverb_status_xg.type_lsb = val;        
6960                                 reverb_status_xg.type = ((int32)reverb_status_xg.type_msb << 8) | (int32)reverb_status_xg.type_lsb;                             
6961                                 if (temp == reverb_status_xg.type){
6962                                         recompute_effect_xg(&reverb_status_xg, 1);
6963                                 }else{
6964                                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type (%02X %02X)", 
6965                                                 reverb_status_xg.type_msb, reverb_status_xg.type_lsb);
6966                                         realloc_effect_xg(&reverb_status_xg);
6967                                 }
6968                                 //if (reverb_status_xg.type_msb = val || reverb_status_xg.type_lsb != val) {
6969                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Type LSB (%02X)", val);
6970                                 //      reverb_status_xg.type_lsb = val;
6971                                 //      realloc_effect_xg(&reverb_status_xg);
6972                                 //}
6973                                 break;
6974                         case 0x02:      /* Reverb Parameter 1 - 10 */
6975                         case 0x03:
6976                         case 0x04:
6977                         case 0x05:
6978                         case 0x06:
6979                         case 0x07:
6980                         case 0x08:
6981                         case 0x09:
6982                         case 0x0A:
6983                         case 0x0B:
6984                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Parameter %d (%d)", b - 0x02 + 1, val);
6985                                 if (reverb_status_xg.param_lsb[b - 0x02] != val) {
6986                                         reverb_status_xg.param_lsb[b - 0x02] = val;
6987                                         recompute_effect_xg(&reverb_status_xg, 1);
6988                                 }
6989                                 break;
6990                         case 0x0C:      /* Reverb Return */
6991         #if 1   /* XG specific reverb is not currently implemented */
6992                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Return (%d)", val);
6993                                 if (reverb_status_xg.ret != val) {
6994                                         reverb_status_xg.ret = val;
6995                                         recompute_effect_xg(&reverb_status_xg, 1);
6996                                 }
6997         #else   /* use GS reverb instead */
6998                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Reverb Return (%d)", val);
6999                                 if (reverb_status_gs.level != val) {
7000                                         reverb_status_gs.level = val;
7001                                         recompute_reverb_status_gs();
7002                                         init_ch_reverb();
7003                                 }
7004         #endif
7005                                 break;
7006                         case 0x0D:      /* Reverb Pan */
7007                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Pan (%d)", val);
7008                                 if (reverb_status_xg.pan != val) {
7009                                         reverb_status_xg.pan = val;
7010                                         recompute_effect_xg(&reverb_status_xg, 1);
7011                                 }
7012                                 break;
7013                         case 0x10:      /* Reverb Parameter 11 - 16 */
7014                         case 0x11:
7015                         case 0x12:
7016                         case 0x13:
7017                         case 0x14:
7018                         case 0x15:
7019                                 temp = b - 0x10 + 10;
7020                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Reverb Parameter %d (%d)", temp + 1, val);
7021                                 if (reverb_status_xg.param_lsb[temp] != val) {
7022                                         reverb_status_xg.param_lsb[temp] = val;
7023                                         recompute_effect_xg(&reverb_status_xg, 1);
7024                                 }
7025                                 break;
7026                         case 0x20:      /* Chorus Type MSB */
7027                                 chorus_status_xg.type_msb = val;
7028                                 //if (chorus_status_xg.type_msb != val) {
7029                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type MSB (%02X)", val);
7030                                 //      chorus_status_xg.type_msb = val;
7031                                 //      realloc_effect_xg(&chorus_status_xg);
7032                                 //}
7033                                 break;
7034                         case 0x21:      /* Chorus Type LSB */
7035                                 temp = chorus_status_xg.type;
7036                                 chorus_status_xg.type_lsb = val;
7037                                 chorus_status_xg.type = ((int32)chorus_status_xg.type_msb << 8) | (int32)chorus_status_xg.type_lsb;                             
7038                                 if (temp == chorus_status_xg.type){
7039                                         recompute_effect_xg(&chorus_status_xg, 1);
7040                                 }else{
7041                                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type (%02X %02X)", 
7042                                                 chorus_status_xg.type_msb, chorus_status_xg.type_lsb);
7043                                         realloc_effect_xg(&chorus_status_xg);
7044                                 }
7045                                 //if (chorus_status_xg.type_lsb != val) {
7046                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Type LSB (%02X)", val);
7047                                 //      chorus_status_xg.type_lsb = val;
7048                                 //      realloc_effect_xg(&chorus_status_xg);
7049                                 //}
7050                                 break;
7051                         case 0x22:      /* Chorus Parameter 1 - 10 */
7052                         case 0x23:
7053                         case 0x24:
7054                         case 0x25:
7055                         case 0x26:
7056                         case 0x27:
7057                         case 0x28:
7058                         case 0x29:
7059                         case 0x2A:
7060                         case 0x2B:
7061                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Parameter %d (%d)", b - 0x22 + 1, val);
7062                                 if (chorus_status_xg.param_lsb[b - 0x22] != val) {
7063                                         chorus_status_xg.param_lsb[b - 0x22] = val;
7064                                         recompute_effect_xg(&chorus_status_xg, 1);
7065                                 }
7066                                 break;
7067                         case 0x2C:      /* Chorus Return */
7068         #if 1   /* XG specific chorus is not currently implemented */
7069                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Return (%d)", val);
7070                                 if (chorus_status_xg.ret != val) {
7071                                         chorus_status_xg.ret = val;
7072                                         recompute_effect_xg(&chorus_status_xg, 1);
7073                                 }
7074         #else   /* use GS chorus instead */
7075                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Return (%d)", val);
7076                                 if (chorus_status_gs.level != val) {
7077                                         chorus_status_gs.level = val;
7078                                         recompute_chorus_status_gs();
7079                                         init_ch_chorus();
7080                                 }
7081         #endif
7082                                 break;
7083                         case 0x2D:      /* Chorus Pan */
7084                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Pan (%d)", val);
7085                                 if (chorus_status_xg.pan != val) {
7086                                         chorus_status_xg.pan = val;
7087                                         recompute_effect_xg(&chorus_status_xg, 1);
7088                                 }
7089                                 break;
7090                         case 0x2E:      /* Send Chorus To Reverb */
7091                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Send Chorus To Reverb (%d)", val);
7092                                 if (chorus_status_xg.send_reverb != val) {
7093                                         chorus_status_xg.send_reverb = val;
7094                                         recompute_effect_xg(&chorus_status_xg, 1);
7095                                 }
7096                                 break;
7097                         case 0x30:      /* Chorus Parameter 11 - 16 */
7098                         case 0x31:
7099                         case 0x32:
7100                         case 0x33:
7101                         case 0x34:
7102                         case 0x35:
7103                                 temp = b - 0x30 + 10;
7104                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Chorus Parameter %d (%d)", temp + 1, val);
7105                                 if (chorus_status_xg.param_lsb[temp] != val) {
7106                                         chorus_status_xg.param_lsb[temp] = val;
7107                                         recompute_effect_xg(&chorus_status_xg, 1);
7108                                 }
7109                                 break;
7110                         case 0x40:      /* Variation Type MSB */
7111                                 variation_effect_xg[msb].type_msb = val;
7112                                 //if (variation_effect_xg[msb].type_msb != val) {
7113                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Type MSB (%02X)", msb + 1, val);
7114                                 //      variation_effect_xg[msb].type_msb = val;
7115                                 //      realloc_effect_xg(&variation_effect_xg[msb]);
7116                                 //}
7117                                 break;
7118                         case 0x41:      /* Variation Type LSB */
7119                                 temp = variation_effect_xg[msb].type;
7120                                 variation_effect_xg[msb].type_lsb = val;
7121                                 variation_effect_xg[msb].type = ((int32)variation_effect_xg[msb].type_msb << 8) | (int32)variation_effect_xg[msb].type_lsb;
7122                                 if(temp == variation_effect_xg[msb].type){
7123                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7124                                 }else{
7125                                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Type (%02X %02X)", msb + 1, 
7126                                                 variation_effect_xg[msb].type_msb, variation_effect_xg[msb].type_lsb);
7127                                         realloc_effect_xg(&variation_effect_xg[msb]);
7128                                 }
7129                                 //if (variation_effect_xg[msb].type_lsb != val) {
7130                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Type LSB (%02X)", msb + 1, val);
7131                                 //      variation_effect_xg[msb].type_lsb = val;
7132                                 //      realloc_effect_xg(&variation_effect_xg[msb]);
7133                                 //}
7134                                 break;
7135                         case 0x42:      /* Variation Parameter 1 - 10 MSB */
7136                         case 0x44:
7137                         case 0x46:
7138                         case 0x48:
7139                         case 0x4A:
7140                         case 0x4C:
7141                         case 0x4E:
7142                         case 0x50:
7143                         case 0x52:
7144                         case 0x54:
7145                                 temp = (b - 0x42) / 2;
7146                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Parameter MSB %d (%d)", msb + 1, temp, val);
7147                                 if (variation_effect_xg[msb].set_param_msb[temp] != val) {
7148                                         variation_effect_xg[msb].set_param_msb[temp] = val;
7149                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7150                                 }
7151                                 break;
7152                         case 0x43:      /* Variation Parameter 1 - 10 LSB */
7153                         case 0x45:
7154                         case 0x47:
7155                         case 0x49:
7156                         case 0x4B:
7157                         case 0x4D:
7158                         case 0x4F:
7159                         case 0x51:
7160                         case 0x53:
7161                         case 0x55:
7162                                 temp = (b - 0x43) / 2;
7163                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Parameter LSB %d (%d)", msb + 1, temp, val);
7164                                 if (variation_effect_xg[msb].set_param_lsb[temp] != val) {
7165                                         variation_effect_xg[msb].set_param_lsb[temp] = val;
7166                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7167                                 }
7168                                 break;
7169                         case 0x56:      /* Variation Return */
7170                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Return (%d)", msb + 1, val);
7171                                 if (variation_effect_xg[msb].ret != val) {
7172                                         variation_effect_xg[msb].ret = val;
7173                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7174                                 }
7175                                 break;
7176                         case 0x57:      /* Variation Pan */
7177                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Pan (%d)", msb + 1, val);
7178                                 if (variation_effect_xg[msb].pan != val) {
7179                                         variation_effect_xg[msb].pan = val;
7180                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7181                                 }
7182                                 break;
7183                         case 0x58:      /* Send Variation To Reverb */
7184                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Send Reverb (%d)", msb + 1, val);
7185                                 if (variation_effect_xg[msb].send_reverb != val) {
7186                                         variation_effect_xg[msb].send_reverb = val;
7187                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7188                                 }
7189                                 break;
7190                         case 0x59:      /* Send Variation To Chorus */
7191                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Send Chorus (%d)", msb + 1, val);
7192                                 if (variation_effect_xg[msb].send_chorus != val) {
7193                                         variation_effect_xg[msb].send_chorus = val;
7194                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7195                                 }
7196                                 break;
7197                         case 0x5A:      /* Variation Connection */
7198                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Connection (%d)", msb + 1, val);
7199                                 if (variation_effect_xg[msb].connection != val) {
7200                                         variation_effect_xg[msb].connection = val; // 0: insertion 1:system
7201                                         recompute_effect_xg(&variation_effect_xg[msb], 1);      
7202                                         {
7203                                                 int i;
7204                                                 for (i = 0; i < MAX_CHANNELS; i++)
7205                                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, i, is_insertion_effect_xg(i));
7206                                         }
7207                                 }
7208                                 break;
7209                         case 0x5B:      /* Variation Part */
7210                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Part (%d)", msb + 1, val);
7211                                 if (variation_effect_xg[msb].part != val) {
7212                                         variation_effect_xg[msb].part = val; // 0~63:ON 64~126:disable(AD part) 127:OFF
7213                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7214                                         {
7215                                                 int i;
7216                                                 for (i = 0; i < MAX_CHANNELS; i++)
7217                                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, i, is_insertion_effect_xg(i));
7218                                         }
7219                                 }
7220                                 break;
7221                         case 0x5C:      /* MW Variation Control Depth */
7222                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "MW XG Variation %d Control Depth (%d)", msb + 1, val);
7223                                 if (variation_effect_xg[msb].control_depth[0] != val) {
7224                                         variation_effect_xg[msb].control_depth[0] = val;
7225                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7226                                 }
7227                                 break;
7228                         case 0x5D:      /* BEND Variation Control Depth */
7229                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND XG Variation %d Control Depth (%d)", msb + 1, val);
7230                                 if (variation_effect_xg[msb].control_depth[1] != val) {
7231                                         variation_effect_xg[msb].control_depth[1] = val;
7232                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7233                                 }
7234                                 break;
7235                         case 0x5E:      /* CAT Variation Control Depth */
7236                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAT XG Variation %d Control Depth (%d)", msb + 1, val);
7237                                 if (variation_effect_xg[msb].control_depth[2] != val) {
7238                                         variation_effect_xg[msb].control_depth[2] = val;
7239                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7240                                 }
7241                                 break;
7242                         case 0x5F:      /* AC1 Variation Control Depth */
7243                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC1 XG Variation %d Control Depth (%d)", msb + 1, val);
7244                                 if (variation_effect_xg[msb].control_depth[3] != val) {
7245                                         variation_effect_xg[msb].control_depth[3] = val;
7246                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7247                                 }
7248                                 break;
7249                         case 0x60:      /* AC2 Variation Control Depth */
7250                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC2 XG Variation %d Control Depth (%d)", msb + 1, val);
7251                                 if (variation_effect_xg[msb].control_depth[4] != val) {
7252                                         variation_effect_xg[msb].control_depth[4] = val;
7253                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7254                                 }
7255                                 break;
7256                         case 0x61:      /* CBC1 Variation Control Depth */
7257                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC1 XG Variation %d Control Depth (%d)", msb + 1, val);
7258                                 if (variation_effect_xg[msb].control_depth[5] != val) {
7259                                         variation_effect_xg[msb].control_depth[5] = val;
7260                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7261                                 }
7262                                 break;
7263                         case 0x62:      /* CBC2 Variation Control Depth */
7264                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC2 XG Variation %d Control Depth (%d)", msb + 1, val);
7265                                 if (variation_effect_xg[msb].control_depth[6] != val) {
7266                                         variation_effect_xg[msb].control_depth[6] = val;
7267                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7268                                 }
7269                                 break;
7270                         case 0x70:      /* Variation Parameter 11 - 16 */
7271                         case 0x71:
7272                         case 0x72:
7273                         case 0x73:
7274                         case 0x74:
7275                         case 0x75:
7276                                 temp = b - 0x70 + 10;
7277                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Variation %d Parameter %d (%d)", msb + 1, temp + 1, val);
7278                                 if (variation_effect_xg[msb].set_param_lsb[temp] != val) {
7279                                         variation_effect_xg[msb].set_param_lsb[temp] = val;
7280                                         recompute_effect_xg(&variation_effect_xg[msb], 1);
7281                                 }
7282                                 break;
7283                         default:
7284                                 break;
7285                         }
7286
7287                 } else if (note == 2 && msb == 0x40) {  /* Multi EQ */
7288                         switch(b)
7289                         {
7290                         case 0x00:      /* EQ type */
7291                                 if(opt_eq_control) {
7292                                         if(val == 0) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ type (0: Flat)");}
7293                                         else if(val == 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ type (1: Jazz)");}
7294                                         else if(val == 2) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ type (2: Pops)");}
7295                                         else if(val == 3) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ type (3: Rock)");}
7296                                         else if(val == 4) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ type (4: Concert)");}
7297                                         multi_eq_xg.type = val;
7298                                         set_multi_eq_type_xg(val);
7299                                         recompute_multi_eq_xg();
7300                                 }
7301                                 break;
7302                         case 0x01:      /* EQ gain1 */
7303                                 if(opt_eq_control) {
7304                                         if(val > 0x4C) {val = 0x4C;}
7305                                         else if(val < 0x34) {val = 0x34;}
7306                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ gain1 (%d dB)", val - 0x40);
7307                                         multi_eq_xg.gain1 = val;
7308                                         recompute_multi_eq_xg();
7309                                 }
7310                                 break;
7311                         case 0x02:      /* EQ frequency1 */
7312                                 if(opt_eq_control) {
7313                                         if(val > 60) {val = 60;}
7314                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ frequency1 (%d Hz)", (int32)eq_freq_table_xg[val]);
7315                                         multi_eq_xg.freq1 = val;
7316                                         recompute_multi_eq_xg();
7317                                 }
7318                                 break;
7319                         case 0x03:      /* EQ Q1 */
7320                                 if(opt_eq_control) {
7321                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ Q1 (%f)", (double)val / 10.0);
7322                                         multi_eq_xg.q1 = val;
7323                                         recompute_multi_eq_xg();
7324                                 }
7325                                 break;
7326                         case 0x04:      /* EQ shape1 */
7327                                 if(opt_eq_control) {
7328                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ shape1 (%d)", val);
7329                                         multi_eq_xg.shape1 = val;
7330                                         recompute_multi_eq_xg();
7331                                 }
7332                                 break;
7333                         case 0x05:      /* EQ gain2 */
7334                                 if(opt_eq_control) {
7335                                         if(val > 0x4C) {val = 0x4C;}
7336                                         else if(val < 0x34) {val = 0x34;}
7337                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ gain2 (%d dB)", val - 0x40);
7338                                         multi_eq_xg.gain2 = val;
7339                                         recompute_multi_eq_xg();
7340                                 }
7341                                 break;
7342                         case 0x06:      /* EQ frequency2 */
7343                                 if(opt_eq_control) {
7344                                         if(val > 60) {val = 60;}
7345                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ frequency2 (%d Hz)", (int32)eq_freq_table_xg[val]);
7346                                         multi_eq_xg.freq2 = val;
7347                                         recompute_multi_eq_xg();
7348                                 }
7349                                 break;
7350                         case 0x07:      /* EQ Q2 */
7351                                 if(opt_eq_control) {
7352                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ Q2 (%f)", (double)val / 10.0);
7353                                         multi_eq_xg.q2 = val;
7354                                         recompute_multi_eq_xg();
7355                                 }
7356                                 break;
7357                         case 0x09:      /* EQ gain3 */
7358                                 if(opt_eq_control) {
7359                                         if(val > 0x4C) {val = 0x4C;}
7360                                         else if(val < 0x34) {val = 0x34;}
7361                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ gain3 (%d dB)", val - 0x40);
7362                                         multi_eq_xg.gain3 = val;
7363                                         recompute_multi_eq_xg();
7364                                 }
7365                                 break;
7366                         case 0x0A:      /* EQ frequency3 */
7367                                 if(opt_eq_control) {
7368                                         if(val > 60) {val = 60;}
7369                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ frequency3 (%d Hz)", (int32)eq_freq_table_xg[val]);
7370                                         multi_eq_xg.freq3 = val;
7371                                         recompute_multi_eq_xg();
7372                                 }
7373                                 break;
7374                         case 0x0B:      /* EQ Q3 */
7375                                 if(opt_eq_control) {
7376                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ Q3 (%f)", (double)val / 10.0);
7377                                         multi_eq_xg.q3 = val;
7378                                         recompute_multi_eq_xg();
7379                                 }
7380                                 break;
7381                         case 0x0D:      /* EQ gain4 */
7382                                 if(opt_eq_control) {
7383                                         if(val > 0x4C) {val = 0x4C;}
7384                                         else if(val < 0x34) {val = 0x34;}
7385                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ gain4 (%d dB)", val - 0x40);
7386                                         multi_eq_xg.gain4 = val;
7387                                         recompute_multi_eq_xg();
7388                                 }
7389                                 break;
7390                         case 0x0E:      /* EQ frequency4 */
7391                                 if(opt_eq_control) {
7392                                         if(val > 60) {val = 60;}
7393                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ frequency4 (%d Hz)", (int32)eq_freq_table_xg[val]);
7394                                         multi_eq_xg.freq4 = val;
7395                                         recompute_multi_eq_xg();
7396                                 }
7397                                 break;
7398                         case 0x0F:      /* EQ Q4 */
7399                                 if(opt_eq_control) {
7400                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ Q4 (%f)", (double)val / 10.0);
7401                                         multi_eq_xg.q4 = val;
7402                                         recompute_multi_eq_xg();
7403                                 }
7404                                 break;
7405                         case 0x11:      /* EQ gain5 */
7406                                 if(opt_eq_control) {
7407                                         if(val > 0x4C) {val = 0x4C;}
7408                                         else if(val < 0x34) {val = 0x34;}
7409                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ gain5 (%d dB)", val - 0x40);
7410                                         multi_eq_xg.gain5 = val;
7411                                         recompute_multi_eq_xg();
7412                                 }
7413                                 break;
7414                         case 0x12:      /* EQ frequency5 */
7415                                 if(opt_eq_control) {
7416                                         if(val > 60) {val = 60;}
7417                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ frequency5 (%d Hz)", (int32)eq_freq_table_xg[val]);
7418                                         multi_eq_xg.freq5 = val;
7419                                         recompute_multi_eq_xg();
7420                                 }
7421                                 break;
7422                         case 0x13:      /* EQ Q5 */
7423                                 if(opt_eq_control) {
7424                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ Q5 (%f)", (double)val / 10.0);
7425                                         multi_eq_xg.q5 = val;
7426                                         recompute_multi_eq_xg();
7427                                 }
7428                                 break;
7429                         case 0x14:      /* EQ shape5 */
7430                                 if(opt_eq_control) {
7431                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG EQ shape5 (%d)", val);
7432                                         multi_eq_xg.shape5 = val;
7433                                         recompute_multi_eq_xg();
7434                                 }
7435                                 break;
7436                         }
7437
7438                 } else if (note == 3 && msb >= 0) {     /* Effect 2 */
7439                         /* msb=0 : insertion 1 */
7440                         /* msb=n : insertion n+1 */
7441                         if ( msb >= XG_INSERTION_EFFECT_NUM) {
7442                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "ERROR! XG Insertion Effect Number (%d)", msb);
7443                                 return;
7444                         }
7445                         switch(b)
7446                         {
7447                         case 0x00:      /* Insertion Effect Type MSB */
7448                                 if(!opt_insertion_effect) {break;}
7449                                 insertion_effect_xg[msb].type_msb = val;                                
7450                                 //if (insertion_effect_xg[msb].type_msb != val) {
7451                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Type MSB (%d %02X)", msb + 1, note, val);
7452                                 //      insertion_effect_xg[msb].type_msb = val;
7453                                 //      realloc_effect_xg(&insertion_effect_xg[msb]);
7454                                 //}
7455                                 break;
7456                         case 0x01:      /* Insertion Effect Type LSB */
7457                                 if(!opt_insertion_effect) {break;}
7458                                 temp = insertion_effect_xg[msb].type;
7459                                 insertion_effect_xg[msb].type_lsb = val;                                
7460                                 insertion_effect_xg[msb].type = ((int32)insertion_effect_xg[msb].type_msb << 8) | (int32)insertion_effect_xg[msb].type_lsb;                             
7461                                 if(temp == insertion_effect_xg[msb].type){
7462                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7463                                 }else{
7464                                         ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Type (%d %02X %02X)", msb + 1, note, 
7465                                                 insertion_effect_xg[msb].type_msb, insertion_effect_xg[msb].type_lsb);
7466                                         realloc_effect_xg(&insertion_effect_xg[msb]);
7467                                 }
7468                                 //if (insertion_effect_xg[msb].type_lsb != val) {
7469                                 //      ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Type LSB (%d %02X)", msb + 1, note, val);
7470                                 //      insertion_effect_xg[msb].type_lsb = val;
7471                                 //      realloc_effect_xg(&insertion_effect_xg[msb]);
7472                                 //}
7473                                 break;
7474                         case 0x02:      /* Insertion Effect Parameter 1 - 10 */
7475                         case 0x03:
7476                         case 0x04:
7477                         case 0x05:
7478                         case 0x06:
7479                         case 0x07:
7480                         case 0x08:
7481                         case 0x09:
7482                         case 0x0A:
7483                         case 0x0B:
7484                                 if (insertion_effect_xg[msb].use_msb) {break;}
7485                                 temp = b - 0x02;
7486                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Parameter %d (%d %d)", msb + 1, temp + 1, note, val);
7487                                 if (insertion_effect_xg[msb].set_param_lsb[temp] != val) {
7488                                         insertion_effect_xg[msb].set_param_lsb[temp] = val;
7489                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7490                                 }
7491                                 break;
7492                         case 0x0C:      /* Insertion Effect Part */
7493                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Part (%d %d)", msb + 1, note, val);
7494                                 if (insertion_effect_xg[msb].part != val) {
7495                                         insertion_effect_xg[msb].part = val;
7496                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7497                                         {
7498                                                 int i;
7499                                                 for (i = 0; i < MAX_CHANNELS; i++)
7500                                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, i, is_insertion_effect_xg(i));
7501                                         }
7502                                 }
7503                                 break;
7504                         case 0x0D:      /* MW Insertion Control Depth */
7505                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "MW XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7506                                 if (insertion_effect_xg[msb].control_depth[0] != val) {
7507                                         insertion_effect_xg[msb].control_depth[0] = val;
7508                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7509                                 }
7510                                 break;
7511                         case 0x0E:      /* BEND Insertion Control Depth */
7512                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "BEND XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7513                                 if (insertion_effect_xg[msb].control_depth[1] != val) {
7514                                         insertion_effect_xg[msb].control_depth[1] = val;
7515                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7516                                 }
7517                                 break;
7518                         case 0x0F:      /* CAT Insertion Control Depth */
7519                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CAT XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7520                                 if (insertion_effect_xg[msb].control_depth[2] != val) {
7521                                         insertion_effect_xg[msb].control_depth[2] = val;
7522                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7523                                 }
7524                                 break;
7525                         case 0x10:      /* AC1 Insertion Control Depth */
7526                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC1 XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7527                                 if (insertion_effect_xg[msb].control_depth[3] != val) {
7528                                         insertion_effect_xg[msb].control_depth[3] = val;
7529                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7530                                 }
7531                                 break;
7532                         case 0x11:      /* AC2 Insertion Control Depth */
7533                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "AC2 XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7534                                 if (insertion_effect_xg[msb].control_depth[4] != val) {
7535                                         insertion_effect_xg[msb].control_depth[4] = val;
7536                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7537                                 }
7538                                 break;
7539                         case 0x12:      /* CBC1 Insertion Control Depth */
7540                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC1 XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7541                                 if (insertion_effect_xg[msb].control_depth[5] != val) {
7542                                         insertion_effect_xg[msb].control_depth[5] = val;
7543                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7544                                 }
7545                                 break;
7546                         case 0x13:      /* CBC2 Insertion Control Depth */
7547                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "CBC2 XG Insertion %d Control Depth (%d %d)", msb + 1, note, val);
7548                                 if (insertion_effect_xg[msb].control_depth[6] != val) {
7549                                         insertion_effect_xg[msb].control_depth[6] = val;
7550                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7551                                 }
7552                                 break;
7553                         case 0x20:      /* Insertion Effect Parameter 11 - 16 */
7554                         case 0x21:
7555                         case 0x22:
7556                         case 0x23:
7557                         case 0x24:
7558                         case 0x25:
7559                                 temp = b - 0x20 + 10;
7560                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Parameter %d (%d %d)", msb + 1, temp + 1, note, val);
7561                                 if (insertion_effect_xg[msb].set_param_lsb[temp] != val) {
7562                                         insertion_effect_xg[msb].set_param_lsb[temp] = val;
7563                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7564                                 }
7565                                 break;
7566                         case 0x30:      /* Insertion Effect Parameter 1 - 10 MSB */
7567                         case 0x32:
7568                         case 0x34:
7569                         case 0x36:
7570                         case 0x38:
7571                         case 0x3A:
7572                         case 0x3C:
7573                         case 0x3E:
7574                         case 0x40:
7575                         case 0x42:
7576                                 if (!insertion_effect_xg[msb].use_msb) {break;}
7577                                 temp = (b - 0x30) / 2;
7578                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Parameter %d MSB (%d %d)", msb + 1, temp + 1, note, val);
7579                                 if (insertion_effect_xg[msb].set_param_msb[temp] != val) {
7580                                         insertion_effect_xg[msb].set_param_msb[temp] = val;
7581                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7582                                 }
7583                                 break;
7584                         case 0x31:      /* Insertion Effect Parameter 1 - 10 LSB */
7585                         case 0x33:
7586                         case 0x35:
7587                         case 0x37:
7588                         case 0x39:
7589                         case 0x3B:
7590                         case 0x3D:
7591                         case 0x3F:
7592                         case 0x41:
7593                         case 0x43:
7594                                 if (!insertion_effect_xg[msb].use_msb) {break;}
7595                                 temp = (b - 0x31) / 2;
7596                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "XG Insertion %d Parameter %d LSB (%d %d)", msb + 1, temp + 1, note, val);
7597                                 if (insertion_effect_xg[msb].set_param_lsb[temp] != val) {
7598                                         insertion_effect_xg[msb].set_param_lsb[temp] = val;
7599                                         recompute_effect_xg(&insertion_effect_xg[msb], 1);
7600                                 }
7601                                 break;
7602                         default:
7603                                 break;
7604                         }
7605
7606                 } else if (note == 8 && msb == 0) {     /* Multi Part */
7607         ///r
7608                         switch(b)
7609                         {
7610         /*
7611                         case 0x01:      // Bank Select MSB
7612                                 channel[ch].bank_msb = val;
7613                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG SysEx Bank Select MSB (CH:%d)",ch);
7614                                 break;
7615                         case 0x02:      // Bank Select LSB
7616                                 channel[ch].bank_lsb = val;
7617                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG SysEx Bank Select LSB (CH:%d)",ch);
7618                                 break;
7619                         case 0x03:      // Program Change
7620                                 channel[ch].program = val;
7621                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG SysEx Program Change (CH:%d)",ch);
7622                                 break;
7623                         case 0x04:      // Rcv CHANNEL, remapped from 0x04 ?
7624                                 reset_controllers(ch);
7625                                 redraw_controllers(ch);
7626                                 all_notes_off(ch);
7627                                 if (val == 0x7f)
7628                                         remove_channel_layer(ch);
7629                                 else {
7630                                         if((ch < REDUCE_CHANNELS) != (val < REDUCE_CHANNELS)) {
7631                                                 channel[ch].port_select = ch < REDUCE_CHANNELS ? 1 : 0;
7632                                         }
7633                                         if((ch % REDUCE_CHANNELS) != (val % REDUCE_CHANNELS)) {
7634                                                 add_channel_layer(ch, val);
7635                                         }
7636                                 }
7637                                 break;
7638                         case 0x05:      // Mono/Poly Mode
7639                                 channel[ch].mono = val;
7640                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG SysEx Mono/Poly Mode (CH:%d)",ch);
7641                                 break;
7642         */
7643         ///r
7644
7645                         case 0x06:      /* Same Note Number Key On Assign */
7646                                 if(val == 0) {
7647                                         channel[ch].assign_mode = 0;
7648                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Single (CH:%d)",ch);
7649                                 } else if(val == 1) {
7650                                         channel[ch].assign_mode = 1; // XG Multi : Not Full Multi
7651                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Multi (CH:%d)",ch);
7652                                 } else if(val == 2) {
7653                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Inst is not supported. (CH:%d)",ch);
7654                                 } else if(val == 3) {
7655                                         channel[ch].assign_mode = 2; // Timidity Full Multi
7656                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Same Note Number Key On Assign: Inst is not supported. (CH:%d)",ch);
7657                                 }
7658                                 break;
7659         /*
7660                         case 0x07:      // Part Mode
7661                                 midi_drumpart_change(ch, TRUE);
7662                                 channel[ch].bank_msb = 127;
7663                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"XG SysEx Part Mode (CH:%d)",ch);
7664                                 break;
7665                         case 0x08:      // note shift
7666                                 break;
7667         */
7668                         case 0x09:      /* Detune 1st bit */
7669                                 channel[ch].detune_param &= 0x0F; // clear bit7-4
7670                                 channel[ch].detune_param |= (val << 4) & 0xF0; // add val bit3-0 to bit7-4
7671                                 {
7672                                         float tmpf = (FLOAT_T)((int)channel[ch].detune_param - 0x80) * DIV_10;
7673                                         if(channel[ch].detune_param != 0x80)
7674                                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Detune 1st bit (CH:%d detune:%.1fHz VAL:%02X)", ch, tmpf, val);
7675                                         else
7676                                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Detune 1st bit (CH:%d detune:0.0Hz VAL:%02X)", ch, val);
7677                                 }
7678                                 break;
7679                         case 0x0A:      /* Detune 2nd bit */
7680                                 channel[ch].detune_param &= 0xF0; // clear bit3-0
7681                                 channel[ch].detune_param |= val & 0x0F; // add val bit3-0 to bit3-0
7682                                 {
7683                                         float tmpf = (FLOAT_T)((int)channel[ch].detune_param - 0x80) * DIV_10;
7684                                         if(channel[ch].detune_param != 0x80)
7685                                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Detune 2nd bit (CH:%d detune:%.1fHz VAL:%02X)", ch, tmpf, val);
7686                                         else
7687                                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Detune 2nd bit (CH:%d detune:0.0Hz VAL:%02X)", ch, val);
7688                                 }
7689                                 break;
7690                         case 0x11:      /* Dry Level */
7691                                 channel[ch].dry_level = val;
7692                                 ctl->cmsg(CMSG_INFO, VERB_NOISY, "Dry Level (CH:%d VAL:%d)", ch, val);
7693                                 break;
7694                         case 0x99:      /* Rcv CHANNEL, remapped from 0x04 */
7695                                 reset_controllers(ch);
7696                                 redraw_controllers(ch);
7697                                 all_notes_off(ch);
7698                                 if (val == 0x7f)
7699                                         remove_channel_layer(ch);
7700                                 else {
7701                                         if((ch < REDUCE_CHANNELS) != (val < REDUCE_CHANNELS)) {
7702                                                 channel[ch].port_select = ch < REDUCE_CHANNELS ? 1 : 0;
7703                                         }
7704                                         if((ch % REDUCE_CHANNELS) != (val % REDUCE_CHANNELS)) {
7705                                                 add_channel_layer(ch, val);
7706                                         }
7707                                 }
7708                                 break;
7709                         }
7710                 } else if ((note & 0xF0) == 0x30) {     /* Drum Setup */
7711                         note = msb;
7712                         switch(b)
7713                         {
7714                         case 0x0E:      /* EG Decay1 */
7715                                 if (channel[ch].drums[note] == NULL)
7716                                         play_midi_setup_drums(ch, note);
7717                                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
7718                                         "Drum Instrument EG Decay1 (CH:%d NOTE:%d VAL:%d)",
7719                                         ch, note, val);
7720                                 channel[ch].drums[note]->drum_envelope_rate[EG_DECAY1] = val;
7721                                 break;
7722                         case 0x0F:      /* EG Decay2 */
7723                                 if (channel[ch].drums[note] == NULL)
7724                                         play_midi_setup_drums(ch, note);
7725                                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
7726                                         "Drum Instrument EG Decay2 (CH:%d NOTE:%d VAL:%d)",
7727                                         ch, note, val);
7728                                 channel[ch].drums[note]->drum_envelope_rate[EG_DECAY2] = val;
7729                                 break;
7730                         case 0x60:      /* Velocity Pitch Sense */                              
7731                                 if (channel[ch].drums[note] == NULL)
7732                                         play_midi_setup_drums(ch, note);
7733                                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
7734                                         "Drum Velocity Pitch Sense (CH:%d NOTE:%d VAL:%d)",
7735                                         ch, note, val - 0x40);
7736                                 channel[ch].drums[note]->drum_velo_pitch_sens = clip_int(val - 0x40, -16, 16);
7737                                 break;
7738                         case 0x61:      /* Velocity LPF Cutoff Sense */
7739                                 if (channel[ch].drums[note] == NULL)
7740                                         play_midi_setup_drums(ch, note);
7741                                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
7742                                         "Drum Velocity LPF Cutoff Sense (CH:%d NOTE:%d VAL:%d)",
7743                                         ch, note, val - 0x40);
7744                                 channel[ch].drums[note]->drum_velo_cutoff_sens = clip_int(val - 0x40, -16, 16);
7745                                 break;
7746                         default:
7747                                 break;
7748                         }
7749                 }
7750                 return;
7751
7752         } else if(ev == ME_SYSEX_SD_LSB) {      /* SD system exclusive message */
7753                 int hsb = channel[ch].sysex_sd_hsb_addr;
7754                 int hval = channel[ch].sysex_sd_hsb_val;
7755                 int part = channel[ch].sysex_sd_msb_addr;
7756                 int mfx = channel[ch].sysex_sd_msb_val;
7757                 
7758                 switch(hsb){
7759                 case 0x00: // System // System Common
7760                         break;
7761                 case 0x01: // System // System Common
7762                         break;
7763                 case 0x02: // System // System EQ
7764                         switch(b){
7765                         case 0x00: // EQ Switch
7766                                 if(opt_eq_control) {
7767                                         if(val == 0) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ (OFF)");}
7768                                         else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ (ON)");}
7769                                         multi_eq_sd.sw = val ? 1 : 0;
7770                                         recompute_multi_eq_sd();
7771                                 }
7772                                 break;
7773                         case 0x01: // EQ Left Low Frequency
7774                                 if(opt_eq_control) {
7775                                         if(val > 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left Low Freq (400Hz)");}
7776                                         else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left Low Freq (200Hz");}
7777                                         multi_eq_sd.freq_ll = val;
7778                                         recompute_multi_eq_xg();
7779                                 }
7780                                 break;
7781                         case 0x02: // EQ Left Low Gain
7782                                 if(opt_eq_control) {                                    
7783                                         if(val > 0x1E) {val = 0x1E;}
7784                                         else if(val < 0x00) {val = 0x00;}
7785                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left Low Gain (%ddB)", (int)val - 0x0F);
7786                                         multi_eq_sd.gain_ll = val;
7787                                         recompute_multi_eq_xg();
7788                                 }       
7789                                 break;
7790                         case 0x03: // EQ Left High Frequency
7791                                 if(opt_eq_control) {
7792                                         if(val > 2) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left High Freq (8000Hz)");}
7793                                         else if(val > 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left High Freq (4000Hz)");}
7794                                         else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left High Freq (2000Hz)");}
7795                                         multi_eq_sd.freq_hl = val;
7796                                         recompute_multi_eq_xg();
7797                                 }
7798                                 break;
7799                         case 0x04: // EQ Left High Gain
7800                                 if(opt_eq_control) {                                    
7801                                         if(val > 0x1E) {val = 0x1E;}
7802                                         else if(val < 0x00) {val = 0x00;}
7803                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left High Gain (%ddB)", (int)val - 0x0F);
7804                                         multi_eq_sd.gain_hl = val;
7805                                         recompute_multi_eq_xg();
7806                                 }
7807                                 break;
7808                         case 0x05: // EQ Right Low Frequency
7809                                 if(opt_eq_control) {
7810                                         if(val > 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right Low Freq (400Hz)");}
7811                                         else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Left Right Freq (200Hz)");}
7812                                         multi_eq_sd.freq_lr = val;
7813                                         recompute_multi_eq_xg();
7814                                 }
7815                                 break;
7816                         case 0x06: // EQ Right Low Gain
7817                                 if(opt_eq_control) {                                    
7818                                         if(val > 0x1E) {val = 0x1E;}
7819                                         else if(val < 0x00) {val = 0x00;}
7820                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right Low Gain (%ddB)", (int)val - 0x0F);
7821                                         multi_eq_sd.gain_lr = val;
7822                                         recompute_multi_eq_xg();
7823                                 }
7824                                 break;
7825                         case 0x07: // EQ Right High Frequency
7826                                 if(opt_eq_control) {
7827                                         if(val > 2) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right High (Freq 8000Hz)");}
7828                                         else if(val > 1) {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right High Freq (4000Hz)");}
7829                                         else {ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right High Freq (2000Hz)");}
7830                                         multi_eq_sd.freq_hr = val;
7831                                         recompute_multi_eq_xg();
7832                                 }
7833                                 break;
7834                         case 0x08: // EQ Right High Gain
7835                                 if(opt_eq_control) {                                    
7836                                         if(val > 0x1E) {val = 0x1E;}
7837                                         else if(val < 0x00) {val = 0x00;}
7838                                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"SD EQ Right High Gain (%ddB)", (int)val - 0x0F);
7839                                         multi_eq_sd.gain_hr = val;
7840                                         recompute_multi_eq_xg();
7841                                 }
7842                                 break;
7843                         }
7844                         break;
7845                 case 0x03: // Audio // Audio Common
7846                         break;
7847                 case 0x04: // Audio // Audio Common Mixer Preset Mode
7848                         break;
7849                 case 0x05: // Audio // Audio Common Mixer Free Edit Mode
7850                         break;
7851                 case 0x06: // Audio // Audio Common AFX Parameter
7852                         break;
7853                 case 0x07: // Temporary Multitimbre // Multitimbre Common
7854                         switch(b){
7855                         case 0x00:
7856                                 break;
7857                         case 0x30: // MFX 1/2/3 source
7858                                 if(val == 0){
7859                                         if(mfx_effect_sd[mfx].efx_source != -1){
7860                                                 channel[mfx_effect_sd[mfx].efx_source].sd_output_assign = 1; // mfx off
7861                                                 ctl_mode_event(CTLE_INSERTION_EFFECT, 1, mfx_effect_sd[mfx].efx_source, 0);
7862                                         }
7863                                         mfx_effect_sd[mfx].efx_source = -1; // common
7864                                         mfx_effect_sd[mfx].type = &mfx_effect_sd[mfx].common_type;
7865                                         mfx_effect_sd[mfx].set_param = mfx_effect_sd[mfx].common_param; 
7866                                 }else{
7867                                         int part = val - 1; // part ?
7868                                         if(part >= 32 || part < 0) {return;}
7869                                         mfx_effect_sd[mfx].efx_source = part; // part
7870                                         mfx_effect_sd[mfx].type = &channel[part].mfx_part_type;
7871                                         mfx_effect_sd[mfx].set_param = channel[part].mfx_part_param;
7872                                 }
7873                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX source (MFX:%d VAL:%02X)", mfx, val);
7874                                 realloc_mfx_effect_sd(&mfx_effect_sd[mfx], 0);
7875                                 break;
7876                         case 0x33: // Chorus source
7877                                 if(val == 0){
7878                                         chorus_status_sd.efx_source = -1; // common
7879                                         chorus_status_sd.type = &chorus_status_sd.common_type;
7880                                         chorus_status_sd.set_param = chorus_status_sd.common_param;     
7881                                 }else{
7882                                         int part = val - 1; // part ?
7883                                         if(part >= 32 || part < 0) {return;}
7884                                         chorus_status_sd.efx_source = part; // part
7885                                         chorus_status_sd.type = &channel[part].chorus_part_type;
7886                                         chorus_status_sd.set_param = channel[part].chorus_part_param;
7887                                 }
7888                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Chorus source (VAL:%02X)", val);
7889                                 realloc_chorus_status_sd(&chorus_status_sd, 0);
7890                                 break;
7891                         case 0x34: // Reverb source
7892                                 if(val == 0){
7893                                         reverb_status_sd.efx_source = -1; // common
7894                                         reverb_status_sd.type = &chorus_status_sd.common_type;
7895                                         reverb_status_sd.set_param = chorus_status_sd.common_param;     
7896                                 }else{
7897                                         int part = val - 1; // part ?
7898                                         if(part >= 32 || part < 0) {return;}
7899                                         reverb_status_sd.efx_source = part; // part
7900                                         reverb_status_sd.type = &channel[part].reverb_part_type;
7901                                         reverb_status_sd.set_param = channel[part].reverb_part_param;
7902                                 }
7903                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Reverb source (VAL:%02X)", val);
7904                                 realloc_reverb_status_sd(&reverb_status_sd, 0);
7905                                 break;
7906                         case 0x35: // MFX 1 control channel
7907                                 if(val >= 0 && val <= 15)
7908                                         mfx_effect_sd[0].ctrl_channel = val;
7909                                 else
7910                                         mfx_effect_sd[0].ctrl_channel = -1; // off
7911                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 1 control channel (%02X)", mfx_effect_sd[0].ctrl_channel);
7912                                 break;
7913                         case 0x36: // MFX 2 control channel
7914                                 if(val >= 0 && val <= 15)
7915                                         mfx_effect_sd[1].ctrl_channel = val;
7916                                 else
7917                                         mfx_effect_sd[1].ctrl_channel = -1; // off
7918                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 2 control channel (%02X)", mfx_effect_sd[1].ctrl_channel);
7919                                 break;
7920                         case 0x37: // MFX 3 control channel
7921                                 if(val >= 0 && val <= 15)
7922                                         mfx_effect_sd[2].ctrl_channel = val;
7923                                 else
7924                                         mfx_effect_sd[2].ctrl_channel = -1; // off
7925                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 3 control channel (%02X)", mfx_effect_sd[2].ctrl_channel);
7926                                 break;
7927                         case 0x38: // MFX 1 control port
7928                                 mfx_effect_sd[0].ctrl_port = val ? 1 : 0;
7929                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 1 control port (%02X)", mfx_effect_sd[0].ctrl_port);
7930                                 break;
7931                         case 0x39: // MFX 2 control port
7932                                 mfx_effect_sd[1].ctrl_port = val ? 1 : 0;
7933                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 2 control port (%02X)", mfx_effect_sd[1].ctrl_port);
7934                                 break;
7935                         case 0x3A: // MFX 3 control port
7936                                 mfx_effect_sd[2].ctrl_port = val ? 1 : 0;
7937                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "MFX 3 control port (%02X)", mfx_effect_sd[2].ctrl_port);
7938                                 break;
7939                         }
7940                         break;
7941                 case 0x08: // Temporary Multitimbre // Multitimbre Common Chorus
7942                         if(!opt_chorus_control) {break;}                        
7943                         switch(b){
7944                         case 0x00: // Chorus Type
7945                                 temp = chorus_status_sd.common_type;
7946                                 chorus_status_sd.common_type = val;
7947                                 if(temp == val) {
7948                                         recompute_chorus_status_sd(&chorus_status_sd, 1);
7949                                 } else {
7950                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Chorus Type (VAL:%02X)", val);
7951                                         if(val == 0x03) // param[0]:type
7952                                                 chorus_status_sd.common_param[0] = 0x7F; // type default 
7953                                         realloc_chorus_status_sd(&chorus_status_sd, 0);
7954                                 }
7955                                 break;
7956                         case 0x01: // Chorus Level
7957                                 chorus_status_sd.common_efx_level = val;
7958                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
7959                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Chorus Level (VAl:%02X)", val);   
7960                                 break;
7961                         case 0x02: // Chorus Output Select
7962                                 chorus_status_sd.common_output_select = val;
7963                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
7964                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Chorus Output Select (VAl:%02X)", val);   
7965                                 break;
7966                         case 0x03: // Chorus Parameter 1
7967                         case 0x04: // Chorus Parameter 2
7968                         case 0x05: // Chorus Parameter 3
7969                         case 0x06: // Chorus Parameter 4
7970                         case 0x07: // Chorus Parameter 5
7971                         case 0x08: // Chorus Parameter 6
7972                         case 0x09: // Chorus Parameter 7
7973                         case 0x0A: // Chorus Parameter 8
7974                         case 0x0B: // Chorus Parameter 9
7975                         case 0x0C: // Chorus Parameter 10
7976                         case 0x0D: // Chorus Parameter 11
7977                         case 0x0E: // Chorus Parameter 12
7978                                 temp = b - 0x03;
7979                                 if(chorus_status_sd.common_type == 0x03 && temp == 0){ // type
7980                                         int prev = chorus_status_sd.common_param[temp];
7981                                         chorus_status_sd.common_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
7982                                         if(prev != chorus_status_sd.common_param[temp])
7983                                                 realloc_chorus_status_sd(&chorus_status_sd, 0);
7984                                         else
7985                                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
7986                                 }else{
7987                                         chorus_status_sd.common_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
7988                                         recompute_chorus_status_sd(&chorus_status_sd, 1);
7989                                 }
7990                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Chorus parameter (param:%02X VAL:%02X)", temp, chorus_status_sd.common_param[temp]);
7991                                 break;
7992                         }
7993                         break;
7994                 case 0x09: // Temporary Multitimbre // Multitimbre Common Reverb
7995                         if(!opt_reverb_control) {break;}                        
7996                         switch(b){
7997                         case 0x00: // Reverb Type
7998                                 temp = reverb_status_sd.common_type;
7999                                 reverb_status_sd.common_type = val;
8000                                 if(temp == val) {
8001                                         recompute_reverb_status_sd(&reverb_status_sd, 1);
8002                                 } else {
8003                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Reverb Type (VAL:%02X)", val);
8004                                         if(val == 0x01 || val == 0x05) // param[0]:type
8005                                                 reverb_status_sd.common_param[0] = 0x7F; // type default 
8006                                         realloc_reverb_status_sd(&reverb_status_sd, 0);
8007                                 }
8008                                 break;
8009                         case 0x01: // Reverb Level
8010                                 reverb_status_sd.common_efx_level = val;
8011                                 recompute_reverb_status_sd(&reverb_status_sd, 1);
8012                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Reverb Level (VAl:%02X)", val);   
8013                                 break;
8014                         case 0x02: // Reverb Parameter 1
8015                         case 0x03: // Reverb Parameter 2
8016                         case 0x04: // Reverb Parameter 3
8017                         case 0x05: // Reverb Parameter 4
8018                         case 0x06: // Reverb Parameter 5
8019                         case 0x07: // Reverb Parameter 6
8020                         case 0x08: // Reverb Parameter 7
8021                         case 0x09: // Reverb Parameter 8
8022                         case 0x0A: // Reverb Parameter 9
8023                         case 0x0B: // Reverb Parameter 10
8024                         case 0x0C: // Reverb Parameter 11
8025                         case 0x0D: // Reverb Parameter 12
8026                         case 0x0E: // Reverb Parameter 13
8027                         case 0x0F: // Reverb Parameter 14
8028                         case 0x10: // Reverb Parameter 15
8029                         case 0x11: // Reverb Parameter 16
8030                         case 0x12: // Reverb Parameter 17
8031                         case 0x13: // Reverb Parameter 18
8032                         case 0x14: // Reverb Parameter 19
8033                         case 0x15: // Reverb Parameter 20
8034                                 temp = b - 0x02;
8035                                 if((reverb_status_sd.common_type == 0x01 || reverb_status_sd.common_type == 0x05) && temp == 0){ // type
8036                                         int prev = reverb_status_sd.common_param[temp];
8037                                         reverb_status_sd.common_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8038                                         if(prev != reverb_status_sd.common_param[temp])
8039                                                 realloc_reverb_status_sd(&reverb_status_sd, 0);
8040                                         else
8041                                                 recompute_reverb_status_sd(&reverb_status_sd, 1);
8042                                 }else{
8043                                         reverb_status_sd.common_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8044                                         recompute_reverb_status_sd(&reverb_status_sd, 1);
8045                                 }
8046                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Reverb parameter (param:%02X VAL:%02X)", temp, reverb_status_sd.common_param[temp]);
8047                                 break;
8048                         }
8049                         break;
8050                 case 0x0A: // Temporary Multitimbre // Multitimbre Common MFX1/2/3
8051                         if(!opt_insertion_effect) {break;}                      
8052                         if(mfx >= SD_MFX_EFFECT_NUM || mfx < 0) {
8053                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Error : SD Common MFX num (%02X)", mfx);
8054                                 break;
8055                         }
8056                         switch(b)       {
8057                         case 0x00: // MFX Type
8058                                 temp = mfx_effect_sd[mfx].common_type;
8059                                 mfx_effect_sd[mfx].common_type = val;
8060                                 if(temp == val) {
8061                                         recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8062                                 } else {
8063                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX type (MFX:%02X VAL:%02X)", mfx, val);
8064                                         realloc_mfx_effect_sd(&mfx_effect_sd[mfx], 0);
8065                                 }
8066                                 if(val > 0){
8067                                         int i;
8068                                         for(i = 0; i < 32; i++)
8069                                                 if(channel[i].sd_output_assign == 0 && channel[i].sd_output_mfx_select == mfx)
8070                                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 1);
8071                                 }else{
8072                                         int i;
8073                                         for(i = 0; i < 32; i++)
8074                                                 if(channel[i].sd_output_assign == 0 && channel[i].sd_output_mfx_select == mfx)
8075                                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 0);
8076                                 }
8077                                 break;
8078                         case 0x01: // MFX Dry Send Level
8079                                 mfx_effect_sd[mfx].common_dry_send = val;
8080                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8081                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common Dry Send Level (MFX:%02X VAL:%02X)", mfx, val);           
8082                                 break;
8083                         case 0x02: // MFX Chorus Send Level
8084                                 mfx_effect_sd[mfx].common_send_chorus = val;
8085                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8086                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Chorus Send Level (MFX:%02X VAL:%02X)", mfx, val);    
8087                                 break;  
8088                         case 0x03: // MFX Reverb Send Level
8089                                 mfx_effect_sd[mfx].common_send_reverb = val;
8090                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8091                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Reverb Send Level (MFX:%02X VAL:%02X)", mfx, val);    
8092                                 break;
8093                         //case 0x04: // none
8094                         case 0x05: // MFX Control 1 Source
8095                                 mfx_effect_sd[mfx].common_ctrl_source[0] = val;
8096                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8097                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 1 Source (MFX:%02X VAL:%02X)", mfx, val);     
8098                                 break;
8099                         case 0x06: // MFX Control 1 Sens 
8100                                 mfx_effect_sd[mfx].common_ctrl_sens[0] = val;
8101                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8102                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 1 Sens (MFX:%02X VAL:%02X)", mfx, val);       
8103                                 break;
8104                         case 0x07: // MFX Control 2 Source
8105                                 mfx_effect_sd[mfx].common_ctrl_source[1] = val;
8106                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8107                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 2 Source (MFX:%02X VAL:%02X)", mfx, val);     
8108                                 break;
8109                         case 0x08: // MFX Control 2 Sens 
8110                                 mfx_effect_sd[mfx].common_ctrl_sens[1] = val;
8111                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8112                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 2 Sens (MFX:%02X VAL:%02X)", mfx, val);       
8113                                 break;
8114                         case 0x09: // MFX Control 3 Source
8115                                 mfx_effect_sd[mfx].common_ctrl_source[2] = val;
8116                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8117                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 3 Source (MFX:%02X VAL:%02X)", mfx, val);     
8118                                 break;
8119                         case 0x0A: // MFX Control 3 Sens 
8120                                 mfx_effect_sd[mfx].common_ctrl_sens[2] = val;
8121                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8122                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 3 Sens (MFX:%02X VAL:%02X)", mfx, val);       
8123                                 break;
8124                         case 0x0B: // MFX Control 4 Source
8125                                 mfx_effect_sd[mfx].common_ctrl_source[3] = val;
8126                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8127                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 4 Source (MFX:%02X VAL:%02X)", mfx, val);     
8128                                 break;
8129                         case 0x0C: // MFX Control 4 Sens 
8130                                 mfx_effect_sd[mfx].common_ctrl_sens[3] = val;
8131                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8132                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control 4 Sens (MFX:%02X VAL:%02X)", mfx, val);       
8133                                 break;
8134                         case 0x0D: // MFX Control Assign 1
8135                                 mfx_effect_sd[mfx].common_ctrl_assign[0] = val;
8136                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8137                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control Assign 1 (MFX:%02X VAL:%02X)", mfx, val);     
8138                                 break;
8139                         case 0x0E: // MFX Control Assign 2
8140                                 mfx_effect_sd[mfx].common_ctrl_assign[1] = val;
8141                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8142                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control Assign 2 (MFX:%02X VAL:%02X)", mfx, val);     
8143                                 break;
8144                         case 0x0F: // MFX Control Assign 3
8145                                 mfx_effect_sd[mfx].common_ctrl_assign[2] = val;
8146                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8147                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control Assign 3 (MFX:%02X VAL:%02X)", mfx, val);     
8148                                 break;
8149                         case 0x10: // MFX Control Assign 4
8150                                 mfx_effect_sd[mfx].common_ctrl_assign[3] = val;
8151                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8152                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX Control Assign 4 (MFX:%02X VAL:%02X)", mfx, val);     
8153                                 break;
8154                         case 0x11: // MFX param
8155                         case 0x12:
8156                         case 0x13:
8157                         case 0x14:
8158                         case 0x15:
8159                         case 0x16:
8160                         case 0x17:
8161                         case 0x18:
8162                         case 0x19:
8163                         case 0x1A:
8164                         case 0x1B:
8165                         case 0x1C:
8166                         case 0x1D:
8167                         case 0x1E:
8168                         case 0x1F:
8169                         case 0x20:
8170                         case 0x21:      
8171                         case 0x22:      
8172                         case 0x23:      
8173                         case 0x24:      
8174                         case 0x25:      
8175                         case 0x26:      
8176                         case 0x27:      
8177                         case 0x28:      
8178                         case 0x29:      
8179                         case 0x2A:      
8180                         case 0x2B:      
8181                         case 0x2C:      
8182                         case 0x2D:      
8183                         case 0x2E:      
8184                         case 0x2F:      
8185                         case 0x30:      
8186                         case 0x31:      
8187                                 temp = b - 0x11;
8188                                 mfx_effect_sd[mfx].common_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8189                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Common MFX parameter (MFX:%02X param:%02X VAL:%02X)", mfx, temp, mfx_effect_sd[mfx].set_param[temp]);
8190                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8191                                 break;
8192                         }
8193                         break;
8194                 case 0x0B: // Temporary Multitimbre // Multitimbre Part
8195                         switch(b){
8196                         case 0x1C: // Part Dry Send Level
8197                                 channel[part].sd_dry_send_level = val;
8198                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Dry Send Level (%02X %02X)", part, val);
8199                                 break;
8200                         case 0x1F: // Part Output Assign
8201                                 if(val >= 33 || val < 0) {
8202                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Error : SD Part Output Assign (%02X %02X)", part, val);
8203                                         return;
8204                                 }
8205                                 channel[part].sd_output_assign = val > 2 ? 2 : val; // 0:MFX 1:NONE 2:Patch
8206                                 if(channel[part].sd_output_assign == 0)
8207                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 1);
8208                                 else if(channel[part].sd_output_assign == 1)
8209                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 0);
8210                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Output Assign (%02X %02X)", part, val);     
8211                                 break;
8212                         case 0x20: // Part Output MFX Select
8213                                 if(val >= SD_MFX_EFFECT_NUM || val < 0) {
8214                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Error : SD Part Output MFX Select (%02X %02X)", part, val);
8215                                         return;
8216                                 }       
8217                                 channel[part].sd_output_mfx_select = val;
8218                                 if(channel[part].sd_output_assign != 1 && *mfx_effect_sd[val].type > 0)
8219                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 1);
8220                                 else
8221                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 0);
8222                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Output MFX Select (%02X %02X)", part, val);
8223                                 break;
8224                         }
8225                         break;
8226                 case 0x0C: // Temporary Multitimbre // Multitimbre MIDI
8227                         break;
8228                 case 0x0D: // Temporary Patch // Patch Common
8229                         break;
8230                 case 0x0E: // Temporary Patch // Patch Common Chorus // Temporary Rhythm // Rhythm Common Chorus
8231                         switch(b)       {
8232                         case 0x00:      // Chorus Type part                             
8233                                 temp = channel[part].chorus_part_type;
8234                                 channel[part].chorus_part_type = val;
8235                                 if(temp == val) {
8236                                         recompute_chorus_status_sd(&chorus_status_sd, 1);
8237                                 } else {
8238                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Chorus Type (VAL:%02X)", val);
8239                                         if(val == 0x03) // param[0]:type
8240                                                 channel[part].chorus_part_param[0] = 0x7F; // type default 
8241                                         realloc_chorus_status_sd(&chorus_status_sd, 0);
8242                                 }
8243                                 break;
8244                         case 0x01:      // Chorus Level part    
8245                                 channel[part].chorus_part_efx_level = val;
8246                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
8247                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Chorus Level (VAl:%02X)", val);     
8248                                 break;
8249                         case 0x02:      // Chorus Output Select part    
8250                                 channel[part].chorus_part_output_select = val;
8251                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
8252                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Chorus Output Select (VAl:%02X)", val);     
8253                                 break;
8254                         case 0x03:      // Chorus Parameter 1 part      
8255                         case 0x04:      // Chorus Parameter 2 part      
8256                         case 0x05:      // Chorus Parameter 3 part      
8257                         case 0x06:      // Chorus Parameter 4 part      
8258                         case 0x07:      // Chorus Parameter 5 part      
8259                         case 0x08:      // Chorus Parameter 6 part      
8260                         case 0x09:      // Chorus Parameter 7 part      
8261                         case 0x0A:      // Chorus Parameter 8 part      
8262                         case 0x0B:      // Chorus Parameter 9 part      
8263                         case 0x0C:      // Chorus Parameter 10 part     
8264                         case 0x0D:      // Chorus Parameter 11 part             
8265                         case 0x0E:      // Chorus Parameter 12 part     
8266                                 temp = b - 0x03;
8267                                 if(channel[part].chorus_part_type == 0x03 && temp == 0){ // type
8268                                         int prev = channel[part].chorus_part_param[temp];
8269                                         channel[part].chorus_part_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8270                                         if(prev != channel[part].chorus_part_param[temp])
8271                                                 realloc_chorus_status_sd(&chorus_status_sd, 0);
8272                                         else
8273                                                 recompute_chorus_status_sd(&chorus_status_sd, 1);
8274                                 }else{
8275                                         channel[part].chorus_part_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8276                                         recompute_chorus_status_sd(&chorus_status_sd, 1);
8277                                 }
8278                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Chorus parameter (param:%02X VAL:%02X)", temp, channel[part].chorus_part_param[temp]);
8279                                 break;
8280                         }
8281                         break;
8282                 case 0x0F: // Temporary Patch // Patch Common Reverb // Temporary Rhythm // Rhythm Common Reverb
8283                         switch(b)       {
8284                         case 0x00:      // Reverb Type part                             
8285                                 temp = channel[part].reverb_part_type;
8286                                 channel[part].reverb_part_type = val;
8287                                 if(temp == val) {
8288                                         recompute_reverb_status_sd(&reverb_status_sd, 1);
8289                                 } else {
8290                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Reverb Type (VAL:%02X)", val);
8291                                         if(val == 0x01 || val == 0x05) // param[0]:type
8292                                                 channel[part].reverb_part_param[0] = 0x7F; // type default 
8293                                         realloc_reverb_status_sd(&reverb_status_sd, 0);
8294                                 }
8295                                 break;
8296                         case 0x01:      // Reverb Level part    
8297                                 channel[part].reverb_part_efx_level = val;
8298                                 recompute_reverb_status_sd(&reverb_status_sd, 1);
8299                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Reverb Level (VAl:%02X)", val);     
8300                                 break;
8301                         case 0x02:      // Reverb Parameter 1 part
8302                         case 0x03:      // Reverb Parameter 2 part
8303                         case 0x04:      // Reverb Parameter 3 part
8304                         case 0x05:      // Reverb Parameter 4 part
8305                         case 0x06:      // Reverb Parameter 5 part
8306                         case 0x07:      // Reverb Parameter 6 part
8307                         case 0x08:      // Reverb Parameter 7 part
8308                         case 0x09:      // Reverb Parameter 8 part
8309                         case 0x0A:      // Reverb Parameter 9 part
8310                         case 0x0B:      // Reverb Parameter 10 part
8311                         case 0x0C:      // Reverb Parameter 11 part
8312                         case 0x0D:      // Reverb Parameter 12 part
8313                         case 0x0E:      // Reverb Parameter 13 part
8314                         case 0x0F:      // Reverb Parameter 14 part
8315                         case 0x10:      // Reverb Parameter 15 part
8316                         case 0x11:      // Reverb Parameter 16 part
8317                         case 0x12:      // Reverb Parameter 17 part
8318                         case 0x13:      // Reverb Parameter 18 part
8319                         case 0x14:      // Reverb Parameter 19 part
8320                         case 0x15:      // Reverb Parameter 20 part
8321                                 temp = b - 0x02;
8322                                 if((channel[part].reverb_part_type == 0x01 || channel[part].reverb_part_type == 0x05) && temp == 0){ // type
8323                                         int prev = channel[part].reverb_part_param[temp];
8324                                         channel[part].reverb_part_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8325                                         if(prev != channel[part].reverb_part_param[temp])
8326                                                 realloc_reverb_status_sd(&reverb_status_sd, 0);
8327                                         else
8328                                                 recompute_reverb_status_sd(&reverb_status_sd, 1);
8329                                 }else{
8330                                         channel[part].reverb_part_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8331                                         recompute_reverb_status_sd(&reverb_status_sd, 1);
8332                                 }
8333                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Reverb Parameter (param:%02X VAL:%02X)", temp, channel[part].reverb_part_param[temp]);
8334                                 break;
8335                         }
8336                         break;
8337                 case 0x10: // Temporary Patch // Patch Common MFX // Temporary Rhythm // Rhythm Common MFX
8338                         mfx = channel[part].sd_output_mfx_select;
8339                         if(!opt_insertion_effect) {break;}
8340                         switch(b)       {
8341                         case 0x00:      /* MFX Type part */
8342                                 temp = channel[part].mfx_part_type;
8343                                 channel[part].mfx_part_type = val;                              
8344                                 if(temp == val) {
8345                                         recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8346                                 } else {
8347                                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX type (%02X %02X)", part, val);
8348                                         realloc_mfx_effect_sd(&mfx_effect_sd[mfx], 0);
8349                                 }
8350                                 if(val > 0)
8351                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 1);
8352                                 else
8353                                         ctl_mode_event(CTLE_INSERTION_EFFECT, 1, ch, 0);
8354                                 break;
8355                         case 0x01: // MFX Dry Send Level
8356                                 channel[part].mfx_part_dry_send = val;
8357                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8358                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part Dry Send Level (%02X %02X)", part, val);            
8359                                 break;
8360                         case 0x02: // MFX Chorus Send Level
8361                                 channel[part].mfx_part_send_chorus = val;
8362                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8363                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Chorus Send Level (%02X %02X)", part, val);     
8364                                 break;  
8365                         case 0x03: // MFX Reverb Send Level
8366                                 channel[part].mfx_part_send_reverb = val;
8367                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8368                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Reverb Send Level (%02X %02X)", part, val);     
8369                                 break;
8370                         //case 0x04: // none
8371                         case 0x05: // MFX Control 1 Source
8372                                 channel[part].mfx_part_ctrl_source[0] = val;
8373                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8374                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 1 Source (%02X %02X)", part, val);      
8375                                 break;
8376                         case 0x06: // MFX Control 1 Sens 
8377                                 channel[part].mfx_part_ctrl_sens[0] = val;
8378                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8379                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 1 Sens (%02X %02X)", part, val);        
8380                                 break;
8381                         case 0x07: // MFX Control 2 Source
8382                                 channel[part].mfx_part_ctrl_source[1] = val;
8383                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8384                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 2 Source (%02X %02X)", part, val);      
8385                                 break;
8386                         case 0x08: // MFX Control 2 Sens 
8387                                 channel[part].mfx_part_ctrl_sens[1] = val;
8388                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8389                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 2 Sens (%02X %02X)", part, val);        
8390                                 break;
8391                         case 0x09: // MFX Control 3 Source
8392                                 channel[part].mfx_part_ctrl_source[2] = val;
8393                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8394                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 3 Source (%02X %02X)", part, val);      
8395                                 break;
8396                         case 0x0A: // MFX Control 3 Sens 
8397                                 channel[part].mfx_part_ctrl_sens[2] = val;
8398                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 3 Sens (%02X %02X)", part, val);        
8399                                 break;
8400                         case 0x0B: // MFX Control 4 Source
8401                                 channel[part].mfx_part_ctrl_source[3] = val;
8402                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8403                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 4 Source (%02X %02X)", part, val);      
8404                                 break;
8405                         case 0x0C: // MFX Control 4 Sens 
8406                                 channel[part].mfx_part_ctrl_sens[3] = val;
8407                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8408                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control 4 Sens (%02X %02X)", part, val);        
8409                                 break;
8410                         case 0x0D: // MFX Control Assign 1
8411                                 channel[part].mfx_part_ctrl_assign[0] = val;
8412                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control Assign 1 (%02X %02X)", part, val);      
8413                                 break;
8414                         case 0x0E: // MFX Control Assign 2
8415                                 channel[part].mfx_part_ctrl_assign[1] = val;
8416                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8417                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control Assign 2 (%02X %02X)", part, val);      
8418                                 break;
8419                         case 0x0F: // MFX Control Assign 3
8420                                 channel[part].mfx_part_ctrl_assign[2] = val;
8421                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8422                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control Assign 3 (%02X %02X)", part, val);      
8423                                 break;
8424                         case 0x10: // MFX Control Assign 4
8425                                 channel[part].mfx_part_ctrl_assign[3] = val;
8426                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8427                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Control Assign 4 (%02X %02X)", part, val);      
8428                                 break;
8429                         case 0x11: // MFX parameter
8430                         case 0x12:
8431                         case 0x13:
8432                         case 0x14:
8433                         case 0x15:
8434                         case 0x16:
8435                         case 0x17:
8436                         case 0x18:
8437                         case 0x19:
8438                         case 0x1A:
8439                         case 0x1B:
8440                         case 0x1C:
8441                         case 0x1D:
8442                         case 0x1E:
8443                         case 0x1F:
8444                         case 0x20:
8445                         case 0x21:      
8446                         case 0x22:      
8447                         case 0x23:      
8448                         case 0x24:      
8449                         case 0x25:      
8450                         case 0x26:      
8451                         case 0x27:      
8452                         case 0x28:      
8453                         case 0x29:      
8454                         case 0x2A:      
8455                         case 0x2B:      
8456                         case 0x2C:      
8457                         case 0x2D:      
8458                         case 0x2E:      
8459                         case 0x2F:      
8460                         case 0x30:      
8461                         case 0x31:      
8462                                 temp = b - 0x11;
8463                                 channel[part].mfx_part_param[temp] = (int32)(((uint16)(hval & 0xFF) << 8) | val) - 0x8000;
8464                                 ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "SD Part MFX Parameter (%02X %02X %02X)", part, temp, channel[part].mfx_part_param[temp]);
8465                                 recompute_mfx_effect_sd(&mfx_effect_sd[mfx], 1);
8466                                 break;
8467                         }
8468                         break;
8469                 case 0x11: // Temporary Patch // Patch Common TMT
8470                         break;
8471                 case 0x12: // Temporary Patch // Patch Common Tone
8472                         break;
8473                 case 0x13: // Temporary Rhythm // Rhythm Common
8474                         break;
8475                 case 0x17: // Temporary Rhythm // Rhythm Common Tone
8476                         break;
8477                 default:
8478                         break;
8479                 }
8480         }
8481 }
8482
8483 /* 
8484 play_midi_prescan()\82Å\8eg\97p\82·\82éprocess_sysex_event()\82Ì\8aÈ\88Õ\94Å
8485 \95K\97v\82È\82Ì\82Í \83m\81[\83g\8aÖ\98A Rx.\8aÖ\98A MasterVolume\8aÖ\98A
8486 \83G\83t\83F\83N\83g\82È\82Ç\82Í\95s\97
8487 \83R\83\93\83\\81[\83\8b\8fo\97Í \83R\83\93\83g\83\8d\81[\83\8b\95\\8e¦ \82à\8dí\8f\9c ctl->cmsg() redraw_controllers()
8488 */
8489 static void process_sysex_event_prescan(int ev, int ch, int val, int b)
8490 {
8491         int temp, msb, note;
8492
8493         if (ch >= MAX_CHANNELS)
8494                 return;
8495         if (ev == ME_SYSEX_MSB) {
8496                 channel[ch].sysex_msb_addr = b;
8497                 channel[ch].sysex_msb_val = val;
8498         } else if(ev == ME_SYSEX_GS_MSB) {
8499                 channel[ch].sysex_gs_msb_addr = b;
8500                 channel[ch].sysex_gs_msb_val = val;
8501         } else if(ev == ME_SYSEX_XG_MSB) {
8502                 channel[ch].sysex_xg_msb_addr = b;
8503                 channel[ch].sysex_xg_msb_val = val;
8504         } else if(ev == ME_SYSEX_SD_MSB) {
8505                 channel[ch].sysex_sd_msb_addr = b;
8506                 channel[ch].sysex_sd_msb_val = val;
8507         } else if(ev == ME_SYSEX_SD_HSB) {
8508                 channel[ch].sysex_sd_hsb_addr = b;
8509                 channel[ch].sysex_sd_hsb_val = val;
8510         } else if(ev == ME_SYSEX_LSB) { /* Universal system exclusive message */
8511                 msb = channel[ch].sysex_msb_addr;
8512                 note = channel[ch].sysex_msb_val;
8513                 channel[ch].sysex_msb_addr = channel[ch].sysex_msb_val = 0;
8514                 switch(b)
8515                 {
8516                 case 0x42:      /* Note Limit Low */
8517                         channel[ch].note_limit_low = val;
8518                         break;
8519                 case 0x43:      /* Note Limit High */
8520                         channel[ch].note_limit_high = val;
8521                         break;
8522                 case 0x44:      /* Velocity Limit Low */
8523                         channel[ch].vel_limit_low = val;
8524                         break;
8525                 case 0x45:      /* Velocity Limit High */
8526                         channel[ch].vel_limit_high = val;
8527                         break;
8528                 case 0x46:      /* Rx. Note Off */
8529                         if (channel[ch].drums[note] == NULL)
8530                                 play_midi_setup_drums(ch, note);
8531                         set_rx_drum(channel[ch].drums[note], RX_NOTE_OFF, val);
8532                         channel[ch].drums[note]->rx_note_off = 1;
8533                         break;
8534                 case 0x47:      /* Rx. Note On */
8535                         if (channel[ch].drums[note] == NULL)
8536                                 play_midi_setup_drums(ch, note);
8537                         set_rx_drum(channel[ch].drums[note], RX_NOTE_ON, val);
8538                         break;
8539                 case 0x48:      /* Rx. Pitch Bend */
8540                         set_rx(ch, RX_PITCH_BEND, val);
8541                         break;
8542                 case 0x49:      /* Rx. Channel Pressure */
8543                         set_rx(ch, RX_CH_PRESSURE, val);
8544                         break;
8545                 case 0x4A:      /* Rx. Program Change */
8546                         set_rx(ch, RX_PROGRAM_CHANGE, val);
8547                         break;
8548                 case 0x4B:      /* Rx. Control Change */
8549                         set_rx(ch, RX_CONTROL_CHANGE, val);
8550                         break;
8551                 case 0x4C:      /* Rx. Poly Pressure */
8552                         set_rx(ch, RX_POLY_PRESSURE, val);
8553                         break;
8554                 case 0x4D:      /* Rx. Note Message */
8555                         set_rx(ch, RX_NOTE_MESSAGE, val); 
8556                         break;
8557                 case 0x4E:      /* Rx. RPN */
8558                         set_rx(ch, RX_RPN, val);
8559                         break;
8560                 case 0x4F:      /* Rx. NRPN */
8561                         set_rx(ch, RX_NRPN, val);
8562                         break;
8563                 case 0x50:      /* Rx. Modulation */
8564                         set_rx(ch, RX_MODULATION, val);
8565                         break;
8566                 case 0x51:      /* Rx. Volume */
8567                         set_rx(ch, RX_VOLUME, val);
8568                         break;
8569                 case 0x52:      /* Rx. Panpot */
8570                         set_rx(ch, RX_PANPOT, val);
8571                         break;
8572                 case 0x53:      /* Rx. Expression */
8573                         set_rx(ch, RX_EXPRESSION, val); 
8574                         break;
8575                 case 0x54:      /* Rx. Hold1 */
8576                         set_rx(ch, RX_HOLD1, val);
8577                         break;
8578                 case 0x55:      /* Rx. Portamento */
8579                         set_rx(ch, RX_PORTAMENTO, val);
8580                         break;
8581                 case 0x56:      /* Rx. Sostenuto */
8582                         set_rx(ch, RX_SOSTENUTO, val);
8583                         break;
8584                 case 0x57:      /* Rx. Soft */
8585                         set_rx(ch, RX_SOFT, val);
8586                         break;
8587                 case 0x58:      /* Rx. Bank Select */
8588                         set_rx(ch, RX_BANK_SELECT, val); 
8589                         break;
8590                 case 0x59:      /* Rx. Bank Select LSB */
8591                         set_rx(ch, RX_BANK_SELECT_LSB, val);
8592                         break;  
8593                 case 0x6C:      /* GM2 Instrument Select */
8594                         if(ch == 0xFF){
8595                                 int i;
8596                                 for(i = 0; i < MAX_CHANNELS; i++)
8597                                         channel[i].gm2_inst = val;
8598                         }else{
8599                                 channel[ch].gm2_inst = val;
8600                         }
8601                         break;
8602                 default:
8603                         break;
8604                 }
8605                 return;
8606         } else if(ev == ME_SYSEX_GS_LSB) {      /* GS system exclusive message */
8607                 msb = channel[ch].sysex_gs_msb_addr;
8608                 note = channel[ch].sysex_gs_msb_val;
8609                 channel[ch].sysex_gs_msb_addr = channel[ch].sysex_gs_msb_val = 0;
8610                 switch(b)
8611                 {
8612                 case 0x21:      /* Velocity Sense Depth */
8613                         channel[ch].velocity_sense_depth = val;
8614                         break;
8615                 case 0x22:      /* Velocity Sense Offset */
8616                         channel[ch].velocity_sense_offset = val;
8617                         break;
8618                 case 0x24:      /* Assign Mode */
8619                         channel[ch].assign_mode = val;
8620                         break;
8621                 case 0x25:      /* TONE MAP-0 NUMBER */
8622                         channel[ch].tone_map0_number = val;
8623                         break;
8624                 case 0x45:      /* Rx. Channel */
8625                         reset_controllers(ch);
8626                         all_notes_off(ch);
8627                         if (val == 0x80)
8628                                 remove_channel_layer(ch);
8629                         else
8630                                 add_channel_layer(ch, val);
8631                         break;
8632                 case 0x46:      /* Channel Msg Rx Port */
8633                         reset_controllers(ch);
8634                         all_notes_off(ch);
8635                         channel[ch].port_select = val;
8636                         break;
8637                 case 0x47:      /* Play Note Number */
8638                         if (channel[ch].drums[note] == NULL)
8639                                 play_midi_setup_drums(ch, note);
8640                         channel[ch].drums[note]->play_note = val;
8641                         break;
8642                 default:
8643                         break;
8644                 }
8645                 return;
8646         } else if(ev == ME_SYSEX_XG_LSB) {      /* XG system exclusive message */
8647                 msb = channel[ch].sysex_xg_msb_addr;
8648                 note = channel[ch].sysex_xg_msb_val;
8649 ///r
8650                 if (note == 2 && msb >= 0 && msb < 0x40) {      /* Effect 1 */
8651                         note = 0;       /* not use */
8652                         if(b >= 0x40){ /* variation effect */
8653                                 msb -= 1;       /* variation effect num start 1 , dim 0*/
8654                                 /* msb=0 variation 1 */ 
8655                                 /* msb=n variation n+1 */ 
8656                                 if(msb < 0 || msb >= XG_VARIATION_EFFECT_NUM){
8657                                         return;
8658                                 }
8659                         }
8660
8661                 } else if (note == 2 && msb == 0x40) {  /* Multi EQ */
8662
8663                 } else if (note == 3 && msb >= 0) {     /* Effect 2 */
8664                         /* msb=0 : insertion 1 */
8665                         /* msb=n : insertion n+1 */
8666                         if ( msb >= XG_INSERTION_EFFECT_NUM) {
8667                                 return;
8668                         }
8669
8670                 } else if (note == 8 && msb == 0) {     /* Multi Part */
8671                         switch(b)
8672                         {
8673         /*
8674                         case 0x01:      // Bank Select MSB
8675                                 channel[ch].bank_msb = val;
8676                                 break;
8677                         case 0x02:      // Bank Select LSB
8678                                 channel[ch].bank_lsb = val;
8679                                 break;
8680                         case 0x03:      // Program Change
8681                                 channel[ch].program = val;
8682                                 break;
8683                         case 0x04:      // Rcv CHANNEL, remapped from 0x04 ?
8684                                 reset_controllers(ch);
8685                                 all_notes_off(ch);
8686                                 if (val == 0x7f)
8687                                         remove_channel_layer(ch);
8688                                 else {
8689                                         if((ch < REDUCE_CHANNELS) != (val < REDUCE_CHANNELS)) {
8690                                                 channel[ch].port_select = ch < REDUCE_CHANNELS ? 1 : 0;
8691                                         }
8692                                         if((ch % REDUCE_CHANNELS) != (val % REDUCE_CHANNELS)) {
8693                                                 add_channel_layer(ch, val);
8694                                         }
8695                                 }
8696                                 break;
8697                         case 0x05:      // Mono/Poly Mode
8698                                 channel[ch].mono = val;
8699                                 break;
8700         */
8701                         case 0x06:      /* Same Note Number Key On Assign */
8702                                 if(val == 0) {
8703                                         channel[ch].assign_mode = 0;
8704                                 } else if(val == 1) {
8705                                         channel[ch].assign_mode = 1; // XG Multi : Not Full Multi
8706                                 } else if(val == 2) {
8707                                 } else if(val == 3) {
8708                                         channel[ch].assign_mode = 2; // Timidity Full Multi
8709                                 }
8710                                 break;
8711         /*
8712                         case 0x07:      // Part Mode
8713                                 midi_drumpart_change(ch, TRUE);
8714                                 channel[ch].bank_msb = 127;
8715                                 break;
8716                         case 0x08:      // note shift
8717                                 break;
8718         */
8719                         case 0x99:      /* Rcv CHANNEL, remapped from 0x04 */
8720                                 reset_controllers(ch);
8721                                 all_notes_off(ch);
8722                                 if (val == 0x7f)
8723                                         remove_channel_layer(ch);
8724                                 else {
8725                                         if((ch < REDUCE_CHANNELS) != (val < REDUCE_CHANNELS)) {
8726                                                 channel[ch].port_select = ch < REDUCE_CHANNELS ? 1 : 0;
8727                                         }
8728                                         if((ch % REDUCE_CHANNELS) != (val % REDUCE_CHANNELS)) {
8729                                                 add_channel_layer(ch, val);
8730                                         }
8731                                 }
8732                                 break;
8733                         }
8734                 } else if ((note & 0xF0) == 0x30) {     /* Drum Setup */
8735                         note = msb;
8736                 }
8737                 return;
8738
8739         }
8740 }
8741
8742 static void play_midi_prescan(MidiEvent *ev)
8743 {
8744     int i, j, k, ch, orig_ch, port_ch, offset, layered;
8745     
8746     if(opt_amp_compensation) {mainvolume_max = 0;}
8747     else {mainvolume_max = 0x7f;}
8748  //   compensation_ratio = 1.0;
8749
8750     prescanning_flag = 1;
8751     change_system_mode(DEFAULT_SYSTEM_MODE);
8752     reset_midi(0);
8753         if(allocate_cache_size > 0)
8754                 resamp_cache_reset();
8755
8756         while (ev->type != ME_EOT) {
8757 #ifndef SUPPRESS_CHANNEL_LAYER
8758                 orig_ch = ev->channel;
8759                 layered = ! IS_SYSEX_EVENT_TYPE(ev);
8760                 for (j = 0; j < MAX_CHANNELS; j += 16) {
8761                         port_ch = (orig_ch + j) % MAX_CHANNELS;
8762                         offset = port_ch & ~0xf;
8763                         for (k = offset; k < offset + 16; k++) {
8764                                 if (! layered && (j || k != offset))
8765                                         continue;
8766                                 if (layered) {
8767                                         if (! IS_SET_CHANNELMASK(
8768                                                         channel[k].channel_layer, port_ch)
8769                                                         || channel[k].port_select != (orig_ch >> 4))
8770                                                 continue;
8771                                         ev->channel = k;
8772                                 }
8773 #endif
8774         ch = ev->channel;
8775
8776         switch(ev->type)
8777         {
8778           case ME_NOTEON:
8779                 note_on_prescan(ev);
8780             break;
8781
8782           case ME_NOTEOFF:
8783                 if(allocate_cache_size > 0)
8784                         resamp_cache_refer_off(ch, MIDI_EVENT_NOTE(ev), ev->time);
8785             break;
8786
8787           case ME_PORTAMENTO_TIME_MSB:
8788                 if(opt_portamento){
8789                         channel[ch].portamento_time_msb = ev->a;
8790                 }
8791             break;
8792
8793           case ME_PORTAMENTO_TIME_LSB:
8794                 if(opt_portamento){
8795                         channel[ch].portamento_time_lsb = ev->a;
8796                 }
8797             break;
8798
8799           case ME_PORTAMENTO:             
8800                 if(!get_rx(ch, RX_PORTAMENTO)) break;
8801                 if(opt_portamento){
8802                         channel[ch].portamento = (ev->a >= 64);
8803                 }
8804             break;
8805
8806       case ME_PORTAMENTO_CONTROL:
8807                 if(opt_portamento){
8808                         channel[ch].portamento_control = ev->a;
8809                 }
8810                 break;
8811
8812           case ME_RESET_CONTROLLERS:
8813             reset_controllers(ch);
8814                 if(allocate_cache_size > 0)
8815                         resamp_cache_refer_alloff(ch, ev->time);
8816             break;
8817
8818           case ME_PROGRAM:
8819             midi_program_change(ch, ev->a);
8820             break;
8821
8822           case ME_TONE_BANK_MSB:
8823             channel[ch].bank_msb = ev->a;
8824             break;
8825
8826           case ME_TONE_BANK_LSB:
8827             channel[ch].bank_lsb = ev->a;
8828             break;
8829
8830           case ME_RESET:
8831             change_system_mode(ev->a);
8832             reset_midi(0);
8833             break;
8834
8835           case ME_MASTER_TUNING:
8836           case ME_PITCHWHEEL:
8837                 adjust_pitch(ch);
8838           case ME_ALL_NOTES_OFF:
8839           case ME_ALL_SOUNDS_OFF:
8840           case ME_MONO:
8841           case ME_POLY:
8842                 if(allocate_cache_size > 0)
8843                         resamp_cache_refer_alloff(ch, ev->time);
8844             break;
8845 ///r
8846           case ME_DRUMPART:
8847                 if(play_system_mode == XG_SYSTEM_MODE && ev->a)
8848                         channel[ch].bank_msb = 127; // Drum kit
8849             if(midi_drumpart_change(ch, ev->a))
8850                 midi_program_change(ch, channel[ch].program);
8851             break;
8852
8853           case ME_KEYSHIFT:
8854                 if(allocate_cache_size > 0)
8855                         resamp_cache_refer_alloff(ch, ev->time);
8856             channel[ch].key_shift = (int)ev->a - 0x40;
8857             break;
8858                 
8859           case ME_SCALE_TUNING:
8860                 if(allocate_cache_size > 0)
8861                         resamp_cache_refer_alloff(ch, ev->time);
8862                 channel[ch].scale_tuning[ev->a] = ev->b;
8863                 break;
8864
8865           case ME_MAINVOLUME:
8866                 if(opt_amp_compensation)
8867                         if (ev->a > mainvolume_max) {
8868                           mainvolume_max = ev->a;
8869                           ctl->cmsg(CMSG_INFO,VERB_DEBUG,"ME_MAINVOLUME/max (CH:%d VAL:%#x)",ev->channel,ev->a);
8870                         }
8871             break;      
8872
8873           case ME_SYSEX_LSB:
8874             process_sysex_event_prescan(ME_SYSEX_LSB,ch,ev->a,ev->b);
8875             break;
8876
8877           case ME_SYSEX_MSB:
8878             process_sysex_event_prescan(ME_SYSEX_MSB,ch,ev->a,ev->b);
8879             break;
8880
8881           case ME_SYSEX_GS_LSB:
8882             process_sysex_event_prescan(ME_SYSEX_GS_LSB,ch,ev->a,ev->b);
8883             break;
8884
8885           case ME_SYSEX_GS_MSB:
8886             process_sysex_event_prescan(ME_SYSEX_GS_MSB,ch,ev->a,ev->b);
8887             break;
8888
8889           case ME_SYSEX_XG_LSB:
8890             process_sysex_event_prescan(ME_SYSEX_XG_LSB,ch,ev->a,ev->b);
8891             break;
8892
8893           case ME_SYSEX_XG_MSB:
8894             process_sysex_event_prescan(ME_SYSEX_XG_MSB,ch,ev->a,ev->b);
8895             break;
8896
8897         case ME_SYSEX_SD_LSB:
8898         //      process_sysex_event_prescan(ME_SYSEX_SD_LSB,ch,ev->a,ev->b);
8899             break;
8900
8901         case ME_SYSEX_SD_MSB:
8902         //      process_sysex_event_prescan(ME_SYSEX_SD_MSB,ch,ev->a,ev->b);
8903             break;
8904
8905         case ME_SYSEX_SD_HSB:
8906         //      process_sysex_event_prescan(ME_SYSEX_SD_HSB,ch,ev->a,ev->b);
8907             break;
8908         }
8909 #ifndef SUPPRESS_CHANNEL_LAYER
8910                         }
8911                 }
8912                 ev->channel = orig_ch;
8913 #endif
8914         ev++;
8915     }
8916                 
8917     /* calculate compensation ratio */
8918         if(opt_amp_compensation){
8919                 if(mainvolume_max < 1)
8920                         mainvolume_max = 1; // div0
8921                 if (opt_user_volume_curve != 0) {
8922                         compensation_ratio = (double)127.0 / user_vol_table[mainvolume_max & 0x7F];
8923                 } else if (play_system_mode == SD_SYSTEM_MODE) {
8924                         compensation_ratio = (double)127.0 / gm2_vol_table[mainvolume_max & 0x7F];
8925                 } else if (play_system_mode == GM2_SYSTEM_MODE) {
8926                         compensation_ratio = (double)127.0 / gm2_vol_table[mainvolume_max & 0x7F];
8927                 } else if(play_system_mode == GS_SYSTEM_MODE) { /* use measured curve */ 
8928                         compensation_ratio = (double)127.0 / sc_vol_table[mainvolume_max & 0x7F];
8929                 } else if(play_system_mode == CM_SYSTEM_MODE) { /* use measured curve */
8930                         compensation_ratio = (double)127.0/ sc_vol_table[mainvolume_max & 0x7F];
8931                 } else if (IS_CURRENT_MOD_FILE) {       /* use linear curve */
8932                         compensation_ratio = (double)127.0 / (double)(mainvolume_max & 0x7F);
8933                 } else {        /* use generic exponential curve */
8934                         compensation_ratio = (double)127.0 / perceived_vol_table[mainvolume_max & 0x7F];
8935                 }
8936                 ctl->cmsg(CMSG_INFO,VERB_DEBUG,"Compensation ratio:%lf",compensation_ratio);
8937         }
8938     //if (0 < mainvolume_max && mainvolume_max < 0x7f) {
8939     //  compensation_ratio = pow((double)0x7f/(double)mainvolume_max, 4);
8940     //  ctl->cmsg(CMSG_INFO,VERB_DEBUG,"Compensation ratio:%lf",compensation_ratio);
8941     //} 
8942         
8943         if(allocate_cache_size > 0){
8944                 for(i = 0; i < MAX_CHANNELS; i++)
8945                         resamp_cache_refer_alloff(i, ev->time);
8946                 resamp_cache_create();
8947         }
8948     prescanning_flag = 0;
8949 }
8950
8951 static int last_rpn_addr(int ch)
8952 {
8953         int lsb, msb, addr, i;
8954         struct rpn_tag_map_t *addrmap;
8955         struct rpn_tag_map_t {
8956                 int addr, mask, tag;
8957         };
8958         static struct rpn_tag_map_t nrpn_addr_map[] = {
8959                 {0x0108, 0xffff, NRPN_ADDR_0108},
8960                 {0x0109, 0xffff, NRPN_ADDR_0109},
8961                 {0x010a, 0xffff, NRPN_ADDR_010A},
8962                 {0x0120, 0xffff, NRPN_ADDR_0120},
8963                 {0x0121, 0xffff, NRPN_ADDR_0121},
8964                 {0x0124, 0xffff, NRPN_ADDR_0124}, // hpf
8965                 {0x0125, 0xffff, NRPN_ADDR_0125}, // hpf
8966                 {0x0130, 0xffff, NRPN_ADDR_0130},
8967                 {0x0131, 0xffff, NRPN_ADDR_0131},
8968                 {0x0132, 0xffff, NRPN_ADDR_0132},
8969                 {0x0133, 0xffff, NRPN_ADDR_0133},
8970                 {0x0134, 0xffff, NRPN_ADDR_0134},
8971                 {0x0135, 0xffff, NRPN_ADDR_0135},
8972                 {0x0136, 0xffff, NRPN_ADDR_0136},
8973                 {0x0137, 0xffff, NRPN_ADDR_0137},
8974                 {0x0138, 0xffff, NRPN_ADDR_0138},
8975                 {0x0139, 0xffff, NRPN_ADDR_0139},
8976                 {0x013A, 0xffff, NRPN_ADDR_013A},
8977                 {0x013B, 0xffff, NRPN_ADDR_013B},
8978                 {0x013C, 0xffff, NRPN_ADDR_013C},
8979                 {0x013D, 0xffff, NRPN_ADDR_013D},
8980                 {0x0163, 0xffff, NRPN_ADDR_0163},
8981                 {0x0164, 0xffff, NRPN_ADDR_0164},
8982                 {0x0166, 0xffff, NRPN_ADDR_0166},
8983                 {0x1400, 0xff00, NRPN_ADDR_1400},
8984                 {0x1500, 0xff00, NRPN_ADDR_1500},
8985                 {0x1600, 0xff00, NRPN_ADDR_1600},
8986                 {0x1700, 0xff00, NRPN_ADDR_1700},
8987                 {0x1800, 0xff00, NRPN_ADDR_1800},
8988                 {0x1900, 0xff00, NRPN_ADDR_1900},
8989                 {0x1a00, 0xff00, NRPN_ADDR_1A00},
8990                 {0x1c00, 0xff00, NRPN_ADDR_1C00},
8991                 {0x1d00, 0xff00, NRPN_ADDR_1D00},
8992                 {0x1e00, 0xff00, NRPN_ADDR_1E00},
8993                 {0x1f00, 0xff00, NRPN_ADDR_1F00},
8994                 {0x2400, 0xff00, NRPN_ADDR_2400}, // hpf
8995                 {0x2500, 0xff00, NRPN_ADDR_2500}, // hpf
8996                 {0x3000, 0xff00, NRPN_ADDR_3000},
8997                 {0x3100, 0xff00, NRPN_ADDR_3100},
8998                 {0x3200, 0xff00, NRPN_ADDR_3200},
8999                 {0x3300, 0xff00, NRPN_ADDR_3300},
9000                 {0x3400, 0xff00, NRPN_ADDR_3400},
9001                 {0x3500, 0xff00, NRPN_ADDR_3500},
9002                 {0x3600, 0xff00, NRPN_ADDR_3600},
9003                 {0x3700, 0xff00, NRPN_ADDR_3700},
9004                 {0x3800, 0xff00, NRPN_ADDR_3800},
9005                 {0x3900, 0xff00, NRPN_ADDR_3900},
9006                 {0x3A00, 0xff00, NRPN_ADDR_3A00},
9007                 {0x3B00, 0xff00, NRPN_ADDR_3B00},
9008                 {0x3C00, 0xff00, NRPN_ADDR_3C00},
9009                 {0x3D00, 0xff00, NRPN_ADDR_3D00},
9010                 {-1, -1, 0}
9011         };
9012         static struct rpn_tag_map_t rpn_addr_map[] = {
9013                 {0x0000, 0xffff, RPN_ADDR_0000},
9014                 {0x0001, 0xffff, RPN_ADDR_0001},
9015                 {0x0002, 0xffff, RPN_ADDR_0002},
9016                 {0x0003, 0xffff, RPN_ADDR_0003},
9017                 {0x0004, 0xffff, RPN_ADDR_0004},
9018                 {0x0005, 0xffff, RPN_ADDR_0005},
9019                 {0x0040, 0xffff, RPN_ADDR_0040},
9020                 {0x7f7f, 0xffff, RPN_ADDR_7F7F},
9021                 {0xffff, 0xffff, RPN_ADDR_FFFF},
9022                 {-1, -1}
9023         };
9024         
9025         if (channel[ch].nrpn == -1)
9026                 return -1;
9027         lsb = channel[ch].lastlrpn;
9028         msb = channel[ch].lastmrpn;
9029         if (lsb == 0xff || msb == 0xff)
9030                 return -1;
9031         addr = (msb << 8 | lsb);
9032         if (channel[ch].nrpn)
9033                 addrmap = nrpn_addr_map;
9034         else
9035                 addrmap = rpn_addr_map;
9036         for (i = 0; addrmap[i].addr != -1; i++)
9037                 if (addrmap[i].addr == (addr & addrmap[i].mask))
9038                         return addrmap[i].tag;
9039         return -1;
9040 }
9041
9042 static void update_rpn_map(int ch, int addr, int update_now)
9043 {
9044         int val, drumflag, i, note;
9045         
9046         val = channel[ch].rpnmap[addr];
9047         drumflag = 0;
9048         switch (addr) {
9049         case NRPN_ADDR_0108:    /* Vibrato Rate */
9050                 if (opt_nrpn_vibrato) {
9051                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9052                                         "NRPN Vibrato Rate (CH:%d VAL:%d)", ch, val - 64);
9053                         channel[ch].param_vibrato_rate = val - 64;
9054                 }
9055                 if (update_now){
9056                 //      adjust_pitch(ch);
9057                         recompute_channel_lfo(ch);
9058                         recompute_channel_pitch(ch);
9059                 }
9060                 break;
9061         case NRPN_ADDR_0109:    /* Vibrato Depth */
9062                 if (opt_nrpn_vibrato) {
9063                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9064                                         "NRPN Vibrato Depth (CH:%d VAL:%d)", ch, val - 64);
9065                         channel[ch].param_vibrato_depth = val - 64;
9066                 }
9067                 if (update_now){
9068                 //      adjust_pitch(ch);
9069                         recompute_channel_lfo(ch);
9070                         recompute_channel_pitch(ch);
9071                 }
9072                 break;
9073         case NRPN_ADDR_010A:    /* Vibrato Delay */
9074                 if (opt_nrpn_vibrato) {
9075                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9076                                         "NRPN Vibrato Delay (CH:%d VAL:%d)", ch, val - 64);
9077                         channel[ch].param_vibrato_delay = val - 64;
9078                 }
9079                 if (update_now){
9080                 //      adjust_pitch(ch);
9081                         recompute_channel_lfo(ch);
9082                         recompute_channel_pitch(ch);
9083                 }
9084                 break;
9085         case NRPN_ADDR_0120:    /* Filter Cutoff Frequency */
9086                 //if (opt_lpf_def) {
9087                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9088                                         "NRPN Filter Cutoff (CH:%d VAL:%d)", ch, val - 64);
9089                         channel[ch].param_cutoff_freq = val - 64;
9090                         if (update_now)
9091                         //      update_channel_filter(ch);
9092                                 recompute_channel_filter(ch);
9093                 //}
9094                 break;
9095         case NRPN_ADDR_0121:    /* Filter Resonance */
9096                 //if (opt_lpf_def) {
9097                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9098                                         "NRPN Filter Resonance (CH:%d VAL:%d)", ch, val - 64);
9099                         channel[ch].param_resonance = val - 64;
9100                         if (update_now)
9101                         //      update_channel_filter(ch);
9102                                 recompute_channel_filter(ch);
9103                 //}
9104                 break;
9105 ///r
9106         case NRPN_ADDR_0124:    /* HPF Filter Cutoff Frequency */
9107                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9108                                         "NRPN HPF Filter Cutoff (CH:%d VAL:%d)", ch, val - 64);
9109                         channel[ch].hpf_param_cutoff_freq = val - 64;
9110                         if (update_now)
9111                         //      update_channel_filter2(ch);
9112                                 recompute_channel_filter(ch);
9113                 break;
9114         case NRPN_ADDR_0125:    /* HPF Filter Resonance */
9115                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9116                                         "NRPN HPF Filter Resonance (CH:%d VAL:%d)", ch, val - 64);
9117                         channel[ch].hpf_param_resonance = val - 64;
9118                         if (update_now)
9119                         //      update_channel_filter2(ch);
9120                                 recompute_channel_filter(ch);
9121                 break;
9122         case NRPN_ADDR_0130:    /* EQ BASS */
9123                 if (opt_eq_control) {
9124                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ BASS (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9125                         channel[ch].eq_xg.bass = val;
9126                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9127                 }
9128                 break;
9129         case NRPN_ADDR_0131:    /* EQ TREBLE */
9130                 if (opt_eq_control) {
9131                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ TREBLE (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9132                         channel[ch].eq_xg.treble = val;
9133                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9134                 }
9135                 break;
9136         case NRPN_ADDR_0132:    /* EQ MID-BASS */
9137                 if (opt_eq_control) {
9138                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-BASS (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9139                         channel[ch].eq_xg.mid_bass = val;
9140                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9141                 }
9142                 break;
9143         case NRPN_ADDR_0133:    /* EQ MID-TREBLE */
9144                 if (opt_eq_control) {
9145                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-TREBLE (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9146                         channel[ch].eq_xg.mid_treble = val;
9147                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9148                 }
9149                 break;
9150         case NRPN_ADDR_0134:    /* EQ BASS frequency */
9151                 if (opt_eq_control) {
9152                         if(val < 4) {val = 4;}
9153                         else if(val > 40) {val = 40;}
9154                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ BASS frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9155                         channel[ch].eq_xg.bass_freq = val;
9156                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9157                 }
9158                 break;
9159         case NRPN_ADDR_0135:    /* EQ TREBLE frequency */
9160                 if (opt_eq_control) {
9161                         if(val < 28) {val = 28;}
9162                         else if(val > 58) {val = 58;}
9163                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ TREBLE frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9164                         channel[ch].eq_xg.treble_freq = val;
9165                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9166                 }
9167                 break;
9168         case NRPN_ADDR_0136:    /* EQ MID-BASS frequency */
9169                 if (opt_eq_control) {
9170                         if(val < 0x0E) {val = 0x0E;}
9171                         else if(val > 0x36) {val = 0x36;}
9172                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-BASS frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9173                         channel[ch].eq_xg.mid_bass_freq = val;
9174                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9175                 }
9176                 break;
9177         case NRPN_ADDR_0137:    /* EQ MID-TREBLE frequency */
9178                 if (opt_eq_control) {
9179                         if(val < 0x0E) {val = 0x0E;}
9180                         else if(val > 0x36) {val = 0x36;}
9181                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-TREBLE frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9182                         channel[ch].eq_xg.mid_treble_freq = val;
9183                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9184                 }
9185                 break;
9186         case NRPN_ADDR_0138:    /* EQ BASS Q */
9187                 if (opt_eq_control) {
9188                         if(val < 0x01) {val = 0x01;}
9189                         else if(val > 0x78) {val = 0x78;}
9190                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ BASS Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9191                         channel[ch].eq_xg.bass_q = val;
9192                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9193                 }
9194                 break;
9195         case NRPN_ADDR_0139:    /* EQ TREBLE Q */
9196                 if (opt_eq_control) {
9197                         if(val < 0x01) {val = 0x01;}
9198                         else if(val > 0x78) {val = 0x78;}
9199                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ TREBLE Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9200                         channel[ch].eq_xg.treble_q = val;
9201                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9202                 }
9203                 break;
9204         case NRPN_ADDR_013A:    /* EQ MID-BASS Q */
9205                 if (opt_eq_control) {
9206                         if(val < 0x01) {val = 0x01;}
9207                         else if(val > 0x78) {val = 0x78;}
9208                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-BASS Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9209                         channel[ch].eq_xg.mid_bass_q = val;
9210                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9211                 }
9212                 break;
9213         case NRPN_ADDR_013B:    /* EQ MID-TREBLE Q */
9214                 if (opt_eq_control) {
9215                         if(val < 0x01) {val = 0x01;}
9216                         else if(val > 0x78) {val = 0x78;}
9217                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ MID-TREBLE Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9218                         channel[ch].eq_xg.mid_treble_q = val;
9219                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9220                 }
9221                 break;
9222         case NRPN_ADDR_013C:    /* EQ BASS shape */
9223                 if (opt_eq_control) {
9224                         if(!val) {
9225                                 channel[ch].eq_xg.bass_shape = 0x00;
9226                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ BASS shape (CH:%d shalving)", ch);                      
9227                         }else{
9228                                 channel[ch].eq_xg.bass_shape = 0x01;
9229                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ BASS shape (CH:%d peaking)", ch);
9230                         }
9231                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9232                 }
9233                 break;
9234         case NRPN_ADDR_013D:    /* EQ TREBLE shape */
9235                 if (opt_eq_control) {
9236                         if(!val) {
9237                                 channel[ch].eq_xg.treble_shape =0x00;
9238                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ TREBLE shape (CH:%d shalving)", ch);                    
9239                         }else{
9240                                 channel[ch].eq_xg.treble_shape =0x01;
9241                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN EQ TREBLE shape (CH:%d peaking)", ch);
9242                         }
9243                         recompute_part_eq_xg(&(channel[ch].eq_xg));
9244                 }
9245                 break;
9246         case NRPN_ADDR_0163:    /* Attack Time */
9247                 if (opt_tva_attack) {set_envelope_time(ch, val, EG_ATTACK);}
9248                 break;
9249         case NRPN_ADDR_0164:    /* EG Decay Time */
9250                 if (opt_tva_decay) {set_envelope_time(ch, val, EG_DECAY);}
9251                 break;
9252         case NRPN_ADDR_0166:    /* EG Release Time */
9253                 if (opt_tva_release) {set_envelope_time(ch, val, EG_RELEASE);}
9254                 break;
9255         case NRPN_ADDR_1400:    /* Drum Filter Cutoff (XG) */
9256                 drumflag = 1;
9257                 note = channel[ch].lastlrpn;
9258                 if (channel[ch].drums[note] == NULL)
9259                         play_midi_setup_drums(ch, note);
9260                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9261                                 "NRPN Drum Instrument Filter Cutoff (CH:%d NOTE:%d VAL:%d)",
9262                                 ch, note, val);
9263                 channel[ch].drums[note]->drum_cutoff_freq = val - 64;
9264                 break;
9265         case NRPN_ADDR_1500:    /* Drum Filter Resonance (XG) */
9266                 drumflag = 1;
9267                 note = channel[ch].lastlrpn;
9268                 if (channel[ch].drums[note] == NULL)
9269                         play_midi_setup_drums(ch, note);
9270                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9271                                 "NRPN Drum Instrument Filter Resonance (CH:%d NOTE:%d VAL:%d)",
9272                                 ch, note, val);
9273                 channel[ch].drums[note]->drum_resonance = val - 64;
9274                 break;
9275         case NRPN_ADDR_1600:    /* Drum EG Attack Time (XG) */
9276                 drumflag = 1;
9277                 if (opt_tva_attack) {
9278                         val = val & 0x7f;
9279                         note = channel[ch].lastlrpn;
9280                         if (channel[ch].drums[note] == NULL)
9281                                 play_midi_setup_drums(ch, note);
9282                         val     -= 64;
9283                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9284                                         "NRPN Drum Instrument Attack Time (CH:%d NOTE:%d VAL:%d)",
9285                                         ch, note, val);
9286                         channel[ch].drums[note]->drum_envelope_rate[EG_ATTACK] = val;
9287                 }
9288                 break;
9289         case NRPN_ADDR_1700:    /* Drum EG Decay Time (XG) */
9290                 drumflag = 1;
9291                 if (opt_tva_decay) {
9292                         val = val & 0x7f;
9293                         note = channel[ch].lastlrpn;
9294                         if (channel[ch].drums[note] == NULL)
9295                                 play_midi_setup_drums(ch, note);
9296                         val     -= 64;
9297                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9298                                         "NRPN Drum Instrument Decay Time (CH:%d NOTE:%d VAL:%d)",
9299                                         ch, note, val);
9300                         channel[ch].drums[note]->drum_envelope_rate[EG_DECAY1] =
9301                                 channel[ch].drums[note]->drum_envelope_rate[EG_DECAY2] = val;
9302                 }
9303                 break;
9304         case NRPN_ADDR_1800:    /* Coarse Pitch of Drum (GS) */
9305                 drumflag = 1;
9306                 note = channel[ch].lastlrpn;
9307                 if (channel[ch].drums[note] == NULL)
9308                         play_midi_setup_drums(ch, note);
9309                 channel[ch].drums[note]->coarse = val - 64;
9310                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9311                         "NRPN Drum Instrument Pitch Coarse (CH:%d NOTE:%d VAL:%d)",
9312                         ch, note, channel[ch].drums[note]->coarse);
9313                 break;
9314         case NRPN_ADDR_1900:    /* Fine Pitch of Drum (XG) */
9315                 drumflag = 1;
9316                 note = channel[ch].lastlrpn;
9317                 if (channel[ch].drums[note] == NULL)
9318                         play_midi_setup_drums(ch, note);
9319                 channel[ch].drums[note]->fine = val - 64;
9320                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9321                                 "NRPN Drum Instrument Pitch Fine (CH:%d NOTE:%d VAL:%d)",
9322                                 ch, note, channel[ch].drums[note]->fine);
9323                 break;
9324         case NRPN_ADDR_1A00:    /* Level of Drum */      
9325                 drumflag = 1;
9326                 note = channel[ch].lastlrpn;
9327                 if (channel[ch].drums[note] == NULL)
9328                         play_midi_setup_drums(ch, note);
9329                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9330                                 "NRPN Drum Instrument TVA Level (CH:%d NOTE:%d VAL:%d)",
9331                                 ch, note, val);
9332                 channel[ch].drums[note]->drum_level =
9333                                 calc_drum_tva_level(ch, note, val);
9334                 break;
9335         case NRPN_ADDR_1C00:    /* Panpot of Drum */
9336                 drumflag = 1;
9337                 note = channel[ch].lastlrpn;
9338                 if (channel[ch].drums[note] == NULL)
9339                         play_midi_setup_drums(ch, note);
9340                 if(val == 0) {
9341                         val = int_rand(128);
9342                         channel[ch].drums[note]->pan_random = 1;
9343                 } else
9344                         channel[ch].drums[note]->pan_random = 0;
9345                 channel[ch].drums[note]->drum_panning = val;
9346                 //if (update_now && adjust_panning_immediately
9347                 //              && ! channel[ch].pan_random)
9348                 //      adjust_drum_panning(ch, note);
9349                 break;
9350         case NRPN_ADDR_1D00:    /* Reverb Send Level of Drum */
9351                 drumflag = 1;
9352                 note = channel[ch].lastlrpn;
9353                 if (channel[ch].drums[note] == NULL)
9354                         play_midi_setup_drums(ch, note);
9355                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9356                                 "NRPN Reverb Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
9357                                 ch, note, val);
9358                 if (channel[ch].drums[note]->reverb_level != val) {
9359                         if(channel[ch].drum_effect_flag)
9360                                 channel[ch].drum_effect_flag |= 0x4; // update effect
9361                 }
9362                 channel[ch].drums[note]->reverb_level = val;
9363                 break;
9364         case NRPN_ADDR_1E00:    /* Chorus Send Level of Drum */
9365                 drumflag = 1;
9366                 note = channel[ch].lastlrpn;
9367                 if (channel[ch].drums[note] == NULL)
9368                         play_midi_setup_drums(ch, note);
9369                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9370                                 "NRPN Chorus Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
9371                                 ch, note, val);
9372                 if (channel[ch].drums[note]->chorus_level != val) {
9373                         if(channel[ch].drum_effect_flag)
9374                                 channel[ch].drum_effect_flag |= 0x4; // update effect
9375                 }
9376                 channel[ch].drums[note]->chorus_level = val;
9377                 
9378                 break;
9379         case NRPN_ADDR_1F00:    /* Variation Send Level of Drum */
9380                 drumflag = 1;
9381                 note = channel[ch].lastlrpn;
9382                 if (channel[ch].drums[note] == NULL)
9383                         play_midi_setup_drums(ch, note);
9384                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9385                                 "NRPN Delay Send Level of Drum (CH:%d NOTE:%d VALUE:%d)",
9386                                 ch, note, val);
9387                 if (channel[ch].drums[note]->delay_level != val) {
9388                         if(channel[ch].drum_effect_flag)
9389                                 channel[ch].drum_effect_flag |= 0x4; // update effect
9390                 }
9391                 channel[ch].drums[note]->delay_level = val;
9392                 break;
9393         case NRPN_ADDR_2400:    /* Drum HPF Cutoff (XG) */
9394                 drumflag = 1;
9395                 note = channel[ch].lastlrpn;
9396                 if (channel[ch].drums[note] == NULL)
9397                         play_midi_setup_drums(ch, note);
9398                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9399                                 "NRPN Drum Instrument HPF Cutoff (CH:%d NOTE:%d VAL:%d)",
9400                                 ch, note, val);
9401                 channel[ch].drums[note]->drum_hpf_cutoff_freq = val - 64;
9402                 break;
9403         case NRPN_ADDR_2500:    /* Drum HPF Resonance (XG) */
9404                 drumflag = 1;
9405                 note = channel[ch].lastlrpn;
9406                 if (channel[ch].drums[note] == NULL)
9407                         play_midi_setup_drums(ch, note);
9408                 ctl->cmsg(CMSG_INFO, VERB_NOISY,
9409                                 "NRPN Drum Instrument HPF Resonance (CH:%d NOTE:%d VAL:%d)",
9410                                 ch, note, val);
9411                 channel[ch].drums[note]->drum_hpf_resonance = val - 64;
9412                 break;
9413         case NRPN_ADDR_3000:    /* Drum EQ BASS */
9414                 drumflag = 1;
9415                 note = channel[ch].lastlrpn;
9416                 if (channel[ch].drums[note] == NULL)
9417                         play_midi_setup_drums(ch, note);
9418                 if (opt_eq_control && opt_drum_effect) {
9419                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ BASS (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9420                         channel[ch].drums[note]->eq_xg.bass = val;
9421                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9422                 }
9423                 break;
9424         case NRPN_ADDR_3100:    /* Drum EQ TREBLE */
9425                 drumflag = 1;
9426                 note = channel[ch].lastlrpn;
9427                 if (channel[ch].drums[note] == NULL)
9428                         play_midi_setup_drums(ch, note);                
9429                 if (opt_eq_control && opt_drum_effect) {
9430                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ TREBLE (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9431                         channel[ch].drums[note]->eq_xg.treble = val;
9432                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9433                 }
9434                 break;
9435         case NRPN_ADDR_3200:    /* Drum EQ MID-BASS */
9436                 drumflag = 1;
9437                 note = channel[ch].lastlrpn;
9438                 if (channel[ch].drums[note] == NULL)
9439                         play_midi_setup_drums(ch, note);
9440                 if (opt_eq_control && opt_drum_effect) {
9441                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-BASS (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9442                         channel[ch].drums[note]->eq_xg.mid_bass = val;
9443                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9444                 }
9445                 break;
9446         case NRPN_ADDR_3300:    /* Drum EQ MID-TREBLE */
9447                 drumflag = 1;
9448                 note = channel[ch].lastlrpn;
9449                 if (channel[ch].drums[note] == NULL)
9450                         play_midi_setup_drums(ch, note);                
9451                 if (opt_eq_control && opt_drum_effect) {
9452                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-TREBLE (CH:%d %.2f dB)", ch, DIV_64 * 12.0 * (double)(val - 0x40));
9453                         channel[ch].drums[note]->eq_xg.mid_treble = val;
9454                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9455                 }
9456                 break;
9457         case NRPN_ADDR_3400:    /* Drum EQ BASS frequency */
9458                 drumflag = 1;
9459                 note = channel[ch].lastlrpn;
9460                 if (channel[ch].drums[note] == NULL)
9461                         play_midi_setup_drums(ch, note);
9462                 if (opt_eq_control && opt_drum_effect) {
9463                         if(val < 4) {val = 4;}
9464                         else if(val > 40) {val = 40;}
9465                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ BASS frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9466                         channel[ch].drums[note]->eq_xg.bass_freq = val;
9467                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9468                 }
9469                 break;
9470         case NRPN_ADDR_3500:    /* Drum EQ TREBLE frequency */
9471                 drumflag = 1;
9472                 note = channel[ch].lastlrpn;
9473                 if (channel[ch].drums[note] == NULL)
9474                         play_midi_setup_drums(ch, note);
9475                 channel[ch].drums[note]->eq_xg.treble_freq = val;
9476                 if (opt_eq_control && opt_drum_effect) {
9477                         if(val < 28) {val = 28;}
9478                         else if(val > 58) {val = 58;}
9479                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ TREBLE frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9480                         channel[ch].drums[note]->eq_xg.treble_freq = val;
9481                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9482                 }
9483                 break;
9484         case NRPN_ADDR_3600:    /* Drum EQ MID-BASS frequency */
9485                 drumflag = 1;
9486                 note = channel[ch].lastlrpn;
9487                 if (channel[ch].drums[note] == NULL)
9488                         play_midi_setup_drums(ch, note);
9489                 if (opt_eq_control && opt_drum_effect) {
9490                         if(val < 0x0E) {val = 0x0E;}
9491                         else if(val > 0x36) {val = 0x36;}
9492                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-BASS frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9493                         channel[ch].drums[note]->eq_xg.mid_bass_freq = val;
9494                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9495                 }
9496                 break;
9497         case NRPN_ADDR_3700:    /* Drum EQ MID-TREBLE frequency */
9498                 drumflag = 1;
9499                 note = channel[ch].lastlrpn;
9500                 if (channel[ch].drums[note] == NULL)
9501                         play_midi_setup_drums(ch, note);
9502                 if (opt_eq_control && opt_drum_effect) {
9503                         if(val < 0x0E) {val = 0x0E;}
9504                         else if(val > 0x36) {val = 0x36;}
9505                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-TREBLE frequency (CH:%d %d Hz)", ch, (int32)eq_freq_table_xg[val]);
9506                         channel[ch].drums[note]->eq_xg.mid_treble_freq = val;
9507                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9508                 }
9509                 break;
9510         case NRPN_ADDR_3800:    /* Drum EQ BASS Q */
9511                 drumflag = 1;
9512                 note = channel[ch].lastlrpn;
9513                 if (channel[ch].drums[note] == NULL)
9514                         play_midi_setup_drums(ch, note);
9515                 if (opt_eq_control && opt_drum_effect) {
9516                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ BASS Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9517                         channel[ch].drums[note]->eq_xg.bass_q = val;
9518                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9519                 }
9520                 break;
9521         case NRPN_ADDR_3900:    /* Drum EQ TREBLE Q */
9522                 drumflag = 1;
9523                 note = channel[ch].lastlrpn;
9524                 if (channel[ch].drums[note] == NULL)
9525                         play_midi_setup_drums(ch, note);                
9526                 if (opt_eq_control && opt_drum_effect) {
9527                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ TREBLE Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9528                         channel[ch].drums[note]->eq_xg.treble_q = val;
9529                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9530                 }
9531                 break;
9532         case NRPN_ADDR_3A00:    /* Drum EQ MID-BASS Q */
9533                 drumflag = 1;
9534                 note = channel[ch].lastlrpn;
9535                 if (channel[ch].drums[note] == NULL)
9536                         play_midi_setup_drums(ch, note);
9537                 channel[ch].drums[note]->eq_xg.mid_bass = val;  
9538                 if (opt_eq_control && opt_drum_effect) {
9539                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-BASS Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9540                         channel[ch].drums[note]->eq_xg.mid_bass_q = val;
9541                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9542                 }
9543                 break;
9544         case NRPN_ADDR_3B00:    /* Drum EQ MID-TREBLE Q */
9545                 drumflag = 1;
9546                 note = channel[ch].lastlrpn;
9547                 if (channel[ch].drums[note] == NULL)
9548                         play_midi_setup_drums(ch, note);                
9549                 if (opt_eq_control && opt_drum_effect) {
9550                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ MID-TREBLE Q (CH:%d %.2f)", ch, (double)val * DIV_10);
9551                         channel[ch].drums[note]->eq_xg.mid_treble_q = val;
9552                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9553                 }
9554                 break;
9555         case NRPN_ADDR_3C00:    /* Drum EQ BASS shape */
9556                 drumflag = 1;
9557                 note = channel[ch].lastlrpn;
9558                 if (channel[ch].drums[note] == NULL)
9559                         play_midi_setup_drums(ch, note);
9560                 if (opt_eq_control && opt_drum_effect) {
9561                         if(!val){
9562                                 channel[ch].drums[note]->eq_xg.bass_shape = 0x0;
9563                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ BASS shape (CH:%d shelving)", ch);
9564                         }else{
9565                                 channel[ch].drums[note]->eq_xg.bass_shape = 0x1;
9566                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ BASS shape (CH:%d peaking)", ch);
9567                         }
9568                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9569                 }
9570                 break;
9571         case NRPN_ADDR_3D00:    /* Drum EQ TREBLE shape */
9572                 drumflag = 1;
9573                 note = channel[ch].lastlrpn;
9574                 if (channel[ch].drums[note] == NULL)
9575                         play_midi_setup_drums(ch, note);                
9576                 if (opt_eq_control && opt_drum_effect) {
9577                         if(!val){
9578                                 channel[ch].drums[note]->eq_xg.treble_shape = 0x0;
9579                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ TREBLE shape (CH:%d shelving)", ch);
9580                         }else{
9581                                 channel[ch].drums[note]->eq_xg.treble_shape = 0x1;
9582                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"NRPN Drum EQ TREBLE shape (CH:%d peaking)", ch);
9583                         }
9584                         recompute_part_eq_xg(&(channel[ch].drums[note]->eq_xg));
9585                 }
9586                 break;
9587         case RPN_ADDR_0000:             /* Pitch bend sensitivity */
9588                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "RPN Pitch Bend Sensitivity (CH:%d VALUE:%d)", ch, val);
9589                 /* for mod2mid.c, arpeggio */
9590                 if (IS_CURRENT_MOD_FILE){
9591                         if(channel[ch].rpnmap[RPN_ADDR_0000] > 0x7F)
9592                                 channel[ch].rpnmap[RPN_ADDR_0000] = 0x7F;
9593                 }else if (play_system_mode == XG_SYSTEM_MODE && channel[ch].rpnmap[RPN_ADDR_0000] > 0x7F){
9594                         if(channel[ch].rpnmap[RPN_ADDR_0000] < 0xE8) // 0x100 -24
9595                                 channel[ch].rpnmap[RPN_ADDR_0000] = 0xE8; // -24
9596                 }else{
9597                         if(channel[ch].rpnmap[RPN_ADDR_0000] > 24)
9598                                 channel[ch].rpnmap[RPN_ADDR_0000] = 24;
9599                 }
9600                 channel[ch].rpnmap[RPN_ADDR_0040] = channel[ch].rpnmap[RPN_ADDR_0000]; // update low control
9601                 break;
9602         case RPN_ADDR_0001:             /* Master Fine Tuning */
9603                 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
9604                                 "RPN Master Fine Tuning (CH:%d VALUE:%d)", ch, val);
9605                 break;
9606         case RPN_ADDR_0002:             /* Master Coarse Tuning */
9607                 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
9608                                 "RPN Master Coarse Tuning (CH:%d VALUE:%d)", ch, val);
9609                 break;
9610         case RPN_ADDR_0003:             /* Tuning Program Select */
9611                 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
9612                                 "RPN Tuning Program Select (CH:%d VALUE:%d)", ch, val);
9613                 for (i = 0; i < upper_voices; i++)
9614                         if (voice[i].status != VOICE_FREE) {
9615                                 voice[i].temper_instant = 1;
9616                         //      recompute_freq(i);
9617                                 recompute_voice_pitch(i);
9618                         }
9619                 break;
9620         case RPN_ADDR_0004:             /* Tuning Bank Select */
9621                 ctl->cmsg(CMSG_INFO, VERB_DEBUG,
9622                                 "RPN Tuning Bank Select (CH:%d VALUE:%d)", ch, val);
9623                 for (i = 0; i < upper_voices; i++)
9624                         if (voice[i].status != VOICE_FREE) {
9625                                 voice[i].temper_instant = 1;
9626                         //      recompute_freq(i);
9627                                 recompute_voice_pitch(i);
9628                         }
9629                 break;
9630         case RPN_ADDR_0005:             /* Modulation Depth Range */
9631         //      channel[ch].mod.lfo1_pitch_depth = (((int32)channel[ch].rpnmap[RPN_ADDR_0005] << 7) | channel[ch].rpnmap_lsb[RPN_ADDR_0005]) * 100 / 128;
9632                 if (play_system_mode == SD_SYSTEM_MODE){
9633                         channel[ch].mod.lfo1_pitch_depth = 
9634                                 (double)(((int32)channel[ch].rpnmap[RPN_ADDR_0005] << 8) | channel[ch].rpnmap_lsb[RPN_ADDR_0005])
9635                                 * 0.03662109375; // cent 600/16384 max0x4000
9636                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9637                                         "RPN Modulation Depth Range (CH:%d MSB:%d LSB:%d cent:%.2f)", ch, 
9638                                         channel[ch].rpnmap[RPN_ADDR_0005], channel[ch].rpnmap_lsb[RPN_ADDR_0005], channel[ch].mod.lfo1_pitch_depth);
9639                 }else{ // GM2_SYSTEM_MODE
9640                         channel[ch].mod.lfo1_pitch_depth = (double)(channel[ch].rpnmap[RPN_ADDR_0005] * 100)
9641                                 + (double)channel[ch].rpnmap_lsb[RPN_ADDR_0005] * 100.0 * DIV_128; // cent
9642                         ctl->cmsg(CMSG_INFO, VERB_NOISY,
9643                                         "RPN Modulation Depth Range (CH:%d MSB:%d LSB:%d cent:%.2f)", ch, 
9644                                         channel[ch].rpnmap[RPN_ADDR_0005], channel[ch].rpnmap_lsb[RPN_ADDR_0005], channel[ch].mod.lfo1_pitch_depth);
9645                 }
9646                 break;
9647         case RPN_ADDR_0040:             /* Pitch bend sensitivity low control */
9648                 ctl->cmsg(CMSG_INFO, VERB_DEBUG, "RPN Pitch Bend Sensitivity Low Control (CH:%d VALUE:%d)", ch, val);
9649                 if (play_system_mode == XG_SYSTEM_MODE && channel[ch].rpnmap[RPN_ADDR_0040] > 0x7F){
9650                         if(channel[ch].rpnmap[RPN_ADDR_0040] < 0xE8) // 0x100 -24
9651                                 channel[ch].rpnmap[RPN_ADDR_0040] = 0xE8; // -24
9652                 }else{
9653                         if(channel[ch].rpnmap[RPN_ADDR_0040] > 24)
9654                                 channel[ch].rpnmap[RPN_ADDR_0040] = 24;
9655                 }
9656                 break;
9657         case RPN_ADDR_7F7F:             /* RPN reset */
9658                 channel[ch].rpn_7f7f_flag = 1;
9659                 break;
9660         case RPN_ADDR_FFFF:             /* RPN initialize */
9661                 /* All reset to defaults */
9662                 channel[ch].rpn_7f7f_flag = 0;
9663                 memset(channel[ch].rpnmap, 0, sizeof(channel[ch].rpnmap));
9664                 channel[ch].lastlrpn = channel[ch].lastmrpn = 0;
9665                 channel[ch].nrpn = -1;
9666                 channel[ch].rpnmap[RPN_ADDR_0000] = 2;
9667                 channel[ch].rpnmap[RPN_ADDR_0001] = 0x40;
9668                 channel[ch].rpnmap[RPN_ADDR_0002] = 0x40;
9669                 channel[ch].rpnmap_lsb[RPN_ADDR_0005] = 0x40;
9670                 channel[ch].rpnmap[RPN_ADDR_0005] = 0;  /* +- 50 cents */
9671                 channel[ch].rpnmap[RPN_ADDR_0040] = 2; // = RPN_ADDR_0000 = -2*-1
9672                 break;
9673         }
9674         drumflag = 0;
9675         if (drumflag && midi_drumpart_change(ch, 1)) {
9676                 midi_program_change(ch, channel[ch].program);
9677                 if (update_now)
9678                         ctl_prog_event(ch);
9679         }
9680 }
9681
9682 /*
9683 cbc\92l\82ð\92Ê\8fíctrl\92l\82É\95Ï\8a· 0~127 -> -64~63 -> -63~63 -> -127~127
9684 \82±\82±\82Å\95Ï\8a·\82·\82é\82Ì\82Íget_midi_controller_amp()~\93\99\82ð\82»\82Ì\82Ü\82Ü\8eg\97p\82·\82é\82½\82ß 
9685 */
9686 static int calc_cbc_val(int val)
9687 {
9688         const int32 coef = (double)127 / (double)63 * (double)(1L << 24); // 127/63
9689         if(val == 0x40) return 0;
9690         val -= 0x40;
9691         if(val < -63) val = 63;
9692         return imuldiv24(val, coef);
9693 }
9694
9695 /*
9696 bend\92l\82ð\92Ê\8fíctrl\92l\82É\95Ï\8a· 0~16383 -> -8192~+8191 -> -8191~+8191 -> -127~127
9697 \82±\82±\82Å\95Ï\8a·\82·\82é\82Ì\82Íget_midi_controller_amp()~\93\99\82ð\82»\82Ì\82Ü\82Ü\8eg\97p\82·\82é\82½\82ß 
9698 */
9699 int calc_bend_val(int val)
9700 {
9701         const int32 coef = (double)127 / (double)8191 * (double)(1L << 16); // 127/8191
9702         if(val == 0x2000) return 0;
9703         val -= 0x2000;
9704         if(val < -8191) val = 8191;
9705         return imuldiv16(val, coef);
9706 }
9707
9708 static void process_channel_control_event(MidiEvent *ev)
9709 {
9710         int ch, cc;
9711
9712         if(!opt_channel_pressure)
9713                 return;
9714         if(ev->type < ME_TONE_BANK_MSB || ev->type > ME_UNDEF_CTRL_CHNG)
9715                 return; // not cc
9716         ch = ev->channel;
9717         cc = ev->b;     // original ctrl change number (if ev->type==ctrl_change
9718         /*! adjust channel control 1 (CC1) */
9719         if(channel[ch].cc1.num != -1 && channel[ch].cc1.num == cc){
9720                 if(channel[ch].cc1.mode){ // CBC mode
9721                         channel[ch].cc1.val = calc_cbc_val(ev->a);
9722                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC1(CBC) (CH:%d VAL:%d CVT:%d)",ch,ev->a,channel[ch].cc1.val);
9723                 }else{
9724                         channel[ch].cc1.val = ev->a;
9725                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC1 (CH:%d VAL:%d)",ch,ev->a);
9726                 }
9727                 recompute_channel_lfo(ch);
9728                 recompute_channel_amp(ch);
9729                 recompute_channel_filter(ch);
9730                 recompute_channel_pitch(ch);
9731                 control_effect_xg(ch);
9732         }
9733         /*! adjust channel control 2 (CC2) */
9734         if(channel[ch].cc2.num != -1 && channel[ch].cc2.num == cc){
9735                 if(channel[ch].cc2.mode){ // CBC mode
9736                         channel[ch].cc2.val = calc_cbc_val(ev->a);
9737                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC2(CBC) (CH:%d VAL:%d CVT:%d)",ch,ev->a,channel[ch].cc2.val);
9738                 }else{
9739                         channel[ch].cc2.val = ev->a;
9740                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC2 (CH:%d VAL:%d)",ch,ev->a);
9741                 }
9742                 recompute_channel_lfo(ch);
9743                 recompute_channel_amp(ch);
9744                 recompute_channel_filter(ch);
9745                 recompute_channel_pitch(ch);
9746                 control_effect_xg(ch);
9747         }
9748         /*! adjust channel control 3 (CC3) */
9749         if(channel[ch].cc3.num != -1 && channel[ch].cc3.num == cc){
9750                 if(channel[ch].cc3.mode){ // CBC mode
9751                         channel[ch].cc3.val = calc_cbc_val(ev->a);
9752                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC3(CBC) (CH:%d VAL:%d CVT:%d)",ch,ev->a, channel[ch].cc3.val);
9753                 }else{
9754                         channel[ch].cc3.val = ev->a;
9755                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC3 (CH:%d VAL:%d)",ch,ev->a);
9756                 }
9757                 recompute_channel_lfo(ch);
9758                 recompute_channel_amp(ch);
9759                 recompute_channel_filter(ch);
9760                 recompute_channel_pitch(ch);
9761                 control_effect_xg(ch);
9762         }
9763         /*! adjust channel control 4 (CC4) */
9764         if(channel[ch].cc4.num != -1 && channel[ch].cc4.num == cc){
9765                 if(channel[ch].cc4.mode){ // CBC mode
9766                         channel[ch].cc4.val = calc_cbc_val(ev->a);
9767                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC4(CBC) (CH:%d VAL:%d CVT:%d)",ch,ev->a, channel[ch].cc4.val);
9768                 }else{
9769                         channel[ch].cc4.val = ev->a;
9770                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"CC4 (CH:%d VAL:%d)",ch,ev->a);
9771                 }
9772                 recompute_channel_lfo(ch);
9773                 recompute_channel_amp(ch);
9774                 recompute_channel_filter(ch);
9775                 recompute_channel_pitch(ch);
9776                 control_effect_xg(ch);
9777         }
9778 }
9779
9780
9781
9782
9783 static void seek_forward(int32 until_time)
9784 {
9785     int32 i;
9786     int j, k, ch, orig_ch, port_ch, offset, layered;
9787
9788     playmidi_seek_flag = 1;
9789     wrd_midi_event(WRD_START_SKIP, WRD_NOARG);
9790         while (MIDI_EVENT_TIME(current_event) < until_time) {
9791 #ifndef SUPPRESS_CHANNEL_LAYER
9792                 orig_ch = current_event->channel;
9793                 layered = ! IS_SYSEX_EVENT_TYPE(current_event);
9794                 for (j = 0; j < MAX_CHANNELS; j += 16) {
9795                         port_ch = (orig_ch + j) % MAX_CHANNELS;
9796                         offset = port_ch & ~0xf;
9797                         for (k = offset; k < offset + 16; k++) {
9798                                 if (! layered && (j || k != offset))
9799                                         continue;
9800                                 if (layered) {
9801                                         if (! IS_SET_CHANNELMASK(
9802                                                         channel[k].channel_layer, port_ch)
9803                                                         || channel[k].port_select != (orig_ch >> 4))
9804                                                 continue;
9805                                         current_event->channel = k;
9806                                 }
9807 #endif
9808         ch = current_event->channel;
9809                 
9810         if(current_event->type >= ME_TONE_BANK_MSB && current_event->type <= ME_UNDEF_CTRL_CHNG)
9811                 if(!get_rx(ch, RX_CONTROL_CHANGE)) 
9812                         current_event->type = ME_NONE;
9813
9814         process_channel_control_event(current_event);
9815         
9816         if(opt_insertion_effect){               
9817                 switch(play_system_mode) {
9818                 case GS_SYSTEM_MODE:
9819                         control_effect_gs(current_event);
9820                         break;
9821                 case SD_SYSTEM_MODE:
9822                         control_effect_sd(current_event);
9823                         break;
9824                 default:
9825                         break;
9826                 }
9827         }
9828         
9829         switch(current_event->type)
9830         {
9831           case ME_PITCHWHEEL:
9832                 if(!get_rx(ch, RX_PITCH_BEND)) break;
9833                 {
9834                         int tmp = (int)current_event->a + (int)current_event->b * 128;
9835                         channel[ch].pitchbend = tmp;
9836                         channel[ch].bend.val = calc_bend_val(tmp);
9837                 }
9838                 adjust_pitch(ch);
9839                 control_effect_xg(ch);
9840             break;
9841
9842           case ME_MAINVOLUME:
9843                 if(!get_rx(ch, RX_VOLUME)) break;
9844             channel[ch].volume = current_event->a;
9845                 adjust_volume(ch);
9846             break;
9847
9848           case ME_MASTER_VOLUME:
9849             master_volume_ratio =
9850                 (int32)current_event->a + 256 * (int32)current_event->b;
9851                 adjust_master_volume();
9852             break;
9853
9854           case ME_PAN:
9855                 if(!get_rx(ch, RX_VOLUME)) break;
9856             channel[ch].panning = current_event->a;
9857             channel[ch].pan_random = 0;
9858                 if(!channel[ch].pan_random)
9859                         adjust_panning(ch);
9860             break;
9861
9862           case ME_EXPRESSION:             
9863                 if(!get_rx(ch, RX_PANPOT)) break;
9864             channel[ch].expression=current_event->a;
9865                 adjust_volume(ch);
9866             break;
9867
9868           case ME_KEYPRESSURE:
9869                 if(!get_rx(ch, RX_POLY_PRESSURE)) break;
9870             adjust_pressure(current_event);
9871             break;
9872
9873           case ME_CHANNEL_PRESSURE:
9874                 if(!get_rx(ch, RX_PROGRAM_CHANGE)) break;
9875             adjust_channel_pressure(current_event);
9876                 control_effect_xg(ch);
9877             break;
9878                 
9879           case ME_PROGRAM:
9880                 if(!get_rx(ch, RX_PROGRAM_CHANGE)) break;
9881             midi_program_change(ch, current_event->a);
9882             break;
9883
9884 ///r
9885           case ME_SUSTAIN:              
9886                 if(!get_rx(ch, RX_HOLD1)) break;                          
9887                 if (channel[ch].damper_mode == 0) {     /* half-damper is not allowed. */
9888                         if (current_event->a >= 64) {
9889                                 if(channel[ch].sustain == 0){
9890                                         channel[ch].sustain = 127;
9891                                 }
9892                         }else {
9893                                 channel[ch].sustain = 0;
9894                         }
9895                 }else{
9896                         if(channel[ch].sustain != current_event->a){
9897                                 channel[ch].sustain = current_event->a;
9898                         }
9899                 }
9900 #if 0
9901                   channel[ch].sustain = current_event->a;
9902                   if (channel[ch].damper_mode == 0) {   /* half-damper is not allowed. */
9903                           if (channel[ch].sustain >= 64) {channel[ch].sustain = 127;}
9904                           else {channel[ch].sustain = 0;}
9905                   }
9906 #endif
9907             break;
9908
9909           case ME_SOSTENUTO:
9910                 if(!get_rx(ch, RX_SOSTENUTO)) break;    
9911                   channel[ch].sostenuto = (current_event->a >= 64);
9912             break;
9913
9914           case ME_LEGATO_FOOTSWITCH:
9915                 if(opt_portamento){
9916         channel[ch].legato = (current_event->a >= 64);
9917                 }
9918             break;
9919
9920       case ME_HOLD2:
9921         break;
9922
9923           case ME_FOOT:
9924             break;
9925
9926           case ME_BREATH:
9927             break;
9928
9929           case ME_BALANCE:
9930             break;
9931
9932           case ME_RESET_CONTROLLERS:
9933             reset_controllers(ch);
9934             break;
9935
9936           case ME_TONE_BANK_MSB:
9937                 if(!get_rx(ch, RX_BANK_SELECT)) break;
9938             channel[ch].bank_msb = current_event->a;
9939             break;
9940
9941           case ME_TONE_BANK_LSB:
9942                 if(!get_rx(ch, RX_BANK_SELECT_LSB)) break;
9943             channel[ch].bank_lsb = current_event->a;
9944             break;
9945
9946           case ME_MODULATION_WHEEL:
9947                 if(!get_rx(ch, RX_MODULATION)) break;
9948                 if(opt_modulation_wheel){
9949                         channel[ch].mod.val = current_event->a;
9950                         update_modulation_wheel(ch);
9951                         control_effect_xg(ch);
9952                 }
9953             break;
9954
9955           case ME_PORTAMENTO_TIME_MSB:
9956                 if(opt_portamento){
9957                         channel[ch].portamento_time_msb = current_event->a;
9958                 }
9959             break;
9960
9961           case ME_PORTAMENTO_TIME_LSB:
9962                 if(opt_portamento){
9963                         channel[ch].portamento_time_lsb = current_event->a;
9964                 }
9965             break;
9966
9967           case ME_PORTAMENTO:
9968                 if(!get_rx(ch, RX_PORTAMENTO)) break;
9969                 if(opt_portamento){
9970                         channel[ch].portamento = (current_event->a >= 64);
9971                 }
9972             break;
9973
9974       case ME_PORTAMENTO_CONTROL:
9975                 if(opt_portamento){
9976                         channel[ch].portamento_control = current_event->a;
9977                 }
9978                 break;
9979
9980           case ME_MONO:
9981             channel[ch].mono = 1;
9982             break;
9983
9984           case ME_POLY:
9985             channel[ch].mono = 0;
9986             break;
9987
9988           case ME_SOFT_PEDAL:
9989                 if(!get_rx(ch, RX_SOFT)) break;
9990                   //if(opt_lpf_def) {
9991                           channel[ch].soft_pedal = current_event->a;
9992                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Soft Pedal (CH:%d VAL:%d)",ch,channel[ch].soft_pedal);
9993                   //}
9994                   break;
9995
9996           case ME_HARMONIC_CONTENT:
9997                   //if(opt_lpf_def) {
9998                           channel[ch].param_resonance = current_event->a - 64;
9999                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Harmonic Content (CH:%d VAL:%d)",ch,channel[ch].param_resonance);
10000                 //        update_channel_filter(ch);//elion add.
10001 //                        recompute_voice_filter(ch);// elion add.
10002                           recompute_channel_filter(ch);
10003                   //}
10004                   break;
10005
10006           case ME_BRIGHTNESS:
10007                   //if(opt_lpf_def) {
10008                           channel[ch].param_cutoff_freq = current_event->a - 64;
10009                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Brightness (CH:%d VAL:%d)",ch,channel[ch].param_cutoff_freq);
10010                 //        update_channel_filter(ch);//elion add.
10011 //                        recompute_voice_filter(ch);// elion add.
10012                           recompute_channel_filter(ch);
10013                   //}
10014                   break;
10015
10016           case ME_VIBRATO_RATE:
10017                 if (opt_nrpn_vibrato) {
10018                         channel[ch].param_vibrato_rate = current_event->a - 64;
10019                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Rate (CH:%d VAL:%d)",ch,current_event->a - 64);
10020                 //      adjust_pitch(ch);
10021                         recompute_channel_lfo(ch);
10022                         recompute_channel_pitch(ch);
10023                 }
10024                 break;
10025
10026           case ME_VIBRATO_DEPTH:
10027                 if (opt_nrpn_vibrato) {
10028                         channel[ch].param_vibrato_depth = current_event->a - 64;
10029                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Depth (CH:%d VAL:%d)",ch,current_event->a - 64);
10030                 //      adjust_pitch(ch);
10031                         recompute_channel_lfo(ch);
10032                         recompute_channel_pitch(ch);
10033                 }
10034                 break;
10035
10036           case ME_VIBRATO_DELAY:
10037                 if (opt_nrpn_vibrato) {
10038                         channel[ch].param_vibrato_delay = current_event->a - 64;
10039                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Delay (CH:%d VAL:%d)",ch,current_event->a - 64);
10040                 //      adjust_pitch(ch);
10041                         recompute_channel_lfo(ch);
10042                         recompute_channel_pitch(ch);
10043                 }
10044                 break;
10045
10046             /* RPNs */
10047           case ME_NRPN_LSB:
10048                 if(!get_rx(ch, RX_NRPN)) break;
10049                   channel[ch].rpn_7f7f_flag = 0;
10050             channel[ch].lastlrpn = current_event->a;
10051             channel[ch].nrpn = 1;
10052             break;
10053           case ME_NRPN_MSB:
10054                 if(!get_rx(ch, RX_NRPN)) break;
10055                   channel[ch].rpn_7f7f_flag = 0;
10056             channel[ch].lastmrpn = current_event->a;
10057             channel[ch].nrpn = 1;
10058             break;
10059           case ME_RPN_LSB:
10060                 if(!get_rx(ch, RX_RPN)) break;
10061                   channel[ch].rpn_7f7f_flag = 0;
10062             channel[ch].lastlrpn = current_event->a;
10063             channel[ch].nrpn = 0;
10064             break;
10065           case ME_RPN_MSB:
10066                 if(!get_rx(ch, RX_RPN)) break;
10067                   channel[ch].rpn_7f7f_flag = 0;
10068             channel[ch].lastmrpn = current_event->a;
10069             channel[ch].nrpn = 0;
10070             break;
10071           case ME_RPN_INC:
10072             if(channel[ch].rpn_7f7f_flag) /* disable */
10073                 break;
10074             if((i = last_rpn_addr(ch)) >= 0)
10075             {
10076                 if(channel[ch].rpnmap[i] < 127)
10077                     channel[ch].rpnmap[i]++;
10078                 update_rpn_map(ch, i, 0);
10079             }
10080             break;
10081         case ME_RPN_DEC:
10082             if(channel[ch].rpn_7f7f_flag) /* disable */
10083                 break;
10084             if((i = last_rpn_addr(ch)) >= 0)
10085             {
10086                 if(channel[ch].rpnmap[i] > 0)
10087                     channel[ch].rpnmap[i]--;
10088                 update_rpn_map(ch, i, 0);
10089             }
10090             break;
10091           case ME_DATA_ENTRY_MSB:
10092             if(channel[ch].rpn_7f7f_flag) /* disable */
10093                 break;
10094             if((i = last_rpn_addr(ch)) >= 0)
10095             {
10096                 channel[ch].rpnmap[i] = current_event->a;
10097                 update_rpn_map(ch, i, 0);
10098         //        update_channel_filter(ch);// elion add.
10099 //                recompute_voice_filter(ch);// elion add.
10100             }
10101             break;
10102           case ME_DATA_ENTRY_LSB:
10103             if(channel[ch].rpn_7f7f_flag) /* disable */
10104                 break;
10105             if((i = last_rpn_addr(ch)) >= 0)
10106             {
10107                 channel[ch].rpnmap_lsb[i] = current_event->a;
10108             }
10109             break;
10110
10111           case ME_REVERB_EFFECT:
10112                   if (opt_reverb_control) {
10113                         if (ISDRUMCHANNEL(ch) && get_reverb_level(ch) != current_event->a) {
10114                                 if(channel[ch].drum_effect_flag)
10115                                         channel[ch].drum_effect_flag |= 0x4; // update effect
10116                         }
10117                         set_reverb_level(ch, current_event->a);
10118                   }
10119             break;
10120
10121           case ME_CHORUS_EFFECT:
10122                 if(opt_chorus_control == 1) {
10123                         if (ISDRUMCHANNEL(ch) && channel[ch].chorus_level != current_event->a) {
10124                                 if(channel[ch].drum_effect_flag)
10125                                         channel[ch].drum_effect_flag |= 0x4; // update effect
10126                         }
10127                         channel[ch].chorus_level = current_event->a;
10128                 } else {
10129                         channel[ch].chorus_level = -opt_chorus_control;
10130                 }
10131
10132                 if(current_event->a) {
10133                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send (CH:%d LEVEL:%d)",ch,current_event->a);
10134                 }
10135                 break;
10136
10137           case ME_TREMOLO_EFFECT:
10138                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tremolo Send (CH:%d LEVEL:%d)",ch,current_event->a);
10139                 break;
10140
10141           case ME_CELESTE_EFFECT:
10142                 if(opt_delay_control) {
10143                         if (ISDRUMCHANNEL(ch) && channel[ch].delay_level != current_event->a) {
10144                                 if(channel[ch].drum_effect_flag)
10145                                         channel[ch].drum_effect_flag |= 0x4; // update effect
10146                         }
10147                         channel[ch].delay_level = current_event->a;
10148                         if (play_system_mode == XG_SYSTEM_MODE) {
10149                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send (CH:%d LEVEL:%d)",ch,current_event->a);
10150                         } else {
10151                                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Variation Send (CH:%d LEVEL:%d)",ch,current_event->a);
10152                         }
10153                 }
10154             break;
10155
10156           case ME_ATTACK_TIME:
10157                 if(!opt_tva_attack) { break; }
10158                 set_envelope_time(ch, current_event->a, EG_ATTACK);
10159                 break;
10160
10161           case ME_DECAY_TIME:
10162                 if(!opt_tva_decay) { break; }
10163                 set_envelope_time(ch, current_event->a, EG_DECAY);
10164                 break;
10165
10166           case ME_RELEASE_TIME:
10167                 if(!opt_tva_release) { break; }
10168                 set_envelope_time(ch, current_event->a, EG_RELEASE);
10169                 break;
10170
10171           case ME_PHASER_EFFECT:
10172                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Phaser Send (CH:%d LEVEL:%d)",ch,current_event->a);
10173                 break;
10174
10175           case ME_RANDOM_PAN:
10176             channel[ch].panning = int_rand(128);
10177             channel[ch].pan_random = 1;
10178             break;
10179
10180           case ME_SET_PATCH:
10181             i = channel[ch].special_sample = current_event->a;
10182             if(special_patch[i] != NULL)
10183                 special_patch[i]->sample_offset = 0;            
10184             break;
10185
10186           case ME_TEMPO:
10187             current_play_tempo = ch +
10188                 current_event->b * 256 + current_event->a * 65536;
10189             break;
10190
10191           case ME_RESET:
10192             change_system_mode(current_event->a);
10193             reset_midi(0);
10194             break;
10195
10196           case ME_PATCH_OFFS:
10197             i = channel[ch].special_sample;
10198             if(special_patch[i] != NULL)
10199                 special_patch[i]->sample_offset =
10200                     (current_event->a | 256 * current_event->b);
10201             break;
10202
10203           case ME_WRD:
10204             wrd_midi_event(ch, current_event->a | 256 * current_event->b);
10205             break;
10206
10207           case ME_SHERRY:
10208             wrd_sherry_event(ch |
10209                              (current_event->a<<8) |
10210                              (current_event->b<<16));
10211             break;
10212
10213           case ME_DRUMPART:
10214                 if(play_system_mode == XG_SYSTEM_MODE && current_event->a)
10215                         channel[ch].bank_msb = 127; // Drum kit
10216             if(midi_drumpart_change(ch, current_event->a))
10217                 midi_program_change(ch, channel[ch].program);   
10218             break;
10219
10220           case ME_KEYSHIFT:
10221             channel[ch].key_shift = (int)current_event->a - 0x40;
10222             break;
10223
10224         case ME_KEYSIG:
10225                 if (opt_init_keysig != 8)
10226                         break;
10227                 current_keysig = current_event->a + current_event->b * 16;
10228                 break;
10229
10230         case ME_MASTER_TUNING:
10231                 set_master_tuning((current_event->b << 8) | current_event->a);
10232                 adjust_pitch(ch);
10233                 break;
10234
10235         case ME_SCALE_TUNING:
10236                 channel[ch].scale_tuning[current_event->a] = current_event->b;
10237                 adjust_pitch(ch);
10238                 break;
10239
10240         case ME_BULK_TUNING_DUMP:
10241                 set_single_note_tuning(ch, current_event->a, current_event->b, 0);
10242                 break;
10243
10244         case ME_SINGLE_NOTE_TUNING:
10245                 set_single_note_tuning(ch, current_event->a, current_event->b, 0);
10246                 break;
10247
10248         case ME_TEMPER_KEYSIG:
10249                 current_temper_keysig = (current_event->a + 8) % 32 - 8;
10250                 temper_adj = ((current_event->a + 8) & 0x20) ? 1 : 0;
10251                 adjust_pitch(ch);
10252                 break;
10253
10254         case ME_TEMPER_TYPE:
10255                 channel[ch].temper_type = current_event->a;
10256                 adjust_pitch(ch);
10257                 break;
10258
10259         case ME_MASTER_TEMPER_TYPE:
10260                 for (i = 0; i < MAX_CHANNELS; i++)
10261                         channel[i].temper_type = current_event->a;
10262                 adjust_pitch(ch);
10263                 break;
10264
10265         case ME_USER_TEMPER_ENTRY:
10266                 set_user_temper_entry(ch, current_event->a, current_event->b);
10267                 adjust_pitch(ch);
10268                 break;
10269
10270           case ME_SYSEX_LSB:
10271             process_sysex_event(ME_SYSEX_LSB,ch,current_event->a,current_event->b);
10272             break;
10273
10274           case ME_SYSEX_MSB:
10275             process_sysex_event(ME_SYSEX_MSB,ch,current_event->a,current_event->b);
10276             break;
10277
10278           case ME_SYSEX_GS_LSB:
10279             process_sysex_event(ME_SYSEX_GS_LSB,ch,current_event->a,current_event->b);
10280             break;
10281
10282           case ME_SYSEX_GS_MSB:
10283             process_sysex_event(ME_SYSEX_GS_MSB,ch,current_event->a,current_event->b);
10284             break;
10285
10286           case ME_SYSEX_XG_LSB:
10287             process_sysex_event(ME_SYSEX_XG_LSB,ch,current_event->a,current_event->b);
10288             break;
10289
10290           case ME_SYSEX_XG_MSB:
10291             process_sysex_event(ME_SYSEX_XG_MSB,ch,current_event->a,current_event->b);
10292             break;
10293
10294         case ME_SYSEX_SD_LSB:
10295                 process_sysex_event(ME_SYSEX_SD_LSB,ch,current_event->a,current_event->b);
10296             break;
10297
10298         case ME_SYSEX_SD_MSB:
10299                 process_sysex_event(ME_SYSEX_SD_MSB,ch,current_event->a,current_event->b);
10300             break;
10301
10302         case ME_SYSEX_SD_HSB:
10303                 process_sysex_event(ME_SYSEX_SD_HSB,ch,current_event->a,current_event->b);
10304             break;
10305
10306           case ME_EOT:
10307             current_sample = current_event->time;
10308             playmidi_seek_flag = 0;
10309             return;
10310         }
10311 #ifndef SUPPRESS_CHANNEL_LAYER
10312                         }
10313                 }
10314                 current_event->channel = orig_ch;
10315 #endif
10316         current_event++;
10317     }
10318     wrd_midi_event(WRD_END_SKIP, WRD_NOARG);
10319
10320     playmidi_seek_flag = 0;
10321     if(current_event != event_list)
10322         current_event--;
10323     current_sample = until_time;
10324 }
10325 ///r
10326 static void skip_to(int32 until_time)
10327 {
10328   int ch;
10329
10330   trace_flush();
10331   current_event = NULL;
10332
10333   if (current_sample > until_time)
10334     current_sample=0;
10335 ///r
10336 //  change_system_mode(DEFAULT_SYSTEM_MODE);
10337   reset_midi(0);
10338
10339   buffered_count=0;
10340   buffer_pointer=common_buffer;
10341   current_event=event_list;
10342   current_play_tempo = 500000; /* 120 BPM */
10343
10344   if (until_time)
10345     seek_forward(until_time);
10346   ctl_mode_event(CTLE_RESET, 0, 0, 0);
10347   for(ch = 0; ch < MAX_CHANNELS; ch++){
10348       channel[ch].lasttime = current_sample;
10349           redraw_controllers(ch);
10350           ctl_prog_event(ch);
10351   }
10352   trace_offset(until_time);
10353 #ifdef SUPPORT_SOUNDSPEC
10354   soundspec_update_wave(NULL, 0);
10355 #endif /* SUPPORT_SOUNDSPEC */
10356 }
10357
10358 static int32 sync_restart(int only_trace_ok)
10359 {
10360     int32 cur;
10361
10362     cur = current_trace_samples();
10363     if(cur == -1)
10364     {
10365         if(only_trace_ok)
10366             return -1;
10367         cur = current_sample;
10368     }
10369     aq_flush(1);
10370     skip_to(cur);
10371     return cur;
10372 }
10373
10374 static int playmidi_change_rate(int32 rate, int restart)
10375 {
10376     int arg;
10377
10378     if(rate == play_mode->rate)
10379         return 1; /* Not need to change */
10380
10381     if(rate < MIN_OUTPUT_RATE || rate > MAX_OUTPUT_RATE)
10382     {
10383         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
10384                   "Out of sample rate: %d", rate);
10385         return -1;
10386     }
10387
10388     if(restart)
10389     {
10390         if((midi_restart_time = current_trace_samples()) == -1)
10391             midi_restart_time = current_sample;
10392     }
10393     else
10394         midi_restart_time = 0;
10395
10396     arg = (int)rate;
10397     if(play_mode->acntl(PM_REQ_RATE, &arg) == -1)
10398     {
10399         ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
10400                   "Can't change sample rate to %d", rate);
10401         return -1;
10402     }
10403
10404     aq_flush(1);
10405     aq_setup();
10406     aq_set_soft_queue(-1.0, -1.0);
10407     free_instruments(1);
10408 #ifdef SUPPORT_SOUNDSPEC
10409     soundspec_reinit();
10410 #endif /* SUPPORT_SOUNDSPEC */
10411     return 0;
10412 }
10413
10414 void playmidi_output_changed(int play_state)
10415 {
10416     if(target_play_mode == NULL)
10417         return;
10418     if(play_mode != NULL && play_mode->close_output)
10419         play_mode->close_output();
10420     play_mode = target_play_mode;
10421
10422     if(play_state == 0)
10423     {
10424         /* Playing */
10425         if((midi_restart_time = current_trace_samples()) == -1)
10426             midi_restart_time = current_sample;
10427     }
10428     else /* Not playing */
10429         midi_restart_time = 0;
10430
10431     if(play_state != 2)
10432     {
10433         aq_flush(1);
10434         aq_setup();
10435         aq_set_soft_queue(-1.0, -1.0);
10436         clear_magic_instruments();
10437     }
10438     free_instruments(1);
10439 #ifdef SUPPORT_SOUNDSPEC
10440     soundspec_reinit();
10441 #endif /* SUPPORT_SOUNDSPEC */
10442     target_play_mode = NULL;
10443 }
10444
10445 int check_apply_control(void)
10446 {
10447     int rc;
10448     ptr_size_t val = 0;
10449
10450     if(file_from_stdin)
10451         return RC_NONE;
10452     rc = ctl->read(&val);
10453     switch(rc)
10454     {
10455       case RC_CHANGE_VOLUME:
10456         if (val>0 || output_amplification > -val)
10457             output_amplification += val;
10458         else
10459             output_amplification=0;
10460         if (output_amplification > MAX_AMPLIFICATION)
10461             output_amplification=MAX_AMPLIFICATION;
10462 //      adjust_amplification();
10463         change_output_volume(output_amplification);
10464         ctl_mode_event(CTLE_MASTER_VOLUME, 0, output_amplification, 0);
10465         break;
10466       case RC_SYNC_RESTART:
10467         aq_flush(1);
10468         break;
10469       case RC_TOGGLE_PAUSE:
10470         play_pause_flag = !play_pause_flag;
10471         ctl_pause_event(play_pause_flag, 0);
10472         return RC_NONE;
10473       case RC_TOGGLE_SNDSPEC:
10474 #ifdef SUPPORT_SOUNDSPEC
10475         if(view_soundspec_flag)
10476             close_soundspec();
10477         else
10478             open_soundspec();
10479         if(view_soundspec_flag || ctl_speana_flag)
10480             soundspec_update_wave(NULL, -1);
10481         return RC_NONE;
10482       case RC_TOGGLE_CTL_SPEANA:
10483         ctl_speana_flag = !ctl_speana_flag;
10484         if(view_soundspec_flag || ctl_speana_flag)
10485             soundspec_update_wave(NULL, -1);
10486 #endif /* SUPPORT_SOUNDSPEC */
10487         return RC_NONE;
10488       case RC_CHANGE_RATE:
10489         if(playmidi_change_rate(val, 0))
10490             return RC_NONE;
10491         return RC_RELOAD;
10492       case RC_OUTPUT_CHANGED:
10493         playmidi_output_changed(1);
10494         return RC_RELOAD;
10495     }
10496     return rc;
10497 }
10498
10499 static void voice_increment(int n)
10500 {
10501     int i;
10502     for(i = 0; i < n; i++)
10503     {
10504         if(voices == max_voices)
10505             break;
10506         voice[voices].status = VOICE_FREE;
10507         voice[voices].temper_instant = 0;
10508         voices++;
10509     }
10510     if(n > 0)
10511         ctl_mode_event(CTLE_MAXVOICES, 1, voices, 0);
10512 }
10513
10514 static void voice_decrement(int n)
10515 {
10516     int i, j, lowest;
10517     int32 lv, v;
10518
10519     /* decrease voice */
10520     for(i = 0; i < n && voices > 0; i++)
10521     {
10522         voices--;
10523         if(voice[voices].status == VOICE_FREE)
10524             continue;   /* found */
10525
10526         for(j = 0; j < voices; j++)
10527             if(voice[j].status == VOICE_FREE)
10528                 break;
10529         if(j != voices)
10530         {
10531             swap_voices(&voice[j], &voice[voices]);
10532             continue;   /* found */
10533         }
10534
10535         /* Look for the decaying note with the lowest volume */
10536         lv = 0x7FFFFFFF;
10537         lowest = -1;
10538         for(j = 0; j <= voices; j++)
10539         {
10540             if(voice[j].status & ~(VOICE_ON | VOICE_DIE))
10541             {
10542                 v = voice[j].left_mix;
10543                 if((voice[j].panned==PANNED_MYSTERY) &&
10544                    (voice[j].right_mix > v))
10545                     v = voice[j].right_mix;
10546                 if(v < lv)
10547                 {
10548                     lv = v;
10549                     lowest = j;
10550                 }
10551             }
10552         }
10553
10554         if(lowest != -1)
10555         {
10556             cut_notes++;
10557             free_voice(lowest);
10558             ctl_note_event(lowest);
10559             swap_voices(&voice[lowest], &voice[voices]);
10560         }
10561         else
10562             lost_notes++;
10563     }
10564     if(upper_voices > voices)
10565         upper_voices = voices;
10566     if(n > 0)
10567         ctl_mode_event(CTLE_MAXVOICES, 1, voices, 0);
10568 }
10569
10570 /* EAW -- do not throw away good notes, stop decrementing */
10571 static void voice_decrement_conservative(int n)
10572 {
10573     int i, j, lowest, finalnv;
10574     int32 lv, v;
10575
10576     /* decrease voice */
10577     finalnv = voices - n;
10578     for(i = 1; i <= n && voices > 0; i++)
10579     {
10580         if(voice[voices-1].status == VOICE_FREE) {
10581             voices--;
10582             continue;   /* found */
10583         }
10584
10585         for(j = 0; j < finalnv; j++)
10586             if(voice[j].status == VOICE_FREE)
10587                 break;
10588         if(j != finalnv)
10589         {
10590             swap_voices(&voice[j], &voice[voices - 1]);
10591             voices--;
10592             continue;   /* found */
10593         }
10594
10595         /* Look for the decaying note with the lowest volume */
10596         lv = 0x7FFFFFFF;
10597         lowest = -1;
10598         for(j = 0; j < voices; j++)
10599         {
10600             if(voice[j].status & ~(VOICE_ON | VOICE_DIE) &&
10601                !(voice[j].sample->note_to_use &&
10602                  ISDRUMCHANNEL(voice[j].channel)))
10603             {
10604                 v = voice[j].left_mix;
10605                 if((voice[j].panned==PANNED_MYSTERY) &&
10606                    (voice[j].right_mix > v))
10607                     v = voice[j].right_mix;
10608                 if(v < lv)
10609                 {
10610                     lv = v;
10611                     lowest = j;
10612                 }
10613             }
10614         }
10615
10616         if(lowest != -1)
10617         {
10618             voices--;
10619             cut_notes++;
10620             free_voice(lowest);
10621             ctl_note_event(lowest);
10622             swap_voices(&voice[lowest], &voice[voices]);
10623         }
10624         else break;
10625     }
10626     if(upper_voices > voices)
10627         upper_voices = voices;
10628 }
10629
10630 void restore_voices(int save_voices)
10631 {
10632 #ifdef REDUCE_VOICE_TIME_TUNING
10633     static int old_voices = -1;
10634     if(old_voices == -1 || save_voices)
10635         old_voices = voices;
10636     else if (voices < old_voices)
10637         voice_increment(old_voices - voices);
10638     else
10639         voice_decrement(voices - old_voices);
10640 #endif /* REDUCE_VOICE_TIME_TUNING */
10641 }
10642         
10643 ///r
10644 static int apply_controls(void)
10645 {
10646     int rc, i, jump_flag = 0;
10647     ptr_size_t val = 0, cur;
10648     FLOAT_T r;
10649     ChannelBitMask tmp_chbitmask;
10650
10651     /* ASCII renditions of CD player pictograms indicate approximate effect */
10652     do
10653     {
10654         switch(rc=ctl->read(&val))
10655         {
10656           case RC_STOP:
10657           case RC_QUIT:         /* [] */
10658           case RC_LOAD_FILE:
10659           case RC_NEXT:         /* >>| */
10660           case RC_REALLY_PREVIOUS: /* |<< */
10661           case RC_TUNE_END:     /* skip */
10662             aq_flush(1);
10663             return rc;
10664
10665           case RC_CHANGE_VOLUME:
10666             if (val>0 || output_amplification > -val)
10667                 output_amplification += val;
10668             else
10669                 output_amplification=0;
10670             if (output_amplification > MAX_AMPLIFICATION)
10671                 output_amplification=MAX_AMPLIFICATION;
10672          //   adjust_amplification();
10673          //   for (i=0; i<upper_voices; i++)
10674                 //if (voice[i].status != VOICE_FREE)
10675                 //{
10676                 //    recompute_amp(i);
10677                 //    apply_envelope_to_amp(i);
10678                 //}
10679                 change_output_volume(output_amplification);
10680             ctl_mode_event(CTLE_MASTER_VOLUME, 0, output_amplification, 0);
10681             continue;
10682
10683           case RC_CHANGE_REV_EFFB:
10684           case RC_CHANGE_REV_TIME:
10685             reverb_rc_event(rc, val);
10686             sync_restart(0);
10687             continue;
10688
10689           case RC_PREVIOUS:     /* |<< */
10690             aq_flush(1);
10691             if (current_sample < 2*play_mode->rate)
10692                 return RC_REALLY_PREVIOUS;
10693             return RC_RESTART;
10694
10695           case RC_RESTART:      /* |<< */
10696             if(play_pause_flag)
10697             {
10698                 midi_restart_time = 0;
10699                 ctl_pause_event(1, 0);
10700                 continue;
10701             }
10702             aq_flush(1);
10703             skip_to(0);
10704             ctl_updatetime(0);
10705             jump_flag = 1;
10706                 midi_restart_time = 0;
10707             continue;
10708
10709           case RC_JUMP:
10710             if(play_pause_flag)
10711             {
10712                 midi_restart_time = val;
10713                 ctl_pause_event(1, val);
10714                 continue;
10715             }
10716             aq_flush(1);
10717             if (val >= sample_count)
10718                 return RC_TUNE_END;
10719             skip_to(val);
10720             ctl_updatetime(val);
10721             return rc;
10722
10723           case RC_FORWARD:      /* >> */
10724             if(play_pause_flag)
10725             {
10726                 midi_restart_time += val;
10727                 if(midi_restart_time > sample_count)
10728                     midi_restart_time = sample_count;
10729                 ctl_pause_event(1, midi_restart_time);
10730                 continue;
10731             }
10732             cur = current_trace_samples();
10733             aq_flush(1);
10734             if(cur == -1)
10735                 cur = current_sample;
10736             if(val + cur >= sample_count)
10737                 return RC_TUNE_END;
10738             skip_to(val + cur);
10739             ctl_updatetime(val + cur);
10740             return RC_JUMP;
10741
10742           case RC_BACK:         /* << */
10743             if(play_pause_flag)
10744             {
10745                 midi_restart_time -= val;
10746                 if(midi_restart_time < 0)
10747                     midi_restart_time = 0;
10748                 ctl_pause_event(1, midi_restart_time);
10749                 continue;
10750             }
10751             cur = current_trace_samples();
10752             aq_flush(1);
10753             if(cur == -1)
10754                 cur = current_sample;
10755             if(cur > val)
10756             {
10757                 skip_to(cur - val);
10758                 ctl_updatetime(cur - val);
10759             }
10760             else
10761             {
10762                 skip_to(0);
10763                 ctl_updatetime(0);
10764                 midi_restart_time = 0;
10765             }
10766             return RC_JUMP;
10767
10768           case RC_TOGGLE_PAUSE:
10769             if(play_pause_flag)
10770             {
10771                 play_pause_flag = 0;
10772                 skip_to(midi_restart_time);
10773 #ifdef USE_TRACE_TIMER
10774                 if(ctl->trace_playing)
10775                         start_trace_timer();
10776 #endif
10777             }
10778             else
10779             {
10780 #ifdef USE_TRACE_TIMER
10781                 if(ctl->trace_playing)
10782                         stop_trace_timer();
10783 #endif
10784                 midi_restart_time = current_trace_samples();
10785                 if(midi_restart_time == -1)
10786                     midi_restart_time = current_sample;
10787                 aq_flush(1);
10788                 play_pause_flag = 1;
10789             }
10790             ctl_pause_event(play_pause_flag, midi_restart_time);
10791             jump_flag = 1;
10792             continue;
10793
10794           case RC_KEYUP:
10795           case RC_KEYDOWN:
10796             note_key_offset += val;
10797             current_freq_table += val;
10798             current_freq_table -= floor(current_freq_table * DIV_12) * 12;
10799             current_temper_freq_table += val;
10800             current_temper_freq_table -=
10801                         floor(current_temper_freq_table * DIV_12) * 12;
10802             if(sync_restart(1) != -1)
10803                 jump_flag = 1;
10804             ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
10805             continue;
10806
10807           case RC_SPEEDUP:
10808             r = 1.0;
10809             for(i = 0; i < val; i++)
10810                 r *= SPEED_CHANGE_RATE;
10811             sync_restart(0);
10812             midi_time_ratio /= r;
10813             current_sample = (int32)(current_sample / r + 0.5);
10814             trace_offset(current_sample);
10815             jump_flag = 1;
10816             ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
10817             continue;
10818
10819           case RC_SPEEDDOWN:
10820             r = 1.0;
10821             for(i = 0; i < val; i++)
10822                 r *= SPEED_CHANGE_RATE;
10823             sync_restart(0);
10824             midi_time_ratio *= r;
10825             current_sample = (int32)(current_sample * r + 0.5);
10826             trace_offset(current_sample);
10827             jump_flag = 1;
10828             ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
10829             continue;
10830
10831           case RC_VOICEINCR:
10832             restore_voices(0);
10833             voice_increment(val);
10834             if(sync_restart(1) != -1)
10835                 jump_flag = 1;
10836             restore_voices(1);
10837             continue;
10838
10839           case RC_VOICEDECR:
10840             restore_voices(0);
10841             if(sync_restart(1) != -1)
10842             {
10843                 voices -= val;
10844                 if(voices < 0)
10845                     voices = 0;
10846                 jump_flag = 1;
10847             }
10848             else
10849                 voice_decrement(val);
10850             restore_voices(1);
10851             continue;
10852
10853           case RC_TOGGLE_DRUMCHAN:
10854             midi_restart_time = current_trace_samples();
10855             if(midi_restart_time == -1)
10856                 midi_restart_time = current_sample;
10857             SET_CHANNELMASK(drumchannel_mask, val);
10858             SET_CHANNELMASK(current_file_info->drumchannel_mask, val);
10859             if(IS_SET_CHANNELMASK(drumchannels, val))
10860             {
10861                 UNSET_CHANNELMASK(drumchannels, val);
10862                 UNSET_CHANNELMASK(current_file_info->drumchannels, val);
10863             }
10864             else
10865             {
10866                 SET_CHANNELMASK(drumchannels, val);
10867                 SET_CHANNELMASK(current_file_info->drumchannels, val);
10868             }
10869             aq_flush(1);
10870             return RC_RELOAD;
10871
10872           case RC_TOGGLE_SNDSPEC:
10873 #ifdef SUPPORT_SOUNDSPEC
10874             if(view_soundspec_flag)
10875                 close_soundspec();
10876             else
10877                 open_soundspec();
10878             if(view_soundspec_flag || ctl_speana_flag)
10879             {
10880                 sync_restart(0);
10881                 soundspec_update_wave(NULL, -1);
10882             }
10883 #endif /* SUPPORT_SOUNDSPEC */
10884             continue;
10885
10886           case RC_TOGGLE_CTL_SPEANA:
10887 #ifdef SUPPORT_SOUNDSPEC
10888             ctl_speana_flag = !ctl_speana_flag;
10889             if(view_soundspec_flag || ctl_speana_flag)
10890             {
10891                 sync_restart(0);
10892                 soundspec_update_wave(NULL, -1);
10893             }
10894 #endif /* SUPPORT_SOUNDSPEC */
10895             continue;
10896
10897           case RC_SYNC_RESTART:
10898             sync_restart(val);
10899             jump_flag = 1;
10900             continue;
10901
10902           case RC_RELOAD:
10903             midi_restart_time = current_trace_samples();
10904             if(midi_restart_time == -1)
10905                 midi_restart_time = current_sample;
10906             aq_flush(1);
10907             return RC_RELOAD;
10908
10909           case RC_CHANGE_RATE:
10910             if(playmidi_change_rate(val, 1))
10911                 return RC_NONE;
10912             return RC_RELOAD;
10913
10914           case RC_OUTPUT_CHANGED:
10915             playmidi_output_changed(0);
10916             return RC_RELOAD;
10917
10918         case RC_TOGGLE_MUTE:
10919                 TOGGLE_CHANNELMASK(channel_mute, val);
10920                 sync_restart(0);
10921                 jump_flag = 1;
10922                 ctl_mode_event(CTLE_MUTE, 0,
10923                                 val, (IS_SET_CHANNELMASK(channel_mute, val)) ? 1 : 0);
10924                 continue;
10925
10926         case RC_SOLO_PLAY:
10927                 COPY_CHANNELMASK(tmp_chbitmask, channel_mute);
10928                 FILL_CHANNELMASK(channel_mute);
10929                 UNSET_CHANNELMASK(channel_mute, val);
10930                 if (! COMPARE_CHANNELMASK(tmp_chbitmask, channel_mute)) {
10931                         sync_restart(0);
10932                         jump_flag = 1;
10933                         for (i = 0; i < MAX_CHANNELS; i++)
10934                                 ctl_mode_event(CTLE_MUTE, 0, i, 1);
10935                         ctl_mode_event(CTLE_MUTE, 0, val, 0);
10936                 }
10937                 continue;
10938
10939         case RC_MUTE_CLEAR:
10940                 COPY_CHANNELMASK(tmp_chbitmask, channel_mute);
10941                 CLEAR_CHANNELMASK(channel_mute);
10942                 if (! COMPARE_CHANNELMASK(tmp_chbitmask, channel_mute)) {
10943                         sync_restart(0);
10944                         jump_flag = 1;
10945                         for (i = 0; i < MAX_CHANNELS; i++)
10946                                 ctl_mode_event(CTLE_MUTE, 0, i, 0);
10947                 }
10948                 continue;
10949         }
10950         if(intr)
10951             return RC_QUIT;
10952         if(play_pause_flag)
10953             usleep(300000);
10954     } while (rc != RC_NONE || play_pause_flag);
10955     return jump_flag ? RC_JUMP : RC_NONE;
10956 }
10957 ///r
10958 #if (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_DOUBLE)
10959 static inline void mix_signal(DATA_T *dest, DATA_T *src, int32 count)
10960 {
10961         int32 i;
10962         for(i = 0; i < count; i += 8){
10963                 MM256_LS_ADD_PD(&dest[i], _mm256_load_pd(&src[i]));
10964                 MM256_LS_ADD_PD(&dest[i + 4], _mm256_load_pd(&src[i + 4]));
10965         }
10966 }
10967 #elif (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_FLOAT)
10968 static inline void mix_signal(DATA_T *dest, DATA_T *src, int32 count)
10969 {
10970         int32 i;        
10971         for(i = 0; i < count; i += 8)
10972                 MM256_LS_ADD_PS(&dest[i], _mm256_load_ps(&src[i]));
10973 }
10974 #elif (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
10975 static inline void mix_signal(DATA_T *dest, DATA_T *src, int32 count)
10976 {
10977         int32 i;        
10978         for(i = 0; i < count; i += 8){
10979                 MM_LS_ADD_PD(&dest[i], _mm_load_pd(&src[i]));
10980                 MM_LS_ADD_PD(&dest[i + 2], _mm_load_pd(&src[i + 2]));
10981                 MM_LS_ADD_PD(&dest[i + 4], _mm_load_pd(&src[i + 4]));
10982                 MM_LS_ADD_PD(&dest[i + 6], _mm_load_pd(&src[i + 6]));
10983         }
10984 }
10985 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)
10986 static inline void mix_signal(DATA_T *dest, DATA_T *src, int32 count)
10987 {
10988         int32 i;        
10989         for(i = 0; i < count; i += 8){
10990                 MM_LS_ADD_PS(&dest[i], _mm_load_ps(&src[i]));
10991                 MM_LS_ADD_PS(&dest[i + 4], _mm_load_ps(&src[i + 4]));
10992         }
10993 }
10994 #else /* floating-point implementation */
10995 static inline void mix_signal(DATA_T *dest, DATA_T *src, int32 count)
10996 {
10997         int32 i;
10998         for (i = 0; i < count; i++) {
10999                 dest[i] += src[i];
11000         }
11001 }
11002 #endif
11003
11004 // mix and clear
11005 #if (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_DOUBLE)
11006 static inline void mix_signal_clear(DATA_T *dest, DATA_T *src, int32 count)
11007 {
11008         int32 i;        
11009         for(i = 0; i < count; i += 8){
11010                 MM256_LS_ADD_PD(&dest[i], _mm256_load_pd(&src[i]));
11011                 MM256_LS_ADD_PD(&dest[i + 4], _mm256_load_pd(&src[i + 4]));
11012         }
11013         memset(src, 0, sizeof(DATA_T) * count);
11014 }
11015 #elif (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_FLOAT)
11016 static inline void mix_signal_clear(DATA_T *dest, DATA_T *src, int32 count)
11017 {
11018         int32 i;        
11019         for(i = 0; i < count; i += 8)
11020                 MM256_LS_ADD_PS(&dest[i], _mm256_load_ps(&src[i]));
11021         memset(src, 0, sizeof(DATA_T) * count);
11022 }
11023 #elif (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
11024 static inline void mix_signal_clear(DATA_T *dest, DATA_T *src, int32 count)
11025 {
11026         int32 i;        
11027         for(i = 0; i < count; i += 8){
11028                 MM_LS_ADD_PD(&dest[i], _mm_load_pd(&src[i]));
11029                 MM_LS_ADD_PD(&dest[i + 2], _mm_load_pd(&src[i + 2]));
11030                 MM_LS_ADD_PD(&dest[i + 4], _mm_load_pd(&src[i + 4]));
11031                 MM_LS_ADD_PD(&dest[i + 6], _mm_load_pd(&src[i + 6]));
11032         }
11033         memset(src, 0, sizeof(DATA_T) * count);
11034 }
11035 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)
11036 static inline void mix_signal_clear(DATA_T *dest, DATA_T *src, int32 count)
11037 {
11038         int32 i;        
11039         for(i = 0; i < count; i += 8){
11040                 MM_LS_ADD_PS(&dest[i], _mm_load_ps(&src[i]));
11041                 MM_LS_ADD_PS(&dest[i + 4], _mm_load_ps(&src[i + 4]));
11042         }
11043         memset(src, 0, sizeof(DATA_T) * count);
11044 }
11045 #else /* floating-point implementation */
11046 static inline void mix_signal_clear(DATA_T *dest, DATA_T *src, int32 count)
11047 {
11048         int32 i;
11049
11050         for (i = 0; i < count; i++)
11051                 dest[i] += src[i];
11052         memset(src, 0, sizeof(DATA_T) * count);
11053 }
11054 #endif
11055
11056 #ifdef __BORLANDC__
11057 static int is_insertion_effect_xg(int ch)
11058 #else
11059 inline static int is_insertion_effect_xg(int ch)
11060 #endif
11061 {
11062         int i;
11063         for (i = 0; i < XG_INSERTION_EFFECT_NUM; i++) {
11064                 if (insertion_effect_xg[i].part == ch) {
11065                         return 1;
11066                 }
11067         }
11068         for (i = 0; i < XG_VARIATION_EFFECT_NUM; i++) {
11069                 if (variation_effect_xg[i].connection == XG_CONN_INSERTION
11070                         && variation_effect_xg[i].part == ch) {
11071                         return 1;
11072                 }
11073         }
11074         return 0;
11075 }
11076
11077 #ifdef __BORLANDC__
11078 static int is_mfx_effect_sd(int ch)
11079 #else
11080 inline static int is_mfx_effect_sd(int ch)
11081 #endif
11082 {
11083         if(channel[ch].sd_output_assign != 1){
11084                 if(!mfx_effect_sd[channel[ch].sd_output_mfx_select].type) // ==NULL
11085                         return 0;
11086                 if(*mfx_effect_sd[channel[ch].sd_output_mfx_select].type > 0)
11087                         return 1;
11088         }
11089         return 0;
11090 }
11091
11092 /*
11093 \83\8a\83A\83\8b\83^\83C\83\80\83\82\81[\83h\8e\9e \96³\89¹\83V\83\93\83Z\8f\88\97\9d\83X\83L\83b\83v
11094 \83{\83C\83X\90\940\8fó\91Ô\82Å\96³\89¹\82Æ\90\84\92è \83{\83C\83X\90\940\8cp\91±\92\86X\95b\8co\89ß\82Å\83o\83b\83t\83@\83`\83F\83b\83N\83t\83\89\83O
11095  (\8cp\91±\83J\83E\83\93\83g\90\94\82Í\89º\88Ê\83r\83b\83\83`\83F\83b\83N\89ñ\90\94\82Í\8fã\88Ê\83r\83b\83\83`\83F\83b\83N\83t\83\89\83O\82Í\89º\88Ê\83r\83b\83g0
11096  (\8co\89ß\8e\9e\8aÔ\82Í\96\88\89ñ\95Ï\82¦\82é\82Ì\82Í\83\8d\83\93\83O\83f\83B\83\8c\83C\89¹\82Ì\82Æ\82«\82Ì\83`\83F\83b\83N\94²\82¯\96h\8e~
11097 \96³\89¹\8am\94F\82µ\82½\82ç\83X\83L\83b\83v\83t\83\89\83O\83Z\83b\83g (\83X\83L\83b\83v\83t\83\89\83O\82Í -1
11098  (\96³\89¹\94»\92èè\87\92l\82Í24bits\8fo\97Í\91\8a\93\96\82Å0.5bit\88È\89º
11099 VST\93\99\82à\82 \82é\82Ì\82Å\83G\83t\83F\83N\83g\82Ì\97L\96³\82É\82æ\82é\96³\89¹\94»\92è\95Ï\8dX\82Í\82Å\82«\82È\82¢     
11100 \91O\89ñ\83o\83b\83t\83@\82Í\97\98\97p\82Å\82«\82È\82¢ aq_add()\82Å\8fã\8f\91\82«
11101 */
11102
11103 #define CDSS_CHECK_MAX 8 // must (CDSS_CHECK_BIT + CDSS_CHECK_MAX(bit) + 1) < 31BIT
11104 #define CDSS_CHECK_BIT 24 // sample rate max < 400kHz
11105
11106 static int compute_data_midi_skip(int32 count, int32 cnt)
11107 {
11108         int32 i;
11109         const FLOAT_T cdss_check_sec[CDSS_CHECK_MAX + 1] = 
11110         { 0.25, 0.3616, 0.3535, 0.1875, 0.3333, 0.2, 0.3141, 0.175, 0.25, }; // MAX8\8aî\8f\80 2sec
11111         const uint32 cdss_check_mask = (0xFFFFFFFF << CDSS_CHECK_BIT); // 0xFFF00000
11112         const DATA_T thres = (double)((1 << (MAX_BITS - GUARD_BITS - 1)) - 1) / (double)(1U << (23 + 1)); // 24bit\8fo\97Í0.5\83r\83b\83g\91\8a\93\96
11113         const uint32 cdss_count_mask = (1 << CDSS_CHECK_BIT) - 1; // 0xFFFFFF
11114         const int32 cdss_check_add = (1 << CDSS_CHECK_BIT); // 0x1000000
11115         const int32 cdss_check_max = cdss_check_add * (CDSS_CHECK_MAX + 1);
11116
11117         if(count){ // \83{\83C\83X\90\94\83`\83F\83b\83N , \8cp\91±\83J\83E\83\93\83g
11118                 if(upper_voices){ // \83{\83C\83X\90\94\83`\83F\83b\83N
11119                         compute_skip_count = 1; // reset (\83o\83b\83t\83@\83`\83F\83b\83N\89ñ\94ð
11120                         return 0; // no skip
11121                 }
11122                 if(compute_skip_count < 0) // \8f\88\97\9d\83X\83L\83b\83v
11123                         return 1; // skip
11124                 if((compute_skip_count += count) < 
11125                         (cdss_check_sec[compute_skip_count >> CDSS_CHECK_BIT] * play_mode->rate)) // \8cp\91±\83J\83E\83\93\83g
11126                         return 0; // no skip
11127                 compute_skip_count &= cdss_check_mask; // count 0 // buffer check on
11128                 return 0; // no skip
11129         }else{ // \83o\83b\83t\83@\83`\83F\83b\83N
11130                 if(compute_skip_count & cdss_count_mask) // !=0
11131                         return 0; // no skip
11132                 for(i = 0; i < cnt; i += 3){ // L/R 
11133 #if defined(DATA_T_DOUBLE) || defined(DATA_T_FLOAT)
11134                         if(fabs((DATA_T)buffer_pointer[i]) > thres){
11135 #else // DATA_T_INT32
11136                         if(abs((DATA_T)buffer_pointer[i]) > thres){
11137 #endif
11138                                 compute_skip_count = 1; // reset (\83o\83b\83t\83@\83`\83F\83b\83N\89ñ\94ð
11139                                 return 0; // no skip
11140                         }
11141                 }
11142                 if((compute_skip_count += cdss_check_add) < cdss_check_max) // next check
11143                         return 0; // no skip
11144                 compute_skip_count = -1; // set skip flag
11145                 return 1; // skip
11146         }
11147 }
11148
11149 // source mix
11150 static inline void mix_ch_signal_source(DATA_T *src, int ch, int count)
11151 {
11152         Channel *cp = channel + ch;
11153         int i;
11154         FLOAT_T left_mix = cp->vol_env.vol[0], right_mix = cp->vol_env.vol[1];
11155         
11156         if (play_mode->encoding & PE_MONO) {
11157                 /* Mono output. */
11158                 if(opt_mix_envelope > 0){
11159                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11160                         for (i = 0; i < count; i++) {
11161                                 if(!(i & mix_env_mask)) // i==0 \82Å\92Ê\82é
11162                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11163                                 *src++ *= cp->mix_env.vol[0];
11164                         }
11165                 }else{
11166                         for (i = 0; i < count; i++) {
11167                                 *src++ *= left_mix;
11168                         }
11169                 }
11170         }else{          
11171                 if(opt_mix_envelope >= 4){
11172                         
11173 // multi 4sample * 2ch  
11174 #if (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_DOUBLE)
11175                         __m128d vevolx;
11176                         __m256d vevol, vsp, vsp1, vsp2;
11177                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11178                         for (i = 0; i < count; i += 4) {
11179                                 if(!(i & mix_env_mask)){ // i==0 \82Å\92Ê\82é
11180                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11181 #if defined(FLOAT_T_DOUBLE)     
11182                                         vevolx = _mm_loadu_pd(cp->mix_env.vol);
11183 #else
11184                                         vevolx = _mm_cvtps_pd(_mm_load_ps(cp->mix_env.vol));
11185 #endif
11186                                         vevol = MM256_SET2X_PD(vevolx, vevolx);
11187                                 }
11188                                 MM256_LSU_MUL_PD(src, vevol);
11189                                 src += 4;
11190                                 MM256_LSU_MUL_PD(src, vevol);
11191                                 src += 4;
11192                         }       
11193         
11194 #elif (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_FLOAT)
11195                         __m128 vevolx;
11196                         __m256 vevol;
11197                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11198                         for (i = 0; i < count; i += 4) {
11199                                 if(!(i & mix_env_mask)){ // i==0 \82Å\92Ê\82é
11200                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11201 #if defined(FLOAT_T_DOUBLE)     
11202                                         vevolx = _mm_cvtpd_ps(_mm_loadu_pd(cp->mix_env.vol));
11203 #else
11204                                         vevolx = _mm_loadu_ps(cp->mix_env.vol);
11205 #endif
11206                                         vevolx = _mm_shuffle_ps(vevolx, vevolx, 0x44);
11207                                         vevol = MM256_SET2X_PS(vevolx, vevolx);
11208                                 }
11209                                 MM256_LSU_MUL_PS(src, vevol);
11210                                 src += 8;
11211                         }
11212
11213 #elif (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
11214                         __m128d vevol;
11215                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11216                         for (i = 0; i < count; i += 4) {
11217                                 if(!(i & mix_env_mask)){ // i==0 \82Å\92Ê\82é
11218                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11219 #if defined(FLOAT_T_DOUBLE)     
11220                                         vevol = _mm_loadu_pd(cp->mix_env.vol);
11221 #else
11222                                         vevol = _mm_cvtps_pd(_mm_load_ps(cp->mix_env.vol));
11223 #endif
11224                                 }
11225                                 MM_LSU_MUL_PD(src, vevol);
11226                                 src += 2;
11227                                 MM_LSU_MUL_PD(src, vevol);
11228                                 src += 2;
11229                                 MM_LSU_MUL_PD(src, vevol);
11230                                 src += 2;
11231                                 MM_LSU_MUL_PD(src, vevol);
11232                                 src += 2;
11233                         }
11234
11235 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)                        
11236                         __m128 vevol;
11237                         __m128 vsp;
11238                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11239                         for (i = 0; i < count; i += 4) {
11240                                 if(!(i & mix_env_mask)){ // i==0 \82Å\92Ê\82é
11241                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11242 #if defined(FLOAT_T_DOUBLE)     
11243 #if (USE_X86_EXT_INTRIN >= 3)
11244                                         vevol = _mm_cvtpd_ps(_mm_loadu_pd(cp->mix_env.vol));
11245 #else
11246                                         vevol = _mm_set_ps(0, 0, (float)cp->mix_env.vol[1], (float)cp->mix_env.vol[0]);
11247 #endif
11248 #else
11249                                         vevol = _mm_loadu_ps(cp->mix_env.vol);
11250 #endif
11251                                         vevol = _mm_shuffle_ps(vevol, vevol, 0x44);
11252                                 }
11253                                 MM_LSU_MUL_PS(src, vevol);
11254                                 src += 4;
11255                                 MM_LSU_MUL_PS(src, vevol);
11256                                 src += 4;
11257                         }
11258
11259 #else // ! USE_X86_EXT_INTRIN
11260                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11261                         for (i = 0; i < count; i++) {
11262                                 if(!(i & mix_env_mask)) // i==0 \82Å\92Ê\82é
11263                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11264                                 *src++ *= cp->mix_env.vol[0]; *src++ *= cp->mix_env.vol[1];
11265                         }
11266 #endif // USE_X86_EXT_INTRIN
11267
11268                 }else if(opt_mix_envelope > 0){
11269
11270 // single 1sample * 2ch
11271 #if (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
11272                         __m128d vevol;
11273                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11274                         for (i = 0; i < count; i++) {
11275                                 if(!(i & mix_env_mask)){
11276                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11277 #if defined(FLOAT_T_DOUBLE)     
11278                                         vevol = _mm_loadu_pd(cp->mix_env.vol);
11279 #else
11280                                         vevol = _mm_cvtps_pd(_mm_load_ps(cp->mix_env.vol));
11281 #endif
11282                                 }
11283                                 MM_LSU_MUL_PD(src, vevol);
11284                                 src += 2;
11285                         }
11286                         
11287 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)                        
11288                         __m128 vevol;
11289                         __m128 vsp;
11290                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11291                         for (i = 0; i < count; i++) {
11292                                 if(!(i & mix_env_mask)){
11293                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11294 #if defined(FLOAT_T_DOUBLE)     
11295 #if (USE_X86_EXT_INTRIN >= 3)
11296                                         vevol = _mm_cvtpd_ps(_mm_loadu_pd(cp->mix_env.vol));
11297 #else
11298                                         vevol = _mm_set_ps(0, 0, (float)cp->mix_env.vol[1], (float)cp->mix_env.vol[0]);
11299 #endif
11300 #else
11301                                         vevol = _mm_loadu_ps(cp->mix_env.vol);
11302 #endif
11303                                         vevol = _mm_shuffle_ps(vevol, vevol, 0x44);
11304                                 }
11305                                 vsp = _mm_mul_ps(_mm_loadu_ps(src), vevol);
11306                                 *(src++) = MM_EXTRACT_F32(vsp,0);
11307                                 *(src++) = MM_EXTRACT_F32(vsp,1);       
11308                         }
11309
11310 #else // ! USE_X86_EXT_INTRIN
11311                         reset_envelope2(&cp->mix_env, left_mix, right_mix, ENVELOPE_KEEP);
11312                         for (i = 0; i < count; i++) {
11313                                 if(!(i & mix_env_mask))
11314                                         compute_envelope2(&cp->mix_env, opt_mix_envelope);
11315                                 *src++ *= cp->mix_env.vol[0]; *src++ *= cp->mix_env.vol[1];
11316                         }
11317 #endif // USE_X86_EXT_INTRIN
11318
11319                 }else{
11320                         for (i = 0; i < count; i++) {
11321                                 *src++ *= left_mix; *src++ *= right_mix;
11322                         }
11323                 }
11324         }
11325 }
11326
11327 // drum efx mix level
11328 static inline void mix_dfx_signal_source(DATA_T *src, int ch, int count)
11329 {
11330         Channel *cp = channel + ch;
11331         int i;
11332         FLOAT_T left_mix = cp->vol_env.vol[0], right_mix = cp->vol_env.vol[1];
11333         
11334         if (play_mode->encoding & PE_MONO) {
11335                 /* Mono output. */
11336                 for (i = 0; i < count; i++) {
11337                         *src++ *= left_mix;
11338                 }
11339         }else{
11340
11341 // multi 4sample * 2ch  
11342 #if (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_DOUBLE)
11343                 __m128d vevolx;
11344                 __m256d vevol;
11345 #if defined(FLOAT_T_DOUBLE)     
11346                 vevolx = _mm_loadu_pd(cp->vol_env.vol);
11347 #else
11348                 vevolx = _mm_cvtps_pd(_mm_load_ps(cp->vol_env.vol);
11349 #endif
11350                 vevol = MM256_SET2X_PD(vevolx, vevolx);
11351                 for (i = 0; i < count; i += 4) {
11352                         MM256_LSU_MUL_PD(src, vevol);
11353                         src += 4;
11354                         MM256_LSU_MUL_PD(src, vevol);
11355                         src += 4;
11356                 }       
11357
11358 #elif (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
11359                 __m128d vevol;
11360 #if defined(FLOAT_T_DOUBLE)     
11361                 vevol = _mm_loadu_pd(cp->vol_env.vol);
11362 #else
11363                 vevol = _mm_cvtps_pd(_mm_load_ps(cp->vol_env.vol));
11364 #endif
11365                 for (i = 0; i < count; i += 4) {
11366                         MM_LSU_MUL_PD(src, vevol);
11367                         src += 2;
11368                         MM_LSU_MUL_PD(src, vevol);
11369                         src += 2;
11370                         MM_LSU_MUL_PD(src, vevol);
11371                         src += 2;
11372                         MM_LSU_MUL_PD(src, vevol);
11373                         src += 2;
11374                 }       
11375         
11376 #elif (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_FLOAT)
11377                 __m128 vevolx;
11378                 __m256 vevol;
11379 #if defined(FLOAT_T_DOUBLE)     
11380                 vevolx = _mm_cvtpd_ps(_mm_loadu_pd(cp->vol_env.vol));
11381 #else
11382                 vevolx = _mm_loadu_ps(cp->vol_env.vol);
11383 #endif
11384                 vevolx = _mm_shuffle_ps(vevolx, vevolx, 0x44);
11385                 vevol = MM256_SET2X_PS(vevolx, vevolx);
11386                 for (i = 0; i < count; i += 4) {
11387                         MM256_LSU_MUL_PS(src, vevol);
11388                         src += 8;
11389                 }
11390
11391 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)                        
11392                 __m128 vevol;   
11393 #if defined(FLOAT_T_DOUBLE)     
11394 #if (USE_X86_EXT_INTRIN >= 3)
11395                 vevol = _mm_cvtpd_ps(_mm_loadu_pd(cp->vol_env.vol));
11396 #else
11397                 vevol = _mm_set_ps(0, 0, (float)cp->vol_env.vol[1], (float)cp->vol_env.vol[0]);
11398 #endif
11399 #else
11400                 vevol = _mm_loadu_ps(cp->vol_env.vol);
11401 #endif
11402                 vevol = _mm_shuffle_ps(vevol, vevol, 0x44);
11403                 for (i = 0; i < count; i += 4) {
11404                         MM_LSU_MUL_PS(src, vevol);
11405                         src += 4;
11406                         MM_LSU_MUL_PS(src, vevol);
11407                         src += 4;
11408                 }
11409                 
11410 #else // ! USE_X86_EXT_INTRIN
11411                 for (i = 0; i < count; i++) {
11412                         *src++ *= left_mix;
11413                         *src++ *= right_mix;
11414                 }
11415 #endif // USE_X86_EXT_INTRIN
11416         }
11417 }
11418
11419 #if (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_DOUBLE)
11420 static inline void mix_signal_level(DATA_T *dest, DATA_T *src, int32 count, int32 level)
11421 {
11422         int32 i;        
11423         __m256d send_level = _mm256_set1_pd((FLOAT_T)level * DIV_127);
11424         for(i = 0; i < count; i += 8){
11425                 MM256_LS_FMA_PD(&dest[i], _mm256_load_pd(&src[i]), send_level);
11426                 MM256_LS_FMA_PD(&dest[i + 4], _mm256_load_pd(&src[i + 4]), send_level);
11427         }
11428 }
11429 #elif (USE_X86_EXT_INTRIN >= 8) && defined(DATA_T_FLOAT)
11430 static inline void mix_signal_level(DATA_T *dest, DATA_T *src, int32 count, int32 level)
11431 {
11432         int32 i;        
11433         __m256 send_level = _mm256_set1_ps((FLOAT_T)level * DIV_127);
11434         for(i = 0; i < count; i += 8)
11435                 MM256_LS_FMA_PS(&dest[i], _mm256_load_ps(&src[i]), send_level);
11436 }
11437 #elif (USE_X86_EXT_INTRIN >= 3) && defined(DATA_T_DOUBLE)
11438 static inline void mix_signal_level(DATA_T *dest, DATA_T *src, int32 count, int32 level)
11439 {
11440         int32 i;
11441         __m128d send_level = _mm_set1_pd((FLOAT_T)level * DIV_127);
11442         for(i = 0; i < count; i += 8){
11443                 MM_LS_FMA_PD(&dest[i], _mm_load_pd(&src[i]), send_level);
11444                 MM_LS_FMA_PD(&dest[i + 2], _mm_load_pd(&src[i + 2]), send_level);
11445                 MM_LS_FMA_PD(&dest[i + 4], _mm_load_pd(&src[i + 4]), send_level);
11446                 MM_LS_FMA_PD(&dest[i + 6], _mm_load_pd(&src[i + 6]), send_level);
11447         }
11448 }
11449 #elif (USE_X86_EXT_INTRIN >= 2) && defined(DATA_T_FLOAT)
11450 static inline void mix_signal_level(DATA_T *dest, DATA_T *src, int32 count, int32 level)
11451 {
11452         int32 i;        
11453         __m128 send_level = _mm_set1_ps((FLOAT_T)level * DIV_127);
11454         for(i = 0; i < count; i += 8){
11455                 MM_LS_FMA_PS(&dest[i], _mm_load_ps(&src[i]), send_level);
11456                 MM_LS_FMA_PS(&dest[i + 4], _mm_load_ps(&src[i + 4]), send_level);
11457         }
11458 }
11459 #else /* floating-point implementation */
11460 static inline void mix_signal_level(DATA_T *dest, DATA_T *src, int32 count, int32 level)
11461 {
11462     int32 i;
11463         FLOAT_T send_level = (FLOAT_T)level * DIV_127;
11464
11465     for(i = 0; i < count; i++)
11466                 dest[i] += src[i] * send_level;
11467 }
11468 #endif
11469
11470
11471 enum _send_type {
11472         SEND_OUTPUT = 0, // dry : common_buffer_pointer
11473         SEND_EFFECT, // reverb, chorus, delay, gs eq : set func
11474         SEND_GS_INS, // gs ins : insertion_effect_buffer
11475         SEND_SD_MFX, // sd mfx : mfx_effect_buffer
11476 };
11477
11478
11479 /* do_compute_data_midi() with DSP Effect */
11480 static void do_compute_data_midi(int32 count)
11481 {
11482         int i, j, ch, note, uv = upper_voices, max_ch = current_file_info->max_channel;
11483         int channel_effect, channel_reverb, channel_chorus, channel_delay, channel_eq, flg_ch_vst;
11484         int stereo = ! (play_mode->encoding & PE_MONO);
11485         int32 cnt = count * ((stereo) ? 2 : 1);
11486         int32 n = cnt * sizeof(DATA_T); /* in bytes */  
11487         struct DrumPartEffect *de;
11488         int channel_drumfx[MAX_CHANNELS];
11489         int channel_silent[MAX_CHANNELS];
11490         int channel_send[MAX_CHANNELS];
11491         
11492         /* output buffer clear */
11493         memset(buffer_pointer, 0, n); // must
11494
11495         if(opt_realtime_playing)
11496                 if(compute_data_midi_skip(count, cnt)){ // silent skip
11497                         current_sample += count;
11498                         return;
11499                 }
11500         
11501         // clear flag
11502         memset(channel_drumfx, 0, sizeof(channel_drumfx));      
11503         memset(channel_silent, 0, sizeof(channel_silent));
11504         memset(channel_send, 0, sizeof(channel_send));
11505         
11506         if(max_ch >= MAX_CHANNELS) max_ch = MAX_CHANNELS - 1;
11507
11508         /* are effects valid? / don't supported in mono */
11509         if(!stereo){
11510                 channel_reverb = channel_chorus = channel_delay = 0;
11511         }else{
11512                 channel_reverb = ((opt_reverb_control > 0 && opt_reverb_control & 0x1)
11513                                 || (opt_reverb_control < 0 && opt_reverb_control & 0x80));
11514                 channel_chorus = opt_chorus_control;
11515                 channel_delay = opt_delay_control > 0;
11516         }
11517         /* is EQ valid? */
11518         channel_eq = opt_eq_control && (eq_status_gs.low_gain != 0x40 || eq_status_gs.high_gain != 0x40
11519                 || play_system_mode == XG_SYSTEM_MODE);
11520         
11521         /* is ch vst valid? */
11522 #ifdef VST_LOADER_ENABLE                // elion add.
11523         flg_ch_vst = (hVSTHost != NULL && use_vst_channel) ? 1 : 0;
11524 #else
11525         flg_ch_vst = 0;
11526 #endif // VST_LOADER_ENABLE
11527
11528         channel_effect = !flg_ch_vst && (stereo && (channel_reverb || channel_chorus
11529                         || channel_delay || channel_eq || opt_insertion_effect));
11530
11531         for(i = 0; i < uv; i++) {
11532                 if(voice[i].status != VOICE_FREE) {
11533                         channel[voice[i].channel].lasttime = current_sample + count;
11534                 }
11535         }
11536
11537         /* appropriate buffers for channels */
11538         if(channel_effect) {
11539                 for(i = 0; i <= max_ch; i++) {
11540                         if(!IS_SET_CHANNELMASK(channel_mute, i))
11541                                 channel_silent[i] = 1;                  
11542                         if(flg_ch_vst){
11543                                 channel_send[i] = SEND_OUTPUT;
11544                         } else if(opt_insertion_effect && channel[i].insertion_effect) { // GS INS
11545                                 channel_send[i] = SEND_GS_INS;
11546                         } else if(opt_insertion_effect && (play_system_mode == SD_SYSTEM_MODE) && is_mfx_effect_sd(i)) { // SD MFX
11547                                 channel_send[i] = SEND_SD_MFX;
11548                         } else if(!flg_ch_vst && opt_drum_effect && ISDRUMCHANNEL(i)    ) {
11549                                 make_drum_effect(i);
11550                                 channel_drumfx[i] = 1;
11551                                 channel_send[i] = SEND_EFFECT;
11552                         } else if((play_system_mode == XG_SYSTEM_MODE && is_insertion_effect_xg(i))
11553                                 || channel[i].eq_gs
11554                                 || channel[i].reverb_level > 0
11555                                 || channel[i].chorus_level > 0
11556                                 || channel[i].delay_level > 0
11557                                 || channel[i].eq_xg.valid
11558                                 || channel[i].dry_level != 127) {
11559                                 channel_send[i] = SEND_EFFECT;
11560                         } else {
11561                                 channel_send[i] = SEND_OUTPUT;
11562                         }
11563                         /* clear buffers of drum-part effect */
11564                         if (opt_drum_effect && ISDRUMCHANNEL(i)){
11565                                 for (j = 0; j < channel[i].drum_effect_num; j++) 
11566                                         if (channel[i].drum_effect[j].buf != NULL) 
11567                                                 memset(channel[i].drum_effect[j].buf, 0, n);
11568                         }
11569                 }
11570         }else{
11571                 for(i = 0; i <= max_ch; i++)
11572                         if(!IS_SET_CHANNELMASK(channel_mute, i))
11573                                 channel_silent[i] = 1;
11574         }
11575
11576         for (i = 0; i < uv; i++) {
11577                 if (voice[i].status != VOICE_FREE) {
11578                         int8 flag;
11579                         ch = voice[i].channel;
11580                         
11581                         if(channel_silent[ch]) {
11582                                 int dfx_flg = 0, dfx_num = 0;
11583                                 if(channel_drumfx[ch]){
11584                                         for (j = 0; j < channel[ch].drum_effect_num; j++){
11585                                                 if (channel[ch].drum_effect[j].note == voice[i].note){
11586                                                         dfx_flg = 1; dfx_num = j;
11587                                                 }                                               
11588                                         }
11589                                 }
11590                                 if(dfx_flg){
11591                                         mix_voice(channel[ch].drum_effect[dfx_num].buf, i, count);
11592                                 }else{
11593                                         mix_voice(ch_buffer[ch], i, count);
11594                                 }
11595                                 if(voice[i].status == VOICE_FREE){
11596                                         ctl_note_event(i);
11597 #ifdef VOICE_EFFECT
11598                                         uninit_voice_effect(i);
11599 #endif
11600                                 }
11601                         } else {
11602                                 free_voice(i);
11603                                 ctl_note_event(i);
11604 #ifdef VOICE_EFFECT
11605                                 uninit_voice_effect(i);
11606 #endif
11607                         }
11608                 }
11609         }
11610
11611         while(uv > 0 && voice[uv - 1].status == VOICE_FREE)     {uv--;}
11612         upper_voices = uv;
11613
11614         
11615         if(!channel_effect){
11616 // channel VST
11617 #ifdef VST_LOADER_ENABLE                // elion add.
11618                 if (flg_ch_vst) {
11619                         // ch mixer             
11620                         //if(adjust_panning_immediately){
11621                         //      for(i = 0; i <= max_ch; i++) {
11622                         //              Channel *cp = channel + i;
11623                         //              reset_envelope2(&cp->vol_env, cp->ch_amp[0], cp->ch_amp[1], ENVELOPE_KEEP);
11624                         //              compute_envelope2(&cp->vol_env, count);
11625                         //              mix_ch_signal_source(ch_buffer[i], i, count);
11626                         //      }
11627                         //}
11628                         do_channel_vst(buffer_pointer, ch_buffer, cnt, max_ch);
11629                         /* clear buffers of channnel buffer */
11630                         for(i = 0; i <= max_ch; i++)
11631                                 memset(ch_buffer[i], 0, n); // clear
11632                 }else 
11633 #endif // VST_LOADER_ENABLE
11634 // all effect off
11635                 {
11636                         // ch mixer             
11637                         //if(adjust_panning_immediately){
11638                         //      for(i = 0; i <= max_ch; i++) {
11639                         //              Channel *cp = channel + i;
11640                         //              reset_envelope2(&cp->vol_env, cp->ch_amp[0], cp->ch_amp[1], ENVELOPE_KEEP);
11641                         //              compute_envelope2(&cp->vol_env, count);
11642                         //              mix_ch_signal_source(ch_buffer[i], i, count);
11643                         //      }
11644                         //}
11645                         for(i = 0; i <= max_ch; i++) {
11646                                 DATA_T *p = ch_buffer[i];
11647         
11648                                 mix_signal(buffer_pointer, p, cnt);
11649                                 /* clear buffers of channnel buffer */
11650                                 memset(p, 0, n); // clear
11651                         }
11652                 }
11653         }else switch(play_system_mode){
11654         case XG_SYSTEM_MODE:    /* XG */
11655                 for(i = 0; i <= max_ch; i++) {  /* system effects */
11656                         DATA_T *p = ch_buffer[i];
11657                         int silent = channel_silent[i];
11658                         int subtime = current_sample - channel[i].lasttime;
11659                         int thru;
11660                         int32 efx_delay_out, delay_out = 0;
11661                         Channel *cp = channel + i;
11662                 
11663                         if(silent && (subtime < delay_out_count[1]) ){
11664                                 int eq_flg = 0;
11665                                 if(!ISDRUMCHANNEL(i) ){
11666                                         if(channel_eq && channel[i].eq_xg.valid){ /* part EQ*/
11667                                                 do_ch_eq_xg(p, cnt, &(channel[i].eq_xg));
11668                                                 eq_flg++;
11669                                         }
11670                                 }else if(channel_drumfx[i] ){
11671                                         for (j = 0; j < channel[i].drum_effect_num; j++) {
11672                                                 de = &(channel[i].drum_effect[j]);
11673                                                 if(channel_eq && de->eq_xg->valid){     /* drum effect part EQ */
11674                                                         do_ch_eq_xg(de->buf, cnt, de->eq_xg);
11675                                                         eq_flg++;
11676                                                 }
11677                                                 mix_signal(p, de->buf, cnt); // drum_efx_buf mix to ch_buff
11678                                         }
11679                                 }
11680                                 if(eq_flg)
11681                                         delay_out += delay_out_count[1];                
11682                         }
11683                         /* insertion effect */
11684                         if(opt_insertion_effect){
11685                                 for (j = 0; j < XG_INSERTION_EFFECT_NUM; j++) {
11686                                         int ch = insertion_effect_xg[j].part;
11687                                         if(i != ch || !channel_silent[i])
11688                                                 continue;
11689                                         efx_delay_out = delay_out_count[delay_out_type_xg[insertion_effect_xg[j].type_msb][insertion_effect_xg[j].type_lsb]];
11690                                         if(subtime < (delay_out + efx_delay_out)){
11691                                                 do_insertion_effect_xg(p, cnt, &insertion_effect_xg[j]);
11692                                                 delay_out += efx_delay_out;
11693                                         }
11694                                 }
11695                         }
11696                         /* variation effect (ins mode) */
11697                         if(opt_delay_control){  
11698                                 for (j = 0; j < XG_VARIATION_EFFECT_NUM; j++) {
11699                                         int ch = variation_effect_xg[j].part;
11700                                         if(i != ch || !channel_silent[i] || variation_effect_xg[j].connection != XG_CONN_INSERTION)
11701                                                 continue;                               
11702                                         efx_delay_out = delay_out_count[delay_out_type_xg[variation_effect_xg[j].type_msb][variation_effect_xg[j].type_lsb]];
11703                                         if(subtime < (delay_out + efx_delay_out)){
11704                                                 do_insertion_effect_xg(p, cnt, &variation_effect_xg[j]);
11705                                                 delay_out += efx_delay_out;
11706                                         }
11707                                 }
11708                         }
11709                         // ch mixer                     
11710                         if(adjust_panning_immediately){
11711                                 reset_envelope2(&cp->vol_env, cp->ch_amp[0], cp->ch_amp[1], ENVELOPE_KEEP);
11712                                 compute_envelope2(&cp->vol_env, count);
11713                                 mix_ch_signal_source(p, i, count);
11714                                 if(channel_drumfx[i]){
11715                                         for (j = 0; j < channel[i].drum_effect_num; j++) {
11716                                                 mix_dfx_signal_source(channel[i].drum_effect[j].buf, i, cnt); // drum_efx_buf mix level
11717                                         }
11718                                 }
11719                         }                       
11720                         // send effect
11721                         thru = silent && (subtime < delay_out);
11722                         if(channel_send[i] == SEND_EFFECT){
11723                                 if(thru) {
11724                                         if (!is_insertion_effect_xg(i) && opt_drum_effect && ISDRUMCHANNEL(i) && channel[i].drum_effect_num) {
11725                                                 for (j = 0; j < channel[i].drum_effect_num; j++) {
11726                                                         de = &(channel[i].drum_effect[j]);
11727                                                         if (de->reverb_send > 0)
11728                                                                 set_ch_reverb(de->buf, cnt, de->reverb_send);
11729                                                         if (de->chorus_send > 0)
11730                                                                 set_ch_chorus(de->buf, cnt, de->chorus_send);
11731                                                         if (de->delay_send > 0)
11732                                                                 set_ch_delay(de->buf, cnt, de->delay_send);
11733                                                 }
11734                                         } else {
11735                                                 if(channel_chorus && channel[i].chorus_level > 0)
11736                                                         set_ch_chorus(p, cnt, channel[i].chorus_level);
11737                                                 if(channel_delay && channel[i].delay_level > 0)
11738                                                         set_ch_delay(p, cnt, channel[i].delay_level);
11739                                                 if(channel_reverb && channel[i].reverb_level > 0)
11740                                                         set_ch_reverb(p, cnt, channel[i].reverb_level);
11741                                         }
11742                                         if(channel[i].dry_level == 127)
11743                                                 mix_signal(buffer_pointer, p, cnt);
11744                                         else if(channel[i].dry_level) // lv != 0
11745                                                 mix_signal_level(buffer_pointer, p, cnt, channel[i].dry_level);
11746                                 
11747                                 }                               
11748                         }else if(channel_send[i] == SEND_OUTPUT){
11749                                 mix_signal(buffer_pointer, p, cnt);
11750                         }
11751                         /* clear buffers of channnel buffer */
11752                         memset(p, 0, n); // clear
11753                 }       
11754                 /* mixing signal and applying system effects */ 
11755                 if(channel_delay) {do_variation_effect1_xg(buffer_pointer, cnt);}
11756                 if(channel_chorus) {do_ch_chorus_xg(buffer_pointer, cnt);}
11757                 if(channel_reverb) {do_ch_reverb_xg(buffer_pointer, cnt);}
11758                 if(multi_eq_xg.valid) {do_multi_eq_xg(buffer_pointer, cnt);}
11759                 break;
11760         case GM2_SYSTEM_MODE:   /* GM2 */
11761                 {
11762                 int mfx_lasttime[SD_MFX_EFFECT_NUM] = {INT_MIN / 2, INT_MIN / 2, INT_MIN / 2,};
11763                 int mfx_silent[SD_MFX_EFFECT_NUM] = {0, 0, 0,};
11764                 
11765                 for(i = 0; i <= max_ch; i++) {  /* system effects */
11766                         DATA_T *p = ch_buffer[i];
11767                         int silent = channel_silent[i];
11768                         int subtime = current_sample - channel[i].lasttime;
11769                         Channel *cp = channel + i;
11770                         
11771                         // drum effect buffer mix
11772                         if(channel_drumfx[i])
11773                                 for (j = 0; j < channel[i].drum_effect_num; j++)
11774                                         mix_signal(p, channel[i].drum_effect[j].buf, cnt);
11775                         // send effect                  
11776                         if(channel_send[i] == SEND_SD_MFX){
11777                                 if(channel[i].lasttime > mfx_lasttime[cp->sd_output_mfx_select])
11778                                         mfx_lasttime[cp->sd_output_mfx_select] = channel[i].lasttime;
11779                                 mfx_silent[cp->sd_output_mfx_select] += silent;
11780                                 set_ch_mfx_sd(p, cnt, cp->sd_output_mfx_select, cp->sd_dry_send_level);
11781                         }else if(channel_send[i] == SEND_EFFECT){
11782                                 if(silent && (subtime < delay_out_count[0])) 
11783                                 {
11784                                         if (opt_drum_effect && ISDRUMCHANNEL(i) && channel[i].drum_effect_num) {
11785                                                 for (j = 0; j < channel[i].drum_effect_num; j++) {
11786                                                         de = &(channel[i].drum_effect[j]);
11787                                                         if (de->reverb_send > 0)
11788                                                                 set_ch_reverb(de->buf, cnt, de->reverb_send);
11789                                                         if (de->chorus_send > 0)
11790                                                                 set_ch_chorus(de->buf, cnt, de->chorus_send);
11791                                                 }
11792                                         } else {
11793                                                 if(channel_chorus && channel[i].chorus_level > 0)
11794                                                         set_ch_chorus(p, cnt, channel[i].chorus_level);
11795                                                 if(channel_reverb && channel[i].reverb_level > 0)
11796                                                         set_ch_reverb(p, cnt, channel[i].reverb_level);
11797                                         }
11798                                         mix_signal(buffer_pointer, p, cnt);
11799                                 }
11800                         }else if(channel_send[i] == SEND_OUTPUT){
11801                                 mix_signal(buffer_pointer, p, cnt);
11802                         }
11803                         /* clear buffers of channnel buffer */
11804                         memset(p, 0, n); // clear
11805                 }
11806                 if(opt_insertion_effect){
11807                         for(j = 0; j < SD_MFX_EFFECT_NUM; j++){
11808                                 if(mfx_silent[j]){
11809                                         int32 efx_delay_out = delay_out_count[delay_out_type_sd[*(mfx_effect_sd[j].type)]];
11810                                         if((current_sample - mfx_lasttime[j]) < efx_delay_out) {
11811                                                 do_mfx_effect_sd(buffer_pointer, cnt, j);                       
11812                                         }
11813                                 }
11814                         }
11815                 }
11816                 /* mixing signal and applying system effects */ 
11817                 if(channel_chorus) {do_ch_chorus(buffer_pointer, cnt);}
11818                 if(channel_reverb) {do_ch_reverb(buffer_pointer, cnt);}
11819                 if(multi_eq_sd.valid) {do_multi_eq_sd(buffer_pointer, cnt);}
11820                 }
11821                 break;
11822         case SD_SYSTEM_MODE:    /* SD */
11823                 {
11824                 int mfx_lasttime[SD_MFX_EFFECT_NUM] = {INT_MIN / 2, INT_MIN / 2, INT_MIN / 2,};
11825                 int mfx_silent[SD_MFX_EFFECT_NUM] = {0, 0, 0,};
11826                 
11827                 for(i = 0; i <= max_ch; i++) {  /* system effects */
11828                         DATA_T *p = ch_buffer[i];
11829                         int silent = channel_silent[i];
11830                         int subtime = current_sample - channel[i].lasttime;
11831                         Channel *cp = channel + i;
11832                         
11833                         // drum effect buffer mix
11834                         if(channel_drumfx[i])
11835                                 for (j = 0; j < channel[i].drum_effect_num; j++)
11836                                         mix_signal(p, channel[i].drum_effect[j].buf, cnt);
11837                         // send effect                  
11838                         if(channel_send[i] == SEND_SD_MFX){
11839                                 if(channel[i].lasttime > mfx_lasttime[cp->sd_output_mfx_select])
11840                                         mfx_lasttime[cp->sd_output_mfx_select] = channel[i].lasttime;
11841                                 mfx_silent[cp->sd_output_mfx_select] += silent;
11842                                 set_ch_mfx_sd(p, cnt, cp->sd_output_mfx_select, cp->sd_dry_send_level);
11843                         }else if(channel_send[i] == SEND_EFFECT){
11844                                 if(silent && (subtime < delay_out_count[0])) 
11845                                 {
11846                                         if (opt_drum_effect && ISDRUMCHANNEL(i) && channel[i].drum_effect_num) {
11847                                                 for (j = 0; j < channel[i].drum_effect_num; j++) {
11848                                                         de = &(channel[i].drum_effect[j]);
11849                                                         if (de->reverb_send > 0)
11850                                                                 set_ch_reverb(de->buf, cnt, de->reverb_send);
11851                                                         if (de->chorus_send > 0)
11852                                                                 set_ch_chorus(de->buf, cnt, de->chorus_send);
11853                                                 }
11854                                         } else {
11855                                                 if(channel_chorus && channel[i].chorus_level > 0)
11856                                                         set_ch_chorus(p, cnt, channel[i].chorus_level);
11857                                                 if(channel_reverb && channel[i].reverb_level > 0)
11858                                                         set_ch_reverb(p, cnt, channel[i].reverb_level);
11859                                         }
11860                                         mix_signal(buffer_pointer, p, cnt);
11861                                 }
11862                         }else if(channel_send[i] == SEND_OUTPUT){
11863                                 mix_signal(buffer_pointer, p, cnt);
11864                         }
11865                         /* clear buffers of channnel buffer */
11866                         memset(p, 0, n); // clear
11867                 }
11868                 if(opt_insertion_effect){
11869                         for(j = 0; j < SD_MFX_EFFECT_NUM; j++){
11870                                 if(mfx_silent[j]){
11871                                         int32 efx_delay_out = delay_out_count[delay_out_type_sd[*(mfx_effect_sd[j].type)]];
11872                                         if((current_sample - mfx_lasttime[j]) < efx_delay_out) {
11873                                                 do_mfx_effect_sd(buffer_pointer, cnt, j);                       
11874                                         }
11875                                 }
11876                         }
11877                 }
11878                 /* mixing signal and applying system effects */ 
11879                 if(channel_chorus) {do_ch_chorus_sd(buffer_pointer, cnt);}
11880                 if(channel_reverb) {do_ch_reverb_sd(buffer_pointer, cnt);}
11881                 if(multi_eq_sd.valid) {do_multi_eq_sd(buffer_pointer, cnt);}
11882                 }
11883                 break;
11884         default:        /* GM & GS */
11885                 {
11886                 int insertion_lasttime = INT_MIN / 2;
11887                 int insertion_silent = 0;
11888
11889                 for(i = 0; i <= max_ch; i++) {  /* system effects */
11890                         DATA_T *p = ch_buffer[i];
11891                         int silent = channel_silent[i];
11892                         int subtime = current_sample - channel[i].lasttime;
11893                         Channel *cp = channel + i;
11894                         
11895                         // drum effect buffer mix
11896                         if(channel_drumfx[i])
11897                                 for (j = 0; j < channel[i].drum_effect_num; j++)
11898                                         mix_signal(p, channel[i].drum_effect[j].buf, cnt);
11899                         // ch mixer
11900                         //if(adjust_panning_immediately){
11901                         //      reset_envelope2(&cp->vol_env, cp->ch_amp[0], cp->ch_amp[1], ENVELOPE_KEEP);
11902                         //      compute_envelope2(&cp->vol_env, count);
11903                         //      mix_ch_signal_source(p, i, count);
11904                         //      if(channel_drumfx[i]){
11905                         //              for (j = 0; j < channel[i].drum_effect_num; j++) {
11906                         //                      mix_dfx_signal_source(channel[i].drum_effect[j].buf, i, cnt); // drum_efx_buf mix level
11907                         //              }
11908                         //      }
11909                         //}
11910                         // send effect
11911                         if(channel_send[i] == SEND_GS_INS){
11912                                 if(channel[i].lasttime > insertion_lasttime)
11913                                         insertion_lasttime = channel[i].lasttime;
11914                                 insertion_silent += silent;
11915                                 set_ch_insertion_gs(p, cnt);
11916                         }else if(channel_send[i] == SEND_EFFECT){
11917                                 if(silent && (subtime < delay_out_count[0])) {
11918                                         if (opt_drum_effect && ISDRUMCHANNEL(i) && channel[i].drum_effect_num) {
11919                                                 for (j = 0; j < channel[i].drum_effect_num; j++) {
11920                                                         de = &(channel[i].drum_effect[j]);
11921                                                         if (de->reverb_send > 0)
11922                                                                 set_ch_reverb(de->buf, cnt, de->reverb_send);
11923                                                         if (de->chorus_send > 0)
11924                                                                 set_ch_chorus(de->buf, cnt, de->chorus_send);
11925                                                         if (de->delay_send > 0)
11926                                                                 set_ch_delay(de->buf, cnt, de->delay_send);
11927                                                 }
11928                                         } else {
11929                                                 if(channel_chorus && channel[i].chorus_level > 0)
11930                                                         set_ch_chorus(p, cnt, channel[i].chorus_level);
11931                                                 if(channel_delay && channel[i].delay_level > 0)
11932                                                         set_ch_delay(p, cnt, channel[i].delay_level);
11933                                                 if(channel_reverb && channel[i].reverb_level > 0)
11934                                                         set_ch_reverb(p, cnt, channel[i].reverb_level);
11935                                         }
11936                                         if(channel_eq && channel[i].eq_gs)      
11937                                                 set_ch_eq_gs(p, cnt);
11938                                         else
11939                                                 mix_signal(buffer_pointer, p, cnt);
11940                                 }
11941                         }else if(channel_send[i] == SEND_OUTPUT){
11942                                 mix_signal(buffer_pointer, p, cnt);
11943                         }
11944                         /* clear buffers of channnel buffer */
11945                         memset(p, 0, n); // clear
11946                 }
11947                 if(opt_insertion_effect && insertion_silent){
11948                         int32 efx_delay_out = delay_out_count[delay_out_type_gs[insertion_effect_gs.type_msb][insertion_effect_gs.type_lsb]];
11949                         if((current_sample - insertion_lasttime) < efx_delay_out) {
11950                                 /* insertion effect */ /* sending insertion effect voice to channel effect, eq, dry */
11951                                 do_insertion_effect_gs(buffer_pointer, cnt, channel_eq);                        
11952                         }
11953                 }
11954                 /* mixing signal and applying system effects */ 
11955                 if(channel_eq) {
11956                         do_ch_eq_gs(buffer_pointer, cnt);
11957                 }
11958                 if(channel_chorus) {do_ch_chorus(buffer_pointer, cnt);}
11959                 if(channel_delay) {do_ch_delay(buffer_pointer, cnt);}
11960                 if(channel_reverb) {do_ch_reverb(buffer_pointer, cnt);}
11961                 }
11962                 break;
11963         }
11964 ///r
11965         // elion add.
11966         // move effect.c do_effect()
11967         //mix_compressor(buffer_pointer, cnt);
11968     do_effect(buffer_pointer, count);
11969
11970         if(opt_realtime_playing)
11971                 compute_data_midi_skip(0, cnt); // silent skip , buffer check
11972         current_sample += count;
11973 }
11974
11975
11976 static void do_compute_data_wav(int32 count)
11977 {
11978         int i, stereo, samples, req_size, act_samples, v;
11979
11980         stereo = !(play_mode->encoding & PE_MONO);
11981         samples = (stereo ? (count * 2) : count);
11982         req_size = samples * 2; /* assume 16bit */
11983
11984         act_samples = tf_read(wav_buffer, 1, req_size, current_file_info->pcm_tf) / 2;
11985         for(i = 0; i < act_samples; i++) {
11986                 v = (uint16)LE_SHORT(wav_buffer[i]);
11987                 buffer_pointer[i] = (int32)((v << 16) | (v ^ 0x8000)) / 4; /* 4 : level down */
11988         }
11989         for(; i < samples; i++)
11990                 buffer_pointer[i] = 0;
11991
11992         current_sample += count;
11993 }
11994
11995 static void do_compute_data_aiff(int32 count)
11996 {
11997         int i, stereo, samples, req_size, act_samples, v;
11998
11999         stereo = !(play_mode->encoding & PE_MONO);
12000         samples = (stereo ? (count * 2) : count);
12001         req_size = samples * 2; /* assume 16bit */
12002
12003         act_samples = tf_read(wav_buffer, 1, req_size, current_file_info->pcm_tf) / 2;
12004         for(i = 0; i < act_samples; i++) {
12005                 v = (uint16)BE_SHORT(wav_buffer[i]);
12006                 buffer_pointer[i] = (int32)((v << 16) | (v ^ 0x8000)) / 4; /* 4 : level down */
12007         }
12008         for(; i < samples; i++)
12009                 buffer_pointer[i] = 0;
12010
12011         current_sample += count;
12012 }
12013
12014
12015 static void do_compute_data(int32 count)
12016 {
12017     switch(current_file_info->pcm_mode)
12018     {
12019       case PCM_MODE_NON:
12020 #ifdef MULTI_THREAD_COMPUTE
12021                 if(compute_thread_ready)
12022                 do_compute_data_midi_thread(count);
12023                 else
12024 #endif
12025         do_compute_data_midi(count);
12026         break;
12027       case PCM_MODE_WAV:
12028         do_compute_data_wav(count);
12029         break;
12030       case PCM_MODE_AIFF:
12031         do_compute_data_aiff(count);
12032         break;
12033       case PCM_MODE_AU:
12034         break;
12035       case PCM_MODE_MP3:
12036         break;
12037     }    
12038 }
12039
12040 static int check_midi_play_end(MidiEvent *e, int len)
12041 {
12042     int i, type;
12043
12044     for(i = 0; i < len; i++)
12045     {
12046         type = e[i].type;
12047         if(type == ME_NOTEON || type == ME_LAST || type == ME_WRD || type == ME_SHERRY)
12048             return 0;
12049         if(type == ME_EOT)
12050             return i + 1;
12051     }
12052     return 0;
12053 }
12054
12055 static int compute_data(int32 count);
12056 static int midi_play_end(void)
12057 {
12058 ///r
12059     int i, rc = RC_TUNE_END;//, time;
12060
12061     check_eot_flag = 0;
12062
12063     if(opt_realtime_playing && current_sample == 0)
12064     {
12065         reset_voices();
12066         return RC_TUNE_END;
12067     }
12068
12069 ///r
12070     /* add play time */
12071     if(opt_realtime_playing)
12072                 rc = compute_data((int32)(play_mode->rate * ADD_PLAY_TIME/2));
12073     else if(add_play_time)
12074                 rc = compute_data(add_play_count);
12075 //      time = play_mode->rate * MAX_DIE_TIME / 1000; // time ms
12076
12077     if(upper_voices > 0)
12078     {
12079                 int fadeout_cnt;
12080
12081                 rc = compute_data(play_mode->rate);
12082                 if(RC_IS_SKIP_FILE(rc))
12083                         goto midi_end;
12084
12085                 for(i = 0; i < upper_voices; i++)
12086                         if(voice[i].status & (VOICE_ON | VOICE_SUSTAINED))
12087                         finish_note(i);
12088                 if(opt_realtime_playing)
12089                         fadeout_cnt = 3;
12090                 else
12091                         fadeout_cnt = 6;
12092                 for(i = 0; i < fadeout_cnt && upper_voices > 0; i++)
12093                 {
12094                         rc = compute_data(play_mode->rate / 2);
12095                         if(RC_IS_SKIP_FILE(rc))
12096                         goto midi_end;
12097                 }
12098
12099                 /* kill voices */
12100                 kill_all_voices();
12101 ///r
12102 //              rc = compute_data(MAX_DIE_TIME); // sample num
12103                 rc = compute_data(ramp_out_count);
12104                 if(RC_IS_SKIP_FILE(rc))
12105                         goto midi_end;
12106                 upper_voices = 0;
12107     }
12108
12109     /* clear reverb echo sound */
12110     init_ch_reverb();
12111     for(i = 0; i < MAX_CHANNELS; i++)
12112     {
12113         channel[i].reverb_level = -1;
12114     }
12115 ///r
12116     /* add silent time */
12117     if(opt_realtime_playing){
12118                 rc = compute_data((int32)(play_mode->rate * ADD_SILENT_TIME/2));
12119                 if(RC_IS_SKIP_FILE(rc))
12120                         goto midi_end;
12121         }else if(add_silent_time){
12122                 rc = compute_data(add_silent_count);
12123         //      rc = compute_data((int32)(play_mode->rate * PLAY_INTERLEAVE_SEC));
12124                 if(RC_IS_SKIP_FILE(rc))
12125                         goto midi_end;
12126         }
12127
12128     compute_data(0); /* flush buffer to device */
12129
12130     if(ctl->trace_playing)
12131     {
12132         rc = aq_flush(0); /* Wait until play out */     
12133         if(RC_IS_SKIP_FILE(rc))
12134             goto midi_end;
12135     }
12136     else
12137     {
12138         trace_flush();
12139         rc = aq_soft_flush();
12140         if(RC_IS_SKIP_FILE(rc))
12141             goto midi_end;
12142     }
12143
12144   midi_end:
12145     if(RC_IS_SKIP_FILE(rc))
12146         aq_flush(1);
12147
12148     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Playing time: ~%d seconds",
12149               current_sample/play_mode->rate+2);
12150     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Notes cut: %d",
12151               cut_notes);
12152     ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Notes lost totally: %d",
12153               lost_notes);
12154     if(RC_IS_SKIP_FILE(rc))
12155         return rc;
12156     return RC_TUNE_END;
12157 }
12158
12159 ///r
12160 static void reduce_control(void)
12161 {
12162         int i, filled, s_filled , q_size , rate, nv;
12163         
12164         if(!reduce_voice_threshold || opt_realtime_playing || !(play_mode->flag & PF_CAN_TRACE))
12165                 return;
12166
12167         /* use Auto voice reduce  &  reduce quality */
12168         filled = aq_filled();
12169         s_filled = aq_soft_filled();
12170         q_size = aq_get_dev_queuesize();
12171         rate = (int)(((double)(filled + s_filled) / q_size) * 100 + 0.5);
12172
12173         if(aq_fill_buffer_flag || q_size <= 0)
12174                 return;
12175
12176         /* fall back to linear interpolation when queue < 100% */
12177         if (reduce_quality_threshold){
12178                 if (rate < reduce_quality_threshold)
12179                         reduce_quality_flag = 1;
12180                 else  if(rate > reduce_quality_threshold * 1.15)
12181                         reduce_quality_flag = 0;
12182         }
12183
12184 #ifdef REDUCE_VOICE_TIME_TUNING
12185         if(!reduce_voice_threshold)
12186                 return;
12187         /* Auto voice reduce implementation by Masanao Izumo */
12188         /* Reduce voices if there is not enough audio device buffer */
12189         /* Calculate rate as it is displayed in ncurs_c.c */
12190         /* The old method of calculating rate resulted in very low values
12191                 when using the new high order interplation methods on "slow"
12192                 CPUs when the queue was being drained WAY too quickly.  This
12193                 caused premature voice reduction under Linux, even if the queue
12194                 was over 2000%, leading to major voice lossage. */
12195         for(i = nv = 0; i < upper_voices; i++)
12196                 if(voice[i].status != VOICE_FREE)
12197                         nv++;
12198         if(reduce_polyphony_threshold) {
12199                 /* calculate ok_nv, the "optimum" max polyphony */
12200 //        if (auto_reduce_polyphony && rate < reduce_polyphony_threshold) {
12201                 if (rate < reduce_polyphony_threshold) {
12202                         reduce_polyphony_flag = 1;
12203                         /* average in current nv */
12204                         if ((rate == old_rate && nv > min_bad_nv) || (rate >= old_rate && rate < (reduce_polyphony_threshold * 0.25))) {
12205                                 ok_nv_total += nv;
12206                                 ok_nv_counts++;                         
12207                         /* increase polyphony when it is too low */
12208                         }else if (nv == voices && (rate > old_rate)) {
12209                         ok_nv_total += nv + 1;
12210                         ok_nv_counts++;                         
12211                         /* reduce polyphony when loosing buffer */
12212                         }else if (rate < (reduce_polyphony_threshold * 0.85) && (rate < old_rate)) {
12213                                 ok_nv_total += min_bad_nv;
12214                         ok_nv_counts++;
12215                         }else
12216                                 goto NO_RESCALE_NV;
12217                         /* rescale ok_nv stuff every 1 seconds */
12218                         if (current_sample >= ok_nv_sample && ok_nv_counts > 1)
12219                         {
12220                                 ok_nv_total >>= 1;
12221                                 ok_nv_counts >>= 1;
12222                                 ok_nv_sample = current_sample + (play_mode->rate);
12223                         }
12224                         NO_RESCALE_NV:;
12225                 } else
12226                         reduce_polyphony_flag = 0;
12227         }
12228
12229         /* EAW -- if buffer is < 75%, start reducing some voices to
12230                 try to let it recover.  This really helps a lot, preserves
12231                 decent sound, and decreases the frequency of lost ON notes */
12232         ///r
12233         if (rate < reduce_voice_threshold) {
12234                 reduce_voice_flag = 1;  
12235
12236                 if(rate <= old_rate) {
12237                         int kill_nv, temp_nv;
12238
12239                         /* set bounds on "good" and "bad" nv */
12240                         if (rate > (reduce_voice_threshold * 0.5) && nv < min_bad_nv) {
12241                                 min_bad_nv = nv;
12242                                 if (max_good_nv < min_bad_nv)
12243                                         max_good_nv = min_bad_nv;
12244                         }
12245                         /* EAW -- count number of !ON voices */
12246                         /* treat chorus notes as !ON */
12247                         for(i = kill_nv = 0; i < upper_voices; i++) {
12248                                 if(voice[i].status & VOICE_FREE || voice[i].cache != NULL)
12249                                         continue;                     
12250                                 if((voice[i].status & ~(VOICE_ON|VOICE_SUSTAINED) &&
12251                                         !(voice[i].status & ~(VOICE_DIE) && voice[i].sample->note_to_use)))
12252                                         kill_nv++;
12253                         }
12254                         /* EAW -- buffer is dangerously low, drasticly reduce
12255                                 voices to a hopefully "safe" amount */
12256                         if (rate < (reduce_voice_threshold * 0.25)) {
12257                                 FLOAT_T n;
12258                                 /* calculate the drastic voice reduction */
12259                                 if(nv > kill_nv){ /* Avoid division by zero */
12260                                         n = (FLOAT_T) nv / (nv - kill_nv);
12261                                         temp_nv = (int)(nv - nv / (n + 1));
12262                                         /* reduce by the larger of the estimates */
12263                                         if (kill_nv < temp_nv && temp_nv < nv)
12264                                                 kill_nv = temp_nv;
12265                                 }else
12266                                         kill_nv = nv - 1; /* do not kill all the voices */
12267                         }else {
12268                                 /* the buffer is still high enough that we can throw
12269                                         fewer voices away; keep the ON voices, use the
12270                                         minimum "bad" nv as a floor on voice reductions */
12271                                 temp_nv = nv - min_bad_nv;
12272                                 if (kill_nv > temp_nv)
12273                                         kill_nv = temp_nv;
12274                         }
12275                         for(i = 0; i < kill_nv; i++)
12276                                 reduce_voice();
12277                         /* lower max # of allowed voices to let the buffer recover */
12278                 //      if (auto_reduce_polyphony) {
12279                         if (reduce_polyphony_threshold) {
12280                                 temp_nv = nv - kill_nv;
12281                                 ok_nv = ok_nv_total / ok_nv_counts;
12282                                 /* decrease it to current nv left */
12283                                 if (voices > temp_nv && temp_nv > ok_nv)
12284                                         voice_decrement_conservative(voices - temp_nv);
12285                                 /* decrease it to ok_nv */
12286                                 else if (voices > ok_nv && temp_nv <= ok_nv)
12287                                         voice_decrement_conservative(voices - ok_nv);
12288                                 /* increase the polyphony */
12289                                 else if (voices < ok_nv)
12290                                         voice_increment(ok_nv - voices);
12291                         }
12292                         while(upper_voices > 0 && voice[upper_voices - 1].status == VOICE_FREE)
12293                                 upper_voices--;
12294                 }
12295         }else {
12296                 reduce_voice_flag = 0;
12297                 /* set bounds on "good" and "bad" nv */
12298                 if (rate > (reduce_voice_threshold * 1.15) && nv > max_good_nv) {
12299                         max_good_nv = nv;
12300                         if (min_bad_nv > max_good_nv)
12301                                 min_bad_nv = max_good_nv;
12302                 }
12303                 if (reduce_polyphony_threshold) {
12304                         /* reset ok_nv stuff when out of danger */
12305                         ok_nv_total = max_good_nv * ok_nv_counts;
12306                         if (ok_nv_counts > 1) {
12307                                 ok_nv_total >>= 1;
12308                                 ok_nv_counts >>= 1;
12309                         }
12310                         /* restore max # of allowed voices to normal */
12311                         restore_voices(0);
12312                 }
12313         }
12314         old_rate = rate;
12315 #endif
12316 }
12317
12318
12319
12320 /* count=0 means flush remaining buffered data to output device, then
12321    flush the device itself */
12322 ///r
12323 static int compute_data(int32 count)
12324 {
12325         int rc;
12326         
12327         if (!count){
12328                 if (buffered_count){
12329                         do_compute_data(compute_buffer_size); // fixed size
12330 #ifdef _DEBUG
12331                         ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY, "output data (%d)", buffered_count);
12332 #endif
12333 #ifdef SUPPORT_SOUNDSPEC
12334                         soundspec_update_wave(common_buffer, compute_buffer_size);
12335 #endif /* SUPPORT_SOUNDSPEC */
12336                         if(aq_add(common_buffer, compute_buffer_size) == -1)
12337                                 return RC_ERROR;
12338                 }
12339                 buffer_pointer=common_buffer;
12340                 buffered_count=0;
12341                 return RC_NONE;
12342     }
12343         count += buffered_count; // \91O\89ñ\82Ì\8ec\82è\83J\83E\83\93\83g\82ð\92Ç\89Á
12344         buffered_count = 0;
12345         if(current_event->type != ME_EOT)
12346                 ctl_timestamp();
12347         if((rc = apply_controls()) != RC_NONE)
12348                 return rc;
12349         while (count >= compute_buffer_size){
12350                 do_compute_data(compute_buffer_size); // fixed size
12351                 count -= compute_buffer_size;
12352 #ifdef _DEBUG
12353                 ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY, "output data (%d)", compute_buffer_size);
12354 #endif
12355 #ifdef SUPPORT_SOUNDSPEC
12356                 soundspec_update_wave(common_buffer, compute_buffer_size);
12357 #endif /* SUPPORT_SOUNDSPEC */
12358                 if(aq_add(common_buffer, compute_buffer_size) == -1)
12359                         return RC_ERROR;
12360                 buffer_pointer=common_buffer;
12361     }
12362         reduce_control();
12363         buffered_count = (count < 0) ? 0 : count; // save
12364         /* check break signals */
12365         VOLATILE_TOUCH(intr);
12366         if(intr)
12367                 return RC_QUIT;
12368         if(upper_voices == 0 && check_eot_flag){
12369                 int i = check_midi_play_end(current_event, EOT_PRESEARCH_LEN);
12370                 if(i > 1)
12371                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "Last %d MIDI events are ignored", i - 1);
12372                 if(i > 0)
12373                         return midi_play_end();
12374         }
12375         return RC_NONE;
12376 }
12377
12378 int play_event(MidiEvent *ev){
12379
12380     int32 i, j, cet;
12381     int k, l, ch, orig_ch, port_ch, offset, layered;
12382
12383     if(play_mode->flag & PF_MIDI_EVENT)
12384         return play_mode->acntl(PM_REQ_MIDI, ev);
12385     if(!(play_mode->flag & PF_PCM_STREAM))
12386         return RC_NONE;
12387
12388     current_event = ev;
12389     cet = MIDI_EVENT_TIME(ev);
12390
12391     if(ctl->verbosity >= VERB_DEBUG_SILLY)
12392         ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
12393                   "Midi Event %d: %s %d %d %d", cet,
12394                   event_name(ev->type), ev->channel, ev->a, ev->b);
12395
12396     if(cet > current_sample)
12397     {
12398         int rc;
12399
12400 #if ! defined(IA_WINSYN) && ! defined(IA_PORTMIDISYN) && ! defined(IA_W32G_SYN)
12401         if (midi_streaming != 0)
12402                 if ((cet - current_sample) * 1000 / play_mode->rate > stream_max_compute) {
12403                         kill_all_voices();
12404                         /* reset_voices(); */
12405                         /* ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
12406                                         "play_event: discard %d samples", cet - current_sample); */
12407                         current_sample = cet;
12408                 }
12409 #endif  
12410         rc = compute_data(cet - current_sample);
12411         ctl_mode_event(CTLE_REFRESH, 0, 0, 0);
12412     if(rc == RC_JUMP)
12413         {
12414                 ctl_timestamp();
12415                 return RC_NONE;
12416         }
12417         if(rc != RC_NONE)
12418             return rc;
12419         }
12420
12421 #ifndef SUPPRESS_CHANNEL_LAYER
12422         orig_ch = ev->channel;
12423         layered = ! IS_SYSEX_EVENT_TYPE(ev);
12424         for (k = 0; k < MAX_CHANNELS; k += 16) {
12425                 port_ch = (orig_ch + k) % MAX_CHANNELS;
12426                 offset = port_ch & ~0xf;
12427                 for (l = offset; l < offset + 16; l++) {
12428                         if (! layered && (k || l != offset))
12429                                 continue;
12430                         if (layered) {
12431                                 if (! IS_SET_CHANNELMASK(channel[l].channel_layer, port_ch)
12432                                                 || channel[l].port_select != (orig_ch >> 4))
12433                                         continue;
12434                                 ev->channel = l;
12435                         }
12436 #endif
12437         ch = ev->channel;
12438
12439         
12440         if(ev->type >= ME_TONE_BANK_MSB && ev->type <= ME_UNDEF_CTRL_CHNG)
12441                 if(!get_rx(ch, RX_CONTROL_CHANGE))                      
12442                         ev->type = ME_NONE;
12443         
12444         process_channel_control_event(ev);
12445         
12446         if(opt_insertion_effect){               
12447                 switch(play_system_mode) {
12448                 case GS_SYSTEM_MODE:
12449                         control_effect_gs(ev);
12450                         break;
12451                 case SD_SYSTEM_MODE:
12452                         control_effect_sd(ev);
12453                         break;
12454                 default:
12455                         break;
12456                 }
12457         }
12458
12459     switch(ev->type)
12460     {
12461         /* MIDI Events */
12462       case ME_NOTEOFF:
12463         if(!get_rx(ch, RX_NOTE_MESSAGE)) break;
12464         note_off(ev);
12465         break;
12466
12467       case ME_NOTEON:
12468         if(!get_rx(ch, RX_NOTE_MESSAGE)) break;
12469         note_on(ev);
12470         break;
12471
12472       case ME_KEYPRESSURE:
12473         if(!get_rx(ch, RX_POLY_PRESSURE)) break;
12474         adjust_pressure(ev);
12475         break;
12476
12477       case ME_PROGRAM:
12478         if(!get_rx(ch, RX_PROGRAM_CHANGE)) break;
12479         midi_program_change(ch, ev->a);
12480         ctl_prog_event(ch);
12481         break;
12482
12483       case ME_CHANNEL_PRESSURE:
12484         if(!get_rx(ch, RX_CH_PRESSURE)) break;
12485         adjust_channel_pressure(ev);
12486         control_effect_xg(ch);
12487         break;
12488
12489       case ME_PITCHWHEEL:
12490         if(!get_rx(ch, RX_PITCH_BEND)) break;
12491         {
12492                 int tmp = (int)ev->a + (int)ev->b * 128;
12493                 channel[ch].pitchbend = tmp;
12494                 channel[ch].bend.val = calc_bend_val(tmp);
12495         }
12496         /* Adjust pitch for notes already playing */
12497         adjust_pitch(ch);
12498         ctl_mode_event(CTLE_PITCH_BEND, 1, ch, channel[ch].pitchbend);
12499         control_effect_xg(ch);
12500         break;
12501
12502         /* Controls */
12503       case ME_TONE_BANK_MSB:
12504         if(!get_rx(ch, RX_BANK_SELECT)) break;
12505         channel[ch].bank_msb = ev->a;
12506         break;
12507
12508       case ME_TONE_BANK_LSB:
12509         if(!get_rx(ch, RX_BANK_SELECT_LSB)) break;
12510         channel[ch].bank_lsb = ev->a;
12511         break;
12512
12513       case ME_MODULATION_WHEEL:
12514         if(!get_rx(ch, RX_MODULATION)) break;
12515         if(opt_modulation_wheel){
12516                 channel[ch].mod.val = ev->a;
12517                 update_modulation_wheel(ch);
12518                 control_effect_xg(ch);
12519         }
12520         ctl_mode_event(CTLE_MOD_WHEEL, 1, ch, channel[ch].mod.val);
12521         break;
12522
12523       case ME_MAINVOLUME:
12524         if(!get_rx(ch, RX_VOLUME)) break;
12525         channel[ch].volume = ev->a;
12526         adjust_volume(ch);
12527         ctl_mode_event(CTLE_VOLUME, 1, ch, ev->a);
12528         break;
12529
12530       case ME_PAN:
12531         if(!get_rx(ch, RX_PANPOT)) break;
12532         channel[ch].panning = ev->a;
12533         channel[ch].pan_random = 0;
12534         if(adjust_panning_immediately && !channel[ch].pan_random)
12535             adjust_panning(ch);
12536         ctl_mode_event(CTLE_PANNING, 1, ch, ev->a);
12537         break;
12538
12539       case ME_EXPRESSION:
12540         if(!get_rx(ch, RX_EXPRESSION)) break;
12541         channel[ch].expression = ev->a;
12542         adjust_volume(ch);
12543         ctl_mode_event(CTLE_EXPRESSION, 1, ch, ev->a);
12544         break;
12545
12546 ///r
12547       case ME_SUSTAIN:
12548         if(!get_rx(ch, RX_HOLD1)) break;                  
12549         if (channel[ch].damper_mode == 0) {     /* half-damper is not allowed. */
12550                 if (ev->a >= 64) {
12551                         if(channel[ch].sustain == 0){
12552                                 channel[ch].sustain = 127;
12553                                 update_redamper_controls(ch);
12554                         }
12555                 }else {
12556                         channel[ch].sustain = 0;
12557                 }
12558         }else{
12559                 if(channel[ch].sustain != ev->a){
12560                         channel[ch].sustain = ev->a;
12561                         update_redamper_controls(ch);
12562                 }
12563         }
12564         if(channel[ch].sustain == 0 && channel[ch].sostenuto == 0)
12565             drop_sustain(ch);
12566         ctl_mode_event(CTLE_SUSTAIN, 1, ch, channel[ch].sustain);
12567 #if 0 
12568     if (channel[ch].sustain == 0 && ev->a >= 64) {
12569                 update_redamper_controls(ch);
12570         }
12571         channel[ch].sustain = ev->a;
12572         if (channel[ch].damper_mode == 0) {     /* half-damper is not allowed. */
12573                 if (channel[ch].sustain >= 64) {channel[ch].sustain = 127;}
12574                 else {channel[ch].sustain = 0;}
12575         }
12576         if(channel[ch].sustain == 0 && channel[ch].sostenuto == 0)
12577             drop_sustain(ch);
12578         ctl_mode_event(CTLE_SUSTAIN, 1, ch, channel[ch].sustain);
12579 #endif
12580         break;
12581 ///r
12582       case ME_SOSTENUTO:
12583         if(!get_rx(ch, RX_SOSTENUTO)) break;    
12584         channel[ch].sostenuto = (ev->a >= 64);
12585         update_sostenuto_controls(ch);
12586         if(channel[ch].sustain == 0 && channel[ch].sostenuto == 0)
12587             drop_sustain(ch);
12588         ctl->cmsg(CMSG_INFO, VERB_NOISY, "Sostenuto %d", channel[ch].sostenuto);
12589         break;
12590
12591       case ME_LEGATO_FOOTSWITCH:
12592         if(opt_portamento){
12593     channel[ch].legato = (ev->a >= 64);
12594         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Legato Footswitch (CH:%d VAL:%d)", ch, ev->a);
12595         }
12596         break;
12597
12598       case ME_HOLD2:
12599         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Hold2 - this function is not supported.");
12600         break;
12601
12602       case ME_BREATH:
12603         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Breath - this function is not supported.");
12604         break;
12605
12606       case ME_FOOT:
12607         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Foot - this function is not supported.");
12608         break;
12609
12610       case ME_BALANCE:
12611         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Balance - this function is not supported.");
12612         break;
12613
12614       case ME_PORTAMENTO_TIME_MSB:
12615         if(opt_portamento){
12616                 channel[ch].portamento_time_msb = ev->a;
12617                 update_portamento_time(ch);
12618                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Portamento Time MSB (CH:%d VAL:%d)",ch,ev->a);
12619         }
12620         break;
12621
12622       case ME_PORTAMENTO_TIME_LSB:
12623         if(opt_portamento){
12624                 channel[ch].portamento_time_lsb = ev->a;
12625                 update_portamento_time(ch);
12626                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Portamento Time LSB (CH:%d VAL:%d)",ch,ev->a);
12627         }
12628         break;
12629
12630       case ME_PORTAMENTO:
12631         if(!get_rx(ch, RX_PORTAMENTO)) break;   
12632         if(opt_portamento){
12633                 channel[ch].portamento = (ev->a >= 64);
12634                 if(!channel[ch].portamento)
12635                         drop_portamento(ch);
12636                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Portamento (CH:%d VAL:%d)",ch,ev->a);
12637         }
12638         break;
12639
12640       case ME_PORTAMENTO_CONTROL:
12641         if(opt_portamento){
12642                 channel[ch].portamento_control = ev->a;
12643                 ctl->cmsg(CMSG_INFO,VERB_NOISY,"Portamento Control (CH:%d VAL:%d)",ch,ev->a);
12644         }
12645         break;
12646
12647           case ME_SOFT_PEDAL:
12648         if(!get_rx(ch, RX_SOFT)) break; 
12649                   //if(opt_lpf_def) {
12650                           channel[ch].soft_pedal = ev->a;
12651                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Soft Pedal (CH:%d VAL:%d)",ch,channel[ch].soft_pedal);
12652                  //}
12653                   break;
12654
12655           case ME_HARMONIC_CONTENT:
12656                   //if(opt_lpf_def) {
12657                           channel[ch].param_resonance = ev->a - 64;
12658                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Harmonic Content (CH:%d VAL:%d)",ch,channel[ch].param_resonance);
12659                 //        update_channel_filter(ch);//elion add.
12660 //                        recompute_voice_filter(ch);// elion add.
12661                           recompute_channel_filter(ch);
12662                   //}
12663                   break;
12664
12665           case ME_BRIGHTNESS:
12666                   //if(opt_lpf_def) {
12667                           channel[ch].param_cutoff_freq = ev->a - 64;
12668                           ctl->cmsg(CMSG_INFO,VERB_NOISY,"Brightness (CH:%d VAL:%d)",ch,channel[ch].param_cutoff_freq);
12669                 //        update_channel_filter(ch);//elion add.
12670 //                        recompute_voice_filter(ch);// elion add.
12671                           recompute_channel_filter(ch);
12672                   //}
12673                   break;
12674
12675           case ME_VIBRATO_RATE:
12676                 if (opt_nrpn_vibrato) {
12677                         channel[ch].param_vibrato_rate = ev->a - 64;
12678                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Rate (CH:%d VAL:%d)",ch,ev->a - 64);
12679                 //      adjust_pitch(ch);
12680                         recompute_channel_lfo(ch);
12681                         recompute_channel_pitch(ch);
12682                 }
12683                 break;
12684
12685           case ME_VIBRATO_DEPTH:
12686                 if (opt_nrpn_vibrato) {
12687                         channel[ch].param_vibrato_depth = ev->a - 64;
12688                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Depth (CH:%d VAL:%d)",ch,ev->a - 64);
12689                 //      adjust_pitch(ch);
12690                         recompute_channel_lfo(ch);
12691                         recompute_channel_pitch(ch);
12692                 }
12693                 break;
12694
12695           case ME_VIBRATO_DELAY:
12696                 if (opt_nrpn_vibrato) {
12697                         channel[ch].param_vibrato_delay = ev->a - 64;
12698                         ctl->cmsg(CMSG_INFO, VERB_NOISY,"Vibrato Delay (CH:%d VAL:%d)",ch,ev->a - 64);
12699                 //      adjust_pitch(ch);
12700                         recompute_channel_lfo(ch);
12701                         recompute_channel_pitch(ch);
12702                 }
12703                 break;
12704
12705       case ME_DATA_ENTRY_MSB:
12706         if(channel[ch].rpn_7f7f_flag) /* disable */
12707             break;
12708         if((i = last_rpn_addr(ch)) >= 0)
12709         {
12710             channel[ch].rpnmap[i] = ev->a;
12711             update_rpn_map(ch, i, 1);
12712         }
12713         break;
12714
12715       case ME_DATA_ENTRY_LSB:
12716         if(channel[ch].rpn_7f7f_flag) /* disable */
12717             break;
12718             if((i = last_rpn_addr(ch)) >= 0)
12719             {
12720                 channel[ch].rpnmap_lsb[i] = ev->a;
12721             }
12722         break;
12723
12724         case ME_REVERB_EFFECT:
12725                 if (opt_reverb_control) {
12726                         if (ISDRUMCHANNEL(ch) && get_reverb_level(ch) != ev->a) {
12727                                 if(channel[ch].drum_effect_flag)
12728                                         channel[ch].drum_effect_flag |= 0x4; // update effect
12729                         }
12730                         set_reverb_level(ch, ev->a);
12731                         ctl_mode_event(CTLE_REVERB_EFFECT, 1, ch, get_reverb_level(ch));
12732                 }
12733                 break;
12734
12735       case ME_CHORUS_EFFECT:
12736         if(opt_chorus_control)
12737         {
12738                 if(opt_chorus_control == 1) {
12739                         if (ISDRUMCHANNEL(ch) && channel[ch].chorus_level != ev->a) {
12740                                 if(channel[ch].drum_effect_flag)
12741                                         channel[ch].drum_effect_flag |= 0x4; // update effect
12742                         }
12743                         channel[ch].chorus_level = ev->a;
12744                 } else {
12745                         channel[ch].chorus_level = -opt_chorus_control;
12746                 }
12747             ctl_mode_event(CTLE_CHORUS_EFFECT, 1, ch, get_chorus_level(ch));
12748                 if(ev->a) {
12749                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Chorus Send (CH:%d LEVEL:%d)",ch,ev->a);
12750                 }
12751         }
12752         break;
12753
12754       case ME_TREMOLO_EFFECT:
12755         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Tremolo Send (CH:%d LEVEL:%d)",ch,ev->a);
12756         break;
12757
12758       case ME_CELESTE_EFFECT:
12759         if(opt_delay_control) {
12760                 if (ISDRUMCHANNEL(ch) && channel[ch].delay_level != ev->a) {
12761                         if(channel[ch].drum_effect_flag)
12762                                 channel[ch].drum_effect_flag |= 0x4; // update effect
12763                 }
12764                 channel[ch].delay_level = ev->a;
12765                 if (play_system_mode == XG_SYSTEM_MODE) {
12766                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Variation Send (CH:%d LEVEL:%d)",ch,ev->a);
12767                 } else {
12768                         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Delay Send (CH:%d LEVEL:%d)",ch,ev->a);
12769                 }
12770         }
12771         break;
12772
12773           case ME_ATTACK_TIME:
12774         if(!opt_tva_attack) { break; }
12775         set_envelope_time(ch, ev->a, EG_ATTACK);
12776         break;
12777
12778           case ME_DECAY_TIME:
12779         if(!opt_tva_decay) { break; }
12780         set_envelope_time(ch, ev->a, EG_DECAY);
12781         break;
12782
12783           case ME_RELEASE_TIME:
12784         if(!opt_tva_release) { break; }
12785         set_envelope_time(ch, ev->a, EG_RELEASE);
12786         break;
12787
12788       case ME_PHASER_EFFECT:
12789         ctl->cmsg(CMSG_INFO,VERB_NOISY,"Phaser Send (CH:%d LEVEL:%d)",ch,ev->a);
12790         break;
12791
12792       case ME_RPN_INC:
12793         if(channel[ch].rpn_7f7f_flag) /* disable */
12794             break;
12795         if((i = last_rpn_addr(ch)) >= 0)
12796         {
12797             if(channel[ch].rpnmap[i] < 127)
12798                 channel[ch].rpnmap[i]++;
12799             update_rpn_map(ch, i, 1);
12800         }
12801         break;
12802
12803       case ME_RPN_DEC:
12804         if(channel[ch].rpn_7f7f_flag) /* disable */
12805             break;
12806         if((i = last_rpn_addr(ch)) >= 0)
12807         {
12808             if(channel[ch].rpnmap[i] > 0)
12809                 channel[ch].rpnmap[i]--;
12810             update_rpn_map(ch, i, 1);
12811         }
12812         break;
12813
12814       case ME_NRPN_LSB:
12815         if(!get_rx(ch, RX_NRPN)) break;
12816         channel[ch].rpn_7f7f_flag = 0;
12817         channel[ch].lastlrpn = ev->a;
12818         channel[ch].nrpn = 1;
12819         break;
12820
12821       case ME_NRPN_MSB:
12822         if(!get_rx(ch, RX_NRPN)) break;
12823         channel[ch].rpn_7f7f_flag = 0;
12824         channel[ch].lastmrpn = ev->a;
12825         channel[ch].nrpn = 1;
12826         break;
12827
12828       case ME_RPN_LSB:
12829         if(!get_rx(ch, RX_RPN)) break;
12830         channel[ch].rpn_7f7f_flag = 0;
12831         channel[ch].lastlrpn = ev->a;
12832         channel[ch].nrpn = 0;
12833         break;
12834
12835       case ME_RPN_MSB:
12836         if(!get_rx(ch, RX_RPN)) break;
12837         channel[ch].rpn_7f7f_flag = 0;
12838         channel[ch].lastmrpn = ev->a;
12839         channel[ch].nrpn = 0;
12840         break;
12841
12842       case ME_ALL_SOUNDS_OFF:
12843         all_sounds_off(ch);
12844         break;
12845
12846       case ME_RESET_CONTROLLERS:
12847         reset_controllers(ch);
12848         redraw_controllers(ch);
12849         break;
12850
12851       case ME_ALL_NOTES_OFF:
12852         all_notes_off(ch);
12853         break;
12854
12855       case ME_MONO:
12856         channel[ch].mono = 1;
12857         all_notes_off(ch);
12858         break;
12859
12860       case ME_POLY:
12861         channel[ch].mono = 0;
12862         all_notes_off(ch);
12863         break;
12864
12865         /* TiMidity Extensionals */
12866       case ME_RANDOM_PAN:
12867         channel[ch].panning = int_rand(128);
12868         channel[ch].pan_random = 1;
12869         if(adjust_panning_immediately && !channel[ch].pan_random)
12870             adjust_panning(ch);
12871         break;
12872
12873       case ME_SET_PATCH:
12874         i = channel[ch].special_sample = current_event->a;
12875         if(special_patch[i] != NULL)
12876             special_patch[i]->sample_offset = 0;
12877         ctl_prog_event(ch);
12878         break;
12879
12880       case ME_TEMPO:
12881         current_play_tempo = ch + ev->b * 256 + ev->a * 65536;
12882         ctl_mode_event(CTLE_TEMPO, 1, current_play_tempo, 0);
12883         break;
12884
12885       case ME_CHORUS_TEXT:
12886       case ME_LYRIC:
12887       case ME_MARKER:
12888       case ME_INSERT_TEXT:
12889       case ME_TEXT:
12890       case ME_KARAOKE_LYRIC:
12891         i = ev->a | ((int)ev->b << 8);
12892         ctl_mode_event(CTLE_LYRIC, 1, i, 0);
12893         break;
12894
12895       case ME_GSLCD:
12896         i = ev->a | ((int)ev->b << 8);
12897         ctl_mode_event(CTLE_GSLCD, 1, i, 0);
12898         break;
12899
12900       case ME_MASTER_VOLUME:
12901         master_volume_ratio = (int32)ev->a + 256 * (int32)ev->b;
12902         adjust_master_volume();
12903         break;
12904
12905       case ME_RESET:
12906         change_system_mode(ev->a);
12907         reset_midi(1);
12908         break;
12909
12910       case ME_PATCH_OFFS:
12911         i = channel[ch].special_sample;
12912         if(special_patch[i] != NULL)
12913             special_patch[i]->sample_offset =
12914                 (current_event->a | 256 * current_event->b);
12915         break;
12916
12917       case ME_WRD:
12918         push_midi_trace2(wrd_midi_event,
12919                          ch, current_event->a | (current_event->b << 8));
12920         break;
12921
12922       case ME_SHERRY:
12923         push_midi_trace1(wrd_sherry_event,
12924                          ch | (current_event->a<<8) | (current_event->b<<16));
12925         break;
12926
12927       case ME_DRUMPART:
12928                 if(play_system_mode == XG_SYSTEM_MODE && current_event->a)
12929                         channel[ch].bank_msb = 127; // Drum kit
12930         if(midi_drumpart_change(ch, current_event->a))
12931         {
12932             /* Update bank information */
12933             midi_program_change(ch, channel[ch].program);
12934             ctl_mode_event(CTLE_DRUMPART, 1, ch, ISDRUMCHANNEL(ch));
12935             ctl_prog_event(ch);
12936         }
12937         break;
12938
12939       case ME_KEYSHIFT:
12940         i = (int)current_event->a - 0x40;
12941         if(i != channel[ch].key_shift)
12942         {
12943             all_sounds_off(ch);
12944             channel[ch].key_shift = (int8)i;
12945         }
12946         break;
12947
12948         case ME_KEYSIG:
12949                 if (opt_init_keysig != 8)
12950                         break;
12951                 current_keysig = (current_event->a + current_event->b * 16)&0xff;
12952                 ctl_mode_event(CTLE_KEYSIG, 1, current_keysig, 0);
12953                 if (opt_force_keysig != 8) {
12954                         i = current_keysig - ((current_keysig < 8) ? 0 : 16), j = 0;
12955                         while (i != opt_force_keysig && i != opt_force_keysig + 12)
12956                                 i += (i > 0) ? -5 : 7, j++;
12957                         while (abs(j - note_key_offset) > 7)
12958                                 j += (j > note_key_offset) ? -12 : 12;
12959                         if (abs(j - key_adjust) >= 12)
12960                                 j += (j > key_adjust) ? -12 : 12;
12961                         note_key_offset = j;
12962                         kill_all_voices();
12963                         ctl_mode_event(CTLE_KEY_OFFSET, 1, note_key_offset, 0);
12964                 }
12965                 i = current_keysig + ((current_keysig < 8) ? 7 : -9), j = 0;
12966                 while (i != 7)
12967                         i += (i < 7) ? 5 : -7, j++;
12968                 j += note_key_offset, j -= floor(j * DIV_12) * 12;
12969                 current_freq_table = j;
12970                 adjust_pitch(ch);
12971                 break;
12972
12973         case ME_MASTER_TUNING:
12974                 set_master_tuning((ev->b << 8) | ev->a);
12975                 adjust_all_pitch();
12976                 break;
12977
12978         case ME_SCALE_TUNING:
12979                 resamp_cache_refer_alloff(ch, current_event->time);
12980                 channel[ch].scale_tuning[current_event->a] = current_event->b;
12981                 adjust_pitch(ch);
12982                 break;
12983
12984         case ME_BULK_TUNING_DUMP:
12985                 set_single_note_tuning(ch, current_event->a, current_event->b, 0);
12986                 break;
12987
12988         case ME_SINGLE_NOTE_TUNING:
12989                 set_single_note_tuning(ch, current_event->a, current_event->b, 1);
12990                 break;
12991
12992         case ME_TEMPER_KEYSIG:
12993                 current_temper_keysig = (current_event->a + 8) % 32 - 8;
12994                 temper_adj = ((current_event->a + 8) & 0x20) ? 1 : 0;
12995                 ctl_mode_event(CTLE_TEMPER_KEYSIG, 1, current_event->a, 0);
12996                 i = current_temper_keysig + ((current_temper_keysig < 8) ? 7 : -9);
12997                 j = 0;
12998                 while (i != 7)
12999                         i += (i < 7) ? 5 : -7, j++;
13000                 j += note_key_offset, j -= floor(j * DIV_12) * 12;
13001                 current_temper_freq_table = j;
13002                 if (current_event->b)
13003                         for (i = 0; i < upper_voices; i++)
13004                                 if (voice[i].status != VOICE_FREE) {
13005                                         voice[i].temper_instant = 1;
13006                                 //      recompute_freq(i);
13007                                 }
13008                 adjust_pitch(ch);
13009                 break;
13010
13011         case ME_TEMPER_TYPE:
13012                 channel[ch].temper_type = current_event->a;
13013                 ctl_mode_event(CTLE_TEMPER_TYPE, 1, ch, channel[ch].temper_type);
13014                 if (temper_type_mute) {
13015                         if (temper_type_mute & (1 << (current_event->a
13016                                         - ((current_event->a >= 0x40) ? 0x3c : 0)))) {
13017                                 SET_CHANNELMASK(channel_mute, ch);
13018                                 ctl_mode_event(CTLE_MUTE, 1, ch, 1);
13019                         } else {
13020                                 UNSET_CHANNELMASK(channel_mute, ch);
13021                                 ctl_mode_event(CTLE_MUTE, 1, ch, 0);
13022                         }
13023                 }
13024                 if (current_event->b)
13025                         for (i = 0; i < upper_voices; i++)
13026                                 if (voice[i].status != VOICE_FREE) {
13027                                         voice[i].temper_instant = 1;
13028                                 //      recompute_freq(i);
13029                                 }
13030                 adjust_pitch(ch);
13031                 break;
13032
13033         case ME_MASTER_TEMPER_TYPE:
13034                 for (i = 0; i < MAX_CHANNELS; i++) {
13035                         channel[i].temper_type = current_event->a;
13036                         ctl_mode_event(CTLE_TEMPER_TYPE, 1, i, channel[i].temper_type);
13037                 }
13038                 if (temper_type_mute) {
13039                         if (temper_type_mute & (1 << (current_event->a
13040                                         - ((current_event->a >= 0x40) ? 0x3c : 0)))) {
13041                                 FILL_CHANNELMASK(channel_mute);
13042                                 for (i = 0; i < MAX_CHANNELS; i++)
13043                                         ctl_mode_event(CTLE_MUTE, 1, i, 1);
13044                         } else {
13045                                 CLEAR_CHANNELMASK(channel_mute);
13046                                 for (i = 0; i < MAX_CHANNELS; i++)
13047                                         ctl_mode_event(CTLE_MUTE, 1, i, 0);
13048                         }
13049                 }
13050                 if (current_event->b)
13051                         for (i = 0; i < upper_voices; i++)
13052                                 if (voice[i].status != VOICE_FREE) {
13053                                         voice[i].temper_instant = 1;
13054                                 //      recompute_freq(i);
13055                                 }
13056                 adjust_pitch(ch);
13057                 break;
13058
13059         case ME_USER_TEMPER_ENTRY:
13060                 set_user_temper_entry(ch, current_event->a, current_event->b);
13061                 adjust_pitch(ch);
13062                 break;
13063
13064         case ME_SYSEX_LSB:
13065                 process_sysex_event(ME_SYSEX_LSB,ch,current_event->a,current_event->b);
13066             break;
13067
13068         case ME_SYSEX_MSB:
13069                 process_sysex_event(ME_SYSEX_MSB,ch,current_event->a,current_event->b);
13070             break;
13071
13072         case ME_SYSEX_GS_LSB:
13073                 process_sysex_event(ME_SYSEX_GS_LSB,ch,current_event->a,current_event->b);
13074             break;
13075
13076         case ME_SYSEX_GS_MSB:
13077                 process_sysex_event(ME_SYSEX_GS_MSB,ch,current_event->a,current_event->b);
13078             break;
13079
13080         case ME_SYSEX_XG_LSB:
13081                 process_sysex_event(ME_SYSEX_XG_LSB,ch,current_event->a,current_event->b);
13082             break;
13083
13084         case ME_SYSEX_XG_MSB:
13085                 process_sysex_event(ME_SYSEX_XG_MSB,ch,current_event->a,current_event->b);
13086             break;
13087
13088         case ME_SYSEX_SD_LSB:
13089                 process_sysex_event(ME_SYSEX_SD_LSB,ch,current_event->a,current_event->b);
13090             break;
13091
13092         case ME_SYSEX_SD_MSB:
13093                 process_sysex_event(ME_SYSEX_SD_MSB,ch,current_event->a,current_event->b);
13094             break;
13095
13096         case ME_SYSEX_SD_HSB:
13097                 process_sysex_event(ME_SYSEX_SD_HSB,ch,current_event->a,current_event->b);
13098             break;
13099
13100         case ME_NOTE_STEP:
13101                 i = ev->a + ((ev->b & 0x0f) << 8);
13102                 j = ev->b >> 4;
13103                 ctl_mode_event(CTLE_METRONOME, 1, i, j);
13104                 if (readmidi_wrd_mode)
13105                         wrdt->update_events();
13106                 break;
13107                 
13108         case ME_CUEPOINT:
13109                 set_cuepoint(ch, current_event->a, current_event->b);
13110                 break;
13111
13112         case ME_EOT:
13113                 ctl_mode_event(CTLE_CURRENT_TIME_END, 0, (long)(current_sample / (midi_time_ratio * play_mode->rate)), 0);
13114                 return midi_play_end();
13115     }
13116 #ifndef SUPPRESS_CHANNEL_LAYER
13117                 }
13118         }
13119         ev->channel = orig_ch;
13120 #endif
13121
13122     return RC_NONE;
13123 }
13124
13125 static void set_master_tuning(int tune)
13126 {
13127         if (tune & 0x4000)      /* 1/8192 semitones + 0x2000 | 0x4000 */
13128                 tune = (tune & 0x3FFF) - 0x2000;
13129         else if (tune & 0x8000) /* 1 semitones | 0x8000 */
13130                 tune = ((tune & 0x7F) - 0x40) << 13;
13131         else    /* millisemitones + 0x400 */
13132                 tune = (((tune - 0x400) << 13) + 500) / 1000;
13133         master_tuning = tune;
13134 }
13135
13136 static void set_single_note_tuning(int part, int a, int b, int rt)
13137 {
13138         static int tp;  /* tuning program number */
13139         static int kn;  /* MIDI key number */
13140         static int st;  /* the nearest equal-tempered semitone */
13141         double f, fst;  /* fraction of semitone */
13142         int i;
13143         
13144         switch (part) {
13145         case 0:
13146                 tp = a;
13147                 break;
13148         case 1:
13149                 kn = a, st = b;
13150                 break;
13151         case 2:
13152                 if (st == 0x7f && a == 0x7f && b == 0x7f)       /* no change */
13153                         break;
13154                 f = 440 * pow(2.0, (st - 69) * DIV_12);
13155                 fst = pow(2.0, (a << 7 | b) / 196608.0);
13156                 freq_table_tuning[tp][kn] = f * fst * 1000 + 0.5;
13157                 if (rt)
13158                         for (i = 0; i < upper_voices; i++)
13159                                 if (voice[i].status != VOICE_FREE) {
13160                                         voice[i].temper_instant = 1;
13161                                 //      recompute_freq(i);
13162                                         recompute_voice_pitch(i);
13163                                 }
13164                 break;
13165         }
13166 }
13167
13168 static void set_user_temper_entry(int part, int a, int b)
13169 {
13170         static int tp;          /* temperament program number */
13171         static int ll;          /* number of formula */
13172         static int fh, fl;      /* applying pitch bit mask (forward) */
13173         static int bh, bl;      /* applying pitch bit mask (backward) */
13174         static int aa, bb;      /* fraction (aa/bb) */
13175         static int cc, dd;      /* power (cc/dd)^(ee/ff) */
13176         static int ee, ff;
13177         static int ifmax, ibmax, count;
13178         static double rf[11], rb[11];
13179         int i, j, k, l, n, m;
13180         double ratio[12], f, sc;
13181         
13182         switch (part) {
13183         case 0:
13184                 for (i = 0; i < 11; i++)
13185                         rf[i] = rb[i] = 1;
13186                 ifmax = ibmax = 0;
13187                 count = 0;
13188                 tp = a, ll = b;
13189                 break;
13190         case 1:
13191                 fh = a, fl = b;
13192                 break;
13193         case 2:
13194                 bh = a, bl = b;
13195                 break;
13196         case 3:
13197                 aa = a, bb = b;
13198                 break;
13199         case 4:
13200                 cc = a, dd = b;
13201                 break;
13202         case 5:
13203                 ee = a, ff = b;
13204                 for (i = 0; i < 11; i++) {
13205                         if (((fh & 0xf) << 7 | fl) & 1 << i) {
13206                                 rf[i] *= (double) aa / bb
13207                                                 * pow((double) cc / dd, (double) ee / ff);
13208                                 if (ifmax < i + 1)
13209                                         ifmax = i + 1;
13210                         }
13211                         if (((bh & 0xf) << 7 | bl) & 1 << i) {
13212                                 rb[i] *= (double) aa / bb
13213                                                 * pow((double) cc / dd, (double) ee / ff);
13214                                 if (ibmax < i + 1)
13215                                         ibmax = i + 1;
13216                         }
13217                 }
13218                 if (++count < ll)
13219                         break;
13220                 ratio[0] = 1;
13221                 for (i = n = m = 0; i < ifmax; i++, m = n) {
13222                         n += (n > 4) ? -5 : 7;
13223                         ratio[n] = ratio[m] * rf[i];
13224                         if (ratio[n] > 2)
13225                                 ratio[n] /= 2;
13226                 }
13227                 for (i = n = m = 0; i < ibmax; i++, m = n) {
13228                         n += (n > 6) ? -7 : 5;
13229                         ratio[n] = ratio[m] / rb[i];
13230                         if (ratio[n] < 1)
13231                                 ratio[n] *= 2;
13232                 }
13233                 sc = 27 / ratio[9] / 16;        /* syntonic comma */
13234                 for (i = 0; i < 12; i++)
13235                         for (j = -1; j < 11; j++) {
13236                                 f = 440 * pow(2.0, (i - 9) * DIV_12 + j - 5);
13237                                 for (k = 0; k < 12; k++) {
13238                                         l = i + j * 12 + k;
13239                                         if (l < 0 || l >= 128)
13240                                                 continue;
13241                                         if (! (fh & 0x40)) {    /* major */
13242                                                 freq_table_user[tp][i][l] =
13243                                                                 f * ratio[k] * 1000 + 0.5;
13244                                                 freq_table_user[tp][i + 36][l] =
13245                                                                 f * ratio[k] * sc * 1000 + 0.5;
13246                                         }
13247                                         if (! (bh & 0x40)) {    /* minor */
13248                                                 freq_table_user[tp][i + 12][l] =
13249                                                                 f * ratio[k] * sc * 1000 + 0.5;
13250                                                 freq_table_user[tp][i + 24][l] =
13251                                                                 f * ratio[k] * 1000 + 0.5;
13252                                         }
13253                                 }
13254                         }
13255                 break;
13256         }
13257 }
13258
13259 static void set_cuepoint(int part, int a, int b)
13260 {
13261         static int a0 = 0, b0 = 0;
13262
13263         if (part == 0) {
13264                 a0 = a, b0 = b;
13265                 return;
13266         }
13267         ctl_mode_event(CTLE_CUEPOINT, 1, a0 << 24 | b0 << 16 | a << 8 | b, 0);
13268 }
13269
13270 static int play_midi(MidiEvent *eventlist, int32 samples)
13271 {
13272     int rc;
13273     static int play_count = 0;
13274
13275     if (play_mode->id_character == 'M') {
13276                 int cnt, err;
13277
13278                 err = convert_mod_to_midi_file(eventlist);
13279
13280                 play_count = 0;
13281                 cnt = free_global_mblock();     /* free unused memory */
13282                 if(cnt > 0)
13283                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
13284                                   "%d memory blocks are free", cnt);
13285                 if (err) return RC_ERROR;
13286                 return RC_TUNE_END;
13287     }
13288         
13289     sample_count = samples;     
13290
13291     event_list = eventlist;
13292     lost_notes = cut_notes = 0;
13293     check_eot_flag = 1;
13294
13295     wrd_midi_event(-1, -1); /* For initialize */
13296
13297     reset_midi(0);
13298  ///r   
13299         // for opt_amp_compensation , see play_midi_prescan() adjust_amplification()
13300         mainvolume_max = 0x7f;
13301         compensation_ratio = 1.0;
13302
13303         if(!opt_realtime_playing
13304         //      && allocate_cache_size > 0
13305                 && !IS_CURRENT_MOD_FILE
13306                 && (play_mode->flag&PF_PCM_STREAM))
13307     {
13308                 play_midi_prescan(eventlist);
13309                 reset_midi(0);
13310     }
13311
13312     rc = aq_flush(0);
13313     if(RC_IS_SKIP_FILE(rc))
13314         return rc;
13315
13316 #ifdef USE_TRACE_TIMER
13317     if(ctl->trace_playing)
13318                 start_trace_timer();
13319 #endif
13320         
13321     skip_to(midi_restart_time);
13322
13323     if(midi_restart_time > 0) { /* Need to update interface display */
13324                 int i;
13325                 for(i = 0; i < MAX_CHANNELS; i++)
13326                         redraw_controllers(i);
13327     }
13328     rc = RC_NONE;
13329         
13330 ///r
13331 #if 0
13332         if(midi_streaming == 0 && add_silent_time){
13333                 sample_count += add_silent_count;
13334                 compute_data(add_silent_count);
13335         }
13336 #endif
13337     for(;;)
13338     {
13339                 midi_restart_time = 1;
13340                 rc = play_event(current_event);
13341                 if(rc != RC_NONE)
13342                         break;
13343                 if (midi_restart_time)    /* don't skip the first event if == 0 */
13344                         current_event++;
13345     }
13346 #ifdef USE_TRACE_TIMER
13347     if(ctl->trace_playing)
13348                 stop_trace_timer();
13349 #endif
13350
13351     if(play_count++ > 3)
13352     {
13353                 int cnt;
13354                 play_count = 0;
13355                 cnt = free_global_mblock();     /* free unused memory */
13356                 if(cnt > 0)
13357                         ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
13358                                   "%d memory blocks are free", cnt);
13359     }
13360     return rc;
13361 }
13362
13363 static void read_header_wav(struct timidity_file* tf)
13364 {
13365     char buff[44];
13366     tf_read( buff, 1, 44, tf);
13367 }
13368
13369 static int read_header_aiff(struct timidity_file* tf)
13370 {
13371     char buff[5]="    ";
13372     int i;
13373     
13374     for( i=0; i<100; i++ ){
13375         buff[0]=buff[1]; buff[1]=buff[2]; buff[2]=buff[3];
13376         tf_read( &buff[3], 1, 1, tf);
13377         if( strcmp(buff,"SSND")==0 ){
13378             /*SSND chunk found */
13379             tf_read( &buff[0], 1, 4, tf);
13380             tf_read( &buff[0], 1, 4, tf);
13381             ctl->cmsg(CMSG_INFO, VERB_NOISY,
13382                       "aiff header read OK.");
13383             return 0;
13384         }
13385     }
13386     /*SSND chunk not found */
13387     return -1;
13388 }
13389
13390 static int load_pcm_file_wav()
13391 {
13392     char *filename;
13393
13394     if(strcmp(pcm_alternate_file, "auto") == 0)
13395     {
13396         filename = safe_malloc(strlen(current_file_info->filename)+5);
13397         strcpy(filename, current_file_info->filename);
13398         strcat(filename, ".wav");
13399     }
13400     else if(strlen(pcm_alternate_file) >= 5 &&
13401             strncasecmp(pcm_alternate_file + strlen(pcm_alternate_file) - 4,
13402                         ".wav", 4) == 0)
13403         filename = safe_strdup(pcm_alternate_file);
13404     else
13405         return -1;
13406
13407     ctl->cmsg(CMSG_INFO, VERB_NOISY,
13408                       "wav filename: %s", filename);
13409     current_file_info->pcm_tf = open_file(filename, 0, OF_SILENT);
13410     if( current_file_info->pcm_tf ){
13411         ctl->cmsg(CMSG_INFO, VERB_NOISY,
13412                       "open successed.");
13413         read_header_wav(current_file_info->pcm_tf);
13414         current_file_info->pcm_filename = filename;
13415         current_file_info->pcm_mode = PCM_MODE_WAV;
13416         return 0;
13417     }else{
13418         ctl->cmsg(CMSG_INFO, VERB_NOISY,
13419                       "open failed.");
13420         safe_free(filename);
13421         current_file_info->pcm_filename = NULL;
13422         return -1;
13423     }
13424 }
13425
13426 static int load_pcm_file_aiff()
13427 {
13428     char *filename;
13429
13430     if(strcmp(pcm_alternate_file, "auto") == 0)
13431     {
13432         filename = safe_malloc(strlen(current_file_info->filename)+6);
13433         strcpy(filename, current_file_info->filename);
13434         strcat( filename, ".aiff");
13435     }
13436     else if(strlen(pcm_alternate_file) >= 6 &&
13437             strncasecmp(pcm_alternate_file + strlen(pcm_alternate_file) - 5,
13438                         ".aiff", 5) == 0)
13439         filename = safe_strdup(pcm_alternate_file);
13440     else
13441         return -1;
13442
13443     ctl->cmsg(CMSG_INFO, VERB_NOISY,
13444                       "aiff filename: %s", filename);
13445     current_file_info->pcm_tf = open_file(filename, 0, OF_SILENT);
13446     if( current_file_info->pcm_tf ){
13447         ctl->cmsg(CMSG_INFO, VERB_NOISY,
13448                       "open successed.");
13449         read_header_aiff(current_file_info->pcm_tf);
13450         current_file_info->pcm_filename = filename;
13451         current_file_info->pcm_mode = PCM_MODE_AIFF;
13452         return 0;
13453     }else{
13454         ctl->cmsg(CMSG_INFO, VERB_NOISY,
13455                       "open failed.");
13456         safe_free(filename);
13457         current_file_info->pcm_filename = NULL;
13458         return -1;
13459     }
13460 }
13461
13462 static void load_pcm_file()
13463 {
13464     if( load_pcm_file_wav()==0 ) return; /*load OK*/
13465     if( load_pcm_file_aiff()==0 ) return; /*load OK*/
13466 }
13467
13468 static int play_midi_load_file(char *fn,
13469                                MidiEvent **event,
13470                                int32 *nsamples)
13471 {
13472     int rc;
13473     struct timidity_file *tf;
13474     int32 nevents;
13475
13476     *event = NULL;
13477
13478     if(!strcmp(fn, "-"))
13479         file_from_stdin = 1;
13480     else
13481         file_from_stdin = 0;
13482
13483     ctl_mode_event(CTLE_NOW_LOADING, 0, (ptr_size_t)fn, 0);
13484     ctl->cmsg(CMSG_INFO, VERB_NORMAL, "MIDI file: %s", fn);
13485     if((tf = open_midi_file(fn, 1, OF_VERBOSE)) == NULL)
13486     {
13487         ctl_mode_event(CTLE_LOADING_DONE, 0, -1, 0);
13488         return RC_ERROR;
13489     }
13490
13491     *event = NULL;
13492     rc = check_apply_control();
13493     if(RC_IS_SKIP_FILE(rc))
13494     {
13495         close_file(tf);
13496         ctl_mode_event(CTLE_LOADING_DONE, 0, 1, 0);
13497         return rc;
13498     }
13499
13500     *event = read_midi_file(tf, &nevents, nsamples, fn);
13501     close_file(tf);
13502
13503     if(*event == NULL)
13504     {
13505         ctl_mode_event(CTLE_LOADING_DONE, 0, -1, 0);
13506         return RC_ERROR;
13507     }
13508
13509     ctl->cmsg(CMSG_INFO, VERB_NOISY,
13510               "%d supported events, %d samples, time %d:%02d",
13511               nevents, *nsamples,
13512               *nsamples / play_mode->rate / 60,
13513               (*nsamples / play_mode->rate) % 60);
13514
13515     current_file_info->pcm_mode = PCM_MODE_NON; /*initialize*/
13516     if(pcm_alternate_file != NULL &&
13517        strcmp(pcm_alternate_file, "none") != 0 &&
13518        (play_mode->flag&PF_PCM_STREAM))
13519         load_pcm_file();
13520
13521     if(!IS_CURRENT_MOD_FILE &&
13522        (play_mode->flag&PF_PCM_STREAM))
13523     {
13524         /* FIXME: Instruments is not need for pcm_alternate_file. */
13525     }
13526     else
13527         clear_magic_instruments();      /* Clear load markers */
13528
13529     ctl_mode_event(CTLE_LOADING_DONE, 0, 0, 0);
13530
13531     return RC_NONE;
13532 }
13533
13534 int play_midi_file(char *fn)
13535 {
13536     int i, j, rc;
13537     static int last_rc = RC_NONE;
13538     MidiEvent *event = NULL;
13539     int32 nsamples;
13540
13541     /* Set current file information */
13542     current_file_info = get_midi_file_info(fn, 1);
13543
13544     rc = check_apply_control();
13545     if(RC_IS_SKIP_FILE(rc) && rc != RC_RELOAD)
13546         return rc;
13547
13548     /* Reset key & speed each files */
13549     current_keysig = (opt_init_keysig == 8) ? 0 : opt_init_keysig;
13550     note_key_offset = key_adjust;
13551     midi_time_ratio = tempo_adjust;
13552         for (i = 0; i < MAX_CHANNELS; i++) {
13553                 for (j = 0; j < 12; j++)
13554                         channel[i].scale_tuning[j] = 0;
13555                 channel[i].prev_scale_tuning = 0;
13556                 channel[i].temper_type = 0;
13557         }
13558     CLEAR_CHANNELMASK(channel_mute);
13559         if (temper_type_mute & 1)
13560                 FILL_CHANNELMASK(channel_mute);
13561
13562     /* Reset restart offset */
13563     midi_restart_time = 0;
13564
13565 #ifdef REDUCE_VOICE_TIME_TUNING
13566     /* Reset voice reduction stuff */
13567     min_bad_nv = 256;
13568     max_good_nv = 1;
13569     ok_nv_total = 32;
13570     ok_nv_counts = 1;
13571     ok_nv = 32;
13572     ok_nv_sample = 0;
13573     old_rate = -1;
13574 ///r
13575 //    reduce_quality_flag = no_4point_interpolation;
13576     reduce_quality_flag = 0;
13577         reduce_voice_flag = 0;
13578         reduce_polyphony_flag = 0;
13579
13580     restore_voices(0);
13581 #endif
13582
13583         ctl_mode_event(CTLE_METRONOME, 0, 0, 0);
13584         ctl_mode_event(CTLE_KEYSIG, 0, current_keysig, 0);
13585         ctl_mode_event(CTLE_TEMPER_KEYSIG, 0, 0, 0);
13586         ctl_mode_event(CTLE_KEY_OFFSET, 0, note_key_offset, 0);
13587         i = current_keysig + ((current_keysig < 8) ? 7 : -9), j = 0;
13588         while (i != 7)
13589                 i += (i < 7) ? 5 : -7, j++;
13590         j += note_key_offset, j -= floor(j * DIV_12) * 12;
13591         current_freq_table = j;
13592         ctl_mode_event(CTLE_TEMPO, 0, current_play_tempo, 0);
13593         ctl_mode_event(CTLE_TIME_RATIO, 0, 100 / midi_time_ratio + 0.5, 0);
13594         for (i = 0; i < MAX_CHANNELS; i++) {
13595                 ctl_mode_event(CTLE_TEMPER_TYPE, 0, i, channel[i].temper_type);
13596                 ctl_mode_event(CTLE_MUTE, 0, i, temper_type_mute & 1);
13597         }
13598   play_reload: /* Come here to reload MIDI file */
13599     rc = play_midi_load_file(fn, &event, &nsamples);
13600     if(RC_IS_SKIP_FILE(rc))
13601         goto play_end; /* skip playing */
13602
13603     init_mblock(&playmidi_pool);
13604     ctl_mode_event(CTLE_PLAY_START, 0, nsamples, 0);
13605     play_mode->acntl(PM_REQ_PLAY_START, NULL);
13606     rc = play_midi(event, nsamples);
13607     play_mode->acntl(PM_REQ_PLAY_END, NULL);
13608     ctl_mode_event(CTLE_PLAY_END, 0, 0, 0);
13609     reuse_mblock(&playmidi_pool);
13610
13611     for(i = 0; i < MAX_CHANNELS; i++)
13612         memset(channel[i].drums, 0, sizeof(channel[i].drums));
13613
13614   play_end:
13615     if(current_file_info->pcm_tf){
13616         close_file(current_file_info->pcm_tf);
13617         current_file_info->pcm_tf = NULL;
13618         safe_free( current_file_info->pcm_filename );
13619         current_file_info->pcm_filename = NULL;
13620     }
13621     
13622     if(wrdt->opened)
13623         wrdt->end();
13624
13625     if(free_instruments_afterwards)
13626     {
13627         int cnt;
13628         free_instruments(0);
13629         cnt = free_global_mblock(); /* free unused memory */
13630         if(cnt > 0)
13631             ctl->cmsg(CMSG_INFO, VERB_VERBOSE, "%d memory blocks are free",
13632                       cnt);
13633     }
13634
13635     free_special_patch(-1);
13636
13637     safe_free(event);
13638     if(rc == RC_RELOAD)
13639         goto play_reload;
13640
13641     if(rc == RC_ERROR)
13642     {
13643         if(current_file_info->file_type == IS_OTHER_FILE)
13644             current_file_info->file_type = IS_ERROR_FILE;
13645         if(last_rc == RC_REALLY_PREVIOUS)
13646             return RC_REALLY_PREVIOUS;
13647     }
13648     last_rc = rc;
13649     return rc;
13650 }
13651
13652 int dumb_pass_playing_list(int number_of_files, char *list_of_files[])
13653 {
13654     #ifndef CFG_FOR_SF
13655     int i = 0;
13656
13657     for(;;)
13658     {
13659         switch(play_midi_file(list_of_files[i]))
13660         {
13661           case RC_REALLY_PREVIOUS:
13662             if(i > 0)
13663                 i--;
13664             break;
13665
13666           default: /* An error or something */
13667           case RC_NEXT:
13668             if(i < number_of_files-1)
13669             {
13670                 i++;
13671                 break;
13672             }
13673             aq_flush(0);
13674
13675             if(!(ctl->flags & CTLF_LIST_LOOP))
13676                 return 0;
13677             i = 0;
13678             break;
13679
13680             case RC_QUIT:
13681                 return 0;
13682         }
13683     }
13684     #endif
13685 }
13686
13687 void default_ctl_lyric(int lyricid)
13688 {
13689     char *lyric;
13690
13691     lyric = event2string(lyricid);
13692     if(lyric != NULL)
13693         ctl->cmsg(CMSG_TEXT, VERB_VERBOSE, "%s", lyric + 1);
13694 }
13695
13696 void ctl_mode_event(int type, int trace, ptr_size_t arg1, ptr_size_t arg2)
13697 {
13698     CtlEvent ce;
13699     ce.type = type;
13700     ce.v1 = arg1;
13701     ce.v2 = arg2;
13702     if(trace && ctl->trace_playing)
13703         push_midi_trace_ce(ctl->event, &ce);
13704     else
13705         ctl->event(&ce);
13706 }
13707
13708 static void ctl_note_event(int noteID)
13709 {
13710     CtlEvent ce;
13711
13712     ce.type = CTLE_NOTE;
13713     ce.v1 = voice[noteID].status;
13714     ce.v2 = voice[noteID].channel;
13715     ce.v3 = voice[noteID].note;
13716     ce.v4 = voice[noteID].velocity;
13717     if(ctl->trace_playing)
13718         push_midi_trace_ce(ctl->event, &ce);
13719     else
13720         ctl->event(&ce);
13721 }
13722 ///r
13723 static void ctl_note_event2(uint8 channel, uint8 note, uint8 status, uint8 velocity)
13724 {
13725     CtlEvent ce;
13726
13727     ce.type = CTLE_NOTE;
13728     ce.v1 = status;
13729     ce.v2 = channel;
13730     ce.v3 = note;
13731     ce.v4 = velocity;
13732     if(ctl->trace_playing)
13733         push_midi_trace_ce(ctl->event, &ce);
13734     else
13735         ctl->event(&ce);
13736 }
13737
13738 static void ctl_timestamp(void)
13739 {
13740     long i, secs, voices;
13741     CtlEvent ce;
13742     static int last_secs = -1, last_voices = -1;
13743
13744     secs = (long)(current_sample / (midi_time_ratio * play_mode->rate));
13745     for(i = voices = 0; i < upper_voices; i++)
13746         if(voice[i].status != VOICE_FREE)
13747             voices++;
13748     if(secs == last_secs && voices == last_voices)
13749         return;
13750     ce.type = CTLE_CURRENT_TIME;
13751     ce.v1 = last_secs = secs;
13752     ce.v2 = last_voices = voices;
13753     if(ctl->trace_playing)
13754         push_midi_trace_ce(ctl->event, &ce);
13755     else
13756         ctl->event(&ce);
13757 }
13758
13759 static void ctl_updatetime(int32 samples)
13760 {
13761     long secs;
13762     secs = (long)(samples / (midi_time_ratio * play_mode->rate));
13763     ctl_mode_event(CTLE_CURRENT_TIME, 0, secs, 0);
13764     ctl_mode_event(CTLE_REFRESH, 0, 0, 0);
13765 }
13766
13767 static void ctl_prog_event(int ch)
13768 {
13769     CtlEvent ce;
13770     int bank, prog;
13771
13772     if(IS_CURRENT_MOD_FILE)
13773     {
13774         bank = 0;
13775         prog = channel[ch].special_sample;
13776     }
13777     else
13778     {
13779         bank = channel[ch].bank;
13780         prog = channel[ch].program;
13781     }
13782
13783     ce.type = CTLE_PROGRAM;
13784     ce.v1 = ch;
13785     ce.v2 = prog;
13786     ce.v3 = (ptr_size_t)channel_instrum_name(ch);
13787     ce.v4 = (bank |
13788              (channel[ch].bank_lsb << 8) |
13789              (channel[ch].bank_msb << 16));
13790     if(ctl->trace_playing)
13791         push_midi_trace_ce(ctl->event, &ce);
13792     else
13793         ctl->event(&ce);
13794 }
13795
13796 static void ctl_pause_event(int pause, int32 s)
13797 {
13798     long secs;
13799     secs = (long)(s / (midi_time_ratio * play_mode->rate));
13800     ctl_mode_event(CTLE_PAUSE, 0, pause, secs);
13801 }
13802 ///r
13803 char *channel_instrum_name(int ch)
13804 {
13805     char *comm;
13806     int bank, prog;
13807         int elm = 0;
13808
13809     if(ISDRUMCHANNEL(ch)) {
13810                 bank = channel[ch].bank;
13811                 prog = 0;
13812                 instrument_map_no_mapped(channel[ch].mapID, &bank, &prog);
13813                 if (drumset[bank] == NULL) return " ----";
13814                 if(drumset[bank]->tone[prog][elm] == NULL) return " ----";
13815                 comm = drumset[bank]->tone[prog][elm]->comment;
13816                 if (comm == NULL) return " ----";
13817                 return comm;
13818     }
13819
13820     if(channel[ch].program == SPECIAL_PROGRAM)
13821         return "Special Program";
13822
13823     if(IS_CURRENT_MOD_FILE)
13824     {
13825         int pr;
13826         pr = channel[ch].special_sample;
13827         if(pr > 0 &&
13828            special_patch[pr] != NULL &&
13829            special_patch[pr]->name != NULL)
13830             return special_patch[pr]->name;
13831         return "MOD";
13832     }
13833
13834     bank = channel[ch].bank;
13835     prog = channel[ch].program;
13836     instrument_map(channel[ch].mapID, &bank, &prog);
13837
13838         if (tonebank[bank] == NULL) {alloc_instrument_bank(0, bank);}
13839         if (tonebank[bank]->tone[prog][elm]){
13840                 if (tonebank[bank]->tone[prog][elm]->name) {
13841                         comm = tonebank[bank]->tone[prog][elm]->comment;
13842                 //      if (comm == NULL) {comm = tonebank[bank]->tone[prog][elm]->name;}
13843                         if (comm == NULL) {comm = " ----";}
13844                         return comm;
13845                 }
13846         }
13847         if (tonebank[0]->tone[prog][elm]){
13848             comm = tonebank[0]->tone[prog][elm]->comment;
13849         //      if (comm == NULL) {comm = tonebank[0]->tone[prog][elm]->name;}
13850                 if (comm == NULL) {comm = " ----";}
13851         }else{
13852                 comm = " ----";
13853         }       
13854     return comm;
13855 }
13856
13857
13858 /*
13859  * For MIDI stream player.
13860  */
13861 void playmidi_stream_init(void)
13862 {
13863     int i;
13864     static int first = 1;
13865
13866     note_key_offset = key_adjust;
13867     midi_time_ratio = tempo_adjust;
13868     CLEAR_CHANNELMASK(channel_mute);
13869         if (temper_type_mute & 1)
13870                 FILL_CHANNELMASK(channel_mute);
13871     midi_restart_time = 0;
13872     if(first)
13873     {
13874         first = 0;
13875         init_mblock(&playmidi_pool);
13876         current_file_info = get_midi_file_info("TiMidity", 1);
13877     midi_streaming=1;
13878     }
13879     else
13880         reuse_mblock(&playmidi_pool);
13881
13882     /* Fill in current_file_info */
13883     current_file_info->readflag = 1;
13884     safe_free(current_file_info->seq_name);
13885     current_file_info->seq_name = safe_strdup("TiMidity server");
13886     safe_free(current_file_info->karaoke_title);
13887     safe_free(current_file_info->first_text);
13888     current_file_info->karaoke_title = current_file_info->first_text = NULL;
13889     current_file_info->mid = 0x7f;
13890     current_file_info->hdrsiz = 0;
13891     current_file_info->format = 0;
13892     current_file_info->tracks = 0;
13893     current_file_info->divisions = 192; /* ?? */
13894     current_file_info->time_sig_n = 4; /* 4/ */
13895     current_file_info->time_sig_d = 4; /* /4 */
13896     current_file_info->time_sig_c = 24; /* clock */
13897     current_file_info->time_sig_b = 8;  /* q.n. */
13898     current_file_info->samples = 0;
13899     current_file_info->max_channel = MAX_CHANNELS;
13900     current_file_info->compressed = 0;
13901     current_file_info->midi_data = NULL;
13902     current_file_info->midi_data_size = 0;
13903     current_file_info->file_type = IS_OTHER_FILE;
13904
13905     current_play_tempo = 500000;
13906     check_eot_flag = 0;
13907
13908     /* Setup default drums */
13909         COPY_CHANNELMASK(current_file_info->drumchannels, default_drumchannels);
13910         COPY_CHANNELMASK(current_file_info->drumchannel_mask, default_drumchannel_mask);
13911     for(i = 0; i < MAX_CHANNELS; i++)
13912         memset(channel[i].drums, 0, sizeof(channel[i].drums));
13913     change_system_mode(DEFAULT_SYSTEM_MODE);
13914     reset_midi(0);
13915
13916     playmidi_tmr_reset();
13917 }
13918
13919 void playmidi_tmr_reset(void)
13920 {
13921     int i;
13922
13923     aq_flush(0);
13924     if(ctl->id_character != 'N')
13925         current_sample = 0;
13926     buffered_count = 0;
13927     buffer_pointer = common_buffer;
13928     for(i = 0; i < MAX_CHANNELS; i++)
13929                 channel[i].lasttime = -M_32BIT;
13930 }
13931
13932
13933 void playmidi_stream_free(void)
13934 {
13935         reuse_mblock(&playmidi_pool);
13936 }
13937
13938
13939
13940 /*! initialize Part EQ (XG) */
13941 void init_part_eq_xg(struct part_eq_xg *p)
13942 {
13943         p->bass = 0x40;
13944         p->treble = 0x40;       
13945         p->mid_bass = 0x40;
13946         p->mid_treble = 0x40;
13947         p->bass_freq = 0x0C;
13948         p->treble_freq = 0x36;
13949         p->mid_bass_freq = 0x22;
13950         p->mid_treble_freq = 0x2E;      
13951         p->bass_q = 0x07;
13952         p->treble_q = 0x07;
13953         p->mid_bass_q = 0x07;
13954         p->mid_treble_q = 0x07;
13955         p->bass_shape= 0x0; // def shelving
13956         p->treble_shape = 0x0; // def shelving
13957         p->valid = 0;   
13958         recompute_part_eq_xg(p);
13959 }
13960
13961 static FLOAT_T clip_part_eq_gain(int in)
13962 {
13963         if(in < 0)
13964                 in = 0;
13965         else if(in > 127)
13966                 in = 127;
13967         in -= 0x40;
13968         return (FLOAT_T)in * DIV_64 * 12.0; // -12.0~+12.0
13969 }
13970
13971 static FLOAT_T clip_part_eq_q(int in)
13972 {
13973         if(in < 1)
13974                 in = 1;
13975         else if(in > 120)
13976                 in = 120;       
13977         return (FLOAT_T)in * DIV_10; // 0.1 ~ 12.0
13978 }
13979
13980 /*! recompute Part EQ (XG) */
13981 void recompute_part_eq_xg(struct part_eq_xg *p)
13982 {
13983         FLOAT_T freq, gain, q;
13984         int8 shape, valid = 0;
13985
13986         if(p->bass != 0x40) {
13987                 ++valid;
13988                 if     (p->bass_freq < 0x04)        p->bass_freq = 0x04;
13989                 else if(p->bass_freq > 0x28)        p->bass_freq = 0x28;
13990                 freq = eq_freq_table_xg[p->bass_freq];
13991                 gain = clip_part_eq_gain(p->bass);
13992                 q = clip_part_eq_q(p->bass_q);
13993                 shape = p->bass_shape ? FILTER_PEAKING : FILTER_SHELVING_LOW;
13994                 init_sample_filter2(&(p->basss), freq, gain, q, shape);
13995         } else {
13996                 init_sample_filter2(&(p->basss), 0, 0, 0, FILTER_NONE);
13997         }
13998         if(p->treble != 0x40) {
13999                 ++valid;
14000                 if     (p->treble_freq < 0x1C)      p->treble_freq = 0x1C;
14001                 else if(p->treble_freq > 0x3A)      p->treble_freq = 0x3A;
14002                 freq = eq_freq_table_xg[p->treble_freq];
14003                 gain = clip_part_eq_gain(p->treble);
14004                 q = clip_part_eq_q(p->treble_q);
14005                 shape = p->treble_shape ? FILTER_PEAKING : FILTER_SHELVING_HI;
14006                 init_sample_filter2(&(p->trebles), freq, gain, q, shape);
14007         } else {
14008                 init_sample_filter2(&(p->trebles), 0, 0, 0, FILTER_NONE);
14009         }
14010         if(p->mid_bass != 0x40) {
14011                 ++valid;
14012                 if     (p->mid_bass_freq < 0x0E)    p->mid_bass_freq = 0x0E;
14013                 else if(p->mid_bass_freq > 0x36)    p->mid_bass_freq = 0x36;
14014                 freq = eq_freq_table_xg[p->mid_bass_freq];
14015                 gain = clip_part_eq_gain(p->mid_bass);
14016                 q = clip_part_eq_q(p->mid_bass_q);
14017                 init_sample_filter2(&(p->mid_basss), freq, gain, q, FILTER_PEAKING);
14018         } else {
14019                 init_sample_filter2(&(p->mid_basss), 0, 0, 0, FILTER_NONE);
14020         }
14021         if(p->mid_treble != 0x40) {
14022                 ++valid;
14023                 if     (p->mid_treble_freq < 0x0E)  p->mid_treble_freq = 0x0E;
14024                 else if(p->mid_treble_freq > 0x36)  p->mid_treble_freq = 0x36;
14025                 freq = eq_freq_table_xg[p->mid_treble_freq];
14026                 gain = clip_part_eq_gain(p->mid_treble);
14027                 q = clip_part_eq_q(p->mid_treble_q);
14028                 init_sample_filter2(&(p->mid_trebles), freq, gain, q, FILTER_PEAKING);
14029         } else {
14030                 init_sample_filter2(&(p->mid_trebles), 0, 0, 0, FILTER_NONE);
14031         }
14032         p->valid = valid ? 1 : 0;
14033 }
14034
14035 static void init_midi_controller(midi_controller *p)
14036 {
14037         p->mode = 0;
14038         p->num = -1;
14039         p->val = 0;
14040         p->pitch = 0;
14041         p->cutoff = 0;
14042         p->amp = 0.0;
14043         p->lfo1_rate = p->lfo2_rate = 0;
14044         p->lfo1_pitch_depth = p->lfo2_pitch_depth = 0;
14045         p->lfo1_tvf_depth = p->lfo2_tvf_depth = 0;
14046         p->lfo1_tva_depth = p->lfo2_tva_depth = 0;
14047 }
14048
14049 static inline float get_midi_controller_amp(midi_controller *p)
14050 {
14051         return (float)p->val * DIV_127 * p->amp; // -1.0 ~ +1.0
14052 }
14053
14054 static inline float get_midi_controller_filter_cutoff(midi_controller *p)
14055 {
14056         return ((float)p->val * DIV_127 * (float)p->cutoff);
14057 }
14058
14059 static inline int32 get_midi_controller_pitch(midi_controller *p)
14060 {
14061         return ((int32)(p->val * p->pitch) << 6);
14062 }
14063
14064 static inline float get_midi_controller_lfo1_pitch_depth(midi_controller *p)
14065 {
14066 //      return (int16)((float)p->val * (float)p->lfo1_pitch_depth * (1.0f * DIV_127 * 256.0 / 400.0));
14067         return (float)p->val * DIV_127 * (float)p->lfo1_pitch_depth; // return cent
14068 }
14069
14070 static inline float get_midi_controller_lfo1_amp_depth(midi_controller *p)
14071 {
14072         return (float)p->val * DIV_127 * (float)p->lfo1_tva_depth; // * (1.0f);
14073 }
14074
14075 static inline float get_midi_controller_lfo1_filter_depth(midi_controller *p)
14076 {
14077         return ((float)p->val * DIV_127 * (float)p->lfo1_tvf_depth);
14078 }
14079
14080 static inline float get_midi_controller_lfo2_pitch_depth(midi_controller *p)
14081 {
14082 //      return (int16)((float)p->val * (float)p->lfo2_pitch_depth * (1.0f * DIV_127 * 256.0 / 400.0));
14083         return (float)p->val * DIV_127 * (float)p->lfo2_pitch_depth; // return cent
14084 }
14085
14086 static inline float get_midi_controller_lfo2_amp_depth(midi_controller *p)
14087 {
14088         return (float)p->val * DIV_127 * (float)p->lfo2_tva_depth; // * (1.0f);
14089 }
14090
14091 static inline float get_midi_controller_lfo2_filter_depth(midi_controller *p)
14092 {
14093         return (float)p->val * DIV_127 * (float)p->lfo2_tvf_depth;
14094 }
14095
14096
14097 static void init_rx(int ch)
14098 {
14099         channel[ch].rx = 0xFFFFFFFF;    /* all on */
14100 }
14101
14102 static void set_rx(int ch, int32 rx, int flag)
14103 {
14104         if(ch > MAX_CHANNELS) {return;}
14105         if(flag) {channel[ch].rx |= rx;}
14106         else {channel[ch].rx &= ~rx;}
14107 }
14108
14109 static int32 get_rx(int ch, int32 rx)
14110 {
14111         if(ch > MAX_CHANNELS) {return 0;}
14112         return (channel[ch].rx & rx);
14113 }
14114
14115 static void init_rx_drum(struct DrumParts *p)
14116 {
14117         p->rx = 0xFFFFFFFF;     /* all on */
14118 }
14119
14120 static void set_rx_drum(struct DrumParts *p, int32 rx, int flag)
14121 {
14122         if(flag) {p->rx |= rx;}
14123         else {p->rx &= ~rx;}
14124 }
14125
14126 static int32 get_rx_drum(struct DrumParts *p, int32 rx)
14127 {
14128         return (p->rx & rx);
14129 }
14130
14131 int32 get_current_play_tempo(void)
14132 {
14133         return current_play_tempo;      // 500000=120bpm
14134 }
14135
14136
14137
14138
14139 #ifdef MULTI_THREAD_COMPUTE
14140 #include "thread_playmidi.c"
14141 #endif
14142
14143
14144