1 /*
2     TiMidity -- Experimental MIDI to WAVE converter
3     Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
4 
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the Perl Artistic License, available in COPYING.
7  */
8 
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 
13 #include <SDL_rwops.h>
14 
15 #include "config.h"
16 #include "common.h"
17 #include "instrum.h"
18 #include "playmidi.h"
19 #include "readmidi.h"
20 #include "output.h"
21 #include "mix.h"
22 #include "ctrlmode.h"
23 #include "timidity.h"
24 
25 #include "tables.h"
26 
27 
28 static int opt_expression_curve = 2;
29 static int opt_volume_curve = 2;
30 static int opt_stereo_surround = 0;
31 
32 
33 Channel channel[MAXCHAN];
34 Voice voice[MAX_VOICES];
35 signed char drumvolume[MAXCHAN][MAXNOTE];
36 signed char drumpanpot[MAXCHAN][MAXNOTE];
37 signed char drumreverberation[MAXCHAN][MAXNOTE];
38 signed char drumchorusdepth[MAXCHAN][MAXNOTE];
39 
40 int
41     voices=DEFAULT_VOICES;
42 
43 int32
44     control_ratio=0,
45     amplification=DEFAULT_AMPLIFICATION;
46 
47 FLOAT_T
48     master_volume;
49 
50 int32 drumchannels=DEFAULT_DRUMCHANNELS;
51 int adjust_panning_immediately=0;
52 
53 struct _MidiSong {
54 	int32 samples;
55 	MidiEvent *events;
56 };
57 static int midi_playing = 0;
58 static int32 lost_notes, cut_notes;
59 static int32 *buffer_pointer;
60 static int32 buffered_count;
61 extern int32 *common_buffer;
62 extern resample_t *resample_buffer; /* to free it on Timidity_Close */
63 
64 static MidiEvent *event_list, *current_event;
65 static int32 sample_count, current_sample;
66 
67 int GM_System_On=0;
68 int XG_System_On=0;
69 int GS_System_On=0;
70 int XG_System_reverb_type;
71 int XG_System_chorus_type;
72 int XG_System_variation_type;
73 
74 
adjust_amplification(void)75 static void adjust_amplification(void)
76 {
77   master_volume = (FLOAT_T)(amplification) / (FLOAT_T)100.0;
78   master_volume /= 2;
79 }
80 
81 
adjust_master_volume(int32 vol)82 static void adjust_master_volume(int32 vol)
83 {
84   master_volume = (double)(vol*amplification) / 1638400.0L;
85   master_volume /= 2;
86 }
87 
88 
reset_voices(void)89 static void reset_voices(void)
90 {
91   int i;
92   for (i=0; i<MAX_VOICES; i++)
93     voice[i].status=VOICE_FREE;
94 }
95 
96 /* Process the Reset All Controllers event */
reset_controllers(int c)97 static void reset_controllers(int c)
98 {
99   channel[c].volume=90; /* Some standard says, although the SCC docs say 0. */
100   channel[c].expression=127; /* SCC-1 does this. */
101   channel[c].sustain=0;
102   channel[c].pitchbend=0x2000;
103   channel[c].pitchfactor=0; /* to be computed */
104 
105   channel[c].reverberation = 0;
106   channel[c].chorusdepth = 0;
107 }
108 
redraw_controllers(int c)109 static void redraw_controllers(int c)
110 {
111   ctl->volume(c, channel[c].volume);
112   ctl->expression(c, channel[c].expression);
113   ctl->sustain(c, channel[c].sustain);
114   ctl->pitch_bend(c, channel[c].pitchbend);
115 }
116 
reset_midi(void)117 static void reset_midi(void)
118 {
119   int i;
120   for (i=0; i<MAXCHAN; i++)
121     {
122       reset_controllers(i);
123       /* The rest of these are unaffected by the Reset All Controllers event */
124       channel[i].program=default_program;
125       channel[i].panning=NO_PANNING;
126       channel[i].pitchsens=2;
127       channel[i].bank=0; /* tone bank or drum set */
128       channel[i].harmoniccontent=64,
129       channel[i].releasetime=64,
130       channel[i].attacktime=64,
131       channel[i].brightness=64,
132       channel[i].sfx=0;
133     }
134   reset_voices();
135 }
136 
select_sample(int v,Instrument * ip)137 static void select_sample(int v, Instrument *ip)
138 {
139   int32 f, cdiff, diff, midfreq;
140   int s,i;
141   Sample *sp, *closest;
142 
143   s=ip->samples;
144   sp=ip->sample;
145 
146   if (s==1)
147     {
148       voice[v].sample=sp;
149       return;
150     }
151 
152   f=voice[v].orig_frequency;
153   /*
154      No suitable sample found! We'll select the sample whose root
155      frequency is closest to the one we want. (Actually we should
156      probably convert the low, high, and root frequencies to MIDI note
157      values and compare those.) */
158 
159   cdiff=0x7FFFFFFF;
160   closest=sp=ip->sample;
161   midfreq = (sp->low_freq + sp->high_freq) / 2;
162   for(i=0; i<s; i++)
163     {
164       diff=sp->root_freq - f;
165   /*  But the root freq. can perfectly well lie outside the keyrange
166    *  frequencies, so let's try:
167    */
168       /* diff=midfreq - f; */
169       if (diff<0) diff=-diff;
170       if (diff<cdiff)
171 	{
172 	  cdiff=diff;
173 	  closest=sp;
174 	}
175       sp++;
176     }
177   voice[v].sample=closest;
178   return;
179 }
180 
181 
182 
select_stereo_samples(int v,InstrumentLayer * lp)183 static void select_stereo_samples(int v, InstrumentLayer *lp)
184 {
185   Instrument *ip;
186   InstrumentLayer *nlp, *bestvel;
187   int diffvel, midvel, mindiff;
188 
189 /* select closest velocity */
190   bestvel = lp;
191   mindiff = 500;
192   for (nlp = lp; nlp; nlp = nlp->next) {
193 	midvel = (nlp->hi + nlp->lo)/2;
194 	if (!midvel) diffvel = 127;
195 	else if (voice[v].velocity < nlp->lo || voice[v].velocity > nlp->hi)
196 		diffvel = 200;
197 	else diffvel = voice[v].velocity - midvel;
198 	if (diffvel < 0) diffvel = -diffvel;
199 	if (diffvel < mindiff) {
200 		mindiff = diffvel;
201 		bestvel = nlp;
202 	}
203   }
204   ip = bestvel->instrument;
205 
206   if (ip->right_sample) {
207     ip->sample = ip->right_sample;
208     ip->samples = ip->right_samples;
209     select_sample(v, ip);
210     voice[v].right_sample = voice[v].sample;
211   }
212   else voice[v].right_sample = 0;
213   ip->sample = ip->left_sample;
214   ip->samples = ip->left_samples;
215   select_sample(v, ip);
216 }
217 
218 
recompute_freq(int v)219 static void recompute_freq(int v)
220 {
221   int
222     sign=(voice[v].sample_increment < 0), /* for bidirectional loops */
223     pb=channel[voice[v].channel].pitchbend;
224   double a;
225 
226   if (!voice[v].sample->sample_rate)
227     return;
228 
229   if (voice[v].vibrato_control_ratio)
230     {
231       /* This instrument has vibrato. Invalidate any precomputed
232          sample_increments. */
233 
234       int i=VIBRATO_SAMPLE_INCREMENTS;
235       while (i--)
236 	voice[v].vibrato_sample_increment[i]=0;
237     }
238 
239   if (pb==0x2000 || pb<0 || pb>0x3FFF)
240     voice[v].frequency=voice[v].orig_frequency;
241   else
242     {
243       pb-=0x2000;
244       if (!(channel[voice[v].channel].pitchfactor))
245 	{
246 	  /* Damn. Somebody bent the pitch. */
247 	  int32 i=pb*channel[voice[v].channel].pitchsens;
248 	  if (pb<0)
249 	    i=-i;
250 	  channel[voice[v].channel].pitchfactor=
251 	    (FLOAT_T)(bend_fine[(i>>5) & 0xFF] * bend_coarse[i>>13]);
252 	}
253       if (pb>0)
254 	voice[v].frequency=
255 	  (int32)(channel[voice[v].channel].pitchfactor *
256 		  (double)(voice[v].orig_frequency));
257       else
258 	voice[v].frequency=
259 	  (int32)((double)(voice[v].orig_frequency) /
260 		  channel[voice[v].channel].pitchfactor);
261     }
262 
263   a = FSCALE(((double)(voice[v].sample->sample_rate) *
264 	      (double)(voice[v].frequency)) /
265 	     ((double)(voice[v].sample->root_freq) *
266 	      (double)(play_mode->rate)),
267 	     FRACTION_BITS);
268 
269   if (sign)
270     a = -a; /* need to preserve the loop direction */
271 
272   voice[v].sample_increment = (int32)(a);
273 }
274 
275 static int expr_curve[128] = {
276 	7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 11,
277 	11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15,
278 	15, 16, 16, 17, 17, 17, 18, 18, 19, 19, 19, 20, 20, 21, 21, 22,
279 	22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 28, 28, 29, 30, 30, 31,
280 	32, 32, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, 42, 43, 44,
281 	45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 59, 60, 61, 63,
282 	64, 65, 67, 68, 70, 71, 73, 75, 76, 78, 80, 82, 83, 85, 87, 89,
283 	91, 93, 95, 97, 99, 102, 104, 106, 109, 111, 113, 116, 118, 121,
284 	124, 127
285 };
286 
panf(int pan,int speaker,int separation)287 static int panf(int pan, int speaker, int separation)
288 {
289 	int val;
290 	val = abs(pan - speaker);
291 	val = (val * 127) / separation;
292 	val = 127 - val;
293 	if (val < 0) val = 0;
294 	if (val > 127) val = 127;
295 	return expr_curve[val];
296 }
297 
298 
299 static int vcurve[128] = {
300 0,0,18,29,36,42,47,51,55,58,
301 60,63,65,67,69,71,73,74,76,77,
302 79,80,81,82,83,84,85,86,87,88,
303 89,90,91,92,92,93,94,95,95,96,
304 97,97,98,99,99,100,100,101,101,102,
305 103,103,104,104,105,105,106,106,106,107,
306 107,108,108,109,109,109,110,110,111,111,
307 111,112,112,112,113,113,114,114,114,115,
308 115,115,116,116,116,116,117,117,117,118,
309 118,118,119,119,119,119,120,120,120,120,
310 121,121,121,122,122,122,122,123,123,123,
311 123,123,124,124,124,124,125,125,125,125,
312 126,126,126,126,126,127,127,127
313 };
314 
recompute_amp(int v)315 static void recompute_amp(int v)
316 {
317   int32 tempamp;
318   int chan = voice[v].channel;
319   int panning = voice[v].panning;
320   int vol = channel[chan].volume;
321   int expr = channel[chan].expression;
322   int vel = vcurve[voice[v].velocity];
323   FLOAT_T curved_expression, curved_volume;
324 
325   if (channel[chan].kit)
326    {
327     int note = voice[v].sample->note_to_use;
328     if (note>0 && drumvolume[chan][note]>=0) vol = drumvolume[chan][note];
329     if (note>0 && drumpanpot[chan][note]>=0) panning = drumvolume[chan][note];
330    }
331 
332   if (opt_expression_curve == 2) curved_expression = 127.0 * vol_table[expr];
333   else if (opt_expression_curve == 1) curved_expression = 127.0 * expr_table[expr];
334   else curved_expression = (FLOAT_T)expr;
335 
336   if (opt_volume_curve == 2) curved_volume = 127.0 * vol_table[vol];
337   else if (opt_volume_curve == 1) curved_volume = 127.0 * expr_table[vol];
338   else curved_volume = (FLOAT_T)vol;
339 
340   tempamp= (int32)((FLOAT_T)vel * curved_volume * curved_expression); /* 21 bits */
341 
342   /* TODO: use fscale */
343 
344   if (num_ochannels > 1)
345     {
346       if (panning > 60 && panning < 68)
347 	{
348 	  voice[v].panned=PANNED_CENTER;
349 
350 	  if (num_ochannels == 6) voice[v].left_amp =
351 		FSCALENEG((double) (tempamp) * voice[v].sample->volume *
352 			    master_volume, 20);
353 	  else voice[v].left_amp=
354 	        FSCALENEG((double)(tempamp) * voice[v].sample->volume *
355 			    master_volume, 21);
356 	}
357       else if (panning<5)
358 	{
359 	  voice[v].panned = PANNED_LEFT;
360 
361 	  voice[v].left_amp=
362 	    FSCALENEG((double)(tempamp) * voice[v].sample->volume * master_volume,
363 		      20);
364 	}
365       else if (panning>123)
366 	{
367 	  voice[v].panned = PANNED_RIGHT;
368 
369 	  voice[v].left_amp= /* left_amp will be used */
370 	    FSCALENEG((double)(tempamp) * voice[v].sample->volume * master_volume,
371 		      20);
372 	}
373       else
374 	{
375 	  FLOAT_T refv = (double)(tempamp) * voice[v].sample->volume * master_volume;
376 	  int wide_panning = 64;
377 
378 	  if (num_ochannels == 4) wide_panning = 95;
379 
380 	  voice[v].panned = PANNED_MYSTERY;
381 	  voice[v].lfe_amp = FSCALENEG(refv * 64, 27);
382 
383 		switch (num_ochannels)
384 		{
385 		    case 2:
386 		      voice[v].lr_amp = 0;
387 		      voice[v].left_amp = FSCALENEG(refv * (128-panning), 27);
388 		      voice[v].ce_amp = 0;
389 		      voice[v].right_amp = FSCALENEG(refv * panning, 27);
390 		      voice[v].rr_amp = 0;
391 		      break;
392 		    case 4:
393 		      voice[v].lr_amp = FSCALENEG(refv * panf(panning, 0, wide_panning), 27);
394 		      voice[v].left_amp = FSCALENEG(refv * panf(panning, 32, wide_panning), 27);
395 		      voice[v].ce_amp = 0;
396 		      voice[v].right_amp = FSCALENEG(refv * panf(panning, 95, wide_panning), 27);
397 		      voice[v].rr_amp = FSCALENEG(refv * panf(panning, 128, wide_panning), 27);
398 		      break;
399 		    case 6:
400 		      voice[v].lr_amp = FSCALENEG(refv * panf(panning, 0, wide_panning), 27);
401 		      voice[v].left_amp = FSCALENEG(refv * panf(panning, 32, wide_panning), 27);
402 		      voice[v].ce_amp = FSCALENEG(refv * panf(panning, 64, wide_panning), 27);
403 		      voice[v].right_amp = FSCALENEG(refv * panf(panning, 95, wide_panning), 27);
404 		      voice[v].rr_amp = FSCALENEG(refv * panf(panning, 128, wide_panning), 27);
405 		      break;
406 		}
407 
408 	}
409     }
410   else
411     {
412       voice[v].panned=PANNED_CENTER;
413 
414       voice[v].left_amp=
415 	FSCALENEG((double)(tempamp) * voice[v].sample->volume * master_volume,
416 		  21);
417     }
418 }
419 
420 
421 #define NOT_CLONE 0
422 #define STEREO_CLONE 1
423 #define REVERB_CLONE 2
424 #define CHORUS_CLONE 3
425 
426 
427 /* just a variant of note_on() */
vc_alloc(int j)428 static int vc_alloc(int j)
429 {
430   int i=voices;
431 
432   while (i--)
433     {
434       if (i == j) continue;
435       if (voice[i].status & VOICE_FREE) {
436 	return i;
437       }
438     }
439   return -1;
440 }
441 
442 static void kill_note(int i);
443 
kill_others(int i)444 static void kill_others(int i)
445 {
446   int j=voices;
447 
448   if (!voice[i].sample->exclusiveClass) return;
449 
450   while (j--)
451     {
452       if (voice[j].status & (VOICE_FREE|VOICE_OFF|VOICE_DIE)) continue;
453       if (i == j) continue;
454       if (voice[i].channel != voice[j].channel) continue;
455       if (voice[j].sample->note_to_use)
456       {
457     	if (voice[j].sample->exclusiveClass != voice[i].sample->exclusiveClass) continue;
458         kill_note(j);
459       }
460     }
461 }
462 
463 
clone_voice(Instrument * ip,int v,MidiEvent * e,int clone_type,int variationbank)464 static void clone_voice(Instrument *ip, int v, MidiEvent *e, int clone_type, int variationbank)
465 {
466   int w, played_note, chorus=0, reverb=0, milli;
467   int chan = voice[v].channel;
468 
469   if (clone_type == STEREO_CLONE) {
470 	if (!voice[v].right_sample && variationbank != 3) return;
471 	if (variationbank == 6) return;
472   }
473 
474   if (channel[chan].kit) {
475 	reverb = drumreverberation[chan][voice[v].note];
476 	chorus = drumchorusdepth[chan][voice[v].note];
477   }
478   else {
479 	reverb = channel[chan].reverberation;
480 	chorus = channel[chan].chorusdepth;
481   }
482 
483   if (clone_type == REVERB_CLONE) chorus = 0;
484   else if (clone_type == CHORUS_CLONE) reverb = 0;
485   else if (clone_type == STEREO_CLONE) reverb = chorus = 0;
486 
487   if (reverb > 127) reverb = 127;
488   if (chorus > 127) chorus = 127;
489 
490   if (clone_type == CHORUS_CLONE) {
491 	 if (variationbank == 32) chorus = 30;
492 	 else if (variationbank == 33) chorus = 60;
493 	 else if (variationbank == 34) chorus = 90;
494   }
495 
496   chorus /= 2;  /* This is an ad hoc adjustment. */
497 
498   if (!reverb && !chorus && clone_type != STEREO_CLONE) return;
499 
500   if ( (w = vc_alloc(v)) < 0 ) return;
501 
502   voice[w] = voice[v];
503   if (clone_type==STEREO_CLONE) voice[v].clone_voice = w;
504   voice[w].clone_voice = v;
505   voice[w].clone_type = clone_type;
506 
507   voice[w].sample = voice[v].right_sample;
508   voice[w].velocity= e->b;
509 
510   milli = play_mode->rate/1000;
511 
512   if (clone_type == STEREO_CLONE) {
513     int left, right, leftpan, rightpan;
514     int panrequest = voice[v].panning;
515     if (variationbank == 3) {
516 	voice[v].panning = 0;
517 	voice[w].panning = 127;
518     }
519     else {
520 	if (voice[v].sample->panning > voice[w].sample->panning) {
521 	  left = w;
522 	  right = v;
523 	}
524 	else {
525 	  left = v;
526 	  right = w;
527 	}
528 #define INSTRUMENT_SEPARATION 12
529 	leftpan = panrequest - INSTRUMENT_SEPARATION / 2;
530 	rightpan = leftpan + INSTRUMENT_SEPARATION;
531 	if (leftpan < 0) {
532 		leftpan = 0;
533 		rightpan = leftpan + INSTRUMENT_SEPARATION;
534 	}
535 	if (rightpan > 127) {
536 		rightpan = 127;
537 		leftpan = rightpan - INSTRUMENT_SEPARATION;
538 	}
539 	voice[left].panning = leftpan;
540 	voice[right].panning = rightpan;
541 	voice[right].echo_delay = 20 * milli;
542     }
543   }
544 
545   voice[w].volume = voice[w].sample->volume;
546 
547   if (reverb) {
548 	if (opt_stereo_surround) {
549 		if (voice[w].panning > 64) voice[w].panning = 127;
550 		else voice[w].panning = 0;
551 	}
552 	else {
553 		if (voice[v].panning < 64) voice[w].panning = 64 + reverb/2;
554 		else voice[w].panning = 64 - reverb/2;
555 	}
556 
557 /* try 98->99 for melodic instruments ? (bit much for percussion) */
558 	voice[w].volume *= vol_table[(127-reverb)/8 + 98];
559 
560 	voice[w].echo_delay += reverb * milli;
561 	voice[w].envelope_rate[DECAY] *= 2;
562 	voice[w].envelope_rate[RELEASE] /= 2;
563 
564 	if (XG_System_reverb_type >= 0) {
565 	    int subtype = XG_System_reverb_type & 0x07;
566 	    int rtype = XG_System_reverb_type >>3;
567 	    switch (rtype) {
568 		case 0: /* no effect */
569 		  break;
570 		case 1: /* hall */
571 		  if (subtype) voice[w].echo_delay += 100 * milli;
572 		  break;
573 		case 2: /* room */
574 		  voice[w].echo_delay /= 2;
575 		  break;
576 		case 3: /* stage */
577 		  voice[w].velocity = voice[v].velocity;
578 		  break;
579 		case 4: /* plate */
580 		  voice[w].panning = voice[v].panning;
581 		  break;
582 		case 16: /* white room */
583 		  voice[w].echo_delay = 0;
584 		  break;
585 		case 17: /* tunnel */
586 		  voice[w].echo_delay *= 2;
587 		  voice[w].velocity /= 2;
588 		  break;
589 		case 18: /* canyon */
590 		  voice[w].echo_delay *= 2;
591 		  break;
592 		case 19: /* basement */
593 		  voice[w].velocity /= 2;
594 		  break;
595 	        default: break;
596 	    }
597 	}
598   }
599   played_note = voice[w].sample->note_to_use;
600   if (!played_note) {
601 	played_note = e->a & 0x7f;
602 	if (variationbank == 35) played_note += 12;
603 	else if (variationbank == 36) played_note -= 12;
604 	else if (variationbank == 37) played_note += 7;
605 	else if (variationbank == 36) played_note -= 7;
606   }
607 #if 0
608   played_note = ( (played_note - voice[w].sample->freq_center) * voice[w].sample->freq_scale ) / 1024 +
609 		voice[w].sample->freq_center;
610 #endif
611   voice[w].note = played_note;
612   voice[w].orig_frequency = freq_table[played_note];
613 
614   if (chorus) {
615 	if (opt_stereo_surround) {
616 	  if (voice[v].panning < 64) voice[w].panning = voice[v].panning + 32;
617 	  else voice[w].panning = voice[v].panning - 32;
618 	}
619 
620 	if (!voice[w].vibrato_control_ratio) {
621 		voice[w].vibrato_control_ratio = 100;
622 		voice[w].vibrato_depth = 6;
623 		voice[w].vibrato_sweep = 74;
624 	}
625 	voice[w].volume *= 0.40;
626 	voice[v].volume = voice[w].volume;
627 	recompute_amp(v);
628         apply_envelope_to_amp(v);
629 	voice[w].vibrato_sweep = chorus/2;
630 	voice[w].vibrato_depth /= 2;
631 	if (!voice[w].vibrato_depth) voice[w].vibrato_depth = 2;
632 	voice[w].vibrato_control_ratio /= 2;
633 	voice[w].echo_delay += 30 * milli;
634 
635 	if (XG_System_chorus_type >= 0) {
636 	    int subtype = XG_System_chorus_type & 0x07;
637 	    int chtype = 0x0f & (XG_System_chorus_type >> 3);
638 	    switch (chtype) {
639 		case 0: /* no effect */
640 		  break;
641 		case 1: /* chorus */
642 		  chorus /= 3;
643 		  if(channel[ voice[w].channel ].pitchbend + chorus < 0x2000)
644             		voice[w].orig_frequency =
645 				(uint32)( (FLOAT_T)voice[w].orig_frequency * bend_fine[chorus] );
646         	  else voice[w].orig_frequency =
647 			(uint32)( (FLOAT_T)voice[w].orig_frequency / bend_fine[chorus] );
648 		  if (subtype) voice[w].vibrato_depth *= 2;
649 		  break;
650 		case 2: /* celeste */
651 		  voice[w].orig_frequency += (voice[w].orig_frequency/128) * chorus;
652 		  break;
653 		case 3: /* flanger */
654 		  voice[w].vibrato_control_ratio = 10;
655 		  voice[w].vibrato_depth = 100;
656 		  voice[w].vibrato_sweep = 8;
657 		  voice[w].echo_delay += 200 * milli;
658 		  break;
659 		case 4: /* symphonic : cf Children of the Night /128 bad, /1024 ok */
660 		  voice[w].orig_frequency += (voice[w].orig_frequency/512) * chorus;
661 		  voice[v].orig_frequency -= (voice[v].orig_frequency/512) * chorus;
662 		  recompute_freq(v);
663 		  break;
664 		case 8: /* phaser */
665 		  break;
666 	      default:
667 		  break;
668 	    }
669 	}
670 	else {
671 	    chorus /= 3;
672 	    if(channel[ voice[w].channel ].pitchbend + chorus < 0x2000)
673           	voice[w].orig_frequency =
674 			(uint32)( (FLOAT_T)voice[w].orig_frequency * bend_fine[chorus] );
675             else voice[w].orig_frequency =
676 		(uint32)( (FLOAT_T)voice[w].orig_frequency / bend_fine[chorus] );
677 	}
678   }
679 #if 0
680   voice[w].loop_start = voice[w].sample->loop_start;
681   voice[w].loop_end = voice[w].sample->loop_end;
682 #endif
683   voice[w].echo_delay_count = voice[w].echo_delay;
684   if (reverb) voice[w].echo_delay *= 2;
685 
686   recompute_freq(w);
687   recompute_amp(w);
688   if (voice[w].sample->modes & MODES_ENVELOPE)
689     {
690       /* Ramp up from 0 */
691       voice[w].envelope_stage=ATTACK;
692       voice[w].modulation_stage=ATTACK;
693       voice[w].envelope_volume=0;
694       voice[w].modulation_volume=0;
695       voice[w].control_counter=0;
696       voice[w].modulation_counter=0;
697       recompute_envelope(w);
698       /*recompute_modulation(w);*/
699     }
700   else
701     {
702       voice[w].envelope_increment=0;
703       voice[w].modulation_increment=0;
704     }
705   apply_envelope_to_amp(w);
706 }
707 
708 
xremap(int * banknumpt,int * this_notept,int this_kit)709 static void xremap(int *banknumpt, int *this_notept, int this_kit) {
710 	int i, newmap;
711 	int banknum = *banknumpt;
712 	int this_note = *this_notept;
713 	int newbank, newnote;
714 
715 	if (!this_kit) {
716 		if (banknum == SFXBANK && tonebank[SFXBANK]) return;
717 		if (banknum == SFXBANK && tonebank[120]) *banknumpt = 120;
718 		return;
719 	}
720 
721 	if (this_kit != 127 && this_kit != 126) return;
722 
723 	for (i = 0; i < XMAPMAX; i++) {
724 		newmap = xmap[i][0];
725 		if (!newmap) return;
726 		if (this_kit == 127 && newmap != XGDRUM) continue;
727 		if (this_kit == 126 && newmap != SFXDRUM1) continue;
728 		if (xmap[i][1] != banknum) continue;
729 		if (xmap[i][3] != this_note) continue;
730 		newbank = xmap[i][2];
731 		newnote = xmap[i][4];
732 		if (newbank == banknum && newnote == this_note) return;
733 		if (!drumset[newbank]) return;
734 		if (!drumset[newbank]->tone[newnote].layer) return;
735 		if (drumset[newbank]->tone[newnote].layer == MAGIC_LOAD_INSTRUMENT) return;
736 		*banknumpt = newbank;
737 		*this_notept = newnote;
738 		return;
739 	}
740 }
741 
742 
start_note(MidiEvent * e,int i)743 static void start_note(MidiEvent *e, int i)
744 {
745   InstrumentLayer *lp;
746   Instrument *ip;
747   int j, banknum, ch=e->channel;
748   int played_note, drumpan=NO_PANNING;
749   int32 rt;
750   int attacktime, releasetime, decaytime, variationbank;
751   int brightness = channel[ch].brightness;
752   int harmoniccontent = channel[ch].harmoniccontent;
753   int this_note = e->a;
754   int this_velocity = e->b;
755   int drumsflag = channel[ch].kit;
756   int this_prog = channel[ch].program;
757 
758   if (channel[ch].sfx) banknum=channel[ch].sfx;
759   else banknum=channel[ch].bank;
760 
761   voice[i].velocity=this_velocity;
762 
763   if (XG_System_On) xremap(&banknum, &this_note, drumsflag);
764   /*   if (current_config_pc42b) pcmap(&banknum, &this_note, &this_prog, &drumsflag); */
765 
766   if (drumsflag)
767     {
768       if (!(lp=drumset[banknum]->tone[this_note].layer))
769 	{
770 	  if (!(lp=drumset[0]->tone[this_note].layer))
771 	    return; /* No instrument? Then we can't play. */
772 	}
773       ip = lp->instrument;
774       if (ip->type == INST_GUS && ip->samples != 1)
775 	{
776 	  ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
777 	       "Strange: percussion instrument with %d samples!", ip->samples);
778 	}
779 
780       if (ip->sample->note_to_use) /* Do we have a fixed pitch? */
781 	{
782 	  voice[i].orig_frequency=freq_table[(int)(ip->sample->note_to_use)];
783 	  drumpan=drumpanpot[ch][(int)ip->sample->note_to_use];
784 	}
785       else
786 	voice[i].orig_frequency=freq_table[this_note & 0x7F];
787 
788     }
789   else
790     {
791       if (channel[ch].program==SPECIAL_PROGRAM)
792 	lp=default_instrument;
793       else if (!(lp=tonebank[channel[ch].bank]->
794 		 tone[channel[ch].program].layer))
795 	{
796 	  if (!(lp=tonebank[0]->tone[this_prog].layer))
797 	    return; /* No instrument? Then we can't play. */
798 	}
799       ip = lp->instrument;
800       if (ip->sample->note_to_use) /* Fixed-pitch instrument? */
801 	voice[i].orig_frequency=freq_table[(int)(ip->sample->note_to_use)];
802       else
803 	voice[i].orig_frequency=freq_table[this_note & 0x7F];
804     }
805 
806     select_stereo_samples(i, lp);
807 
808   voice[i].starttime = e->time;
809   played_note = voice[i].sample->note_to_use;
810 
811   if (!played_note || !drumsflag) played_note = this_note & 0x7f;
812 #if 0
813   played_note = ( (played_note - voice[i].sample->freq_center) * voice[i].sample->freq_scale ) / 1024 +
814 		voice[i].sample->freq_center;
815 #endif
816   voice[i].status=VOICE_ON;
817   voice[i].channel=ch;
818   voice[i].note=played_note;
819   voice[i].velocity=this_velocity;
820   voice[i].sample_offset=0;
821   voice[i].sample_increment=0; /* make sure it isn't negative */
822 
823   voice[i].tremolo_phase=0;
824   voice[i].tremolo_phase_increment=voice[i].sample->tremolo_phase_increment;
825   voice[i].tremolo_sweep=voice[i].sample->tremolo_sweep_increment;
826   voice[i].tremolo_sweep_position=0;
827 
828   voice[i].vibrato_sweep=voice[i].sample->vibrato_sweep_increment;
829   voice[i].vibrato_sweep_position=0;
830   voice[i].vibrato_depth=voice[i].sample->vibrato_depth;
831   voice[i].vibrato_control_ratio=voice[i].sample->vibrato_control_ratio;
832   voice[i].vibrato_control_counter=voice[i].vibrato_phase=0;
833   voice[i].vibrato_delay = voice[i].sample->vibrato_delay;
834 
835   kill_others(i);
836 
837   for (j=0; j<VIBRATO_SAMPLE_INCREMENTS; j++)
838     voice[i].vibrato_sample_increment[j]=0;
839 
840 
841   attacktime = channel[ch].attacktime;
842   releasetime = channel[ch].releasetime;
843   decaytime = 64;
844   variationbank = channel[ch].variationbank;
845 
846   switch (variationbank) {
847 	case  8:
848 		attacktime = 64+32;
849 		break;
850 	case 12:
851 		decaytime = 64-32;
852 		break;
853 	case 16:
854 		brightness = 64+16;
855 		break;
856 	case 17:
857 		brightness = 64+32;
858 		break;
859 	case 18:
860 		brightness = 64-16;
861 		break;
862 	case 19:
863 		brightness = 64-32;
864 		break;
865 	case 20:
866 		harmoniccontent = 64+16;
867 		break;
868 #if 0
869 	case 24:
870 		voice[i].modEnvToFilterFc=2.0;
871       		voice[i].sample->cutoff_freq = 800;
872 		break;
873 	case 25:
874 		voice[i].modEnvToFilterFc=-2.0;
875       		voice[i].sample->cutoff_freq = 800;
876 		break;
877 	case 27:
878 		voice[i].modLfoToFilterFc=2.0;
879 		voice[i].lfo_phase_increment=109;
880 		voice[i].lfo_sweep=122;
881       		voice[i].sample->cutoff_freq = 800;
882 		break;
883 	case 28:
884 		voice[i].modLfoToFilterFc=-2.0;
885 		voice[i].lfo_phase_increment=109;
886 		voice[i].lfo_sweep=122;
887       		voice[i].sample->cutoff_freq = 800;
888 		break;
889 #endif
890 	default:
891 		break;
892   }
893 
894 
895   for (j=ATTACK; j<MAXPOINT; j++)
896     {
897 	voice[i].envelope_rate[j]=voice[i].sample->envelope_rate[j];
898 	voice[i].envelope_offset[j]=voice[i].sample->envelope_offset[j];
899     }
900 
901   voice[i].echo_delay=voice[i].envelope_rate[DELAY];
902   voice[i].echo_delay_count = voice[i].echo_delay;
903 
904   if (attacktime!=64)
905     {
906 	rt = voice[i].envelope_rate[ATTACK];
907 	rt = rt + ( (64-attacktime)*rt ) / 100;
908 	if (rt > 1000) voice[i].envelope_rate[ATTACK] = rt;
909     }
910   if (releasetime!=64)
911     {
912 	rt = voice[i].envelope_rate[RELEASE];
913 	rt = rt + ( (64-releasetime)*rt ) / 100;
914 	if (rt > 1000) voice[i].envelope_rate[RELEASE] = rt;
915     }
916   if (decaytime!=64)
917     {
918 	rt = voice[i].envelope_rate[DECAY];
919 	rt = rt + ( (64-decaytime)*rt ) / 100;
920 	if (rt > 1000) voice[i].envelope_rate[DECAY] = rt;
921     }
922 
923   if (channel[ch].panning != NO_PANNING)
924     voice[i].panning=channel[ch].panning;
925   else
926     voice[i].panning=voice[i].sample->panning;
927   if (drumpan != NO_PANNING)
928     voice[i].panning=drumpan;
929 
930   if (variationbank == 1) {
931     int pan = voice[i].panning;
932     int disturb = 0;
933     /* If they're close up (no reverb) and you are behind the pianist,
934      * high notes come from the right, so we'll spread piano etc. notes
935      * out horizontally according to their pitches.
936      */
937     if (this_prog < 21) {
938 	    int n = voice[i].velocity - 32;
939 	    if (n < 0) n = 0;
940 	    if (n > 64) n = 64;
941 	    pan = pan/2 + n;
942 	}
943     /* For other types of instruments, the music sounds more alive if
944      * notes come from slightly different directions.  However, instruments
945      * do drift around in a sometimes disconcerting way, so the following
946      * might not be such a good idea.
947      */
948     else disturb = (voice[i].velocity/32 % 8) +
949 	(voice[i].note % 8); /* /16? */
950 
951     if (pan < 64) pan += disturb;
952     else pan -= disturb;
953     if (pan < 0) pan = 0;
954     else if (pan > 127) pan = 127;
955     voice[i].panning = pan;
956   }
957 
958   recompute_freq(i);
959   recompute_amp(i);
960   if (voice[i].sample->modes & MODES_ENVELOPE)
961     {
962       /* Ramp up from 0 */
963       voice[i].envelope_stage=ATTACK;
964       voice[i].envelope_volume=0;
965       voice[i].control_counter=0;
966       recompute_envelope(i);
967     }
968   else
969     {
970       voice[i].envelope_increment=0;
971     }
972   apply_envelope_to_amp(i);
973 
974   voice[i].clone_voice = -1;
975   voice[i].clone_type = NOT_CLONE;
976 
977   clone_voice(ip, i, e, STEREO_CLONE, variationbank);
978   clone_voice(ip, i, e, CHORUS_CLONE, variationbank);
979   clone_voice(ip, i, e, REVERB_CLONE, variationbank);
980 
981   ctl->note(i);
982 }
983 
kill_note(int i)984 static void kill_note(int i)
985 {
986   voice[i].status=VOICE_DIE;
987   if (voice[i].clone_voice >= 0)
988 	voice[ voice[i].clone_voice ].status=VOICE_DIE;
989   ctl->note(i);
990 }
991 
992 
993 /* Only one instance of a note can be playing on a single channel. */
note_on(MidiEvent * e)994 static void note_on(MidiEvent *e)
995 {
996   int i=voices, lowest=-1;
997   int32 lv=0x7FFFFFFF, v;
998 
999   while (i--)
1000     {
1001       if (voice[i].status == VOICE_FREE)
1002 	lowest=i; /* Can't get a lower volume than silence */
1003       else if (voice[i].channel==e->channel &&
1004 	       (voice[i].note==e->a || channel[voice[i].channel].mono))
1005 	kill_note(i);
1006     }
1007 
1008   if (lowest != -1)
1009     {
1010       /* Found a free voice. */
1011       start_note(e,lowest);
1012       return;
1013     }
1014 
1015 #if 0
1016   /* Look for the decaying note with the lowest volume */
1017   i=voices;
1018   while (i--)
1019     {
1020       if (voice[i].status & ~(VOICE_ON | VOICE_DIE | VOICE_FREE))
1021 	{
1022 	  v=voice[i].left_mix;
1023 	  if ((voice[i].panned==PANNED_MYSTERY) && (voice[i].right_mix>v))
1024 	    v=voice[i].right_mix;
1025 	  if (v<lv)
1026 	    {
1027 	      lv=v;
1028 	      lowest=i;
1029 	    }
1030 	}
1031     }
1032 #endif
1033 
1034   /* Look for the decaying note with the lowest volume */
1035   if (lowest==-1)
1036    {
1037    i=voices;
1038    while (i--)
1039     {
1040       if ( (voice[i].status & ~(VOICE_ON | VOICE_DIE | VOICE_FREE)) &&
1041 	  (!voice[i].clone_type))
1042 	{
1043 	  v=voice[i].left_mix;
1044 	  if ((voice[i].panned==PANNED_MYSTERY) && (voice[i].right_mix>v))
1045 	    v=voice[i].right_mix;
1046 	  if (v<lv)
1047 	    {
1048 	      lv=v;
1049 	      lowest=i;
1050 	    }
1051 	}
1052     }
1053    }
1054 
1055   if (lowest != -1)
1056     {
1057       int cl = voice[lowest].clone_voice;
1058 
1059       /* This can still cause a click, but if we had a free voice to
1060 	 spare for ramping down this note, we wouldn't need to kill it
1061 	 in the first place... Still, this needs to be fixed. Perhaps
1062 	 we could use a reserve of voices to play dying notes only. */
1063 
1064       if (cl >= 0) {
1065 	if (voice[cl].clone_type==STEREO_CLONE ||
1066 		       	(!voice[cl].clone_type && voice[lowest].clone_type==STEREO_CLONE))
1067 	   voice[cl].status=VOICE_FREE;
1068 	else if (voice[cl].clone_voice==lowest) voice[cl].clone_voice=-1;
1069       }
1070 
1071       cut_notes++;
1072       voice[lowest].status=VOICE_FREE;
1073       ctl->note(lowest);
1074       start_note(e,lowest);
1075     }
1076   else
1077     lost_notes++;
1078 }
1079 
finish_note(int i)1080 static void finish_note(int i)
1081 {
1082   if (voice[i].sample->modes & MODES_ENVELOPE)
1083     {
1084       /* We need to get the envelope out of Sustain stage */
1085       voice[i].envelope_stage=3;
1086       voice[i].status=VOICE_OFF;
1087       recompute_envelope(i);
1088       apply_envelope_to_amp(i);
1089       ctl->note(i);
1090     }
1091   else
1092     {
1093       /* Set status to OFF so resample_voice() will let this voice out
1094          of its loop, if any. In any case, this voice dies when it
1095          hits the end of its data (ofs>=data_length). */
1096       voice[i].status=VOICE_OFF;
1097     }
1098 
1099   { int v;
1100     if ( (v=voice[i].clone_voice) >= 0)
1101       {
1102 	voice[i].clone_voice = -1;
1103         finish_note(v);
1104       }
1105   }
1106 }
1107 
note_off(MidiEvent * e)1108 static void note_off(MidiEvent *e)
1109 {
1110   int i=voices, v;
1111   while (i--)
1112     if (voice[i].status==VOICE_ON &&
1113 	voice[i].channel==e->channel &&
1114 	voice[i].note==e->a)
1115       {
1116 	if (channel[e->channel].sustain)
1117 	  {
1118 	    voice[i].status=VOICE_SUSTAINED;
1119 
1120     	    if ( (v=voice[i].clone_voice) >= 0)
1121 	      {
1122 		if (voice[v].status == VOICE_ON)
1123 		  voice[v].status=VOICE_SUSTAINED;
1124 	      }
1125 
1126 	    ctl->note(i);
1127 	  }
1128 	else
1129 	  finish_note(i);
1130 	return;
1131       }
1132 }
1133 
1134 /* Process the All Notes Off event */
all_notes_off(int c)1135 static void all_notes_off(int c)
1136 {
1137   int i=voices;
1138   ctl->cmsg(CMSG_INFO, VERB_DEBUG, "All notes off on channel %d", c);
1139   while (i--)
1140     if (voice[i].status==VOICE_ON &&
1141 	voice[i].channel==c)
1142       {
1143 	if (channel[c].sustain)
1144 	  {
1145 	    voice[i].status=VOICE_SUSTAINED;
1146 	    ctl->note(i);
1147 	  }
1148 	else
1149 	  finish_note(i);
1150       }
1151 }
1152 
1153 /* Process the All Sounds Off event */
all_sounds_off(int c)1154 static void all_sounds_off(int c)
1155 {
1156   int i=voices;
1157   while (i--)
1158     if (voice[i].channel==c &&
1159 	voice[i].status != VOICE_FREE &&
1160 	voice[i].status != VOICE_DIE)
1161       {
1162 	kill_note(i);
1163       }
1164 }
1165 
adjust_pressure(MidiEvent * e)1166 static void adjust_pressure(MidiEvent *e)
1167 {
1168   int i=voices;
1169   while (i--)
1170     if (voice[i].status==VOICE_ON &&
1171 	voice[i].channel==e->channel &&
1172 	voice[i].note==e->a)
1173       {
1174 	voice[i].velocity=e->b;
1175 	recompute_amp(i);
1176 	apply_envelope_to_amp(i);
1177 	return;
1178       }
1179 }
1180 
adjust_panning(int c)1181 static void adjust_panning(int c)
1182 {
1183   int i=voices;
1184   while (i--)
1185     if ((voice[i].channel==c) &&
1186 	(voice[i].status==VOICE_ON || voice[i].status==VOICE_SUSTAINED))
1187       {
1188 	if (voice[i].clone_type != NOT_CLONE) continue;
1189 	voice[i].panning=channel[c].panning;
1190 	recompute_amp(i);
1191 	apply_envelope_to_amp(i);
1192       }
1193 }
1194 
drop_sustain(int c)1195 static void drop_sustain(int c)
1196 {
1197   int i=voices;
1198   while (i--)
1199     if (voice[i].status==VOICE_SUSTAINED && voice[i].channel==c)
1200       finish_note(i);
1201 }
1202 
adjust_pitchbend(int c)1203 static void adjust_pitchbend(int c)
1204 {
1205   int i=voices;
1206   while (i--)
1207     if (voice[i].status!=VOICE_FREE && voice[i].channel==c)
1208       {
1209 	recompute_freq(i);
1210       }
1211 }
1212 
adjust_volume(int c)1213 static void adjust_volume(int c)
1214 {
1215   int i=voices;
1216   while (i--)
1217     if (voice[i].channel==c &&
1218 	(voice[i].status==VOICE_ON || voice[i].status==VOICE_SUSTAINED))
1219       {
1220 	recompute_amp(i);
1221 	apply_envelope_to_amp(i);
1222       }
1223 }
1224 
seek_forward(int32 until_time)1225 static void seek_forward(int32 until_time)
1226 {
1227   reset_voices();
1228   while (current_event->time < until_time)
1229     {
1230       switch(current_event->type)
1231 	{
1232 	  /* All notes stay off. Just handle the parameter changes. */
1233 
1234 	case ME_PITCH_SENS:
1235 	  channel[current_event->channel].pitchsens=
1236 	    current_event->a;
1237 	  channel[current_event->channel].pitchfactor=0;
1238 	  break;
1239 
1240 	case ME_PITCHWHEEL:
1241 	  channel[current_event->channel].pitchbend=
1242 	    current_event->a + current_event->b * 128;
1243 	  channel[current_event->channel].pitchfactor=0;
1244 	  break;
1245 
1246 	case ME_MAINVOLUME:
1247 	  channel[current_event->channel].volume=current_event->a;
1248 	  break;
1249 
1250 	case ME_MASTERVOLUME:
1251 	  adjust_master_volume(current_event->a + (current_event->b <<7));
1252 	  break;
1253 
1254 	case ME_PAN:
1255 	  channel[current_event->channel].panning=current_event->a;
1256 	  break;
1257 
1258 	case ME_EXPRESSION:
1259 	  channel[current_event->channel].expression=current_event->a;
1260 	  break;
1261 
1262 	case ME_PROGRAM:
1263 	  /* if (ISDRUMCHANNEL(current_event->channel)) */
1264 	  if (channel[current_event->channel].kit)
1265 	    /* Change drum set */
1266 	    channel[current_event->channel].bank=current_event->a;
1267 	  else
1268 	    channel[current_event->channel].program=current_event->a;
1269 	  break;
1270 
1271 	case ME_SUSTAIN:
1272 	  channel[current_event->channel].sustain=current_event->a;
1273 	  break;
1274 
1275 
1276 	case ME_REVERBERATION:
1277 	  channel[current_event->channel].reverberation=current_event->a;
1278 	  break;
1279 
1280 	case ME_CHORUSDEPTH:
1281 	  channel[current_event->channel].chorusdepth=current_event->a;
1282 	  break;
1283 
1284 	case ME_HARMONICCONTENT:
1285 	  channel[current_event->channel].harmoniccontent=current_event->a;
1286 	  break;
1287 
1288 	case ME_RELEASETIME:
1289 	  channel[current_event->channel].releasetime=current_event->a;
1290 	  break;
1291 
1292 	case ME_ATTACKTIME:
1293 	  channel[current_event->channel].attacktime=current_event->a;
1294 	  break;
1295 
1296 	case ME_BRIGHTNESS:
1297 	  channel[current_event->channel].brightness=current_event->a;
1298 	  break;
1299 
1300 	case ME_TONE_KIT:
1301 	  if (current_event->a==SFX_BANKTYPE)
1302 		{
1303 		    channel[current_event->channel].sfx=SFXBANK;
1304 		    channel[current_event->channel].kit=0;
1305 		}
1306 	  else
1307 		{
1308 		    channel[current_event->channel].sfx=0;
1309 		    channel[current_event->channel].kit=current_event->a;
1310 		}
1311 	  break;
1312 
1313 
1314 	case ME_RESET_CONTROLLERS:
1315 	  reset_controllers(current_event->channel);
1316 	  break;
1317 
1318 	case ME_TONE_BANK:
1319 	  channel[current_event->channel].bank=current_event->a;
1320 	  break;
1321 
1322 	case ME_EOT:
1323 	  current_sample=current_event->time;
1324 	  return;
1325 	}
1326       current_event++;
1327     }
1328   /*current_sample=current_event->time;*/
1329   if (current_event != event_list)
1330     current_event--;
1331   current_sample=until_time;
1332 }
1333 
skip_to(int32 until_time)1334 static void skip_to(int32 until_time)
1335 {
1336   if (current_sample > until_time)
1337     current_sample=0;
1338 
1339   reset_midi();
1340   buffered_count=0;
1341   buffer_pointer=common_buffer;
1342   current_event=event_list;
1343 
1344   if (until_time)
1345     seek_forward(until_time);
1346   ctl->reset();
1347 }
1348 
apply_controls(void)1349 static int apply_controls(void)
1350 {
1351   int rc, i, did_skip=0;
1352   int32 val;
1353   /* ASCII renditions of CD player pictograms indicate approximate effect */
1354   do
1355     switch(rc=ctl->read(&val))
1356       {
1357       case RC_QUIT: /* [] */
1358       case RC_LOAD_FILE:
1359       case RC_NEXT: /* >>| */
1360       case RC_REALLY_PREVIOUS: /* |<< */
1361 	return rc;
1362 
1363       case RC_CHANGE_VOLUME:
1364 	if (val>0 || amplification > -val)
1365 	  amplification += val;
1366 	else
1367 	  amplification=0;
1368 	if (amplification > MAX_AMPLIFICATION)
1369 	  amplification=MAX_AMPLIFICATION;
1370 	adjust_amplification();
1371 	for (i=0; i<voices; i++)
1372 	  if (voice[i].status != VOICE_FREE)
1373 	    {
1374 	      recompute_amp(i);
1375 	      apply_envelope_to_amp(i);
1376 	    }
1377 	ctl->master_volume(amplification);
1378 	break;
1379 
1380       case RC_PREVIOUS: /* |<< */
1381 	if (current_sample < 2*play_mode->rate)
1382 	  return RC_REALLY_PREVIOUS;
1383 	return RC_RESTART;
1384 
1385       case RC_RESTART: /* |<< */
1386 	skip_to(0);
1387 	did_skip=1;
1388 	break;
1389 
1390       case RC_JUMP:
1391 	if (val >= sample_count)
1392 	  return RC_NEXT;
1393 	skip_to(val);
1394 	return rc;
1395 
1396       case RC_FORWARD: /* >> */
1397 	if (val+current_sample >= sample_count)
1398 	  return RC_NEXT;
1399 	skip_to(val+current_sample);
1400 	did_skip=1;
1401 	break;
1402 
1403       case RC_BACK: /* << */
1404 	if (current_sample > val)
1405 	  skip_to(current_sample-val);
1406 	else
1407 	  skip_to(0); /* We can't seek to end of previous song. */
1408 	did_skip=1;
1409 	break;
1410       }
1411   while (rc!= RC_NONE);
1412 
1413   /* Advertise the skip so that we stop computing the audio buffer */
1414   if (did_skip)
1415     return RC_JUMP;
1416   else
1417     return rc;
1418 }
1419 
do_compute_data(uint32 count)1420 static void do_compute_data(uint32 count)
1421 {
1422   int i;
1423   if (!count) return; /* (gl) */
1424   memset(buffer_pointer, 0, count * num_ochannels * 4);
1425   for (i=0; i<voices; i++)
1426     {
1427       if(voice[i].status != VOICE_FREE)
1428 	{
1429 	  if (!voice[i].sample_offset && voice[i].echo_delay_count)
1430 	    {
1431 		if ((uint32)voice[i].echo_delay_count >= count) voice[i].echo_delay_count -= count;
1432 		else
1433 		  {
1434 	            mix_voice(buffer_pointer+voice[i].echo_delay_count, i, count-voice[i].echo_delay_count);
1435 		    voice[i].echo_delay_count = 0;
1436 		  }
1437 	    }
1438 	  else mix_voice(buffer_pointer, i, count);
1439 	}
1440     }
1441   current_sample += count;
1442 }
1443 
1444 
1445 /* count=0 means flush remaining buffered data to output device, then
1446    flush the device itself */
compute_data(void * stream,int32 count)1447 static int compute_data(void *stream, int32 count)
1448 {
1449   int rc, channels;
1450 
1451   if ( play_mode->encoding & PE_MONO )
1452     channels = 1;
1453   else
1454     channels = num_ochannels;
1455 
1456   if (!count)
1457     {
1458       if (buffered_count)
1459           s32tobuf(stream, common_buffer, channels*buffered_count);
1460       buffer_pointer=common_buffer;
1461       buffered_count=0;
1462       return RC_NONE;
1463     }
1464 
1465   while ((count+buffered_count) >= AUDIO_BUFFER_SIZE)
1466     {
1467       do_compute_data(AUDIO_BUFFER_SIZE-buffered_count);
1468       count -= AUDIO_BUFFER_SIZE-buffered_count;
1469       s32tobuf(stream, common_buffer, channels*AUDIO_BUFFER_SIZE);
1470       buffer_pointer=common_buffer;
1471       buffered_count=0;
1472 
1473       ctl->current_time(current_sample);
1474       if ((rc=apply_controls())!=RC_NONE)
1475 	return rc;
1476     }
1477   if (count>0)
1478     {
1479       do_compute_data(count);
1480       buffered_count += count;
1481       buffer_pointer += count * channels;
1482     }
1483   return RC_NONE;
1484 }
1485 
Timidity_PlaySome(void * stream,int samples)1486 int Timidity_PlaySome(void *stream, int samples)
1487 {
1488   int rc = RC_NONE;
1489   int32 end_sample;
1490 
1491   if ( ! midi_playing ) {
1492     return RC_NONE;
1493   }
1494   end_sample = current_sample+samples;
1495   while ( current_sample < end_sample ) {
1496     /* Handle all events that should happen at this time */
1497     while (current_event->time <= current_sample) {
1498       switch(current_event->type) {
1499 
1500         /* Effects affecting a single note */
1501 
1502         case ME_NOTEON:
1503 	  current_event->a += channel[current_event->channel].transpose;
1504           if (!(current_event->b)) /* Velocity 0? */
1505             note_off(current_event);
1506           else
1507             note_on(current_event);
1508           break;
1509 
1510         case ME_NOTEOFF:
1511 	  current_event->a += channel[current_event->channel].transpose;
1512           note_off(current_event);
1513           break;
1514 
1515         case ME_KEYPRESSURE:
1516           adjust_pressure(current_event);
1517           break;
1518 
1519           /* Effects affecting a single channel */
1520 
1521         case ME_PITCH_SENS:
1522           channel[current_event->channel].pitchsens=current_event->a;
1523           channel[current_event->channel].pitchfactor=0;
1524           break;
1525 
1526         case ME_PITCHWHEEL:
1527           channel[current_event->channel].pitchbend=
1528             current_event->a + current_event->b * 128;
1529           channel[current_event->channel].pitchfactor=0;
1530           /* Adjust pitch for notes already playing */
1531           adjust_pitchbend(current_event->channel);
1532           ctl->pitch_bend(current_event->channel,
1533               channel[current_event->channel].pitchbend);
1534           break;
1535 
1536         case ME_MAINVOLUME:
1537           channel[current_event->channel].volume=current_event->a;
1538           adjust_volume(current_event->channel);
1539           ctl->volume(current_event->channel, current_event->a);
1540           break;
1541 
1542 	case ME_MASTERVOLUME:
1543 	  adjust_master_volume(current_event->a + (current_event->b <<7));
1544 	  break;
1545 
1546 	case ME_REVERBERATION:
1547 	  channel[current_event->channel].reverberation=current_event->a;
1548 	  break;
1549 
1550 	case ME_CHORUSDEPTH:
1551 	  channel[current_event->channel].chorusdepth=current_event->a;
1552 	  break;
1553 
1554         case ME_PAN:
1555           channel[current_event->channel].panning=current_event->a;
1556           if (adjust_panning_immediately)
1557             adjust_panning(current_event->channel);
1558           ctl->panning(current_event->channel, current_event->a);
1559           break;
1560 
1561         case ME_EXPRESSION:
1562           channel[current_event->channel].expression=current_event->a;
1563           adjust_volume(current_event->channel);
1564           ctl->expression(current_event->channel, current_event->a);
1565           break;
1566 
1567         case ME_PROGRAM:
1568           /* if (ISDRUMCHANNEL(current_event->channel)) { */
1569 	  if (channel[current_event->channel].kit) {
1570             /* Change drum set */
1571             channel[current_event->channel].bank=current_event->a;
1572           }
1573           else
1574           {
1575             channel[current_event->channel].program=current_event->a;
1576           }
1577           ctl->program(current_event->channel, current_event->a);
1578           break;
1579 
1580         case ME_SUSTAIN:
1581           channel[current_event->channel].sustain=current_event->a;
1582           if (!current_event->a)
1583             drop_sustain(current_event->channel);
1584           ctl->sustain(current_event->channel, current_event->a);
1585           break;
1586 
1587         case ME_RESET_CONTROLLERS:
1588           reset_controllers(current_event->channel);
1589           redraw_controllers(current_event->channel);
1590           break;
1591 
1592         case ME_ALL_NOTES_OFF:
1593           all_notes_off(current_event->channel);
1594           break;
1595 
1596         case ME_ALL_SOUNDS_OFF:
1597           all_sounds_off(current_event->channel);
1598           break;
1599 
1600 	case ME_HARMONICCONTENT:
1601 	  channel[current_event->channel].harmoniccontent=current_event->a;
1602 	  break;
1603 
1604 	case ME_RELEASETIME:
1605 	  channel[current_event->channel].releasetime=current_event->a;
1606 	  break;
1607 
1608 	case ME_ATTACKTIME:
1609 	  channel[current_event->channel].attacktime=current_event->a;
1610 	  break;
1611 
1612 	case ME_BRIGHTNESS:
1613 	  channel[current_event->channel].brightness=current_event->a;
1614 	  break;
1615 
1616         case ME_TONE_BANK:
1617           channel[current_event->channel].bank=current_event->a;
1618           break;
1619 
1620 
1621 	case ME_TONE_KIT:
1622 	  if (current_event->a==SFX_BANKTYPE)
1623 	  {
1624 	    channel[current_event->channel].sfx=SFXBANK;
1625 	    channel[current_event->channel].kit=0;
1626 	  }
1627 	  else
1628 	  {
1629 	    channel[current_event->channel].sfx=0;
1630 	    channel[current_event->channel].kit=current_event->a;
1631 	  }
1632 	  break;
1633 
1634         case ME_EOT:
1635           /* Give the last notes a couple of seconds to decay  */
1636           ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
1637             "Playing time: ~%d seconds", current_sample/play_mode->rate+2);
1638           ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
1639             "Notes cut: %d", cut_notes);
1640           ctl->cmsg(CMSG_INFO, VERB_VERBOSE,
1641           "Notes lost totally: %d", lost_notes);
1642           midi_playing = 0;
1643           return RC_TUNE_END;
1644         }
1645       current_event++;
1646     }
1647     if (current_event->time > end_sample)
1648       rc=compute_data(stream, end_sample-current_sample);
1649     else
1650       rc=compute_data(stream, current_event->time-current_sample);
1651     ctl->refresh();
1652     if ( (rc!=RC_NONE) && (rc!=RC_JUMP))
1653       break;
1654   }
1655   return rc;
1656 }
1657 
1658 
Timidity_SetVolume(int volume)1659 void Timidity_SetVolume(int volume)
1660 {
1661   int i;
1662   if (volume > MAX_AMPLIFICATION)
1663     amplification=MAX_AMPLIFICATION;
1664   else
1665   if (volume < 0)
1666     amplification=0;
1667   else
1668     amplification=volume;
1669   adjust_amplification();
1670   for (i=0; i<voices; i++)
1671     if (voice[i].status != VOICE_FREE)
1672       {
1673         recompute_amp(i);
1674         apply_envelope_to_amp(i);
1675       }
1676   ctl->master_volume(amplification);
1677 }
1678 
Timidity_LoadSong_RW(SDL_RWops * rw,int freerw)1679 MidiSong *Timidity_LoadSong_RW(SDL_RWops *rw, int freerw)
1680 {
1681   MidiSong *song;
1682   int32 events;
1683 
1684   /* Allocate memory for the song */
1685   song = (MidiSong *)safe_malloc(sizeof(*song));
1686   memset(song, 0, sizeof(*song));
1687 
1688   strcpy(midi_name, "SDLrwops source");
1689 
1690   song->events = read_midi_file(rw, &events, &song->samples);
1691   if (freerw) {
1692     SDL_RWclose(rw);
1693   }
1694 
1695   /* Make sure everything is okay */
1696   if (!song->events) {
1697     free(song);
1698     song = NULL;
1699   }
1700   return(song);
1701 }
1702 
Timidity_Start(MidiSong * song)1703 void Timidity_Start(MidiSong *song)
1704 {
1705   load_missing_instruments();
1706   adjust_amplification();
1707   sample_count = song->samples;
1708   event_list = song->events;
1709   lost_notes=cut_notes=0;
1710 
1711   skip_to(0);
1712   midi_playing = 1;
1713 }
1714 
Timidity_Active(void)1715 int Timidity_Active(void)
1716 {
1717 	return(midi_playing);
1718 }
1719 
Timidity_Stop(void)1720 void Timidity_Stop(void)
1721 {
1722   midi_playing = 0;
1723 }
1724 
Timidity_FreeSong(MidiSong * song)1725 void Timidity_FreeSong(MidiSong *song)
1726 {
1727   if (free_instruments_afterwards)
1728     free_instruments();
1729 
1730   free(song->events);
1731   free(song);
1732 }
1733 
Timidity_Close(void)1734 void Timidity_Close(void)
1735 {
1736   if (resample_buffer) {
1737     free(resample_buffer);
1738     resample_buffer=NULL;
1739   }
1740   if (common_buffer) {
1741     free(common_buffer);
1742     common_buffer=NULL;
1743   }
1744   free_instruments();
1745   free_pathlist();
1746 }
1747 
1748