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