Home | History | Annotate | Line # | Download | only in dev
midisyn.c revision 1.17.2.14
      1 /*	$NetBSD: midisyn.c,v 1.17.2.14 2006/06/08 04:55:22 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.14 2006/06/08 04:55:22 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 int	midisyn_allocvoice(midisyn *, uint_fast8_t, uint_fast8_t);
     73 u_int32_t midisyn_note_to_freq(int);
     74 u_int32_t midisyn_finetune(u_int32_t, int, int, int);
     75 
     76 static midictl_notify midisyn_notify;
     77 
     78 int	midisyn_open(void *, int,
     79 		     void (*iintr)(void *, int),
     80 		     void (*ointr)(void *), void *arg);
     81 void	midisyn_close(void *);
     82 int	midisyn_sysrt(void *, int);
     83 void	midisyn_getinfo(void *, struct midi_info *);
     84 int	midisyn_ioctl(void *, u_long, caddr_t, int, struct lwp *);
     85 
     86 const struct midi_hw_if midisyn_hw_if = {
     87 	midisyn_open,
     88 	midisyn_close,
     89 	midisyn_sysrt,
     90 	midisyn_getinfo,
     91 	midisyn_ioctl,
     92 };
     93 
     94 int	midisyn_channelmsg(void *, int, int, u_char *, int);
     95 int	midisyn_commonmsg(void *, int, u_char *, int);
     96 int	midisyn_sysex(void *, u_char *, int);
     97 
     98 struct midi_hw_if_ext midisyn_hw_if_ext = {
     99 	.channel = midisyn_channelmsg,
    100 	.common  = midisyn_commonmsg,
    101 	.sysex   = midisyn_sysex,
    102 };
    103 
    104 int
    105 midisyn_open(void *addr, int flags, void (*iintr)(void *, int),
    106 	     void (*ointr)(void *), void *arg)
    107 {
    108 	midisyn *ms = addr;
    109 
    110 	DPRINTF(("midisyn_open: ms=%p ms->mets=%p\n", ms, ms->mets));
    111 
    112 	midictl_open(&ms->ctl);
    113 
    114 	if (ms->mets->open)
    115 		return (ms->mets->open(ms, flags));
    116 	else
    117 		return (0);
    118 }
    119 
    120 void
    121 midisyn_close(void *addr)
    122 {
    123 	midisyn *ms = addr;
    124 	struct midisyn_methods *fs;
    125 	int v;
    126 
    127 	DPRINTF(("midisyn_close: ms=%p ms->mets=%p\n", ms, ms->mets));
    128 	fs = ms->mets;
    129 	for (v = 0; v < ms->nvoice; v++)
    130 		if (ms->voices[v].inuse) {
    131 			fs->noteoff(ms, v, 0, 0);
    132 			midisyn_freevoice(ms, v);
    133 		}
    134 	if (fs->close)
    135 		fs->close(ms);
    136 
    137 	midictl_close(&ms->ctl);
    138 }
    139 
    140 void
    141 midisyn_getinfo(void *addr, struct midi_info *mi)
    142 {
    143 	midisyn *ms = addr;
    144 
    145 	mi->name = ms->name;
    146 	/*
    147 	 * I was going to add a property here to suppress midi(4)'s warning
    148 	 * about an output device that uses no transmit interrupt, on the
    149 	 * assumption that as an onboard synth we handle "output" internally
    150 	 * with nothing like the 320 us per byte busy wait of a dumb UART.
    151 	 * Then I noticed that opl (at least as currently implemented) seems
    152 	 * to need 40 us busy wait to set each register on an OPL2, and sets
    153 	 * about 21 registers for every note-on. (Half of that is patch loading
    154 	 * and could probably be reduced by different management of voices and
    155 	 * patches.) For now I won't bother suppressing that warning....
    156 	 */
    157 	mi->props = 0;
    158 
    159 	midi_register_hw_if_ext(&midisyn_hw_if_ext);
    160 }
    161 
    162 int
    163 midisyn_ioctl(void *maddr, u_long cmd, caddr_t addr, int flag, struct lwp *l)
    164 {
    165 	midisyn *ms = maddr;
    166 
    167 	if (ms->mets->ioctl)
    168 		return (ms->mets->ioctl(ms, cmd, addr, flag, l));
    169 	else
    170 		return (EINVAL);
    171 }
    172 
    173 int
    174 midisyn_findvoice(midisyn *ms, int chan, int note)
    175 {
    176 	u_int cn;
    177 	int v;
    178 
    179 	if (!(ms->flags & MS_DOALLOC))
    180 		return (chan);
    181 	cn = MS_CHANNOTE(chan, note);
    182 	for (v = 0; v < ms->nvoice; v++)
    183 		if (ms->voices[v].chan_note == cn && ms->voices[v].inuse)
    184 			return (v);
    185 	return (-1);
    186 }
    187 
    188 void
    189 midisyn_attach(struct midi_softc *sc, midisyn *ms)
    190 {
    191 	if (ms->flags & MS_DOALLOC) {
    192 		ms->voices = malloc(ms->nvoice * sizeof (struct voice),
    193 				    M_DEVBUF, M_WAITOK|M_ZERO);
    194 		ms->seqno = 1;
    195 		if (ms->mets->allocv == 0)
    196 			ms->mets->allocv = &midisyn_allocvoice;
    197 	}
    198 
    199 	ms->ctl = (midictl) {
    200 		.base_channel = 16,
    201 		.cookie = ms,
    202 		.notify = midisyn_notify
    203 	};
    204 
    205 	sc->hw_if = &midisyn_hw_if;
    206 	sc->hw_hdl = ms;
    207 	DPRINTF(("midisyn_attach: ms=%p\n", sc->hw_hdl));
    208 }
    209 
    210 void
    211 midisyn_freevoice(midisyn *ms, int voice)
    212 {
    213 	if (!(ms->flags & MS_DOALLOC))
    214 		return;
    215 	ms->voices[voice].inuse = 0;
    216 }
    217 
    218 int
    219 midisyn_allocvoice(midisyn *ms, uint_fast8_t chan, uint_fast8_t note)
    220 {
    221 	int bestv, v;
    222 	u_int bestseq, s;
    223 
    224 	/* Find a free voice, or if no free voice is found the oldest. */
    225 	bestv = 0;
    226 	bestseq = ms->voices[0].seqno + (ms->voices[0].inuse ? 0x40000000 : 0);
    227 	for (v = 1; v < ms->nvoice; v++) {
    228 		s = ms->voices[v].seqno;
    229 		if (ms->voices[v].inuse)
    230 			s += 0x40000000;
    231 		if (s < bestseq) {
    232 			bestseq = s;
    233 			bestv = v;
    234 		}
    235 	}
    236 	DPRINTFN(10,("midisyn_allocvoice: v=%d seq=%d cn=%x inuse=%d\n",
    237 		     bestv, ms->voices[bestv].seqno,
    238 		     ms->voices[bestv].chan_note,
    239 		     ms->voices[bestv].inuse));
    240 #ifdef AUDIO_DEBUG
    241 	if (ms->voices[bestv].inuse)
    242 		DPRINTFN(1,("midisyn_allocvoice: steal %x\n",
    243 			    ms->voices[bestv].chan_note));
    244 #endif
    245 	ms->voices[bestv].chan_note = MS_CHANNOTE(chan, note);
    246 	ms->voices[bestv].seqno = ms->seqno++;
    247 	ms->voices[bestv].inuse = 1;
    248 	return (bestv);
    249 }
    250 
    251 int
    252 midisyn_sysrt(void *addr, int b)
    253 {
    254 	return 0;
    255 }
    256 
    257 int midisyn_channelmsg(void *addr, int status, int chan, u_char *buf, int len)
    258 {
    259 	midisyn *ms = addr;
    260 	int voice = 0;		/* initialize to keep gcc quiet */
    261 	struct midisyn_methods *fs;
    262 	u_int32_t note, vel;
    263 
    264 	DPRINTF(("midisyn_channelmsg: ms=%p status=%#02x chan=%d\n",
    265 	       ms, status, chan));
    266 	fs = ms->mets;
    267 	note = buf[1];
    268 	if (ms->flags & MS_FREQXLATE)
    269 		note = midisyn_note_to_freq(note);
    270 	vel = buf[2];
    271 
    272 	switch (status) {
    273 	case MIDI_NOTEOFF:
    274 		/*
    275 		 * for a device that leaves voice allocation to us--and that's
    276 		 * all of 'em at the moment--the voice and release velocity
    277 		 * should be the only necessary arguments to noteoff. what use
    278 		 * are they making of note? checking... None. Cool.
    279 		 */
    280 		voice = midisyn_findvoice(ms, chan, buf[1]);
    281 		if (voice >= 0) {
    282 			fs->noteoff(ms, voice, note, vel);
    283 			midisyn_freevoice(ms, voice);
    284 		}
    285 		break;
    286 	case MIDI_NOTEON:
    287 		/*
    288 		 * opl combines vel with a 'mainvol' that has no setter
    289 		 * anywhere. pcppi punts volume entirely. cms uses vel alone.
    290 		 * what's called for here, given current drivers, is an i/f
    291 		 * where midisyn computes a volume from vel*volume*expression*
    292 		 * mastervolume and passes that result as a single arg. It can
    293 		 * evolve later to support drivers that expose some of those
    294 		 * bits separately (e.g. a driver could expose a mixer register
    295 		 * on its sound card and use that for mastervolume).
    296 		 */
    297 		voice = fs->allocv(ms, chan, buf[1]);
    298 		fs->noteon(ms, voice, note, vel);
    299 		break;
    300 	case MIDI_KEY_PRESSURE:
    301 		/*
    302 		 * unimplemented by the existing drivers. if we are doing
    303 		 * voice allocation, find the voice that corresponds to this
    304 		 * chan/note and define a method that passes the voice and
    305 		 * pressure to the driver ... not the note, /it/ doesn't matter.
    306 		 * For a driver that does its own allocation, a different
    307 		 * method may be needed passing pressure, chan, note so it can
    308 		 * find the right voice on its own. Be sure that whatever is
    309 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    310 		 */
    311 		break;
    312 	case MIDI_CTL_CHANGE:
    313 		midictl_change(&ms->ctl, chan, buf+1);
    314 		break;
    315 	case MIDI_PGM_CHANGE:
    316 		if (fs->pgmchg)
    317 			fs->pgmchg(ms, chan, buf[1]);
    318 		break;
    319 	case MIDI_CHN_PRESSURE:
    320 		/*
    321 		 * unimplemented by the existing drivers. if driver exposes no
    322 		 * distinct method, can use KEY_PRESSURE method for each voice
    323 		 * on channel. Be sure that whatever is
    324 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    325 		 */
    326 		break;
    327 	case MIDI_PITCH_BEND:
    328 		/*
    329 		 * unimplemented by existing drivers. it is good that most
    330 		 * existing drivers take a /frequency/ rather than a /note no/
    331 		 * for control; midisyn should use this event to update some
    332 		 * internal state and use it (along with tuning) to derive the
    333 		 * frequency passed to the driver for any note on. A driver that
    334 		 * can change freq of a sounding voice should expose a method
    335 		 * for that, i.e. m(voice,newfreq) and we should call that too,
    336 		 * for each voice on the affected channel, when a pitch bend
    337 		 * change is received. Note RPN 0 must be used in scaling the
    338 		 * pitch bend. Be sure that whatever is
    339 		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
    340 		 */
    341 		break;
    342 	}
    343 	return 0;
    344 }
    345 
    346 int midisyn_commonmsg(void *addr, int status, u_char *buf, int len)
    347 {
    348 	return 0;
    349 }
    350 
    351 int midisyn_sysex(void *addr, u_char *buf, int len)
    352 {
    353 	/*
    354 	 * unimplemented by existing drivers. it is surely more sensible
    355 	 * to do some parsing of well-defined sysex messages here, either
    356 	 * handling them internally or calling specific methods on the
    357 	 * driver after parsing out the details, than to ask every driver
    358 	 * to deal with sysex messages poked at it a byte at a time.
    359 	 */
    360 	return 0;
    361 }
    362 
    363 /*
    364  * Convert a MIDI note to the corresponding frequency.
    365  * The frequency is scaled by 2^16.
    366  */
    367 u_int32_t
    368 midisyn_note_to_freq(int note)
    369 {
    370 	int o, n, f;
    371 #define BASE_OCTAVE 5
    372 	static const u_int32_t notes[] = {
    373 		17145893, 18165441, 19245614, 20390018, 21602472, 22887021,
    374 		24247954, 25689813, 27217409, 28835840, 30550508, 32367136
    375 	};
    376 
    377 
    378 	o = note / 12;
    379 	n = note % 12;
    380 
    381 	f = notes[n];
    382 
    383 	if (o < BASE_OCTAVE)
    384 		f >>= (BASE_OCTAVE - o);
    385 	else if (o > BASE_OCTAVE)
    386 		f <<= (o - BASE_OCTAVE);
    387 	return (f);
    388 }
    389 
    390 u_int32_t
    391 midisyn_finetune(u_int32_t base_freq, int bend, int range, int vibrato_cents)
    392 {
    393 	static const u_int16_t semitone_tuning[24] =
    394 	{
    395 /*   0 */ 10000, 10595, 11225, 11892, 12599, 13348, 14142, 14983,
    396 /*   8 */ 15874, 16818, 17818, 18877, 20000, 21189, 22449, 23784,
    397 /*  16 */ 25198, 26697, 28284, 29966, 31748, 33636, 35636, 37755
    398 	};
    399 	static const u_int16_t cent_tuning[100] =
    400 	{
    401 /*   0 */ 10000, 10006, 10012, 10017, 10023, 10029, 10035, 10041,
    402 /*   8 */ 10046, 10052, 10058, 10064, 10070, 10075, 10081, 10087,
    403 /*  16 */ 10093, 10099, 10105, 10110, 10116, 10122, 10128, 10134,
    404 /*  24 */ 10140, 10145, 10151, 10157, 10163, 10169, 10175, 10181,
    405 /*  32 */ 10187, 10192, 10198, 10204, 10210, 10216, 10222, 10228,
    406 /*  40 */ 10234, 10240, 10246, 10251, 10257, 10263, 10269, 10275,
    407 /*  48 */ 10281, 10287, 10293, 10299, 10305, 10311, 10317, 10323,
    408 /*  56 */ 10329, 10335, 10341, 10347, 10353, 10359, 10365, 10371,
    409 /*  64 */ 10377, 10383, 10389, 10395, 10401, 10407, 10413, 10419,
    410 /*  72 */ 10425, 10431, 10437, 10443, 10449, 10455, 10461, 10467,
    411 /*  80 */ 10473, 10479, 10485, 10491, 10497, 10503, 10509, 10515,
    412 /*  88 */ 10521, 10528, 10534, 10540, 10546, 10552, 10558, 10564,
    413 /*  96 */ 10570, 10576, 10582, 10589
    414 	};
    415 	u_int32_t amount;
    416 	int negative, semitones, cents, multiplier;
    417 
    418 	if (range == 0)
    419 		return base_freq;
    420 
    421 	if (base_freq == 0)
    422 		return base_freq;
    423 
    424 	if (range >= 8192)
    425 		range = 8192;
    426 
    427 	bend = bend * range / 8192;
    428 	bend += vibrato_cents;
    429 
    430 	if (bend == 0)
    431 		return base_freq;
    432 
    433 	if (bend < 0) {
    434 		bend = -bend;
    435 		negative = 1;
    436 	} else
    437 		negative = 0;
    438 
    439 	if (bend > range)
    440 		bend = range;
    441 
    442 	multiplier = 1;
    443 	while (bend > 2399) {
    444 		multiplier *= 4;
    445 		bend -= 2400;
    446 	}
    447 
    448 	semitones = bend / 100;
    449 	cents = bend % 100;
    450 
    451 	amount = semitone_tuning[semitones] * multiplier * cent_tuning[cents]
    452 		/ 10000;
    453 
    454 	if (negative)
    455 		return (base_freq * 10000 / amount);	/* Bend down */
    456 	else
    457 		return (base_freq * amount / 10000);	/* Bend up */
    458 }
    459 
    460 static void
    461 midisyn_notify(void *cookie, midictl_evt evt,
    462                uint_fast8_t chan, uint_fast16_t key)
    463 {
    464 }
    465 
    466 int16_t
    467 midisyn_vol2cB(uint_fast16_t vol)
    468 {
    469 	int16_t cB = 0;
    470 	int32_t v;
    471 
    472 	if ( 0 == vol )
    473 		return INT16_MIN;
    474 	/*
    475 	 * Adjust vol to fall in the range 8192..16383. Each doubling is
    476 	 * worth 12 dB.
    477 	 */
    478 	while ( vol < 8192 ) {
    479 		vol <<= 1;
    480 		cB -= 120;
    481 	}
    482 	v = vol; /* ensure evaluation in signed 32 bit below */
    483 	/*
    484 	 * The GM vol-to-dB formula is dB = 40 log ( v / 127 ) for 7-bit v.
    485 	 * The vol and expression controllers are in 14-bit space so the
    486 	 * equivalent is 40 log ( v / 16256 ) - that is, MSB 127 LSB 0 because
    487 	 * the LSB is commonly unused. MSB 127 LSB 127 would then be a tiny
    488 	 * bit over.
    489 	 * 1 dB resolution is a little coarser than we'd like, so let's shoot
    490 	 * for centibels, i.e. 400 log ( v / 16256 ), and shift everything left
    491 	 * as far as will fit in 32 bits, which turns out to be a shift of 22.
    492 	 * This minimax polynomial approximation is good to about a centibel
    493 	 * on the range 8192..16256, a shade worse (1.4 or so) above that.
    494 	 * 26385/10166 is the 6th convergent of the coefficient for v^2.
    495 	 */
    496 	cB += ( v * ( 124828 - ( v * 26385 ) / 10166 ) - 1347349038 ) >> 22;
    497 	return cB;
    498 }
    499 
    500 uint32_t
    501 midisyn_mt2hz18(uint32_t mt)
    502 {
    503 	int64_t t64a, t64b;
    504 	uint_fast8_t shift;
    505 
    506 	/*
    507 	 * Scale from the logarithmic MIDI-Tuning units to Hz<<18. Uses the
    508 	 * continued-fraction form of a 2/2 rational function derived to
    509 	 * cover the highest octave (mt 1900544..2097151 or 74.00.00..7f.7f.7f
    510 	 * in RP-012-speak, the dotted bits are 7 wide) to produce Hz shifted
    511 	 * left just as far as the maximum Hz will fit in a uint32, which
    512 	 * turns out to be 18. Just shift off the result for lower octaves.
    513 	 * Fit is within 1/4 MIDI tuning unit throughout (disclaimer: the
    514 	 * comparison relied on the double-precision log in libm).
    515 	 *
    516 	 */
    517 
    518 	if ( 0 == mt )
    519 		return 2143236;
    520 
    521 	for ( shift = 0; mt < 1900544; ++ shift )
    522 		mt += 196608; /* 12 << 14 */
    523 
    524 	if ( 1998848 == mt )
    525 		return UINT32_C(2463438621) >> shift;
    526 
    527 	t64a  = 0x5a1a0ee4; /* INT64_C(967879298788) gcc333: spurious warning */
    528 	t64a |= (int64_t)0xe1 << 32;
    529 	t64a /= (int32_t)mt - 1998848;
    530 	t64a += (int32_t)mt - 3704981;
    531 	t64b  = 0x6763759d; /* INT64_C(8405905567872413) and here too */
    532 	t64b |= (int64_t)0x1ddd20 << 32;
    533 	t64b /= t64a;
    534 	t64b += UINT32_C(2463438619);
    535 	return (uint32_t)t64b >> shift;
    536 }
    537