Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / dev / sound / isa / i386 / sequencer.c
1 /*
2  * sound/sequencer.c
3  * 
4  * The sequencer personality manager.
5  * 
6  * Copyright by Hannu Savolainen 1993
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are
10  * met: 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer. 2.
12  * Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  * 
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  * 
28  * $FreeBSD: src/sys/i386/isa/sound/sequencer.c,v 1.25.2.1 2001/06/10 02:02:05 dd Exp $
29  * $DragonFly: src/sys/dev/sound/isa/i386/Attic/sequencer.c,v 1.2 2003/06/17 04:28:38 dillon Exp $
30  */
31
32 #define SEQUENCER_C
33 #include <i386/isa/sound/sound_config.h>
34
35 #if NSND > 0
36
37 #ifdef CONFIG_SEQUENCER
38
39 #include <sys/select.h>
40
41 #include <i386/isa/sound/midi_ctrl.h>
42
43 static void seq_drain_midi_queues(void);
44 int
45 sequencer_poll (int dev, struct fileinfo *file, int events, select_table * wait);
46 static int      sequencer_ok = 0;
47 static struct sound_timer_operations *tmr;
48 static int      tmr_no = -1;    /* Currently selected timer */
49 static int      pending_timer = -1;     /* For timer change operation */
50
51 /*
52  * Local counts for number of synth and MIDI devices. These are initialized
53  * by the sequencer_open.
54  */
55 static int      max_mididev = 0;
56 static int      max_synthdev = 0;
57
58 /*
59  * The seq_mode gives the operating mode of the sequencer: 1 = level1 (the
60  * default) 2 = level2 (extended capabilites)
61  */
62
63 #define SEQ_1   1
64 #define SEQ_2   2
65 static int      seq_mode = SEQ_1;
66
67 static int     *seq_sleeper = NULL;
68 static volatile struct snd_wait seq_sleep_flag = {0};
69 static int     *midi_sleeper = NULL;
70 static volatile struct snd_wait midi_sleep_flag = {0};
71
72 static int      midi_opened[MAX_MIDI_DEV] = {0};
73 static int      midi_written[MAX_MIDI_DEV] = {0};
74
75 static u_long   prev_input_time = 0;
76 static int      prev_event_time;
77 static u_long   seq_time = 0;
78
79 #include <i386/isa/sound/tuning.h>
80
81 #define EV_SZ   8
82 #define IEV_SZ  8
83 static u_char *queue = NULL;
84 static u_char *iqueue = NULL;
85
86 static volatile int qhead = 0, qtail = 0, qlen = 0;
87 static volatile int iqhead = 0, iqtail = 0, iqlen = 0;
88 static volatile int seq_playing = 0;
89 static volatile int sequencer_busy = 0;
90 static int      output_treshold;
91 static int      pre_event_timeout;
92 static u_int synth_open_mask;
93
94 static int      seq_queue(u_char *note, char nonblock);
95 static void     seq_startplay(void);
96 static int      seq_sync(void);
97 static void     seq_reset(void);
98 static int      pmgr_present[MAX_SYNTH_DEV] =
99 {0};
100 static struct callout_handle sequencertimeout_ch
101     = CALLOUT_HANDLE_INITIALIZER(&sequencertimeout_ch);
102
103 #if MAX_SYNTH_DEV > 15
104 #error Too many synthesizer devices enabled.
105 #endif
106
107 /*
108  * sound_timer stuff -- originally in soundcard.c
109  *
110  * A negative value means a relative timeout in |count| ticks.
111  * A positive value is used for what ?
112  *
113  * In any case, this is only used in sequencer.c
114  */
115
116 static int      timer_running = 0;
117
118 void
119 request_sound_timer(int count)
120 {
121     static int      current = 0;
122     int             tmp = count;
123
124     if (count < 0)
125         sequencertimeout_ch = timeout(sequencer_timer, 0, -count);
126     else {
127
128         if (count < current)
129             current = 0;        /* Timer restarted */
130
131         count = count - current;
132         current = tmp;
133         if (!count)
134             count = 1;
135         sequencertimeout_ch = timeout(sequencer_timer, 0, count);
136     }
137     timer_running = 1;
138 }
139
140 void
141 sound_stop_timer(void)
142 {
143     if (timer_running)
144         untimeout( sequencer_timer, 0, sequencertimeout_ch);
145     timer_running = 0;
146 }
147
148 int
149 sequencer_read(int dev, struct fileinfo * file, snd_rw_buf * buf, int count)
150 {
151     int             c = count, p = 0;
152     int             ev_len;
153     u_long   flags;
154
155     dev = dev >> 4;
156
157     ev_len = seq_mode == SEQ_1 ? 4 : 8;
158
159     if (dev)            /* Patch manager device */
160         return pmgr_read(dev - 1, file, buf, count);
161
162     flags = splhigh();
163     if (!iqlen) {
164         int             chn;
165
166
167         midi_sleeper = &chn;
168         DO_SLEEP(chn, midi_sleep_flag, pre_event_timeout); 
169
170         if (!iqlen) {
171             splx(flags);
172             return 0;
173         }
174     }
175     while (iqlen && c >= ev_len) {
176
177         if (uiomove((char *) &iqueue[iqhead * IEV_SZ], ev_len, buf))
178             printf("sb: Bad copyout()!\n");
179         p += ev_len;
180         c -= ev_len;
181
182         iqhead = (iqhead + 1) % SEQ_MAX_QUEUE;
183         iqlen--;
184     }
185     splx(flags);
186
187     return count - c;
188 }
189
190 static void
191 sequencer_midi_output(int dev)
192 {
193     /*
194      * Currently NOP
195      */
196 }
197
198 void
199 seq_copy_to_input(u_char *event, int len)
200 {
201     u_long   flags;
202
203     /*
204      * Verify that the len is valid for the current mode.
205      */
206
207     if (len != 4 && len != 8)
208         return;
209     if ((seq_mode == SEQ_1) != (len == 4))
210         return;
211
212     if (iqlen >= (SEQ_MAX_QUEUE - 1))
213         return;         /* Overflow */
214
215     flags = splhigh();
216     bcopy(event, &iqueue[iqtail * IEV_SZ], len);
217     iqlen++;
218     iqtail = (iqtail + 1) % SEQ_MAX_QUEUE;
219
220     if ((midi_sleep_flag.mode & WK_SLEEP)) {
221         midi_sleep_flag.mode = WK_WAKEUP;
222         wakeup(midi_sleeper);
223     }
224     splx(flags);
225 }
226
227 static void
228 sequencer_midi_input(int dev, u_char data)
229 {
230     u_int    tstamp;
231     u_char   event[4];
232
233     if (data == 0xfe)   /* Ignore active sensing */
234         return;
235
236     tstamp = get_time() - seq_time;
237     if (tstamp != prev_input_time) {
238         tstamp = (tstamp << 8) | SEQ_WAIT;
239
240         seq_copy_to_input((u_char *) &tstamp, 4);
241         prev_input_time = tstamp;
242     }
243     event[0] = SEQ_MIDIPUTC;
244     event[1] = data;
245     event[2] = dev;
246     event[3] = 0;
247
248     seq_copy_to_input(event, 4);
249 }
250
251 void
252 seq_input_event(u_char *event, int len)
253 {
254     u_long   this_time;
255
256     if (seq_mode == SEQ_2)
257         this_time = tmr->get_time(tmr_no);
258     else
259         this_time = get_time() - seq_time;
260
261     if (this_time != prev_input_time) {
262         u_char   tmp_event[8];
263
264         tmp_event[0] = EV_TIMING;
265         tmp_event[1] = TMR_WAIT_ABS;
266         tmp_event[2] = 0;
267         tmp_event[3] = 0;
268         *(u_long *) &tmp_event[4] = this_time;
269
270         seq_copy_to_input(tmp_event, 8);
271         prev_input_time = this_time;
272     }
273     seq_copy_to_input(event, len);
274 }
275
276 int
277 sequencer_write(int dev, struct fileinfo * file, snd_rw_buf * buf, int count)
278 {
279     u_char   event[EV_SZ], ev_code;
280     int             p = 0, c, ev_size;
281     int             err;
282     int             mode = file->mode & O_ACCMODE;
283
284     dev = dev >> 4;
285
286     DEB(printf("sequencer_write(dev=%d, count=%d)\n", dev, count));
287
288     if (mode == OPEN_READ)
289         return -(EIO);
290
291     if (dev)
292         return pmgr_write(dev - 1, file, buf, count);
293
294     c = count;
295
296     while (c >= 4) {
297
298         if (uiomove((char *) event, 4, buf))
299             printf("sb: Bad copyin()!\n");
300         ev_code = event[0];
301
302         if (ev_code == SEQ_FULLSIZE) {
303             int             err;
304
305             dev = *(u_short *) &event[2];
306             if (dev < 0 || dev >= max_synthdev)
307                 return -(ENXIO);
308
309             if (!(synth_open_mask & (1 << dev)))
310                 return -(ENXIO);
311
312             err = synth_devs[dev]->load_patch(dev,
313                         *(short *) &event[0], buf, p + 4, c, 0);
314             if (err < 0)
315                 return err;
316
317             return err;
318         }
319         if (ev_code >= 128) {
320             if (seq_mode == SEQ_2 && ev_code == SEQ_EXTENDED) {
321                 printf("Sequencer: Invalid level 2 event %x\n", ev_code);
322                 return -(EINVAL);
323             }
324             ev_size = 8;
325
326             if (c < ev_size) {
327                 if (!seq_playing)
328                     seq_startplay();
329                 return count - c;
330             }
331             if (uiomove((char *) &event[4], 4, buf))
332                 printf("sb: Bad copyin()!\n");
333         } else {
334             if (seq_mode == SEQ_2) {
335                 printf("Sequencer: 4 byte event in level 2 mode\n");
336                 return -(EINVAL);
337             }
338             ev_size = 4;
339         }
340
341         if (event[0] == SEQ_MIDIPUTC) {
342
343             if (!midi_opened[event[2]]) {
344                 int             mode;
345                 int             dev = event[2];
346
347                 if (dev >= max_mididev) {
348                     printf("Sequencer Error: Nonexistent MIDI device %d\n",dev);
349                     return -(ENXIO);
350                 }
351                 mode = file->mode & O_ACCMODE;
352
353                 if ((err = midi_devs[dev]->open(dev, mode,
354                         sequencer_midi_input, sequencer_midi_output)) < 0) {
355                     seq_reset();
356                     printf("Sequencer Error: Unable to open Midi #%d\n", dev);
357                     return err;
358                 }
359                 midi_opened[dev] = 1;
360             }
361         }
362         if (!seq_queue(event, 0)) {
363             int             processed = count - c;
364
365             if (!seq_playing)
366                 seq_startplay();
367
368             return processed;
369         }
370         p += ev_size;
371         c -= ev_size;
372     }
373
374     if (!seq_playing)
375         seq_startplay();
376
377     return count;       /* This will "eat" chunks shorter than 4 bytes
378                          * (if written alone) Should we really do that ?
379                          */
380 }
381
382 static int
383 seq_queue(u_char *note, char nonblock)
384 {
385
386     /*
387      * Test if there is space in the queue
388      */
389
390     if (qlen >= SEQ_MAX_QUEUE)
391         if (!seq_playing)
392             seq_startplay();    /* Give chance to drain the queue */
393
394     if (!nonblock && qlen >= SEQ_MAX_QUEUE &&
395                 !(seq_sleep_flag.mode & WK_SLEEP)) {
396         /*
397          * Sleep until there is enough space on the queue
398          */
399
400         int chn;
401
402
403         seq_sleeper = &chn;
404         DO_SLEEP(chn, seq_sleep_flag, 0);
405
406     }
407     if (qlen >= SEQ_MAX_QUEUE)
408         return 0;       /* To be sure */
409     bcopy(note, &queue[qtail * EV_SZ], EV_SZ);
410
411     qtail = (qtail + 1) % SEQ_MAX_QUEUE;
412     qlen++;
413
414     return 1;
415 }
416
417 static int
418 extended_event(u_char *q)
419 {
420     int             dev = q[2];
421
422     if (dev < 0 || dev >= max_synthdev)
423         return -(ENXIO);
424
425     if (!(synth_open_mask & (1 << dev)))
426         return -(ENXIO);
427
428     switch (q[1]) {
429     case SEQ_NOTEOFF:
430         synth_devs[dev]->kill_note(dev, q[3], q[4], q[5]);
431         break;
432
433     case SEQ_NOTEON:
434         if (q[4] > 127 && q[4] != 255)
435             return 0;
436
437         synth_devs[dev]->start_note(dev, q[3], q[4], q[5]);
438         break;
439
440     case SEQ_PGMCHANGE:
441         synth_devs[dev]->set_instr(dev, q[3], q[4]);
442         break;
443
444     case SEQ_AFTERTOUCH:
445         synth_devs[dev]->aftertouch(dev, q[3], q[4]);
446         break;
447
448     case SEQ_BALANCE:
449         synth_devs[dev]->panning(dev, q[3], (char) q[4]);
450         break;
451
452     case SEQ_CONTROLLER:
453         synth_devs[dev]->controller(dev, q[3], q[4], *(short *) &q[5]);
454         break;
455
456     case SEQ_VOLMODE:
457         if (synth_devs[dev]->volume_method != NULL)
458             synth_devs[dev]->volume_method(dev, q[3]);
459         break;
460
461     default:
462         return -(EINVAL);
463     }
464
465     return 0;
466 }
467
468 static int
469 find_voice(int dev, int chn, int note)
470 {
471     u_short  key;
472     int             i;
473
474     key = (chn << 8) | (note + 1);
475
476     for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++)
477         if (synth_devs[dev]->alloc.map[i] == key)
478             return i;
479
480     return -1;
481 }
482
483 static int
484 alloc_voice(int dev, int chn, int note)
485 {
486     u_short  key;
487     int             voice;
488
489     key = (chn << 8) | (note + 1);
490
491     voice = synth_devs[dev]->alloc_voice(dev, chn, note,
492                              &synth_devs[dev]->alloc);
493     synth_devs[dev]->alloc.map[voice] = key;
494     synth_devs[dev]->alloc.alloc_times[voice] =
495             synth_devs[dev]->alloc.timestamp++;
496     return voice;
497 }
498
499 static void
500 seq_chn_voice_event(u_char *event)
501 {
502     u_char   dev = event[1];
503     u_char   cmd = event[2];
504     u_char   chn = event[3];
505     u_char   note = event[4];
506     u_char   parm = event[5];
507     int             voice = -1;
508
509     if ((int) dev > max_synthdev)
510         return;
511     if (!(synth_open_mask & (1 << dev)))
512         return;
513     if (!synth_devs[dev])
514         return;
515
516     if (seq_mode == SEQ_2) {
517         if (synth_devs[dev]->alloc_voice)
518             voice = find_voice(dev, chn, note);
519
520         if (cmd == MIDI_NOTEON && parm == 0) {
521             cmd = MIDI_NOTEOFF;
522             parm = 64;
523         }
524     }
525     switch (cmd) {
526     case MIDI_NOTEON:
527         if (note > 127 && note != 255)  /* Not a seq2 feature */
528             return;
529
530         if (voice == -1 && seq_mode == SEQ_2 && synth_devs[dev]->alloc_voice) { 
531             /* Internal synthesizer (FM, GUS, etc) */
532             voice = alloc_voice(dev, chn, note);
533         }
534         if (voice == -1)
535             voice = chn;
536
537         if (seq_mode == SEQ_2 && (int) dev < num_synths) {
538             /*
539              * The MIDI channel 10 is a percussive channel. Use
540              * the note number to select the proper patch (128 to
541              * 255) to play.
542              */
543
544             if (chn == 9) {
545                 synth_devs[dev]->set_instr(dev, voice, 128 + note);
546                 note = 60;      /* Middle C */
547
548             }
549         }
550         if (seq_mode == SEQ_2)
551             synth_devs[dev]->setup_voice(dev, voice, chn);
552         synth_devs[dev]->start_note(dev, voice, note, parm);
553         break;
554
555     case MIDI_NOTEOFF:
556         if (voice == -1)
557             voice = chn;
558         synth_devs[dev]->kill_note(dev, voice, note, parm);
559         break;
560
561     case MIDI_KEY_PRESSURE:
562         if (voice == -1)
563             voice = chn;
564         synth_devs[dev]->aftertouch(dev, voice, parm);
565         break;
566
567     default:;
568     }
569 }
570
571 static void
572 seq_chn_common_event(u_char *event)
573 {
574     u_char   dev = event[1];
575     u_char   cmd = event[2];
576     u_char   chn = event[3];
577     u_char   p1 = event[4];
578
579     /* u_char   p2 = event[5]; */
580     u_short  w14 = *(short *) &event[6];
581
582     if ((int) dev > max_synthdev)
583         return;
584     if (!(synth_open_mask & (1 << dev)))
585         return;
586     if (!synth_devs[dev])
587         return;
588
589     switch (cmd) {
590     case MIDI_PGM_CHANGE:
591         if (seq_mode == SEQ_2) {
592             synth_devs[dev]->chn_info[chn].pgm_num = p1;
593             if ((int) dev >= num_synths)
594                 synth_devs[dev]->set_instr(dev, chn, p1);
595         } else
596             synth_devs[dev]->set_instr(dev, chn, p1);
597
598         break;
599
600     case MIDI_CTL_CHANGE:
601         if (seq_mode == SEQ_2) {
602             if (chn > 15 || p1 > 127)
603                 break;
604
605             synth_devs[dev]->chn_info[chn].controllers[p1] = w14 & 0x7f;
606
607             if (p1 < 32)        /* Setting MSB should clear LSB to 0 */
608                 synth_devs[dev]->chn_info[chn].controllers[p1 + 32] = 0;
609
610             if ((int) dev < num_synths) {
611                 int             val = w14 & 0x7f;
612                 int             i, key;
613
614                 if (p1 < 64) {  /* Combine MSB and LSB */
615                     val = ((synth_devs[dev]->
616                            chn_info[chn].controllers[p1 & ~32] & 0x7f) << 7)
617                         | (synth_devs[dev]->
618                            chn_info[chn].controllers[p1 | 32] & 0x7f);
619                     p1 &= ~32;
620                 }
621                 /* Handle all playing notes on this channel */
622
623                 key = ((int) chn << 8);
624
625                 for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++)
626                     if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key)
627                         synth_devs[dev]->controller(dev, i, p1, val);
628             } else
629                 synth_devs[dev]->controller(dev, chn, p1, w14);
630         } else          /* Mode 1 */
631             synth_devs[dev]->controller(dev, chn, p1, w14);
632         break;
633
634     case MIDI_PITCH_BEND:
635         if (seq_mode == SEQ_2) {
636             synth_devs[dev]->chn_info[chn].bender_value = w14;
637
638             if ((int) dev < num_synths) {       /* Handle all playing
639                                                  * notes on this channel */
640                 int             i, key;
641
642                 key = (chn << 8);
643
644                 for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++)
645                     if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key)
646                         synth_devs[dev]->bender(dev, i, w14);
647             } else
648                 synth_devs[dev]->bender(dev, chn, w14);
649         } else          /* MODE 1 */
650             synth_devs[dev]->bender(dev, chn, w14);
651         break;
652
653     default:;
654     }
655 }
656
657 static int
658 seq_timing_event(u_char *event)
659 {
660     u_char   cmd = event[1];
661     u_int    parm = *(int *) &event[4];
662
663     if (seq_mode == SEQ_2) {
664         int             ret;
665
666         if ((ret = tmr->event(tmr_no, event)) == TIMER_ARMED) {
667             if ((SEQ_MAX_QUEUE - qlen) >= output_treshold) {
668                 u_long   flags;
669
670                 flags = splhigh();
671                 if ((seq_sleep_flag.mode & WK_SLEEP)) {
672                     seq_sleep_flag.mode = WK_WAKEUP;
673                     wakeup(seq_sleeper);
674                 }
675                 splx(flags);
676             }
677         }
678         return ret;
679     }
680     switch (cmd) {
681     case TMR_WAIT_REL:
682         parm += prev_event_time;
683
684         /*
685          * NOTE!  No break here. Execution of TMR_WAIT_REL continues
686          * in the next case (TMR_WAIT_ABS)
687          */
688
689     case TMR_WAIT_ABS:
690         if (parm > 0) {
691             long            time;
692
693             seq_playing = 1;
694             time = parm;
695             prev_event_time = time;
696
697             request_sound_timer(time);
698
699             if ((SEQ_MAX_QUEUE - qlen) >= output_treshold) {
700                 u_long   flags;
701
702                 flags = splhigh();
703                 if ((seq_sleep_flag.mode & WK_SLEEP)) {
704                     seq_sleep_flag.mode = WK_WAKEUP;
705                     wakeup(seq_sleeper);
706                 }
707                 splx(flags);
708             }
709             return TIMER_ARMED;
710         }
711         break;
712
713     case TMR_START:
714         seq_time = get_time();
715         prev_input_time = 0;
716         prev_event_time = 0;
717         break;
718
719     case TMR_STOP:
720         break;
721
722     case TMR_CONTINUE:
723         break;
724
725     case TMR_TEMPO:
726         break;
727
728     case TMR_ECHO:
729         if (seq_mode == SEQ_2)
730             seq_copy_to_input(event, 8);
731         else {
732             parm = (parm << 8 | SEQ_ECHO);
733             seq_copy_to_input((u_char *) &parm, 4);
734         }
735         break;
736
737     default:;
738     }
739
740     return TIMER_NOT_ARMED;
741 }
742
743 static void
744 seq_local_event(u_char *event)
745 {
746     u_char   cmd = event[1];
747     u_int    parm = *((u_int *) &event[4]);
748
749     switch (cmd) {
750     case LOCL_STARTAUDIO:
751 #ifdef CONFIG_AUDIO
752         DMAbuf_start_devices(parm);
753 #endif
754         break;
755
756     default:;
757     }
758 }
759
760 static void
761 seq_sysex_message(u_char *event)
762 {
763     int             dev = event[1];
764     int             i, l = 0;
765     u_char  *buf = &event[2];
766
767     if ((int) dev > max_synthdev)
768         return;
769     if (!(synth_open_mask & (1 << dev)))
770         return;
771     if (!synth_devs[dev])
772         return;
773     if (!synth_devs[dev]->send_sysex)
774         return;
775
776     l = 0;
777     for (i = 0; i < 6 && buf[i] != 0xff; i++)
778         l = i + 1;
779
780     if (l > 0)
781         synth_devs[dev]->send_sysex(dev, buf, l);
782 }
783
784 static int
785 play_event(u_char *q)
786 {
787     /*
788      * NOTE! This routine returns 0 = normal event played. 1 = Timer
789      * armed. Suspend playback until timer callback. 2 = MIDI output
790      * buffer full. Restore queue and suspend until timer
791      */
792     u_long  *delay;
793
794     switch (q[0]) {
795     case SEQ_NOTEOFF:
796         if (synth_open_mask & (1 << 0))
797             if (synth_devs[0])
798                 synth_devs[0]->kill_note(0, q[1], 255, q[3]);
799         break;
800
801     case SEQ_NOTEON:
802         if (q[4] < 128 || q[4] == 255)
803             if (synth_open_mask & (1 << 0))
804                 if (synth_devs[0])
805                     synth_devs[0]->start_note(0, q[1], q[2], q[3]);
806         break;
807
808     case SEQ_WAIT:
809         delay = (u_long *) q;   /* Bytes 1 to 3 are
810                                          * containing the * delay in
811                                          * get_time() */
812         *delay = (*delay >> 8) & 0xffffff;
813
814         if (*delay > 0) {
815             long            time;
816
817             seq_playing = 1;
818             time = *delay;
819             prev_event_time = time;
820
821             request_sound_timer(time);
822
823             if ((SEQ_MAX_QUEUE - qlen) >= output_treshold) {
824                 u_long   flags;
825
826                 flags = splhigh();
827                 if ((seq_sleep_flag.mode & WK_SLEEP)) {
828                     seq_sleep_flag.mode = WK_WAKEUP;
829                     wakeup(seq_sleeper);
830                 }
831                 splx(flags);
832             }
833             /*
834              * The timer is now active and will reinvoke this
835              * function after the timer expires. Return to the
836              * caller now.
837              */
838             return 1;
839         }
840         break;
841
842     case SEQ_PGMCHANGE:
843         if (synth_open_mask & (1 << 0))
844             if (synth_devs[0])
845                 synth_devs[0]->set_instr(0, q[1], q[2]);
846         break;
847
848     case SEQ_SYNCTIMER: /* Reset timer */
849         seq_time = get_time();
850         prev_input_time = 0;
851         prev_event_time = 0;
852         break;
853
854     case SEQ_MIDIPUTC:  /* Put a midi character */
855         if (midi_opened[q[2]]) {
856             int             dev;
857
858             dev = q[2];
859
860             if (!midi_devs[dev]->putc(dev, q[1])) {
861                 /*
862                  * Output FIFO is full. Wait one timer cycle and try again.
863                  */
864
865                 seq_playing = 1;
866                 request_sound_timer(-1);
867                 return 2;
868             } else
869                 midi_written[dev] = 1;
870         }
871         break;
872
873     case SEQ_ECHO:
874         seq_copy_to_input(q, 4);        /* Echo back to the process */
875         break;
876
877     case SEQ_PRIVATE:
878         if ((int) q[1] < max_synthdev)
879             synth_devs[q[1]]->hw_control(q[1], q);
880         break;
881
882     case SEQ_EXTENDED:
883         extended_event(q);
884         break;
885
886     case EV_CHN_VOICE:
887         seq_chn_voice_event(q);
888         break;
889
890     case EV_CHN_COMMON:
891         seq_chn_common_event(q);
892         break;
893
894     case EV_TIMING:
895         if (seq_timing_event(q) == TIMER_ARMED) {
896             return 1;
897         }
898         break;
899
900     case EV_SEQ_LOCAL:
901         seq_local_event(q);
902         break;
903
904     case EV_SYSEX:
905         seq_sysex_message(q);
906         break;
907
908     default:;
909     }
910
911     return 0;
912 }
913
914 static void
915 seq_startplay(void)
916 {
917     u_long   flags;
918     int             this_one, action;
919
920     while (qlen > 0) {
921
922         flags = splhigh();
923         qhead = ((this_one = qhead) + 1) % SEQ_MAX_QUEUE;
924         qlen--;
925         splx(flags);
926
927         seq_playing = 1;
928
929         if ((action = play_event(&queue[this_one * EV_SZ]))) {
930             /*
931              * Suspend playback. Next timer routine invokes this routine again
932              */
933             if (action == 2) {
934                 qlen++;
935                 qhead = this_one;
936             }
937             return;
938         }
939     }
940
941     seq_playing = 0;
942
943     if ((SEQ_MAX_QUEUE - qlen) >= output_treshold) {
944         u_long   flags;
945
946         flags = splhigh();
947         if ((seq_sleep_flag.mode & WK_SLEEP)) {
948             seq_sleep_flag.mode = WK_WAKEUP;
949             wakeup(seq_sleeper);
950         }
951         splx(flags);
952     }
953 }
954
955 static void
956 reset_controllers(int dev, u_char *controller, int update_dev)
957 {
958
959     int             i;
960
961     for (i = 0; i < 128; i++)
962         controller[i] = ctrl_def_values[i];
963 }
964
965 static void
966 setup_mode2(void)
967 {
968     int             dev;
969
970     max_synthdev = num_synths;
971
972     for (dev = 0; dev < num_midis; dev++)
973         if (midi_devs[dev]->converter != NULL)
974             synth_devs[max_synthdev++] = midi_devs[dev]->converter;
975     for (dev = 0; dev < max_synthdev; dev++) {
976         int             chn;
977
978         for (chn = 0; chn < 16; chn++) {
979             synth_devs[dev]->chn_info[chn].pgm_num = 0;
980             reset_controllers(dev,
981                      synth_devs[dev]->chn_info[chn].controllers, 0);
982             synth_devs[dev]->chn_info[chn].bender_value = (1<<7); /* Neutral */
983         }
984     }
985
986     max_mididev = 0;
987     seq_mode = SEQ_2;
988 }
989
990 int
991 sequencer_open(int dev, struct fileinfo * file)
992 {
993     int             retval, mode, i;
994     int             level, tmp;
995     u_long   flags;
996
997     level = ((dev & 0x0f) == SND_DEV_SEQ2) ? 2 : 1;
998
999     dev = dev >> 4;
1000     mode = file->mode & O_ACCMODE;
1001
1002     DEB(printf("sequencer_open(dev=%d)\n", dev));
1003
1004     if (!sequencer_ok) {
1005         printf("Soundcard: Sequencer not initialized\n");
1006         return -(ENXIO);
1007     }
1008     if (dev) {          /* Patch manager device */
1009         int             err;
1010
1011         printf("Patch manager interface is currently broken. Sorry\n");
1012         return -(ENXIO);
1013
1014         dev--;
1015
1016         if (dev >= MAX_SYNTH_DEV)
1017             return -(ENXIO);
1018         if (pmgr_present[dev])
1019             return -(EBUSY);
1020         if ((err = pmgr_open(dev)) < 0)
1021             return err;
1022
1023         pmgr_present[dev] = 1;
1024         return err;
1025     }
1026     flags = splhigh();
1027     if (sequencer_busy) {
1028         printf("Sequencer busy\n");
1029         splx(flags);
1030         return -(EBUSY);
1031     }
1032     sequencer_busy = 1;
1033     splx(flags);
1034
1035     max_mididev = num_midis;
1036     max_synthdev = num_synths;
1037     pre_event_timeout = 0;
1038     seq_mode = SEQ_1;
1039
1040     if (pending_timer != -1) {
1041         tmr_no = pending_timer;
1042         pending_timer = -1;
1043     }
1044     if (tmr_no == -1) { /* Not selected yet */
1045         int             i, best;
1046
1047         best = -1;
1048         for (i = 0; i < num_sound_timers; i++)
1049             if (sound_timer_devs[i]->priority > best) {
1050                 tmr_no = i;
1051                 best = sound_timer_devs[i]->priority;
1052             }
1053             if (tmr_no == -1)   /* Should not be */
1054                 tmr_no = 0;
1055     }
1056     tmr = sound_timer_devs[tmr_no];
1057
1058     if (level == 2) {
1059         if (tmr == NULL) {
1060             printf("sequencer: No timer for level 2\n");
1061             sequencer_busy = 0;
1062             return -(ENXIO);
1063         }
1064         setup_mode2();
1065     }
1066     if (seq_mode == SEQ_1 && (mode == OPEN_READ || mode == OPEN_READWRITE))
1067         if (!max_mididev) {
1068             printf("Sequencer: No Midi devices. Input not possible\n");
1069             sequencer_busy = 0;
1070             return -(ENXIO);
1071         }
1072     if (!max_synthdev && !max_mididev)
1073         return -(ENXIO);
1074
1075     synth_open_mask = 0;
1076
1077     for (i = 0; i < max_mididev; i++) {
1078         midi_opened[i] = 0;
1079         midi_written[i] = 0;
1080     }
1081
1082     /*
1083      * if (mode == OPEN_WRITE || mode == OPEN_READWRITE)
1084      */
1085     for (i = 0; i < max_synthdev; i++)  /* Open synth devices */
1086         if ((tmp = synth_devs[i]->open(i, mode)) < 0) {
1087             printf("Sequencer: Warning! Cannot open synth device #%d (%d)\n",
1088                 i, tmp);
1089             if (synth_devs[i]->midi_dev)
1090                 printf("(Maps to MIDI dev #%d)\n", synth_devs[i]->midi_dev);
1091         } else {
1092             synth_open_mask |= (1 << i);
1093             if (synth_devs[i]->midi_dev)        /* Is a midi interface */
1094                 midi_opened[synth_devs[i]->midi_dev] = 1;
1095         }
1096
1097     seq_time = get_time();
1098     prev_input_time = 0;
1099     prev_event_time = 0;
1100
1101     if (seq_mode == SEQ_1 && (mode == OPEN_READ || mode == OPEN_READWRITE)) {
1102         /* Initialize midi input devices */
1103         for (i = 0; i < max_mididev; i++)
1104             if (!midi_opened[i]) {
1105                 if ((retval = midi_devs[i]->open(i, mode,
1106                          sequencer_midi_input, sequencer_midi_output)) >= 0)
1107                     midi_opened[i] = 1;
1108             }
1109     }
1110     if (seq_mode == SEQ_2) {
1111         tmr->open(tmr_no, seq_mode);
1112     }
1113     seq_sleep_flag.aborting = 0;
1114     seq_sleep_flag.mode = WK_NONE;
1115     midi_sleep_flag.aborting = 0;
1116     midi_sleep_flag.mode = WK_NONE;
1117     output_treshold = SEQ_MAX_QUEUE / 2;
1118
1119     for (i = 0; i < num_synths; i++)
1120         if (pmgr_present[i])
1121             pmgr_inform(i, PM_E_OPENED, 0, 0, 0, 0);
1122
1123     return 0;
1124 }
1125
1126 static void
1127 seq_drain_midi_queues(void)
1128 {
1129     int             i, n;
1130
1131     /*
1132      * Give the Midi drivers time to drain their output queues
1133      */
1134
1135     n = 1;
1136
1137     while (!(seq_sleep_flag.aborting) && n) {
1138         n = 0;
1139
1140         for (i = 0; i < max_mididev; i++)
1141             if (midi_opened[i] && midi_written[i])
1142                 if (midi_devs[i]->buffer_status != NULL)
1143                     if (midi_devs[i]->buffer_status(i))
1144                                                 n++;
1145
1146         /*
1147          * Let's have a delay
1148          */
1149         if (n) {
1150             int   chn;
1151
1152             seq_sleeper = &chn;
1153             DO_SLEEP(chn, seq_sleep_flag, hz / 10);
1154
1155         }
1156     }
1157 }
1158
1159 void
1160 sequencer_release(int dev, struct fileinfo * file)
1161 {
1162     int             i;
1163     int             mode = file->mode & O_ACCMODE;
1164
1165     dev = dev >> 4;
1166
1167     DEB(printf("sequencer_release(dev=%d)\n", dev));
1168
1169     if (dev) {          /* Patch manager device */
1170         dev--;
1171         pmgr_release(dev);
1172         pmgr_present[dev] = 0;
1173         return;
1174     }
1175     /*
1176      * Wait until the queue is empty (if we don't have nonblock)
1177      */
1178
1179     if (mode != OPEN_READ && !0)
1180         while (!(seq_sleep_flag.aborting) && qlen) {
1181             seq_sync();
1182         }
1183
1184     if (mode != OPEN_READ)
1185         seq_drain_midi_queues(); /* Ensure the output queues are empty */
1186     seq_reset();
1187     if (mode != OPEN_READ)
1188         seq_drain_midi_queues();        /* Flush the all notes off messages */
1189
1190     for (i = 0; i < max_synthdev; i++)
1191         if (synth_open_mask & (1 << i)) /* Actually opened */
1192             if (synth_devs[i]) {
1193                 synth_devs[i]->close(i);
1194
1195                 if (synth_devs[i]->midi_dev)
1196                     midi_opened[synth_devs[i]->midi_dev] = 0;
1197             }
1198     for (i = 0; i < num_synths; i++)
1199         if (pmgr_present[i])
1200             pmgr_inform(i, PM_E_CLOSED, 0, 0, 0, 0);
1201
1202     for (i = 0; i < max_mididev; i++)
1203         if (midi_opened[i])
1204             midi_devs[i]->close(i);
1205
1206     if (seq_mode == SEQ_2)
1207         tmr->close(tmr_no);
1208
1209     sequencer_busy = 0;
1210 }
1211
1212 static int
1213 seq_sync(void)
1214 {
1215     u_long   flags;
1216
1217     if (qlen && !seq_playing && !(seq_sleep_flag.aborting))
1218         seq_startplay();
1219
1220     flags = splhigh();
1221     if (qlen && !(seq_sleep_flag.mode & WK_SLEEP)) {
1222         int  chn;
1223
1224         seq_sleeper = &chn;
1225         DO_SLEEP(chn, seq_sleep_flag, 0);
1226
1227     }
1228     splx(flags);
1229
1230     return qlen;
1231 }
1232
1233 static void
1234 midi_outc(int dev, u_char data)
1235 {
1236     /*
1237      * NOTE! Calls sleep(). Don't call this from interrupt.
1238      */
1239
1240     int             n;
1241     u_long   flags;
1242
1243     /*
1244      * This routine sends one byte to the Midi channel. If the output
1245      * Fifo is full, it waits until there is space in the queue
1246      */
1247
1248     n = 3 * hz;         /* Timeout */
1249
1250     flags = splhigh();
1251     while (n && !midi_devs[dev]->putc(dev, data)) {
1252         int    chn;
1253         seq_sleeper = &chn;
1254         DO_SLEEP(chn, seq_sleep_flag, 4);
1255
1256         n--;
1257     }
1258     splx(flags);
1259 }
1260
1261 static void
1262 seq_reset(void)
1263 {
1264     /*
1265      * NOTE! Calls sleep(). Don't call this from interrupt.
1266      */
1267
1268     int             i;
1269     int             chn;
1270     u_long   flags;
1271
1272     sound_stop_timer();
1273     seq_time = get_time();
1274     prev_input_time = 0;
1275     prev_event_time = 0;
1276
1277     qlen = qhead = qtail = 0;
1278     iqlen = iqhead = iqtail = 0;
1279
1280     for (i = 0; i < max_synthdev; i++)
1281         if (synth_open_mask & (1 << i))
1282             if (synth_devs[i])
1283                 synth_devs[i]->reset(i);
1284
1285     if (seq_mode == SEQ_2) {
1286         for (chn = 0; chn < 16; chn++)
1287             for (i = 0; i < max_synthdev; i++)
1288                 if ( (synth_open_mask & (1 << i)) && (synth_devs[i]) ) {
1289                     synth_devs[i]->controller(i, chn,123,0);/* All notes off */
1290                     synth_devs[i]->controller(i, chn,121,0);/* Reset all ctl */
1291                     synth_devs[i]->bender(i, chn, 1 << 13); /* Bender off */
1292                 }
1293
1294     } else {                                    /* seq_mode == SEQ_1 */
1295         for (i = 0; i < max_mididev; i++)
1296             if (midi_written[i]) {
1297                 /* Midi used. Some notes may still be playing */
1298                 /*
1299                  * Sending just a ACTIVE SENSING message
1300                  * should be enough to stop all playing
1301                  * notes. Since there are devices not
1302                  * recognizing the active sensing, we have to
1303                  * send some all notes off messages also.
1304                  */
1305                 midi_outc(i, 0xfe);
1306
1307                 for (chn = 0; chn < 16; chn++) {
1308                     midi_outc(i, (u_char) (0xb0 + (chn & 0x0f))); /* control change */
1309                     midi_outc(i, 0x7b); /* All notes off */
1310                     midi_outc(i, 0);    /* Dummy parameter */
1311                 }
1312
1313                 midi_devs[i]->close(i);
1314
1315                 midi_written[i] = 0;
1316                 midi_opened[i] = 0;
1317             }
1318     }
1319
1320     seq_playing = 0;
1321
1322     flags = splhigh();
1323     if ((seq_sleep_flag.mode & WK_SLEEP)) {
1324         seq_sleep_flag.mode = WK_WAKEUP;
1325         wakeup(seq_sleeper);
1326     }
1327     splx(flags);
1328
1329 }
1330
1331 static void
1332 seq_panic(void)
1333 {
1334     /*
1335      * This routine is called by the application in case the user wants
1336      * to reset the system to the default state.
1337      */
1338
1339     seq_reset();
1340
1341     /*
1342      * Since some of the devices don't recognize the active sensing and
1343      * all notes off messages, we have to shut all notes manually.
1344      * 
1345      * TO BE IMPLEMENTED LATER
1346      */
1347
1348     /*
1349      * Also return the controllers to their default states
1350      */
1351 }
1352
1353 int
1354 sequencer_ioctl(int dev, struct fileinfo * file,
1355                 u_int cmd, ioctl_arg arg)
1356 {
1357     int             midi_dev, orig_dev;
1358     int             mode = file->mode & O_ACCMODE;
1359
1360     orig_dev = dev = dev >> 4;
1361
1362     switch (cmd) {
1363     case SNDCTL_TMR_TIMEBASE:
1364     case SNDCTL_TMR_TEMPO:
1365     case SNDCTL_TMR_START:
1366     case SNDCTL_TMR_STOP:
1367     case SNDCTL_TMR_CONTINUE:
1368     case SNDCTL_TMR_METRONOME:
1369     case SNDCTL_TMR_SOURCE:
1370         if (dev)        /* Patch manager */
1371             return -(EIO);
1372
1373         if (seq_mode != SEQ_2)
1374             return -(EINVAL);
1375         return tmr->ioctl(tmr_no, cmd, arg);
1376         break;
1377
1378     case SNDCTL_TMR_SELECT:
1379         if (dev)        /* Patch manager */
1380             return -(EIO);
1381
1382         if (seq_mode != SEQ_2)
1383             return -(EINVAL);
1384         pending_timer = (*(int *) arg);
1385
1386         if (pending_timer < 0 || pending_timer >= num_sound_timers) {
1387             pending_timer = -1;
1388             return -(EINVAL);
1389         }
1390         return *(int *) arg = pending_timer;
1391         break;
1392
1393     case SNDCTL_SEQ_PANIC:
1394         seq_panic();
1395         break;
1396
1397     case SNDCTL_SEQ_SYNC:
1398         if (dev)        /* Patch manager */
1399             return -(EIO);
1400
1401         if (mode == OPEN_READ)
1402             return 0;
1403         while (qlen && !(seq_sleep_flag.aborting))
1404             seq_sync();
1405         if (qlen)
1406             return -(EINTR);
1407         else
1408             return 0;
1409         break;
1410
1411     case SNDCTL_SEQ_RESET:
1412         if (dev)        /* Patch manager */
1413             return -(EIO);
1414
1415         seq_reset();
1416         return 0;
1417         break;
1418
1419     case SNDCTL_SEQ_TESTMIDI:
1420         if (dev)        /* Patch manager */
1421             return -(EIO);
1422
1423         midi_dev = (*(int *) arg);
1424         if (midi_dev >= max_mididev)
1425             return -(ENXIO);
1426
1427         if (!midi_opened[midi_dev]) {
1428             int             err, mode;
1429
1430             mode = file->mode & O_ACCMODE;
1431             if ((err = midi_devs[midi_dev]->open(midi_dev, mode,
1432                        sequencer_midi_input, sequencer_midi_output)) < 0)
1433                 return err;
1434         }
1435         midi_opened[midi_dev] = 1;
1436
1437         return 0;
1438         break;
1439
1440     case SNDCTL_SEQ_GETINCOUNT:
1441         if (dev)        /* Patch manager */
1442             return -(EIO);
1443
1444         if (mode == OPEN_WRITE)
1445             return 0;
1446         return *(int *) arg = iqlen;
1447         break;
1448
1449     case SNDCTL_SEQ_GETOUTCOUNT:
1450
1451         if (mode == OPEN_READ)
1452             return 0;
1453         return *(int *) arg = SEQ_MAX_QUEUE - qlen;
1454         break;
1455
1456     case SNDCTL_SEQ_CTRLRATE:
1457         if (dev)        /* Patch manager */
1458             return -(EIO);
1459
1460         /*
1461          * If *arg == 0, just return the current rate
1462          */
1463         if (seq_mode == SEQ_2)
1464             return tmr->ioctl(tmr_no, cmd, arg);
1465
1466         if ((*(int *) arg) != 0)
1467             return -(EINVAL);
1468
1469         return *(int *) arg = hz;
1470         break;
1471
1472     case SNDCTL_SEQ_RESETSAMPLES:
1473         {
1474             int             err;
1475
1476             dev = (*(int *) arg);
1477             if (dev < 0 || dev >= num_synths)
1478                 return -(ENXIO);
1479             if (!(synth_open_mask & (1 << dev)) && !orig_dev)
1480                 return -(EBUSY);
1481             if (!orig_dev && pmgr_present[dev])
1482                 pmgr_inform(dev, PM_E_PATCH_RESET, 0, 0, 0, 0);
1483
1484             err = synth_devs[dev]->ioctl(dev, cmd, arg);
1485             return err;
1486         }
1487         break;
1488
1489     case SNDCTL_SEQ_NRSYNTHS:
1490         return *(int *) arg = max_synthdev;
1491         break;
1492
1493     case SNDCTL_SEQ_NRMIDIS:
1494         return *(int *) arg = max_mididev;
1495         break;
1496
1497     case SNDCTL_SYNTH_MEMAVL:
1498         {
1499             int             dev = (*(int *) arg);
1500
1501             if (dev < 0 || dev >= num_synths)
1502                 return -(ENXIO);
1503
1504             if (!(synth_open_mask & (1 << dev)) && !orig_dev)
1505                 return -(EBUSY);
1506
1507             return *(int *) arg = synth_devs[dev]->ioctl(dev, cmd, arg);
1508         }
1509         break;
1510
1511     case SNDCTL_FM_4OP_ENABLE:
1512         {
1513             int             dev = (*(int *) arg);
1514
1515             if (dev < 0 || dev >= num_synths)
1516                 return -(ENXIO);
1517
1518             if (!(synth_open_mask & (1 << dev)))
1519                 return -(ENXIO);
1520
1521             synth_devs[dev]->ioctl(dev, cmd, arg);
1522             return 0;
1523         }
1524         break;
1525
1526     case SNDCTL_SYNTH_INFO:
1527         {
1528             struct synth_info inf;
1529             int             dev;
1530
1531             bcopy(&(((char *) arg)[0]), (char *) &inf, sizeof(inf));
1532             dev = inf.device;
1533
1534             if (dev < 0 || dev >= max_synthdev)
1535                 return -(ENXIO);
1536
1537             if (!(synth_open_mask & (1 << dev)) && !orig_dev)
1538                 return -(EBUSY);
1539
1540             return synth_devs[dev]->ioctl(dev, cmd, arg);
1541         }
1542         break;
1543
1544     case SNDCTL_SEQ_OUTOFBAND:
1545         {
1546             struct seq_event_rec event;
1547             u_long   flags;
1548
1549             bcopy(&(((char *) arg)[0]), (char *) &event, sizeof(event));
1550
1551             flags = splhigh();
1552             play_event(event.arr);
1553             splx(flags);
1554
1555             return 0;
1556         }
1557         break;
1558
1559     case SNDCTL_MIDI_INFO:
1560         {
1561             struct midi_info inf;
1562             int             dev;
1563
1564             bcopy(&(((char *) arg)[0]), (char *) &inf, sizeof(inf));
1565             dev = inf.device;
1566
1567             if (dev < 0 || dev >= max_mididev)
1568                 return -(ENXIO);
1569
1570             bcopy((char *) &(midi_devs[dev]->info), &(((char *) arg)[0]), sizeof(inf));
1571             return 0;
1572         }
1573         break;
1574
1575     case SNDCTL_PMGR_IFACE:
1576         {
1577             struct patmgr_info *inf;
1578             int             dev, err;
1579
1580             if ((inf = (struct patmgr_info *) malloc(sizeof(*inf), M_TEMP, M_WAITOK)) == NULL) {
1581                 printf("patmgr: Can't allocate memory for a message\n");
1582                 return -(EIO);
1583             }
1584             bcopy(&(((char *) arg)[0]), (char *) inf, sizeof(*inf));
1585             dev = inf->device;
1586
1587             if (dev < 0 || dev >= num_synths) {
1588                 free(inf, M_TEMP);
1589                 return -(ENXIO);
1590             }
1591             if (!synth_devs[dev]->pmgr_interface) {
1592                 free(inf, M_TEMP);
1593                 return -(ENXIO);
1594             }
1595             if ((err = synth_devs[dev]->pmgr_interface(dev, inf)) == -1) {
1596                 free(inf, M_TEMP);
1597                 return err;
1598             }
1599             bcopy((char *) inf, &(((char *) arg)[0]), sizeof(*inf));
1600             free(inf, M_TEMP);
1601             return 0;
1602         }
1603         break;
1604
1605     case SNDCTL_PMGR_ACCESS:
1606         {
1607             struct patmgr_info *inf;
1608             int             dev, err;
1609
1610             if ((inf = (struct patmgr_info *) malloc(sizeof(*inf), M_TEMP, M_WAITOK)) == NULL) {
1611                 printf("patmgr: Can't allocate memory for a message\n");
1612                 return -(EIO);
1613             }
1614             bcopy(&(((char *) arg)[0]), (char *) inf, sizeof(*inf));
1615             dev = inf->device;
1616
1617             if (dev < 0 || dev >= num_synths) {
1618                 free(inf, M_TEMP);
1619                 return -(ENXIO);
1620             }
1621             if (!pmgr_present[dev]) {
1622                 free(inf, M_TEMP);
1623                 return -(ESRCH);
1624             }
1625             if ((err = pmgr_access(dev, inf)) < 0) {
1626                 free(inf, M_TEMP);
1627                 return err;
1628             }
1629             bcopy((char *) inf, &(((char *) arg)[0]), sizeof(*inf));
1630             free(inf, M_TEMP);
1631             return 0;
1632         }
1633         break;
1634
1635     case SNDCTL_SEQ_THRESHOLD:
1636         {
1637             int             tmp = (*(int *) arg);
1638
1639             if (dev)/* Patch manager */
1640                 return -(EIO);
1641
1642             if (tmp < 1)
1643                 tmp = 1;
1644             if (tmp >= SEQ_MAX_QUEUE)
1645                 tmp = SEQ_MAX_QUEUE - 1;
1646             output_treshold = tmp;
1647             return 0;
1648         }
1649         break;
1650
1651     case SNDCTL_MIDI_PRETIME:
1652         {
1653             int             val = (*(int *) arg);
1654
1655             if (val < 0)
1656                 val = 0;
1657
1658             val = (hz * val) / 10;
1659             pre_event_timeout = val;
1660             return *(int *) arg = val;
1661         }
1662         break;
1663
1664     default:
1665         if (dev)        /* Patch manager */
1666             return -(EIO);
1667
1668         if (mode == OPEN_READ)
1669             return -(EIO);
1670
1671         if (!synth_devs[0])
1672             return -(ENXIO);
1673         if (!(synth_open_mask & (1 << 0)))
1674             return -(ENXIO);
1675         return synth_devs[0]->ioctl(0, cmd, arg);
1676         break;
1677     }
1678
1679     return -(EINVAL);
1680 }
1681
1682 #ifdef ALLOW_POLL
1683 int
1684 sequencer_poll (int dev, struct fileinfo *file, int events, select_table * wait)
1685 {
1686   unsigned long   flags;
1687   int revents = 0;
1688
1689   dev = dev >> 4;
1690   flags = splhigh();
1691
1692
1693   if (events & (POLLIN | POLLRDNORM)) {
1694     if (!iqlen)
1695       selrecord(wait, &selinfo[dev]);
1696     else {
1697       revents |= events & (POLLIN | POLLRDNORM);
1698       midi_sleep_flag.mode &= ~WK_SLEEP;
1699     }
1700   }
1701   if (events & (POLLOUT | POLLWRNORM)) {
1702     if (qlen >= SEQ_MAX_QUEUE)
1703       selrecord(wait, &selinfo[dev]);
1704     else {
1705       revents |= events & (POLLOUT | POLLWRNORM);
1706       seq_sleep_flag.mode &= ~WK_SLEEP;
1707     }
1708   }
1709   splx(flags);
1710
1711   return (revents);
1712 }
1713
1714 #endif
1715
1716
1717 void
1718 sequencer_timer(void *dummy)
1719 {
1720     seq_startplay();
1721 }
1722
1723 int
1724 note_to_freq(int note_num)
1725 {
1726
1727     /*
1728      * This routine converts a midi note to a frequency (multiplied by
1729      * 1000)
1730      */
1731
1732     int             note, octave, note_freq;
1733     int             notes[] =
1734     {
1735             261632, 277189, 293671, 311132, 329632, 349232,
1736             369998, 391998, 415306, 440000, 466162, 493880
1737     };
1738
1739 #define BASE_OCTAVE     5
1740
1741     octave = note_num / 12;
1742     note = note_num % 12;
1743
1744     note_freq = notes[note];
1745
1746     if (octave < BASE_OCTAVE)
1747         note_freq >>= (BASE_OCTAVE - octave);
1748     else if (octave > BASE_OCTAVE)
1749         note_freq <<= (octave - BASE_OCTAVE);
1750
1751     /*
1752      * note_freq >>= 1;
1753      */
1754
1755     return note_freq;
1756 }
1757
1758 u_long
1759 compute_finetune(u_long base_freq, int bend, int range)
1760 {
1761     u_long   amount;
1762     int             negative, semitones, cents, multiplier = 1;
1763
1764     if (!bend)
1765         return base_freq;
1766     if (!range)
1767         return base_freq;
1768
1769     if (!base_freq)
1770         return base_freq;
1771
1772     if (range >= 8192)
1773         range = 8192;
1774
1775     bend = bend * range / 8192;
1776     if (!bend)
1777         return base_freq;
1778
1779     negative = bend < 0 ? 1 : 0;
1780
1781     if (bend < 0)
1782         bend *= -1;
1783     if (bend > range)
1784         bend = range;
1785
1786     /*
1787      * if (bend > 2399) bend = 2399;
1788      */
1789     while (bend > 2399) {
1790         multiplier *= 4;
1791         bend -= 2400;
1792     }
1793
1794     semitones = bend / 100;
1795     cents = bend % 100;
1796
1797     amount = (int) (semitone_tuning[semitones] * multiplier * cent_tuning[cents])
1798             / 10000;
1799
1800     if (negative)
1801         return (base_freq * 10000) / amount;    /* Bend down */
1802     else
1803         return (base_freq * amount) / 10000;    /* Bend up */
1804 }
1805
1806
1807 void
1808 sequencer_init()
1809 {
1810
1811     sequencer_ok = 1;
1812
1813     queue = (u_char *) malloc(SEQ_MAX_QUEUE * EV_SZ, M_DEVBUF, M_NOWAIT);
1814     if (!queue)
1815         panic("SOUND: Cannot allocate memory\n");
1816
1817     iqueue = (u_char *) malloc(SEQ_MAX_QUEUE * IEV_SZ, M_DEVBUF, M_NOWAIT);
1818     if (!iqueue)
1819         panic("SOUND: Cannot allocate memory\n");
1820 }
1821
1822 #endif
1823 #endif