Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / dev / sound / isa / i386 / opl3.c
1 /*
2  * sound/opl3.c
3  * 
4  * A low level driver for Yamaha YM3812 and OPL-3 -chips
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/opl3.c,v 1.20 1999/12/27 04:37:18 tanimura Exp $
29  *
30  */
31
32 /*
33  * Major improvements to the FM handling 30AUG92 by Rob Hooft,
34  */
35 /*
36  * hooft@chem.ruu.nl
37  */
38 #include <i386/isa/sound/sound_config.h>
39
40
41 #if defined(CONFIG_YM3812)
42
43 #include <i386/isa/sound/opl3.h>
44 #include <machine/clock.h>
45
46 #define MAX_VOICE       18
47 #define OFFS_4OP        11
48
49 struct voice_info {
50         u_char   keyon_byte;
51         long            bender;
52         long            bender_range;
53         u_long   orig_freq;
54         u_long   current_freq;
55         int             volume;
56         int             mode;
57 };
58
59 typedef struct opl_devinfo {
60         int             left_io, right_io;
61         int             nr_voice;
62         int             lv_map[MAX_VOICE];
63
64         struct voice_info voc[MAX_VOICE];
65         struct voice_alloc_info *v_alloc;
66         struct channel_info *chn_info;
67
68         struct sbi_instrument i_map[SBFM_MAXINSTR];
69         struct sbi_instrument *act_i[MAX_VOICE];
70
71         struct synth_info fm_info;
72
73         int             busy;
74         int             model;
75         u_char   cmask;
76
77         int             is_opl4;
78         sound_os_info  *osp;
79 }
80                 opl_devinfo;
81
82 static struct opl_devinfo *devc = NULL;
83
84
85 static int      detected_model;
86
87 static int      store_instr(int instr_no, struct sbi_instrument * instr);
88 static void     freq_to_fnum(int freq, int *block, int *fnum);
89 static void     opl3_command(int io_addr, u_int addr, u_int val);
90 static int      opl3_kill_note(int dev, int voice, int note, int velocity);
91
92 void
93 enable_opl3_mode(int left, int right, int both)
94 {
95         /* NOP */
96 }
97
98 static void
99 enter_4op_mode(void)
100 {
101     int             i;
102     static int      v4op[MAX_VOICE] =
103         {0, 1, 2, 9, 10, 11, 6, 7, 8, 15, 16, 17};
104
105     devc->cmask = 0x3f; /* Connect all possible 4 OP voice operators */
106     opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x3f);
107
108     for (i = 0; i < 3; i++)
109         pv_map[i].voice_mode = 4;
110     for (i = 3; i < 6; i++)
111         pv_map[i].voice_mode = 0;
112
113     for (i = 9; i < 12; i++)
114         pv_map[i].voice_mode = 4;
115     for (i = 12; i < 15; i++)
116         pv_map[i].voice_mode = 0;
117
118     for (i = 0; i < 12; i++)
119         devc->lv_map[i] = v4op[i];
120     devc->v_alloc->max_voice = devc->nr_voice = 12;
121 }
122
123 static int
124 opl3_ioctl(int dev,
125            u_int cmd, ioctl_arg arg)
126 {
127     switch (cmd) {
128
129     case SNDCTL_FM_LOAD_INSTR:
130         {
131             struct sbi_instrument ins;
132
133             bcopy(&(((char *) arg)[0]), (char *) &ins, sizeof(ins));
134
135             if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) {
136                 printf("FM Error: Invalid instrument number %d\n", ins.channel);
137                 return -(EINVAL);
138             }
139             pmgr_inform(dev, PM_E_PATCH_LOADED, ins.channel, 0, 0, 0);
140             return store_instr(ins.channel, &ins);
141         }
142         break;
143
144     case SNDCTL_SYNTH_INFO:
145         devc->fm_info.nr_voices = (devc->nr_voice == 12) ? 6 : devc->nr_voice;
146         bcopy(&devc->fm_info, &(((char *) arg)[0]), sizeof(devc->fm_info));
147         return 0;
148         break;
149
150     case SNDCTL_SYNTH_MEMAVL:
151         return 0x7fffffff;
152         break;
153
154     case SNDCTL_FM_4OP_ENABLE:
155         if (devc->model == 2)
156             enter_4op_mode();
157         return 0;
158         break;
159
160     default:
161         return -(EINVAL);
162     }
163
164 }
165
166 int
167 opl3_detect(int ioaddr, sound_os_info * osp)
168 {
169     /*
170      * This function returns 1 if the FM chip is present at the given
171      * I/O port The detection algorithm plays with the timer built in the
172      * FM chip and looks for a change in the status register.
173      * 
174      * Note! The timers of the FM chip are not connected to AdLib (and
175      * compatible) boards.
176      * 
177      * Note2! The chip is initialized if detected.
178      */
179
180     u_char   stat1, stat2, signature;
181     int             i;
182
183     if (devc != NULL)
184         return 0;
185
186     devc = (struct opl_devinfo *) malloc(sizeof(*devc), M_DEVBUF, M_NOWAIT);
187     if (!devc)
188         panic("SOUND: Cannot allocate memory\n");
189
190     if (devc == NULL) {
191         printf("OPL3: Can't allocate memory for device control structure\n");
192         return 0;
193     }
194     devc->osp = osp;
195
196     /* Reset timers 1 and 2 */
197     opl3_command(ioaddr, TIMER_CONTROL_REGISTER, TIMER1_MASK | TIMER2_MASK);
198
199     /* Reset the IRQ of the FM chip */
200     opl3_command(ioaddr, TIMER_CONTROL_REGISTER, IRQ_RESET);
201
202     signature = stat1 = inb(ioaddr);    /* Status register */
203
204     if ((stat1 & 0xE0) != 0x00) {
205         return 0;       /* Should be 0x00 */
206     }
207     opl3_command(ioaddr, TIMER1_REGISTER, 0xff);        /* Set timer1 to 0xff */
208
209     opl3_command(ioaddr, TIMER_CONTROL_REGISTER,
210                  TIMER2_MASK | TIMER1_START);   /* Unmask and start timer 1 */
211
212
213     DELAY(150);          /* Now we have to delay at least 80 usec */
214
215     stat2 = inb(ioaddr);        /* Read status after timers have expired */
216
217     /*
218      * Stop the timers
219      */
220
221     /* Reset timers 1 and 2 */
222     opl3_command(ioaddr, TIMER_CONTROL_REGISTER, TIMER1_MASK | TIMER2_MASK);
223     /* Reset the IRQ of the FM chip */
224     opl3_command(ioaddr, TIMER_CONTROL_REGISTER, IRQ_RESET);
225
226     if ((stat2 & 0xE0) != 0xc0) {
227         return 0;       /* There is no YM3812 */
228     }
229     /*
230      * There is a FM chicp in this address. Detect the type (OPL2 to
231      * OPL4)
232      */
233
234     if (signature == 0x06) {/* OPL2 */
235         detected_model = 2;
236     } else if (signature == 0x00) {     /* OPL3 or OPL4 */
237         u_char   tmp;
238
239         detected_model = 3;
240
241         /*
242          * Detect availability of OPL4 (_experimental_). Works
243          * propably only after a cold boot. In addition the OPL4 port
244          * of the chip may not be connected to the PC bus at all.
245          */
246
247         opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0x00);
248         opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, OPL3_ENABLE | OPL4_ENABLE);
249
250         if ((tmp = inb(ioaddr)) == 0x02) {      /* Have a OPL4 */
251             detected_model = 4;
252         }
253         if (!0) { /* OPL4 port is free */ /* XXX check here lr970711 */
254             int  tmp;
255
256             outb(ioaddr - 8, 0x02);     /* Select OPL4 ID register */
257             DELAY(10);
258             tmp = inb(ioaddr - 7);      /* Read it */
259             DELAY(10);
260
261             if (tmp == 0x20) {  /* OPL4 should return 0x20 here */
262                 detected_model = 4;
263
264                 outb(ioaddr - 8, 0xF8); /* Select OPL4 FM mixer control */
265                 DELAY(10);
266                 outb(ioaddr - 7, 0x1B); /* Write value */
267                 DELAY(10);
268             } else
269                 detected_model = 3;
270         }
271         opl3_command(ioaddr + 2, OPL3_MODE_REGISTER, 0);
272
273     }
274     for (i = 0; i < 9; i++)
275         opl3_command(ioaddr, KEYON_BLOCK + i, 0);       /* Note off */
276
277     opl3_command(ioaddr, TEST_REGISTER, ENABLE_WAVE_SELECT);
278     opl3_command(ioaddr, PERCUSSION_REGISTER, 0x00);    /* Melodic mode. */
279
280     return 1;
281 }
282
283 static int
284 opl3_kill_note(int dev, int voice, int note, int velocity)
285 {
286     struct physical_voice_info *map;
287
288     if (voice < 0 || voice >= devc->nr_voice)
289         return 0;
290
291     devc->v_alloc->map[voice] = 0;
292
293     map = &pv_map[devc->lv_map[voice]];
294
295     DEB(printf("Kill note %d\n", voice));
296
297     if (map->voice_mode == 0)
298         return 0;
299
300     opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num,
301                 devc->voc[voice].keyon_byte & ~0x20);
302
303     devc->voc[voice].keyon_byte = 0;
304     devc->voc[voice].bender = 0;
305     devc->voc[voice].volume = 64;
306     devc->voc[voice].bender_range = 200;        /* 200 cents = 2 semitones */
307     devc->voc[voice].orig_freq = 0;
308     devc->voc[voice].current_freq = 0;
309     devc->voc[voice].mode = 0;
310
311     return 0;
312 }
313
314 #define HIHAT                   0
315 #define CYMBAL                  1
316 #define TOMTOM                  2
317 #define SNARE                   3
318 #define BDRUM                   4
319 #define UNDEFINED               TOMTOM
320 #define DEFAULT                 TOMTOM
321
322 static int
323 store_instr(int instr_no, struct sbi_instrument * instr)
324 {
325
326     if (instr->key !=FM_PATCH && (instr->key !=OPL3_PATCH || devc->model != 2))
327         printf("FM warning: Invalid patch format field (key) 0x%x\n",
328                         instr->key);
329     bcopy((char *) instr, (char *) &(devc->i_map[instr_no]), sizeof(*instr));
330
331     return 0;
332 }
333
334 static int
335 opl3_set_instr(int dev, int voice, int instr_no)
336 {
337     if (voice < 0 || voice >= devc->nr_voice)
338         return 0;
339
340     if (instr_no < 0 || instr_no >= SBFM_MAXINSTR)
341         return 0;
342
343     devc->act_i[voice] = &devc->i_map[instr_no];
344     return 0;
345 }
346
347 /*
348  * The next table looks magical, but it certainly is not. Its values have
349  * been calculated as table[i]=8*log(i/64)/log(2) with an obvious exception
350  * for i=0. This log-table converts a linear volume-scaling (0..127) to a
351  * logarithmic scaling as present in the FM-synthesizer chips. so :    Volume
352  * 64 =  0 db = relative volume  0 and:    Volume 32 = -6 db = relative
353  * volume -8 it was implemented as a table because it is only 128 bytes and
354  * it saves a lot of log() calculations. (RH)
355  */
356 static char         fm_volume_table[128] =
357 {
358         -64, -48, -40, -35, -32, -29, -27, -26,
359         -24, -23, -21, -20, -19, -18, -18, -17,
360         -16, -15, -15, -14, -13, -13, -12, -12,
361         -11, -11, -10, -10, -10, -9, -9, -8,
362         -8, -8, -7, -7, -7, -6, -6, -6,
363         -5, -5, -5, -5, -4, -4, -4, -4,
364         -3, -3, -3, -3, -2, -2, -2, -2,
365         -2, -1, -1, -1, -1, 0, 0, 0,
366         0, 0, 0, 1, 1, 1, 1, 1,
367         1, 2, 2, 2, 2, 2, 2, 2,
368         3, 3, 3, 3, 3, 3, 3, 4,
369         4, 4, 4, 4, 4, 4, 4, 5,
370         5, 5, 5, 5, 5, 5, 5, 5,
371         6, 6, 6, 6, 6, 6, 6, 6,
372         6, 7, 7, 7, 7, 7, 7, 7,
373         7, 7, 7, 8, 8, 8, 8, 8};
374
375 static void
376 calc_vol(u_char *regbyte, int volume, int main_vol)
377 {
378     int             level = (~*regbyte & 0x3f);
379
380     if (main_vol > 127)
381         main_vol = 127;
382
383     volume = (volume * main_vol) / 127;
384
385     if (level)
386         level += fm_volume_table[volume];
387
388     RANGE (level, 0, 0x3f );
389
390     *regbyte = (*regbyte & 0xc0) | (~level & 0x3f);
391 }
392
393 static void
394 set_voice_volume(int voice, int volume, int main_vol)
395 {
396     u_char   vol1, vol2, vol3, vol4;
397     struct sbi_instrument *instr;
398     struct physical_voice_info *map;
399
400     if (voice < 0 || voice >= devc->nr_voice)
401         return;
402
403     map = &pv_map[devc->lv_map[voice]];
404
405     instr = devc->act_i[voice];
406
407     if (!instr)
408         instr = &devc->i_map[0];
409
410     if (instr->channel < 0)
411         return;
412
413     if (devc->voc[voice].mode == 0)
414         return;
415
416     if (devc->voc[voice].mode == 2) {
417
418         vol1 = instr->operators[2];
419         vol2 = instr->operators[3];
420
421         if ((instr->operators[10] & 0x01)) {
422             calc_vol(&vol1, volume, main_vol);
423         }
424         calc_vol(&vol2, volume, main_vol);
425
426         opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
427         opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
428     } else {            /* 4 OP voice */
429         int             connection;
430
431         vol1 = instr->operators[2];
432         vol2 = instr->operators[3];
433         vol3 = instr->operators[OFFS_4OP + 2];
434         vol4 = instr->operators[OFFS_4OP + 3];
435
436         /*
437          * The connection method for 4 OP devc->voc is defined by the
438          * rightmost bits at the offsets 10 and 10+OFFS_4OP
439          */
440
441         connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
442
443         switch (connection) {
444         case 0:
445             calc_vol(&vol4, volume, main_vol);
446             break;
447
448         case 1:
449             calc_vol(&vol2, volume, main_vol);
450             calc_vol(&vol4, volume, main_vol);
451             break;
452
453         case 2:
454             calc_vol(&vol1, volume, main_vol);
455             calc_vol(&vol4, volume, main_vol);
456             break;
457
458         case 3:
459             calc_vol(&vol1, volume, main_vol);
460             calc_vol(&vol3, volume, main_vol);
461             calc_vol(&vol4, volume, main_vol);
462             break;
463
464         default:;
465         }
466
467         opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], vol1);
468         opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], vol2);
469         opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], vol3);
470         opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], vol4);
471     }
472 }
473
474 static int
475 opl3_start_note(int dev, int voice, int note, int volume)
476 {
477     u_char   data, fpc;
478     int             block, fnum, freq, voice_mode;
479     struct sbi_instrument *instr;
480     struct physical_voice_info *map;
481
482     if (voice < 0 || voice >= devc->nr_voice)
483         return 0;
484
485     map = &pv_map[devc->lv_map[voice]];
486
487     if (map->voice_mode == 0)
488         return 0;
489
490     if (note == 255) {  /* Just change the volume */
491         set_voice_volume(voice, volume, devc->voc[voice].volume);
492         return 0;
493     }
494     /*
495      * Kill previous note before playing
496      */
497     opl3_command(map->ioaddr, KSL_LEVEL + map->op[1], 0xff);    /* Carrier volume to min */
498     opl3_command(map->ioaddr, KSL_LEVEL + map->op[0], 0xff);    /* Modulator volume to */
499
500     if (map->voice_mode == 4) {
501         opl3_command(map->ioaddr, KSL_LEVEL + map->op[2], 0xff);
502         opl3_command(map->ioaddr, KSL_LEVEL + map->op[3], 0xff);
503     }
504     opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, 0x00);      /* Note off */
505
506     instr = devc->act_i[voice];
507
508     if (!instr)
509         instr = &devc->i_map[0];
510
511     if (instr->channel < 0) {
512         printf( "OPL3: Initializing voice %d with undefined instrument\n",
513                voice);
514         return 0;
515     }
516     if (map->voice_mode == 2 && instr->key == OPL3_PATCH)
517         return 0;       /* Cannot play */
518
519     voice_mode = map->voice_mode;
520
521     if (voice_mode == 4) {
522         int             voice_shift;
523
524         voice_shift = (map->ioaddr == devc->left_io) ? 0 : 3;
525         voice_shift += map->voice_num;
526
527         if (instr->key != OPL3_PATCH) { /* Just 2 OP patch */
528             voice_mode = 2;
529             devc->cmask &= ~(1 << voice_shift);
530         } else
531             devc->cmask |= (1 << voice_shift);
532
533         opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
534     }
535     /*
536      * Set Sound Characteristics
537      */
538     opl3_command(map->ioaddr, AM_VIB + map->op[0], instr->operators[0]);
539     opl3_command(map->ioaddr, AM_VIB + map->op[1], instr->operators[1]);
540
541     /*
542      * Set Attack/Decay
543      */
544     opl3_command(map->ioaddr, ATTACK_DECAY + map->op[0], instr->operators[4]);
545     opl3_command(map->ioaddr, ATTACK_DECAY + map->op[1], instr->operators[5]);
546
547     /*
548      * Set Sustain/Release
549      */
550     opl3_command(map->ioaddr,SUSTAIN_RELEASE + map->op[0], instr->operators[6]);
551     opl3_command(map->ioaddr,SUSTAIN_RELEASE + map->op[1], instr->operators[7]);
552
553     /*
554      * Set Wave Select
555      */
556     opl3_command(map->ioaddr, WAVE_SELECT + map->op[0], instr->operators[8]);
557     opl3_command(map->ioaddr, WAVE_SELECT + map->op[1], instr->operators[9]);
558
559     /*
560      * Set Feedback/Connection
561      */
562     fpc = instr->operators[10];
563     if (!(fpc & 0x30))
564         fpc |= 0x30;    /* Ensure that at least one chn is enabled */
565     opl3_command(map->ioaddr, FEEDBACK_CONNECTION + map->voice_num, fpc);
566
567     /*
568      * If the voice is a 4 OP one, initialize the operators 3 and 4 also
569      */
570
571     if (voice_mode == 4) {
572
573         /*
574          * Set Sound Characteristics
575          */
576         opl3_command(map->ioaddr, AM_VIB + map->op[2],
577                         instr->operators[OFFS_4OP + 0]);
578         opl3_command(map->ioaddr, AM_VIB + map->op[3],
579                         instr->operators[OFFS_4OP + 1]);
580
581         /*
582          * Set Attack/Decay
583          */
584         opl3_command(map->ioaddr, ATTACK_DECAY + map->op[2],
585                         instr->operators[OFFS_4OP + 4]);
586         opl3_command(map->ioaddr, ATTACK_DECAY + map->op[3],
587                         instr->operators[OFFS_4OP + 5]);
588
589         /*
590          * Set Sustain/Release
591          */
592         opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[2],
593                         instr->operators[OFFS_4OP + 6]);
594         opl3_command(map->ioaddr, SUSTAIN_RELEASE + map->op[3],
595                         instr->operators[OFFS_4OP + 7]);
596
597         /*
598          * Set Wave Select
599          */
600         opl3_command(map->ioaddr, WAVE_SELECT + map->op[2],
601                         instr->operators[OFFS_4OP + 8]);
602         opl3_command(map->ioaddr, WAVE_SELECT + map->op[3],
603                         instr->operators[OFFS_4OP + 9]);
604
605         /*
606          * Set Feedback/Connection
607          */
608         fpc = instr->operators[OFFS_4OP + 10];
609         if (!(fpc & 0x30))
610             fpc |= 0x30;        /* Ensure that at least one chn is enabled */
611         opl3_command(map->ioaddr,FEEDBACK_CONNECTION + map->voice_num + 3, fpc);
612     }
613     devc->voc[voice].mode = voice_mode;
614
615     set_voice_volume(voice, volume, devc->voc[voice].volume);
616
617     freq = devc->voc[voice].orig_freq = note_to_freq(note) / 1000;
618
619     /*
620      * Since the pitch bender may have been set before playing the note,
621      * we have to calculate the bending now.
622      */
623
624     freq = compute_finetune(devc->voc[voice].orig_freq,
625                 devc->voc[voice].bender, devc->voc[voice].bender_range);
626     devc->voc[voice].current_freq = freq;
627
628     freq_to_fnum(freq, &block, &fnum);
629
630     /*
631      * Play note
632      */
633
634     data = fnum & 0xff; /* Least significant bits of fnumber */
635     opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
636
637     data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
638     devc->voc[voice].keyon_byte = data;
639     opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
640     if (voice_mode == 4)
641         opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num + 3, data);
642
643     return 0;
644 }
645
646 static void
647 freq_to_fnum(int freq, int *block, int *fnum)
648 {
649     int             f, octave;
650
651     /*
652      * Converts the note frequency to block and fnum values for the FM
653      * chip
654      */
655     /*
656      * First try to compute the block -value (octave) where the note
657      * belongs
658      */
659
660     f = freq;
661
662     octave = 5;
663
664     if (f == 0)
665         octave = 0;
666     else if (f < 261) {
667         while (f < 261) {
668             octave--;
669             f <<= 1;
670         }
671     } else if (f > 493) {
672         while (f > 493) {
673             octave++;
674             f >>= 1;
675         }
676     }
677     if (octave > 7)
678         octave = 7;
679
680     *fnum = freq * (1 << (20 - octave)) / 49716;
681     *block = octave;
682 }
683
684 static void
685 opl3_command(int io_addr, u_int addr, u_int val)
686 {
687     int             i;
688
689     /*
690      * The original 2-OP synth requires a quite long delay after writing
691      * to a register. The OPL-3 survives with just two INBs
692      */
693
694     outb(io_addr, (u_char) (addr & 0xff));
695
696     if (!devc->model != 2)
697         DELAY(10);
698     else
699         for (i = 0; i < 2; i++)
700             inb(io_addr);
701
702 #ifdef PC98
703     outb(io_addr + 0x100, (u_char) (val & 0xff));
704 #else
705     outb(io_addr + 1, (u_char) (val & 0xff));
706 #endif
707     if (devc->model != 2)
708         DELAY(30);
709     else
710         for (i = 0; i < 2; i++)
711             inb(io_addr);
712 }
713
714 static void
715 opl3_reset(int dev)
716 {
717     int             i;
718
719     for (i = 0; i < 18; i++)
720         devc->lv_map[i] = i;
721
722     for (i = 0; i < devc->nr_voice; i++) {
723         opl3_command(pv_map[devc->lv_map[i]].ioaddr,
724                KSL_LEVEL + pv_map[devc->lv_map[i]].op[0], 0xff);
725
726         opl3_command(pv_map[devc->lv_map[i]].ioaddr,
727                KSL_LEVEL + pv_map[devc->lv_map[i]].op[1], 0xff);
728
729         if (pv_map[devc->lv_map[i]].voice_mode == 4) {
730             opl3_command(pv_map[devc->lv_map[i]].ioaddr,
731                    KSL_LEVEL + pv_map[devc->lv_map[i]].op[2], 0xff);
732
733             opl3_command(pv_map[devc->lv_map[i]].ioaddr,
734                    KSL_LEVEL + pv_map[devc->lv_map[i]].op[3], 0xff);
735         }
736         opl3_kill_note(dev, i, 0, 64);
737     }
738
739     if (devc->model == 2) {
740         devc->v_alloc->max_voice = devc->nr_voice = 18;
741
742         for (i = 0; i < 18; i++)
743             pv_map[i].voice_mode = 2;
744
745     }
746 }
747
748 static int
749 opl3_open(int dev, int mode)
750 {
751     int             i;
752
753     if (devc->busy)
754         return -(EBUSY);
755     devc->busy = 1;
756
757     devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
758     devc->v_alloc->timestamp = 0;
759
760     for (i = 0; i < 18; i++) {
761         devc->v_alloc->map[i] = 0;
762         devc->v_alloc->alloc_times[i] = 0;
763     }
764
765     devc->cmask = 0x00; /* Just 2 OP mode */
766     if (devc->model == 2)
767         opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, devc->cmask);
768     return 0;
769 }
770
771 static void
772 opl3_close(int dev)
773 {
774     devc->busy = 0;
775     devc->v_alloc->max_voice = devc->nr_voice = (devc->model == 2) ? 18 : 9;
776
777     devc->fm_info.nr_drums = 0;
778     devc->fm_info.perc_mode = 0;
779
780     opl3_reset(dev);
781 }
782
783 static void
784 opl3_hw_control(int dev, u_char *event)
785 {
786 }
787
788 static int
789 opl3_load_patch(int dev, int format, snd_rw_buf * addr,
790                 int offs, int count, int pmgr_flag)
791 {
792     struct sbi_instrument ins;
793
794     if (count < sizeof(ins)) {
795         printf("FM Error: Patch record too short\n");
796         return -(EINVAL);
797     }
798     if (uiomove(&((char *) &ins)[offs], sizeof(ins) - offs, addr)) {
799         printf("sb: Bad copyin()!\n");
800     };
801
802     if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) {
803         printf("FM Error: Invalid instrument number %d\n", ins.channel);
804         return -(EINVAL);
805     }
806     ins.key = format;
807
808     return store_instr(ins.channel, &ins);
809 }
810
811 static void
812 opl3_panning(int dev, int voice, int pressure)
813 {
814 }
815
816 static void
817 opl3_volume_method(int dev, int mode)
818 {
819 }
820
821 #define SET_VIBRATO(cell) { \
822       tmp = instr->operators[(cell-1)+(((cell-1)/2)*OFFS_4OP)]; \
823       if (pressure > 110) \
824         tmp |= 0x40;            /* Vibrato on */ \
825       opl3_command (map->ioaddr, AM_VIB + map->op[cell-1], tmp);}
826
827 static void
828 opl3_aftertouch(int dev, int voice, int pressure)
829 {
830     int             tmp;
831     struct sbi_instrument *instr;
832     struct physical_voice_info *map;
833
834     if (voice < 0 || voice >= devc->nr_voice)
835         return;
836
837     map = &pv_map[devc->lv_map[voice]];
838
839     DEB(printf("Aftertouch %d\n", voice));
840
841     if (map->voice_mode == 0)
842         return;
843
844     /*
845      * Adjust the amount of vibrato depending the pressure
846      */
847
848     instr = devc->act_i[voice];
849
850     if (!instr)
851         instr = &devc->i_map[0];
852
853     if (devc->voc[voice].mode == 4) {
854         int             connection = ((instr->operators[10] & 0x01) << 1) | (instr->operators[10 + OFFS_4OP] & 0x01);
855
856         switch (connection) {
857         case 0:
858             SET_VIBRATO(4);
859             break;
860
861         case 1:
862             SET_VIBRATO(2);
863             SET_VIBRATO(4);
864             break;
865
866         case 2:
867             SET_VIBRATO(1);
868             SET_VIBRATO(4);
869             break;
870
871         case 3:
872             SET_VIBRATO(1);
873             SET_VIBRATO(3);
874             SET_VIBRATO(4);
875             break;
876
877         }
878         /*
879          * Not implemented yet
880          */
881     } else {
882         SET_VIBRATO(1);
883
884         if ((instr->operators[10] & 0x01))      /* Additive synthesis */
885             SET_VIBRATO(2);
886     }
887 }
888
889 #undef SET_VIBRATO
890
891 static void
892 bend_pitch(int dev, int voice, int value)
893 {
894     u_char   data;
895     int             block, fnum, freq;
896     struct physical_voice_info *map;
897
898     map = &pv_map[devc->lv_map[voice]];
899
900     if (map->voice_mode == 0)
901         return;
902
903     devc->voc[voice].bender = value;
904     if (!value)
905         return;
906     if (!(devc->voc[voice].keyon_byte & 0x20))
907         return;         /* Not keyed on */
908
909     freq = compute_finetune(devc->voc[voice].orig_freq, devc->voc[voice].bender, devc->voc[voice].bender_range);
910     devc->voc[voice].current_freq = freq;
911
912     freq_to_fnum(freq, &block, &fnum);
913
914     data = fnum & 0xff; /* Least significant bits of fnumber */
915     opl3_command(map->ioaddr, FNUM_LOW + map->voice_num, data);
916
917     data = 0x20 | ((block & 0x7) << 2) | ((fnum >> 8) & 0x3);
918         /* KEYON|OCTAVE|MS  bits of f-num */
919     devc->voc[voice].keyon_byte = data;
920     opl3_command(map->ioaddr, KEYON_BLOCK + map->voice_num, data);
921 }
922
923 static void
924 opl3_controller(int dev, int voice, int ctrl_num, int value)
925 {
926     if (voice < 0 || voice >= devc->nr_voice)
927         return;
928
929     switch (ctrl_num) {
930     case CTRL_PITCH_BENDER:
931         bend_pitch(dev, voice, value);
932         break;
933
934     case CTRL_PITCH_BENDER_RANGE:
935         devc->voc[voice].bender_range = value;
936         break;
937
938     case CTL_MAIN_VOLUME:
939         devc->voc[voice].volume = value / 128;
940         break;
941     }
942 }
943
944 static int
945 opl3_patchmgr(int dev, struct patmgr_info * rec)
946 {
947     return -(EINVAL);
948 }
949
950 static void
951 opl3_bender(int dev, int voice, int value)
952 {
953     if (voice < 0 || voice >= devc->nr_voice)
954         return;
955
956     bend_pitch(dev, voice, value - 8192);
957 }
958
959 static int
960 opl3_alloc_voice(int dev, int chn, int note, struct voice_alloc_info * alloc)
961 {
962     int             i, p, best, first, avail, best_time = 0x7fffffff;
963     struct sbi_instrument *instr;
964     int             is4op;
965     int             instr_no;
966
967     if (chn < 0 || chn > 15)
968         instr_no = 0;
969     else
970         instr_no = devc->chn_info[chn].pgm_num;
971
972     instr = &devc->i_map[instr_no];
973     if (instr->channel < 0 ||   /* Instrument not loaded */
974             devc->nr_voice != 12)       /* Not in 4 OP mode */
975         is4op = 0;
976     else if (devc->nr_voice == 12)      /* 4 OP mode */
977         is4op = (instr->key == OPL3_PATCH);
978     else
979         is4op = 0;
980
981     if (is4op) {
982         first = p = 0;
983         avail = 6;
984     } else {
985         if (devc->nr_voice == 12)       /* 4 OP mode. Use the '2 OP
986                                          * only' operators first */
987             first = p = 6;
988         else
989             first = p = 0;
990         avail = devc->nr_voice;
991     }
992
993     /*
994      * Now try to find a free voice
995      */
996     best = first;
997
998     for (i = 0; i < avail; i++) {
999         if (alloc->map[p] == 0) {
1000             return p;
1001         }
1002         if (alloc->alloc_times[p] < best_time) { /* Find oldest playing note */
1003             best_time = alloc->alloc_times[p];
1004             best = p;
1005         }
1006         p = (p + 1) % avail;
1007     }
1008
1009     /*
1010      * Insert some kind of priority mechanism here.
1011      */
1012
1013     if (best < 0)
1014         best = 0;
1015     if (best > devc->nr_voice)
1016         best -= devc->nr_voice;
1017
1018     return best;                /* All devc->voc in use. Select the first
1019                                  * one. */
1020 }
1021
1022 static void
1023 opl3_setup_voice(int dev, int voice, int chn)
1024 {
1025     struct channel_info *info =
1026         &synth_devs[dev]->chn_info[chn];
1027
1028     opl3_set_instr(dev, voice, info->pgm_num);
1029
1030     devc->voc[voice].bender = info->bender_value;
1031     devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];
1032 }
1033
1034 static struct synth_operations opl3_operations =
1035 {
1036         NULL,
1037         0,
1038         SYNTH_TYPE_FM,
1039         FM_TYPE_ADLIB,
1040         opl3_open,
1041         opl3_close,
1042         opl3_ioctl,
1043         opl3_kill_note,
1044         opl3_start_note,
1045         opl3_set_instr,
1046         opl3_reset,
1047         opl3_hw_control,
1048         opl3_load_patch,
1049         opl3_aftertouch,
1050         opl3_controller,
1051         opl3_panning,
1052         opl3_volume_method,
1053         opl3_patchmgr,
1054         opl3_bender,
1055         opl3_alloc_voice,
1056         opl3_setup_voice
1057 };
1058
1059 void
1060 opl3_init(int ioaddr, sound_os_info * osp)
1061 {
1062     int             i;
1063
1064     if (num_synths >= MAX_SYNTH_DEV) {
1065         printf("OPL3 Error: Too many synthesizers\n");
1066         return ;
1067     }
1068     if (devc == NULL) {
1069         printf("OPL3: Device control structure not initialized.\n");
1070         return ;
1071     }
1072     bzero((char *) devc, sizeof(*devc));
1073     devc->osp = osp;
1074
1075     devc->nr_voice = 9;
1076     strcpy(devc->fm_info.name, "OPL2-");
1077
1078     devc->fm_info.device = 0;
1079     devc->fm_info.synth_type = SYNTH_TYPE_FM;
1080     devc->fm_info.synth_subtype = FM_TYPE_ADLIB;
1081     devc->fm_info.perc_mode = 0;
1082     devc->fm_info.nr_voices = 9;
1083     devc->fm_info.nr_drums = 0;
1084     devc->fm_info.instr_bank_size = SBFM_MAXINSTR;
1085     devc->fm_info.capabilities = 0;
1086     devc->left_io = ioaddr;
1087     devc->right_io = ioaddr + 2;
1088
1089     if (detected_model <= 2)
1090         devc->model = 1;
1091     else {
1092         devc->model = 2;
1093         if (detected_model == 4)
1094             devc->is_opl4 = 1;
1095     }
1096
1097     opl3_operations.info = &devc->fm_info;
1098
1099     synth_devs[num_synths++] = &opl3_operations;
1100     devc->v_alloc = &opl3_operations.alloc;
1101     devc->chn_info = &opl3_operations.chn_info[0];
1102
1103     if (devc->model == 2) {
1104         if (devc->is_opl4)
1105             conf_printf2("Yamaha OPL4/OPL3 FM", ioaddr, 0, -1, -1);
1106         else
1107             conf_printf2("Yamaha OPL3 FM", ioaddr, 0, -1, -1);
1108
1109         devc->v_alloc->max_voice = devc->nr_voice = 18;
1110         devc->fm_info.nr_drums = 0;
1111         devc->fm_info.capabilities |= SYNTH_CAP_OPL3;
1112         strcpy(devc->fm_info.name, "Yamaha OPL-3");
1113
1114         for (i = 0; i < 18; i++)
1115             if (pv_map[i].ioaddr == USE_LEFT)
1116                 pv_map[i].ioaddr = devc->left_io;
1117             else
1118                 pv_map[i].ioaddr = devc->right_io;
1119
1120             opl3_command(devc->right_io, OPL3_MODE_REGISTER, OPL3_ENABLE);
1121             opl3_command(devc->right_io, CONNECTION_SELECT_REGISTER, 0x00);
1122     } else {
1123         conf_printf2("Yamaha OPL2 FM", ioaddr, 0, -1, -1);
1124         devc->v_alloc->max_voice = devc->nr_voice = 9;
1125         devc->fm_info.nr_drums = 0;
1126
1127         for (i = 0; i < 18; i++)
1128             pv_map[i].ioaddr = devc->left_io;
1129     };
1130
1131     for (i = 0; i < SBFM_MAXINSTR; i++)
1132         devc->i_map[i].channel = -1;
1133
1134     return ;
1135 }
1136
1137 #endif