Home | History | Annotate | Line # | Download | only in dev
midisyn.c revision 1.17.2.17
      1 /*	$NetBSD: midisyn.c,v 1.17.2.17 2006/06/09 17:05:28 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.17 2006/06/09 17:05:28 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, midipitch_t,
     74                                     int16_t, uint_fast8_t);
     75 static int16_t midisyn_adj_level(midisyn *, uint_fast8_t);
     76 static midipitch_t midisyn_adj_pitch(midisyn *, uint_fast8_t);
     77 
     78 static midictl_notify midisyn_notify;
     79 
     80 int	midisyn_open(void *, int,
     81 		     void (*iintr)(void *, int),
     82 		     void (*ointr)(void *), void *arg);
     83 void	midisyn_close(void *);
     84 int	midisyn_sysrt(void *, int);
     85 void	midisyn_getinfo(void *, struct midi_info *);
     86 int	midisyn_ioctl(void *, u_long, caddr_t, int, struct lwp *);
     87 
     88 const struct midi_hw_if midisyn_hw_if = {
     89 	midisyn_open,
     90 	midisyn_close,
     91 	midisyn_sysrt,
     92 	midisyn_getinfo,
     93 	midisyn_ioctl,
     94 };
     95 
     96 int	midisyn_channelmsg(void *, int, int, u_char *, int);
     97 int	midisyn_commonmsg(void *, int, u_char *, int);
     98 int	midisyn_sysex(void *, u_char *, int);
     99 
    100 struct midi_hw_if_ext midisyn_hw_if_ext = {
    101 	.channel = midisyn_channelmsg,
    102 	.common  = midisyn_commonmsg,
    103 	.sysex   = midisyn_sysex,
    104 };
    105 
    106 int
    107 midisyn_open(void *addr, int flags, void (*iintr)(void *, int),
    108 	     void (*ointr)(void *), void *arg)
    109 {
    110 	midisyn *ms = addr;
    111 	int rslt;
    112 	uint_fast8_t chan;
    113 
    114 	DPRINTF(("midisyn_open: ms=%p ms->mets=%p\n", ms, ms->mets));
    115 
    116 	midictl_open(&ms->ctl);
    117 
    118 	rslt = 0;
    119 	if (ms->mets->open)
    120 		rslt = (ms->mets->open(ms, flags));
    121 
    122 	/*
    123 	 * Make the right initial things happen by faking receipt of RESET on
    124 	 * all channels. The hw driver's ctlnotice() will be called in turn.
    125 	 */
    126 	for ( chan = 0 ; chan < MIDI_MAX_CHANS ; ++ chan )
    127 		midisyn_notify(ms, MIDICTL_RESET, chan, 0);
    128 
    129 	return rslt;
    130 }
    131 
    132 void
    133 midisyn_close(void *addr)
    134 {
    135 	midisyn *ms = addr;
    136 	struct midisyn_methods *fs;
    137 	int v;
    138 
    139 	DPRINTF(("midisyn_close: ms=%p ms->mets=%p\n", ms, ms->mets));
    140 	fs = ms->mets;
    141 	/* TODO
    142 	 * This loop is much like what midisyn_notify should do for NOTES_OFF
    143 	 * or SOUND_OFF. It should be moved there, and here we should call
    144 	 * notify faking one of those events.
    145 	 */
    146 	for (v = 0; v < ms->nvoice; v++)
    147 		if (ms->voices[v].inuse) {
    148 			fs->releasev(ms, v, 127);
    149 			midisyn_freevoice(ms, v);
    150 		}
    151 	if (fs->close)
    152 		fs->close(ms);
    153 
    154 	midictl_close(&ms->ctl);
    155 }
    156 
    157 void
    158 midisyn_getinfo(void *addr, struct midi_info *mi)
    159 {
    160 	midisyn *ms = addr;
    161 
    162 	mi->name = ms->name;
    163 	/*
    164 	 * I was going to add a property here to suppress midi(4)'s warning
    165 	 * about an output device that uses no transmit interrupt, on the
    166 	 * assumption that as an onboard synth we handle "output" internally
    167 	 * with nothing like the 320 us per byte busy wait of a dumb UART.
    168 	 * Then I noticed that opl (at least as currently implemented) seems
    169 	 * to need 40 us busy wait to set each register on an OPL2, and sets
    170 	 * about 21 registers for every note-on. (Half of that is patch loading
    171 	 * and could probably be reduced by different management of voices and
    172 	 * patches.) For now I won't bother suppressing that warning....
    173 	 */
    174 	mi->props = 0;
    175 
    176 	midi_register_hw_if_ext(&midisyn_hw_if_ext);
    177 }
    178 
    179 int
    180 midisyn_ioctl(void *maddr, u_long cmd, caddr_t addr, int flag, struct lwp *l)
    181 {
    182 	midisyn *ms = maddr;
    183 
    184 	if (ms->mets->ioctl)
    185 		return (ms->mets->ioctl(ms, cmd, addr, flag, l));
    186 	else
    187 		return (EINVAL);
    188 }
    189 
    190 int
    191 midisyn_findvoice(midisyn *ms, int chan, int note)
    192 {
    193 	u_int cn;
    194 	int v;
    195 
    196 	cn = MS_CHANNOTE(chan, note);
    197 	for (v = 0; v < ms->nvoice; v++)
    198 		if (ms->voices[v].chan_note == cn && ms->voices[v].inuse)
    199 			return (v);
    200 	return (-1);
    201 }
    202 
    203 void
    204 midisyn_attach(struct midi_softc *sc, midisyn *ms)
    205 {
    206 	if (ms->mets->allocv == 0) {
    207 		ms->voices = malloc(ms->nvoice * sizeof (struct voice),
    208 				    M_DEVBUF, M_WAITOK|M_ZERO);
    209 		ms->seqno = 1;
    210 		ms->mets->allocv = midisyn_allocvoice;
    211 	}
    212 
    213 	if (ms->mets->attackv_vel == 0 && ms->mets->attackv != 0)
    214 		ms->mets->attackv_vel = midisyn_attackv_vel;
    215 
    216 	ms->ctl = (midictl) {
    217 		.base_channel = 16,
    218 		.cookie = ms,
    219 		.notify = midisyn_notify
    220 	};
    221 
    222 	sc->hw_if = &midisyn_hw_if;
    223 	sc->hw_hdl = ms;
    224 	DPRINTF(("midisyn_attach: ms=%p\n", sc->hw_hdl));
    225 }
    226 
    227 void
    228 midisyn_freevoice(midisyn *ms, int voice)
    229 {
    230 	if (ms->mets->allocv != midisyn_allocvoice)
    231 		return;
    232 	ms->voices[voice].inuse = 0;
    233 }
    234 
    235 uint_fast16_t
    236 midisyn_allocvoice(midisyn *ms, uint_fast8_t chan, uint_fast8_t note)
    237 {
    238 	int bestv, v;
    239 	u_int bestseq, s;
    240 
    241 	/* Find a free voice, or if no free voice is found the oldest. */
    242 	bestv = 0;
    243 	bestseq = ms->voices[0].seqno + (ms->voices[0].inuse ? 0x40000000 : 0);
    244 	for (v = 1; v < ms->nvoice; v++) {
    245 		s = ms->voices[v].seqno;
    246 		if (ms->voices[v].inuse)
    247 			s += 0x40000000;
    248 		if (s < bestseq) {
    249 			bestseq = s;
    250 			bestv = v;
    251 		}
    252 	}
    253 	DPRINTFN(10,("midisyn_allocvoice: v=%d seq=%d cn=%x inuse=%d\n",
    254 		     bestv, ms->voices[bestv].seqno,
    255 		     ms->voices[bestv].chan_note,
    256 		     ms->voices[bestv].inuse));
    257 #ifdef AUDIO_DEBUG
    258 	if (ms->voices[bestv].inuse)
    259 		DPRINTFN(1,("midisyn_allocvoice: steal %x\n",
    260 			    ms->voices[bestv].chan_note));
    261 #endif
    262 	ms->voices[bestv].chan_note = MS_CHANNOTE(chan, note);
    263 	ms->voices[bestv].seqno = ms->seqno++;
    264 	ms->voices[bestv].inuse = 1;
    265 	return (bestv);
    266 }
    267 
    268 /* dummy attackv_vel that just adds vel into level for simple drivers */
    269 static void
    270 midisyn_attackv_vel(midisyn *ms, uint_fast16_t voice, midipitch_t mp,
    271                     int16_t level_cB, uint_fast8_t vel)
    272 {
    273 	ms->mets->attackv(ms, voice, mp,
    274 	                  level_cB + midisyn_vol2cB((uint_fast16_t)vel << 7));
    275 }
    276 
    277 int
    278 midisyn_sysrt(void *addr, int b)
    279 {
    280 	return 0;
    281 }
    282 
    283 int midisyn_channelmsg(void *addr, int status, int chan, u_char *buf, int len)
    284 {
    285 	midisyn *ms = addr;
    286 	int voice = 0;		/* initialize to keep gcc quiet */
    287 	struct midisyn_methods *fs;
    288 
    289 	DPRINTF(("midisyn_channelmsg: ms=%p status=%#02x chan=%d\n",
    290 	       ms, status, chan));
    291 	fs = ms->mets;
    292 
    293 	switch (status) {
    294 	case MIDI_NOTEOFF:
    295 		/*
    296 		 * for a device that leaves voice allocation to us--and that's
    297 		 * all of 'em at the moment--the voice and release velocity
    298 		 * should be the only necessary arguments to noteoff. what use
    299 		 * are they making of note? checking... None. Cool.
    300 		 * IF there is ever a device added that does its own allocation,
    301 		 * extend the interface; this findvoice won't be what to do...
    302 		 */
    303 		voice = midisyn_findvoice(ms, chan, buf[1]);
    304 		if (voice >= 0) {
    305 			fs->releasev(ms, voice, buf[2]);
    306 			midisyn_freevoice(ms, voice);
    307 		}
    308 		break;
    309 	case MIDI_NOTEON:
    310 		/*
    311 		 * opl combines vel with a 'mainvol' that has no setter
    312 		 * anywhere. pcppi punts volume entirely. cms uses vel alone.
    313 		 * what's called for here, given current drivers, is an i/f
    314 		 * where midisyn computes a volume from vel*volume*expression*
    315 		 * mastervolume and passes that result as a single arg. It can
    316 		 * evolve later to support drivers that expose some of those
    317 		 * bits separately (e.g. a driver could expose a mixer register
    318 		 * on its sound card and use that for mastervolume).
    319 		 */
    320 		voice = fs->allocv(ms, chan, buf[1]);
    321 		fs->attackv_vel(ms, voice,
    322 		                MIDIPITCH_FROM_KEY(buf[1])
    323 				+ midisyn_adj_pitch(ms, chan),
    324 				midisyn_adj_level(ms,chan), buf[2]);
    325 		break;
    326 	case MIDI_KEY_PRESSURE:
    327 		/*
    328 		 * unimplemented by the existing drivers. if we are doing
    329 		 * voice allocation, find the voice that corresponds to this
    330 		 * chan/note and define a method that passes the voice and
    331 		 * pressure to the driver ... not the note, /it/ doesn't matter.
    332 		 * For a driver that does its own allocation, a different
    333 		 * method may be needed passing pressure, chan, note so it can
    334 		 * find the right voice on its own. Be sure that whatever is
    335 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    336 		 */
    337 		break;
    338 	case MIDI_CTL_CHANGE:
    339 		midictl_change(&ms->ctl, chan, buf+1);
    340 		break;
    341 	case MIDI_PGM_CHANGE:
    342 		if (fs->pgmchg)
    343 			fs->pgmchg(ms, chan, buf[1]);
    344 		break;
    345 	case MIDI_CHN_PRESSURE:
    346 		/*
    347 		 * unimplemented by the existing drivers. if driver exposes no
    348 		 * distinct method, can use KEY_PRESSURE method for each voice
    349 		 * on channel. Be sure that whatever is
    350 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    351 		 */
    352 		break;
    353 	case MIDI_PITCH_BEND:
    354 		/*
    355 		 * unimplemented by existing drivers. it is good that most
    356 		 * existing drivers take a /frequency/ rather than a /note no/
    357 		 * for control; midisyn should use this event to update some
    358 		 * internal state and use it (along with tuning) to derive the
    359 		 * frequency passed to the driver for any note on. A driver that
    360 		 * can change freq of a sounding voice should expose a method
    361 		 * for that, i.e. m(voice,newfreq) and we should call that too,
    362 		 * for each voice on the affected channel, when a pitch bend
    363 		 * change is received. Note RPN 0 must be used in scaling the
    364 		 * pitch bend. Be sure that whatever is
    365 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    366 		 */
    367 		break;
    368 	}
    369 	return 0;
    370 }
    371 
    372 int midisyn_commonmsg(void *addr, int status, u_char *buf, int len)
    373 {
    374 	return 0;
    375 }
    376 
    377 int midisyn_sysex(void *addr, u_char *buf, int len)
    378 {
    379 	/*
    380 	 * unimplemented by existing drivers. it is surely more sensible
    381 	 * to do some parsing of well-defined sysex messages here, either
    382 	 * handling them internally or calling specific methods on the
    383 	 * driver after parsing out the details, than to ask every driver
    384 	 * to deal with sysex messages poked at it a byte at a time.
    385 	 */
    386 	return 0;
    387 }
    388 
    389 static void
    390 midisyn_notify(void *cookie, midictl_evt evt,
    391                uint_fast8_t chan, uint_fast16_t key)
    392 {
    393 	struct midisyn *ms;
    394 	int drvhandled;
    395 
    396 	ms = (struct midisyn *)cookie;
    397 	drvhandled = 0;
    398 	if ( ms->mets->ctlnotice )
    399 		drvhandled = ms->mets->ctlnotice(ms, evt, chan, key);
    400 
    401 	switch ( evt ) {
    402 	case MIDICTL_RESET:
    403 		/* re-read all ctls we use, revert pitchbend state */
    404 		break;
    405 	case MIDICTL_NOTES_OFF:
    406 		if ( drvhandled )
    407 			break;
    408 		/* releasev all voices sounding on chan; use normal vel 64 */
    409 		break;
    410 	case MIDICTL_SOUND_OFF:
    411 		if ( drvhandled )
    412 			break;
    413 		/* releasev all voices sounding on chan; use max vel 127 */
    414 		/* it is really better for driver to handle this, instantly */
    415 		break;
    416 	default:
    417 		break;
    418 	}
    419 }
    420 
    421 static int16_t
    422 midisyn_adj_level(midisyn *ms, uint_fast8_t chan)
    423 {
    424 	return 0; /* XXX for now. Use Volume and Expression ctlrs. */
    425 }
    426 
    427 static midipitch_t
    428 midisyn_adj_pitch(midisyn *ms, uint_fast8_t chan)
    429 {
    430 	return 0; /* XXX for now. Use Pitchbend, PBrange, fine/coarse tuning. */
    431 }
    432 
    433 int16_t
    434 midisyn_vol2cB(uint_fast16_t vol)
    435 {
    436 	int16_t cB = 0;
    437 	int32_t v;
    438 
    439 	if ( 0 == vol )
    440 		return INT16_MIN;
    441 	/*
    442 	 * Adjust vol to fall in the range 8192..16383. Each doubling is
    443 	 * worth 12 dB.
    444 	 */
    445 	while ( vol < 8192 ) {
    446 		vol <<= 1;
    447 		cB -= 120;
    448 	}
    449 	v = vol; /* ensure evaluation in signed 32 bit below */
    450 	/*
    451 	 * The GM vol-to-dB formula is dB = 40 log ( v / 127 ) for 7-bit v.
    452 	 * The vol and expression controllers are in 14-bit space so the
    453 	 * equivalent is 40 log ( v / 16256 ) - that is, MSB 127 LSB 0 because
    454 	 * the LSB is commonly unused. MSB 127 LSB 127 would then be a tiny
    455 	 * bit over.
    456 	 * 1 dB resolution is a little coarser than we'd like, so let's shoot
    457 	 * for centibels, i.e. 400 log ( v / 16256 ), and shift everything left
    458 	 * as far as will fit in 32 bits, which turns out to be a shift of 22.
    459 	 * This minimax polynomial approximation is good to about a centibel
    460 	 * on the range 8192..16256, a shade worse (1.4 or so) above that.
    461 	 * 26385/10166 is the 6th convergent of the coefficient for v^2.
    462 	 */
    463 	cB += ( v * ( 124828 - ( v * 26385 ) / 10166 ) - 1347349038 ) >> 22;
    464 	return cB;
    465 }
    466 
    467 /*
    468  * MIDI RP-012 constitutes a MIDI Tuning Specification. The units are
    469  * fractional-MIDIkeys, that is, the key number 00 - 7f left shifted
    470  * 14 bits to provide a 14-bit fraction that divides each semitone. The
    471  * whole thing is just a 21-bit number that is bent and tuned simply by
    472  * adding and subtracting--the same offset is the same pitch change anywhere
    473  * on the scale. One downside is that a cent is 163.84 of these units, so
    474  * you can't expect a lengthy integer sum of cents to come out in tune; if you
    475  * do anything in cents it is best to use them only for local adjustment of
    476  * a pitch.
    477  *
    478  * This function converts a pitch in MIDItune units to Hz left-shifted 18 bits.
    479  * That should leave you enough to shift down to whatever precision the hardware
    480  * supports.
    481  *
    482  * Its prototype is exposed in <sys/midiio.h>.
    483  */
    484 midihz18_t
    485 midisyn_mp2hz18(midipitch_t mp)
    486 {
    487 	int64_t t64a, t64b;
    488 	uint_fast8_t shift;
    489 
    490 	/*
    491 	 * Scale from the logarithmic MIDI-Tuning units to Hz<<18. Uses the
    492 	 * continued-fraction form of a 2/2 rational function derived to
    493 	 * cover the highest octave (mt 1900544..2097151 or 74.00.00..7f.7f.7f
    494 	 * in RP-012-speak, the dotted bits are 7 wide) to produce Hz shifted
    495 	 * left just as far as the maximum Hz will fit in a uint32, which
    496 	 * turns out to be 18. Just shift off the result for lower octaves.
    497 	 * Fit is within 1/4 MIDI tuning unit throughout (disclaimer: the
    498 	 * comparison relied on the double-precision log in libm).
    499 	 */
    500 
    501 	if ( 0 == mp )
    502 		return 2143236;
    503 
    504 	for ( shift = 0; mp < 1900544; ++ shift )
    505 		mp += MIDIPITCH_OCTAVE;
    506 
    507 	if ( 1998848 == mp )
    508 		return UINT32_C(2463438621) >> shift;
    509 
    510 	t64a  = 0x5a1a0ee4; /* INT64_C(967879298788) gcc333: spurious warning */
    511 	t64a |= (int64_t)0xe1 << 32;
    512 	t64a /= mp - 1998848; /* here's why 1998848 is special-cased above ;) */
    513 	t64a += mp - 3704981;
    514 	t64b  = 0x6763759d; /* INT64_C(8405905567872413) and here too */
    515 	t64b |= (int64_t)0x1ddd20 << 32;
    516 	t64b /= t64a;
    517 	t64b += UINT32_C(2463438619);
    518 	return (uint32_t)t64b >> shift;
    519 }
    520