midisyn.c revision 1.17.2.16 1 /* $NetBSD: midisyn.c,v 1.17.2.16 2006/06/09 04:20:02 chap Exp $ */
2
3 /*
4 * Copyright (c) 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Lennart Augustsson (augustss (at) NetBSD.org).
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: midisyn.c,v 1.17.2.16 2006/06/09 04:20:02 chap Exp $");
41
42 #include <sys/param.h>
43 #include <sys/ioctl.h>
44 #include <sys/fcntl.h>
45 #include <sys/vnode.h>
46 #include <sys/select.h>
47 #include <sys/proc.h>
48 #include <sys/malloc.h>
49 #include <sys/systm.h>
50 #include <sys/syslog.h>
51 #include <sys/kernel.h>
52 #include <sys/audioio.h>
53 #include <sys/midiio.h>
54 #include <sys/device.h>
55
56 #include <dev/audio_if.h>
57 #include <dev/midi_if.h>
58 #include <dev/midivar.h>
59 #include <dev/midisynvar.h>
60
61 #ifdef AUDIO_DEBUG
62 #define DPRINTF(x) if (midisyndebug) printf x
63 #define DPRINTFN(n,x) if (midisyndebug >= (n)) printf x
64 int midisyndebug = 0;
65 #else
66 #define DPRINTF(x)
67 #define DPRINTFN(n,x)
68 #endif
69
70 int midisyn_findvoice(midisyn *, int, int);
71 void midisyn_freevoice(midisyn *, int);
72 uint_fast16_t midisyn_allocvoice(midisyn *, uint_fast8_t, uint_fast8_t);
73 static void midisyn_attackv_vel(midisyn *, uint_fast16_t, uint32_t,
74 int16_t, uint_fast8_t);
75 u_int32_t midisyn_note_to_freq(int);
76 u_int32_t midisyn_finetune(u_int32_t, int, int, int);
77 static int16_t midisyn_adj_level(midisyn *, uint_fast8_t);
78 static uint32_t midisyn_adj_pitch(midisyn *, uint_fast8_t);
79
80 static midictl_notify midisyn_notify;
81
82 int midisyn_open(void *, int,
83 void (*iintr)(void *, int),
84 void (*ointr)(void *), void *arg);
85 void midisyn_close(void *);
86 int midisyn_sysrt(void *, int);
87 void midisyn_getinfo(void *, struct midi_info *);
88 int midisyn_ioctl(void *, u_long, caddr_t, int, struct lwp *);
89
90 const struct midi_hw_if midisyn_hw_if = {
91 midisyn_open,
92 midisyn_close,
93 midisyn_sysrt,
94 midisyn_getinfo,
95 midisyn_ioctl,
96 };
97
98 int midisyn_channelmsg(void *, int, int, u_char *, int);
99 int midisyn_commonmsg(void *, int, u_char *, int);
100 int midisyn_sysex(void *, u_char *, int);
101
102 struct midi_hw_if_ext midisyn_hw_if_ext = {
103 .channel = midisyn_channelmsg,
104 .common = midisyn_commonmsg,
105 .sysex = midisyn_sysex,
106 };
107
108 int
109 midisyn_open(void *addr, int flags, void (*iintr)(void *, int),
110 void (*ointr)(void *), void *arg)
111 {
112 midisyn *ms = addr;
113 int rslt;
114 uint_fast8_t chan;
115
116 DPRINTF(("midisyn_open: ms=%p ms->mets=%p\n", ms, ms->mets));
117
118 midictl_open(&ms->ctl);
119
120 rslt = 0;
121 if (ms->mets->open)
122 rslt = (ms->mets->open(ms, flags));
123
124 /*
125 * Make the right initial things happen by faking receipt of RESET on
126 * all channels. The hw driver's ctlnotice() will be called in turn.
127 */
128 for ( chan = 0 ; chan < MIDI_MAX_CHANS ; ++ chan )
129 midisyn_notify(ms, MIDICTL_RESET, chan, 0);
130
131 return rslt;
132 }
133
134 void
135 midisyn_close(void *addr)
136 {
137 midisyn *ms = addr;
138 struct midisyn_methods *fs;
139 int v;
140
141 DPRINTF(("midisyn_close: ms=%p ms->mets=%p\n", ms, ms->mets));
142 fs = ms->mets;
143 /* TODO
144 * This loop is much like what midisyn_notify should do for NOTES_OFF
145 * or SOUND_OFF. It should be moved there, and here we should call
146 * notify faking one of those events.
147 */
148 for (v = 0; v < ms->nvoice; v++)
149 if (ms->voices[v].inuse) {
150 fs->releasev(ms, v, 127);
151 midisyn_freevoice(ms, v);
152 }
153 if (fs->close)
154 fs->close(ms);
155
156 midictl_close(&ms->ctl);
157 }
158
159 void
160 midisyn_getinfo(void *addr, struct midi_info *mi)
161 {
162 midisyn *ms = addr;
163
164 mi->name = ms->name;
165 /*
166 * I was going to add a property here to suppress midi(4)'s warning
167 * about an output device that uses no transmit interrupt, on the
168 * assumption that as an onboard synth we handle "output" internally
169 * with nothing like the 320 us per byte busy wait of a dumb UART.
170 * Then I noticed that opl (at least as currently implemented) seems
171 * to need 40 us busy wait to set each register on an OPL2, and sets
172 * about 21 registers for every note-on. (Half of that is patch loading
173 * and could probably be reduced by different management of voices and
174 * patches.) For now I won't bother suppressing that warning....
175 */
176 mi->props = 0;
177
178 midi_register_hw_if_ext(&midisyn_hw_if_ext);
179 }
180
181 int
182 midisyn_ioctl(void *maddr, u_long cmd, caddr_t addr, int flag, struct lwp *l)
183 {
184 midisyn *ms = maddr;
185
186 if (ms->mets->ioctl)
187 return (ms->mets->ioctl(ms, cmd, addr, flag, l));
188 else
189 return (EINVAL);
190 }
191
192 int
193 midisyn_findvoice(midisyn *ms, int chan, int note)
194 {
195 u_int cn;
196 int v;
197
198 cn = MS_CHANNOTE(chan, note);
199 for (v = 0; v < ms->nvoice; v++)
200 if (ms->voices[v].chan_note == cn && ms->voices[v].inuse)
201 return (v);
202 return (-1);
203 }
204
205 void
206 midisyn_attach(struct midi_softc *sc, midisyn *ms)
207 {
208 if (ms->mets->allocv == 0) {
209 ms->voices = malloc(ms->nvoice * sizeof (struct voice),
210 M_DEVBUF, M_WAITOK|M_ZERO);
211 ms->seqno = 1;
212 ms->mets->allocv = midisyn_allocvoice;
213 }
214
215 if (ms->mets->attackv_vel == 0 && ms->mets->attackv != 0)
216 ms->mets->attackv_vel = midisyn_attackv_vel;
217
218 ms->ctl = (midictl) {
219 .base_channel = 16,
220 .cookie = ms,
221 .notify = midisyn_notify
222 };
223
224 sc->hw_if = &midisyn_hw_if;
225 sc->hw_hdl = ms;
226 DPRINTF(("midisyn_attach: ms=%p\n", sc->hw_hdl));
227 }
228
229 void
230 midisyn_freevoice(midisyn *ms, int voice)
231 {
232 if (ms->mets->allocv != midisyn_allocvoice)
233 return;
234 ms->voices[voice].inuse = 0;
235 }
236
237 uint_fast16_t
238 midisyn_allocvoice(midisyn *ms, uint_fast8_t chan, uint_fast8_t note)
239 {
240 int bestv, v;
241 u_int bestseq, s;
242
243 /* Find a free voice, or if no free voice is found the oldest. */
244 bestv = 0;
245 bestseq = ms->voices[0].seqno + (ms->voices[0].inuse ? 0x40000000 : 0);
246 for (v = 1; v < ms->nvoice; v++) {
247 s = ms->voices[v].seqno;
248 if (ms->voices[v].inuse)
249 s += 0x40000000;
250 if (s < bestseq) {
251 bestseq = s;
252 bestv = v;
253 }
254 }
255 DPRINTFN(10,("midisyn_allocvoice: v=%d seq=%d cn=%x inuse=%d\n",
256 bestv, ms->voices[bestv].seqno,
257 ms->voices[bestv].chan_note,
258 ms->voices[bestv].inuse));
259 #ifdef AUDIO_DEBUG
260 if (ms->voices[bestv].inuse)
261 DPRINTFN(1,("midisyn_allocvoice: steal %x\n",
262 ms->voices[bestv].chan_note));
263 #endif
264 ms->voices[bestv].chan_note = MS_CHANNOTE(chan, note);
265 ms->voices[bestv].seqno = ms->seqno++;
266 ms->voices[bestv].inuse = 1;
267 return (bestv);
268 }
269
270 /* dummy attackv_vel that just adds vel into level for simple drivers */
271 static void
272 midisyn_attackv_vel(midisyn *ms, uint_fast16_t voice, uint32_t miditune,
273 int16_t level_cB, uint_fast8_t vel)
274 {
275 ms->mets->attackv(ms, voice, miditune,
276 level_cB + midisyn_vol2cB((uint_fast16_t)vel << 7));
277 }
278
279 int
280 midisyn_sysrt(void *addr, int b)
281 {
282 return 0;
283 }
284
285 int midisyn_channelmsg(void *addr, int status, int chan, u_char *buf, int len)
286 {
287 midisyn *ms = addr;
288 int voice = 0; /* initialize to keep gcc quiet */
289 struct midisyn_methods *fs;
290
291 DPRINTF(("midisyn_channelmsg: ms=%p status=%#02x chan=%d\n",
292 ms, status, chan));
293 fs = ms->mets;
294
295 switch (status) {
296 case MIDI_NOTEOFF:
297 /*
298 * for a device that leaves voice allocation to us--and that's
299 * all of 'em at the moment--the voice and release velocity
300 * should be the only necessary arguments to noteoff. what use
301 * are they making of note? checking... None. Cool.
302 * IF there is ever a device added that does its own allocation,
303 * extend the interface; this findvoice won't be what to do...
304 */
305 voice = midisyn_findvoice(ms, chan, buf[1]);
306 if (voice >= 0) {
307 fs->releasev(ms, voice, buf[2]);
308 midisyn_freevoice(ms, voice);
309 }
310 break;
311 case MIDI_NOTEON:
312 /*
313 * opl combines vel with a 'mainvol' that has no setter
314 * anywhere. pcppi punts volume entirely. cms uses vel alone.
315 * what's called for here, given current drivers, is an i/f
316 * where midisyn computes a volume from vel*volume*expression*
317 * mastervolume and passes that result as a single arg. It can
318 * evolve later to support drivers that expose some of those
319 * bits separately (e.g. a driver could expose a mixer register
320 * on its sound card and use that for mastervolume).
321 */
322 voice = fs->allocv(ms, chan, buf[1]);
323 fs->attackv_vel(ms, voice,
324 MIDISYN_KEY_TO_MT(buf[1])
325 + midisyn_adj_pitch(ms, chan),
326 midisyn_adj_level(ms,chan), buf[2]);
327 break;
328 case MIDI_KEY_PRESSURE:
329 /*
330 * unimplemented by the existing drivers. if we are doing
331 * voice allocation, find the voice that corresponds to this
332 * chan/note and define a method that passes the voice and
333 * pressure to the driver ... not the note, /it/ doesn't matter.
334 * For a driver that does its own allocation, a different
335 * method may be needed passing pressure, chan, note so it can
336 * find the right voice on its own. Be sure that whatever is
337 * done here is undone when midisyn_notify sees MIDICTL_RESET.
338 */
339 break;
340 case MIDI_CTL_CHANGE:
341 midictl_change(&ms->ctl, chan, buf+1);
342 break;
343 case MIDI_PGM_CHANGE:
344 if (fs->pgmchg)
345 fs->pgmchg(ms, chan, buf[1]);
346 break;
347 case MIDI_CHN_PRESSURE:
348 /*
349 * unimplemented by the existing drivers. if driver exposes no
350 * distinct method, can use KEY_PRESSURE method for each voice
351 * on channel. Be sure that whatever is
352 * done here is undone when midisyn_notify sees MIDICTL_RESET.
353 */
354 break;
355 case MIDI_PITCH_BEND:
356 /*
357 * unimplemented by existing drivers. it is good that most
358 * existing drivers take a /frequency/ rather than a /note no/
359 * for control; midisyn should use this event to update some
360 * internal state and use it (along with tuning) to derive the
361 * frequency passed to the driver for any note on. A driver that
362 * can change freq of a sounding voice should expose a method
363 * for that, i.e. m(voice,newfreq) and we should call that too,
364 * for each voice on the affected channel, when a pitch bend
365 * change is received. Note RPN 0 must be used in scaling the
366 * pitch bend. Be sure that whatever is
367 * done here is undone when midisyn_notify sees MIDICTL_RESET.
368 */
369 break;
370 }
371 return 0;
372 }
373
374 int midisyn_commonmsg(void *addr, int status, u_char *buf, int len)
375 {
376 return 0;
377 }
378
379 int midisyn_sysex(void *addr, u_char *buf, int len)
380 {
381 /*
382 * unimplemented by existing drivers. it is surely more sensible
383 * to do some parsing of well-defined sysex messages here, either
384 * handling them internally or calling specific methods on the
385 * driver after parsing out the details, than to ask every driver
386 * to deal with sysex messages poked at it a byte at a time.
387 */
388 return 0;
389 }
390
391 static void
392 midisyn_notify(void *cookie, midictl_evt evt,
393 uint_fast8_t chan, uint_fast16_t key)
394 {
395 struct midisyn *ms;
396 int drvhandled;
397
398 ms = (struct midisyn *)cookie;
399 drvhandled = 0;
400 if ( ms->mets->ctlnotice )
401 drvhandled = ms->mets->ctlnotice(ms, evt, chan, key);
402
403 switch ( evt ) {
404 case MIDICTL_RESET:
405 /* re-read all ctls we use, revert pitchbend state */
406 break;
407 case MIDICTL_NOTES_OFF:
408 if ( drvhandled )
409 break;
410 /* releasev all voices sounding on chan; use normal vel 64 */
411 break;
412 case MIDICTL_SOUND_OFF:
413 if ( drvhandled )
414 break;
415 /* releasev all voices sounding on chan; use max vel 127 */
416 /* it is really better for driver to handle this, instantly */
417 break;
418 default:
419 break;
420 }
421 }
422
423 static int16_t
424 midisyn_adj_level(midisyn *ms, uint_fast8_t chan)
425 {
426 return 0; /* XXX for now. Use Volume and Expression ctlrs. */
427 }
428
429 static uint32_t
430 midisyn_adj_pitch(midisyn *ms, uint_fast8_t chan)
431 {
432 return 0; /* XXX for now. Use Pitchbend, PBrange, fine/coarse tuning. */
433 }
434
435 int16_t
436 midisyn_vol2cB(uint_fast16_t vol)
437 {
438 int16_t cB = 0;
439 int32_t v;
440
441 if ( 0 == vol )
442 return INT16_MIN;
443 /*
444 * Adjust vol to fall in the range 8192..16383. Each doubling is
445 * worth 12 dB.
446 */
447 while ( vol < 8192 ) {
448 vol <<= 1;
449 cB -= 120;
450 }
451 v = vol; /* ensure evaluation in signed 32 bit below */
452 /*
453 * The GM vol-to-dB formula is dB = 40 log ( v / 127 ) for 7-bit v.
454 * The vol and expression controllers are in 14-bit space so the
455 * equivalent is 40 log ( v / 16256 ) - that is, MSB 127 LSB 0 because
456 * the LSB is commonly unused. MSB 127 LSB 127 would then be a tiny
457 * bit over.
458 * 1 dB resolution is a little coarser than we'd like, so let's shoot
459 * for centibels, i.e. 400 log ( v / 16256 ), and shift everything left
460 * as far as will fit in 32 bits, which turns out to be a shift of 22.
461 * This minimax polynomial approximation is good to about a centibel
462 * on the range 8192..16256, a shade worse (1.4 or so) above that.
463 * 26385/10166 is the 6th convergent of the coefficient for v^2.
464 */
465 cB += ( v * ( 124828 - ( v * 26385 ) / 10166 ) - 1347349038 ) >> 22;
466 return cB;
467 }
468
469 uint32_t
470 midisyn_mt2hz18(uint32_t mt)
471 {
472 int64_t t64a, t64b;
473 uint_fast8_t shift;
474
475 /*
476 * Scale from the logarithmic MIDI-Tuning units to Hz<<18. Uses the
477 * continued-fraction form of a 2/2 rational function derived to
478 * cover the highest octave (mt 1900544..2097151 or 74.00.00..7f.7f.7f
479 * in RP-012-speak, the dotted bits are 7 wide) to produce Hz shifted
480 * left just as far as the maximum Hz will fit in a uint32, which
481 * turns out to be 18. Just shift off the result for lower octaves.
482 * Fit is within 1/4 MIDI tuning unit throughout (disclaimer: the
483 * comparison relied on the double-precision log in libm).
484 *
485 */
486
487 if ( 0 == mt )
488 return 2143236;
489
490 for ( shift = 0; mt < 1900544; ++ shift )
491 mt += 196608; /* 12 << 14 */
492
493 if ( 1998848 == mt )
494 return UINT32_C(2463438621) >> shift;
495
496 t64a = 0x5a1a0ee4; /* INT64_C(967879298788) gcc333: spurious warning */
497 t64a |= (int64_t)0xe1 << 32;
498 t64a /= (int32_t)mt - 1998848;
499 t64a += (int32_t)mt - 3704981;
500 t64b = 0x6763759d; /* INT64_C(8405905567872413) and here too */
501 t64b |= (int64_t)0x1ddd20 << 32;
502 t64b /= t64a;
503 t64b += UINT32_C(2463438619);
504 return (uint32_t)t64b >> shift;
505 }
506