1/*	$NetBSD$	*/
2
3/*
4 * Copyright (c) 1998, 2008 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@NetBSD.org), and by Andrew Doran.
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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__KERNEL_RCSID(0, "$NetBSD$");
34
35#include <sys/param.h>
36#include <sys/ioctl.h>
37#include <sys/fcntl.h>
38#include <sys/vnode.h>
39#include <sys/select.h>
40#include <sys/proc.h>
41#include <sys/kmem.h>
42#include <sys/systm.h>
43#include <sys/syslog.h>
44#include <sys/kernel.h>
45#include <sys/audioio.h>
46#include <sys/midiio.h>
47#include <sys/device.h>
48
49#include <dev/audio_if.h>
50#include <dev/midi_if.h>
51#include <dev/midivar.h>
52#include <dev/midisynvar.h>
53
54#ifdef AUDIO_DEBUG
55#define DPRINTF(x)	if (midisyndebug) printf x
56#define DPRINTFN(n,x)	if (midisyndebug >= (n)) printf x
57int	midisyndebug = 0;
58#else
59#define DPRINTF(x)
60#define DPRINTFN(n,x)
61#endif
62
63static int	midisyn_findvoice(midisyn *, int, int);
64static void	midisyn_freevoice(midisyn *, int);
65static uint_fast16_t	midisyn_allocvoice(midisyn *, uint_fast8_t, uint_fast8_t);
66static void	midisyn_attackv_vel(midisyn *, uint_fast16_t, midipitch_t,
67                                    int16_t, uint_fast8_t);
68
69static midictl_notify midisyn_notify;
70
71static midipitch_t midisyn_clamp_pitch(midipitch_t);
72static int16_t midisyn_adj_level(midisyn *, uint_fast8_t);
73static midipitch_t midisyn_adj_pitch(midisyn *, uint_fast8_t);
74static void midisyn_chan_releasev(midisyn *, uint_fast8_t, uint_fast8_t);
75static void midisyn_upd_level(midisyn *, uint_fast8_t);
76static void midisyn_upd_pitch(midisyn *, uint_fast8_t);
77
78static int	midisyn_open(void *, int,
79			     void (*iintr)(void *, int),
80			     void (*ointr)(void *), void *arg);
81static void	midisyn_close(void *);
82static int	midisyn_sysrt(void *, int);
83static void	midisyn_getinfo(void *, struct midi_info *);
84static int	midisyn_ioctl(void *, u_long, void *, int, struct lwp *);
85static void	midisyn_get_locks(void *, kmutex_t **, kmutex_t **);
86
87const struct midi_hw_if midisyn_hw_if = {
88	midisyn_open,
89	midisyn_close,
90	midisyn_sysrt,
91	midisyn_getinfo,
92	midisyn_ioctl,
93	midisyn_get_locks,
94};
95
96static int	midisyn_channelmsg(void *, int, int, u_char *, int);
97static int	midisyn_commonmsg(void *, int, u_char *, int);
98static int	midisyn_sysex(void *, u_char *, int);
99
100struct midi_hw_if_ext midisyn_hw_if_ext = {
101	.channel = midisyn_channelmsg,
102	.common  = midisyn_commonmsg,
103	.sysex   = midisyn_sysex,
104};
105
106struct channelstate { /* dyamically allocated in open() on account of size */
107	/* volume state components in centibels; just sum for overall level */
108	int16_t volume;
109	int16_t expression;
110	/* pitch state components in midipitch units; sum for overall effect */
111	midipitch_t bend;
112	midipitch_t tuning_fine;
113	midipitch_t tuning_coarse;
114	/* used by bend handlers */
115	int16_t bendraw;
116	int16_t pendingreset;
117/* rearrange as more controls supported - 16 bits should last for a while */
118#define PEND_VOL 1
119#define PEND_EXP 2
120#define PEND_LEVEL (PEND_VOL|PEND_EXP)
121#define PEND_PBS 4
122#define PEND_TNF 8
123#define PEND_TNC 16
124#define PEND_PITCH (PEND_PBS|PEND_TNF|PEND_TNC)
125#define PEND_ALL   (PEND_LEVEL|PEND_PITCH)
126};
127
128static int
129midisyn_open(void *addr, int flags, void (*iintr)(void *, int),
130    void (*ointr)(void *), void *arg)
131{
132	midisyn *ms = addr;
133	int rslt, error;
134	uint_fast8_t chan;
135
136	if (ms->lock == NULL) {
137		panic("midisyn_open: no lock");
138	}
139
140	KASSERT(mutex_owned(ms->lock));
141	DPRINTF(("midisyn_open: ms=%p ms->mets=%p\n", ms, ms->mets));
142
143	mutex_exit(ms->lock);
144	ms->ctl.lock = ms->lock;
145	error = midictl_open(&ms->ctl);
146	if (error != 0) {
147		mutex_enter(ms->lock);
148		return error;
149	}
150	ms->chnstate = kmem_alloc(MIDI_MAX_CHANS * sizeof(*ms->chnstate),
151	    KM_SLEEP); /* init'd by RESET below */
152	mutex_enter(ms->lock);
153
154	rslt = 0;
155	if (ms->mets->open)
156		rslt = (ms->mets->open(ms, flags));
157
158	/*
159	 * Make the right initial things happen by faking receipt of RESET on
160	 * all channels. The hw driver's ctlnotice() will be called in turn.
161	 */
162	for ( chan = 0 ; chan < MIDI_MAX_CHANS ; ++ chan )
163		midisyn_notify(ms, MIDICTL_RESET, chan, 0);
164
165	return rslt;
166}
167
168static void
169midisyn_close(void *addr)
170{
171	midisyn *ms = addr;
172	struct midisyn_methods *fs;
173	int chan;
174
175	KASSERT(mutex_owned(ms->lock));
176	DPRINTF(("midisyn_close: ms=%p ms->mets=%p\n", ms, ms->mets));
177	fs = ms->mets;
178
179	for (chan = 0; chan < MIDI_MAX_CHANS; chan++)
180		midisyn_notify(ms, MIDICTL_SOUND_OFF, chan, 0);
181
182	if (fs->close)
183		fs->close(ms);
184
185	mutex_exit(ms->lock);
186	midictl_close(&ms->ctl);
187	kmem_free(ms->chnstate, MIDI_MAX_CHANS * sizeof(*ms->chnstate));
188	mutex_enter(ms->lock);
189}
190
191static void
192midisyn_getinfo(void *addr, struct midi_info *mi)
193{
194	midisyn *ms = addr;
195
196	KASSERT(mutex_owned(ms->lock));
197
198	mi->name = ms->name;
199	/*
200	 * I was going to add a property here to suppress midi(4)'s warning
201	 * about an output device that uses no transmit interrupt, on the
202	 * assumption that as an onboard synth we handle "output" internally
203	 * with nothing like the 320 us per byte busy wait of a dumb UART.
204	 * Then I noticed that opl (at least as currently implemented) seems
205	 * to need 40 us busy wait to set each register on an OPL2, and sets
206	 * about 21 registers for every note-on. (Half of that is patch loading
207	 * and could probably be reduced by different management of voices and
208	 * patches.) For now I won't bother suppressing that warning....
209	 */
210	mi->props = 0;
211
212	midi_register_hw_if_ext(&midisyn_hw_if_ext);
213}
214
215static void
216midisyn_get_locks(void *addr, kmutex_t **intr, kmutex_t **proc)
217{
218	midisyn *ms = addr;
219
220	*intr = ms->lock;
221	*proc = NULL;
222}
223
224static int
225midisyn_ioctl(void *maddr, u_long cmd, void *addr, int flag, struct lwp *l)
226{
227	midisyn *ms = maddr;
228
229	KASSERT(mutex_owned(ms->lock));
230
231	if (ms->mets->ioctl)
232		return (ms->mets->ioctl(ms, cmd, addr, flag, l));
233	else
234		return (EINVAL);
235}
236
237static int
238midisyn_findvoice(midisyn *ms, int chan, int note)
239{
240	u_int cn;
241	int v;
242
243	KASSERT(mutex_owned(ms->lock));
244
245	cn = MS_CHANNOTE(chan, note);
246	for (v = 0; v < ms->nvoice; v++)
247		if (ms->voices[v].chan_note == cn && ms->voices[v].inuse)
248			return (v);
249	return (-1);
250}
251
252void
253midisyn_attach(struct midi_softc *sc, midisyn *ms)
254{
255
256	if (ms->lock == NULL) {
257		panic("midisyn_attach: no lock");
258	}
259
260	/*
261	 * XXX there should be a way for this function to indicate failure
262	 * (other than panic) if some preconditions aren't met, for example
263	 * if some nonoptional methods are missing.
264	 */
265	if (ms->mets->allocv == 0) {
266		ms->voices = kmem_zalloc(ms->nvoice * sizeof(struct voice),
267		    KM_SLEEP);
268		ms->seqno = 1;
269		ms->mets->allocv = midisyn_allocvoice;
270	}
271
272	if (ms->mets->attackv_vel == 0 && ms->mets->attackv != 0)
273		ms->mets->attackv_vel = midisyn_attackv_vel;
274
275	ms->ctl = (midictl) {
276		.base_channel = 16,
277		.cookie = ms,
278		.notify = midisyn_notify
279	};
280
281	sc->hw_if = &midisyn_hw_if;
282	sc->hw_hdl = ms;
283	DPRINTF(("midisyn_attach: ms=%p\n", sc->hw_hdl));
284}
285
286static void
287midisyn_freevoice(midisyn *ms, int voice)
288{
289
290	KASSERT(mutex_owned(ms->lock));
291
292	if (ms->mets->allocv != midisyn_allocvoice)
293		return;
294	ms->voices[voice].inuse = 0;
295}
296
297static uint_fast16_t
298midisyn_allocvoice(midisyn *ms, uint_fast8_t chan, uint_fast8_t note)
299{
300	int bestv, v;
301	u_int bestseq, s;
302
303	KASSERT(mutex_owned(ms->lock));
304
305	/* Find a free voice, or if no free voice is found the oldest. */
306	bestv = 0;
307	bestseq = ms->voices[0].seqno + (ms->voices[0].inuse ? 0x40000000 : 0);
308	for (v = 1; v < ms->nvoice; v++) {
309		s = ms->voices[v].seqno;
310		if (ms->voices[v].inuse)
311			s += 0x40000000;
312		if (s < bestseq) {
313			bestseq = s;
314			bestv = v;
315		}
316	}
317	DPRINTFN(10,("midisyn_allocvoice: v=%d seq=%d cn=%x inuse=%d\n",
318		     bestv, ms->voices[bestv].seqno,
319		     ms->voices[bestv].chan_note,
320		     ms->voices[bestv].inuse));
321#ifdef AUDIO_DEBUG
322	if (ms->voices[bestv].inuse)
323		DPRINTFN(1,("midisyn_allocvoice: steal %x\n",
324			    ms->voices[bestv].chan_note));
325#endif
326	ms->voices[bestv].chan_note = MS_CHANNOTE(chan, note);
327	ms->voices[bestv].seqno = ms->seqno++;
328	ms->voices[bestv].inuse = 1;
329	return (bestv);
330}
331
332/* dummy attackv_vel that just adds vel into level for simple drivers */
333static void
334midisyn_attackv_vel(midisyn *ms, uint_fast16_t voice, midipitch_t mp,
335                    int16_t level_cB, uint_fast8_t vel)
336{
337
338	KASSERT(mutex_owned(ms->lock));
339
340	ms->voices[voice].velcB = midisyn_vol2cB((uint_fast16_t)vel << 7);
341	ms->mets->attackv(ms, voice, mp, level_cB + ms->voices[voice].velcB);
342}
343
344static int
345midisyn_sysrt(void *addr, int b)
346{
347
348	return 0;
349}
350
351static int
352midisyn_channelmsg(void *addr, int status, int chan, u_char *buf, int len)
353{
354	midisyn *ms = addr;
355	int voice = 0;		/* initialize to keep gcc quiet */
356	struct midisyn_methods *fs;
357
358	KASSERT(mutex_owned(ms->lock));
359
360	DPRINTF(("midisyn_channelmsg: ms=%p status=%#02x chan=%d\n",
361	       ms, status, chan));
362	fs = ms->mets;
363
364	switch (status) {
365	case MIDI_NOTEOFF:
366		/*
367		 * for a device that leaves voice allocation to us--and that's
368		 * all of 'em at the moment--the voice and release velocity
369		 * should be the only necessary arguments to noteoff. what use
370		 * are they making of note? checking... None. Cool.
371		 * IF there is ever a device added that does its own allocation,
372		 * extend the interface; this findvoice won't be what to do...
373		 */
374		voice = midisyn_findvoice(ms, chan, buf[1]);
375		if (voice >= 0) {
376			fs->releasev(ms, voice, buf[2]);
377			midisyn_freevoice(ms, voice);
378		}
379		break;
380	case MIDI_NOTEON:
381		/*
382		 * what's called for here, given current drivers, is an i/f
383		 * where midisyn computes a volume from vel*volume*expression*
384		 * mastervolume and passes that result as a single arg. It can
385		 * evolve later to support drivers that expose some of those
386		 * bits separately (e.g. a driver could expose a mixer register
387		 * on its sound card and use that for mastervolume).
388		 */
389		voice = fs->allocv(ms, chan, buf[1]);
390		ms->voices[voice].velcB = 0; /* assume driver handles vel */
391		fs->attackv_vel(ms, voice,
392		    midisyn_clamp_pitch(MIDIPITCH_FROM_KEY(buf[1]) +
393		                        midisyn_adj_pitch(ms, chan)),
394		    midisyn_adj_level(ms,chan), buf[2]);
395		break;
396	case MIDI_KEY_PRESSURE:
397		/*
398		 * unimplemented by the existing drivers. if we are doing
399		 * voice allocation, find the voice that corresponds to this
400		 * chan/note and define a method that passes the voice and
401		 * pressure to the driver ... not the note, /it/ doesn't matter.
402		 * For a driver that does its own allocation, a different
403		 * method may be needed passing pressure, chan, note so it can
404		 * find the right voice on its own. Be sure that whatever is
405		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
406		 */
407		break;
408	case MIDI_CTL_CHANGE:
409		midictl_change(&ms->ctl, chan, buf+1);
410		break;
411	case MIDI_PGM_CHANGE:
412		if (fs->pgmchg)
413			fs->pgmchg(ms, chan, buf[1]);
414		break;
415	case MIDI_CHN_PRESSURE:
416		/*
417		 * unimplemented by the existing drivers. if driver exposes no
418		 * distinct method, can use KEY_PRESSURE method for each voice
419		 * on channel. Be sure that whatever is
420		 * done here is undone when midisyn_notify sees MIDICTL_RESET.
421		 */
422		break;
423	case MIDI_PITCH_BEND:
424		/*
425		 * Will work for most drivers that simply render the midipitch
426		 * as we pass it (but not cms, which chops all the bits after
427		 * the note number and then computes its own pitch :( ). If the
428		 * driver has a repitchv method for voices already sounding, so
429		 * much the better.
430		 * The bending logic lives in the handler for bend sensitivity,
431		 * so fake a change to that to kick it off.
432		 */
433		ms->chnstate[chan].bendraw = buf[2]<<7 | buf[1];
434		ms->chnstate[chan].bendraw -= MIDI_BEND_NEUTRAL;
435		midisyn_notify(ms, MIDICTL_RPN, chan,
436		               MIDI_RPN_PITCH_BEND_SENSITIVITY);
437		break;
438	}
439	return 0;
440}
441
442static int
443midisyn_commonmsg(void *addr, int status, u_char *buf, int len)
444{
445
446	return 0;
447}
448
449static int
450midisyn_sysex(void *addr, u_char *buf, int len)
451{
452
453	/*
454	 * unimplemented by existing drivers. it is surely more sensible
455	 * to do some parsing of well-defined sysex messages here, either
456	 * handling them internally or calling specific methods on the
457	 * driver after parsing out the details, than to ask every driver
458	 * to deal with sysex messages poked at it a byte at a time.
459	 */
460	return 0;
461}
462
463static void
464midisyn_notify(void *cookie, midictl_evt evt,
465               uint_fast8_t chan, uint_fast16_t key)
466{
467	struct midisyn *ms;
468	int drvhandled;
469
470	ms = (struct midisyn *)cookie;
471
472	KASSERT(mutex_owned(ms->lock));
473
474	drvhandled = 0;
475	if ( ms->mets->ctlnotice )
476		drvhandled = ms->mets->ctlnotice(ms, evt, chan, key);
477
478	switch ( evt | key ) {
479	case MIDICTL_RESET:
480		/*
481		 * Re-read all ctls we use, revert pitchbend state.
482		 * Can do it by faking change notifications.
483		 */
484		ms->chnstate[chan].pendingreset |= PEND_ALL;
485		midisyn_notify(ms, MIDICTL_CTLR, chan,
486		               MIDI_CTRL_CHANNEL_VOLUME_MSB);
487		midisyn_notify(ms, MIDICTL_CTLR, chan,
488		               MIDI_CTRL_EXPRESSION_MSB);
489		ms->chnstate[chan].bendraw = 0; /* MIDI_BEND_NEUTRAL - itself */
490		midisyn_notify(ms, MIDICTL_RPN, chan,
491		               MIDI_RPN_PITCH_BEND_SENSITIVITY);
492		midisyn_notify(ms, MIDICTL_RPN, chan,
493		               MIDI_RPN_CHANNEL_FINE_TUNING);
494		midisyn_notify(ms, MIDICTL_RPN, chan,
495		               MIDI_RPN_CHANNEL_COARSE_TUNING);
496		break;
497	case MIDICTL_NOTES_OFF:
498		if ( drvhandled )
499			break;
500		/* releasev all voices sounding on chan; use normal vel 64 */
501		midisyn_chan_releasev(ms, chan, 64);
502		break;
503	case MIDICTL_SOUND_OFF:
504		if ( drvhandled )
505			break;
506		/* releasev all voices sounding on chan; use max vel 127 */
507		/* it is really better for driver to handle this, instantly */
508		midisyn_chan_releasev(ms, chan, 127);
509		break;
510	case MIDICTL_CTLR | MIDI_CTRL_CHANNEL_VOLUME_MSB:
511		ms->chnstate[chan].pendingreset &= ~PEND_VOL;
512		if ( drvhandled ) {
513			ms->chnstate[chan].volume = 0;
514			break;
515		}
516		ms->chnstate[chan].volume = midisyn_vol2cB(
517	    	    midictl_read(&ms->ctl, chan, key, 100<<7));
518		midisyn_upd_level(ms, chan);
519		break;
520	case MIDICTL_CTLR | MIDI_CTRL_EXPRESSION_MSB:
521		ms->chnstate[chan].pendingreset &= ~PEND_EXP;
522		if ( drvhandled ) {
523			ms->chnstate[chan].expression = 0;
524			break;
525		}
526		ms->chnstate[chan].expression = midisyn_vol2cB(
527	    	    midictl_read(&ms->ctl, chan, key, 16383));
528		midisyn_upd_level(ms, chan);
529		break;
530	/*
531	 * SOFT_PEDAL: supporting this will be trickier; must apply only
532	 * to notes subsequently struck, and must remember which voices
533	 * they are for follow-on adjustments. For another day....
534	 */
535	case MIDICTL_RPN | MIDI_RPN_PITCH_BEND_SENSITIVITY:
536		ms->chnstate[chan].pendingreset &= ~PEND_PBS;
537		if ( drvhandled )
538			ms->chnstate[chan].bend = 0;
539		else {
540			uint16_t w;
541			int8_t semis, cents;
542			w = midictl_rpn_read(&ms->ctl, chan, key, 2<<7);
543			semis = w>>7;
544			cents = w&0x7f;
545			/*
546			 * Mathematically, multiply semis by
547			 * MIDIPITCH_SEMITONE*bendraw/8192. Practically, avoid
548			 * shifting significant bits off by observing that
549			 * MIDIPITCH_SEMITONE == 1<<14 and 8192 == 1<<13, so
550			 * just take semis*bendraw<<1. Do the same with cents
551			 * except <<1 becomes /50 (but rounded).
552			 */
553			ms->chnstate[chan].bend =
554			    ( ms->chnstate[chan].bendraw * semis ) << 1;
555			ms->chnstate[chan].bend +=
556			    ((ms->chnstate[chan].bendraw * cents)/25 + 1) >> 1;
557			midisyn_upd_pitch(ms, chan);
558		}
559		break;
560	case MIDICTL_RPN | MIDI_RPN_CHANNEL_FINE_TUNING:
561		if ( drvhandled )
562			ms->chnstate[chan].tuning_fine = 0;
563		else {
564			midipitch_t mp;
565			mp = midictl_rpn_read(&ms->ctl, chan, key, 8192);
566			/*
567			 * Mathematically, subtract 8192 and scale by
568			 * MIDIPITCH_SEMITONE/8192. Practically, subtract 8192
569			 * and then << 1.
570			 */
571			ms->chnstate[chan].tuning_fine = ( mp - 8192 ) << 1;
572			midisyn_upd_pitch(ms, chan);
573		}
574		break;
575	case MIDICTL_RPN | MIDI_RPN_CHANNEL_COARSE_TUNING:
576		ms->chnstate[chan].pendingreset &= ~PEND_TNC;
577		if ( drvhandled )
578			ms->chnstate[chan].tuning_coarse = 0;
579		else {
580			midipitch_t mp;
581			/*
582			 * By definition only the MSB of this parameter is used.
583			 * Subtract 64 for a signed count of semitones; << 14
584			 * will convert to midipitch scale.
585			 */
586			mp = midictl_rpn_read(&ms->ctl, chan, key, 64<<7) >> 7;
587			ms->chnstate[chan].tuning_coarse = ( mp - 64 ) << 14;
588			midisyn_upd_pitch(ms, chan);
589		}
590		break;
591	}
592}
593
594static midipitch_t
595midisyn_clamp_pitch(midipitch_t mp)
596{
597
598	if ( mp <= 0 )
599		return 0;
600	if ( mp >= MIDIPITCH_MAX )
601		return MIDIPITCH_MAX;
602	return mp;
603}
604
605static int16_t
606midisyn_adj_level(midisyn *ms, uint_fast8_t chan)
607{
608	int32_t level;
609
610	KASSERT(mutex_owned(ms->lock));
611
612	level = ms->chnstate[chan].volume + ms->chnstate[chan].expression;
613	if ( level <= INT16_MIN )
614		return INT16_MIN;
615	return level;
616}
617
618static midipitch_t
619midisyn_adj_pitch(midisyn *ms, uint_fast8_t chan)
620{
621	struct channelstate *s = ms->chnstate + chan;
622
623	KASSERT(mutex_owned(ms->lock));
624
625	return s->bend + s->tuning_fine +s->tuning_coarse;
626}
627
628#define VOICECHAN_FOREACH_BEGIN(ms,vp,ch)			\
629	{							\
630		struct voice *vp, *_end_##vp;			\
631		for (vp=(ms)->voices,_end_##vp=vp+(ms)->nvoice;	\
632		    vp < _end_##vp; ++ vp) {			\
633			if ( !vp->inuse )			\
634				continue;			\
635			if ( MS_GETCHAN(vp) == (ch) )		\
636				;				\
637			else					\
638				continue;
639#define VOICECHAN_FOREACH_END }}
640
641static void
642midisyn_chan_releasev(midisyn *ms, uint_fast8_t chan, uint_fast8_t vel)
643{
644
645	KASSERT(mutex_owned(ms->lock));
646
647	VOICECHAN_FOREACH_BEGIN(ms,vp,chan)
648		ms->mets->releasev(ms, vp - ms->voices, vel);
649		midisyn_freevoice(ms, vp - ms->voices);
650	VOICECHAN_FOREACH_END
651}
652
653static void
654midisyn_upd_level(midisyn *ms, uint_fast8_t chan)
655{
656	int32_t level;
657	int16_t chan_level;
658
659	KASSERT(mutex_owned(ms->lock));
660
661	if ( NULL == ms->mets->relevelv )
662		return;
663
664	if ( ms->chnstate[chan].pendingreset & PEND_LEVEL )
665		return;
666
667	chan_level = midisyn_adj_level(ms, chan);
668
669	VOICECHAN_FOREACH_BEGIN(ms,vp,chan)
670		level = vp->velcB + chan_level;
671		ms->mets->relevelv(ms, vp - ms->voices,
672		    level <= INT16_MIN ? INT16_MIN : level);
673	VOICECHAN_FOREACH_END
674}
675
676static void
677midisyn_upd_pitch(midisyn *ms, uint_fast8_t chan)
678{
679	midipitch_t chan_adj;
680
681	KASSERT(mutex_owned(ms->lock));
682
683	if ( NULL == ms->mets->repitchv )
684		return;
685
686	if ( ms->chnstate[chan].pendingreset & PEND_PITCH )
687		return;
688
689	chan_adj = midisyn_adj_pitch(ms, chan);
690
691	VOICECHAN_FOREACH_BEGIN(ms,vp,chan)
692		ms->mets->repitchv(ms, vp - ms->voices,
693		    midisyn_clamp_pitch(chan_adj +
694		        MIDIPITCH_FROM_KEY(vp->chan_note&0x7f)));
695	VOICECHAN_FOREACH_END
696}
697
698#undef VOICECHAN_FOREACH_END
699#undef VOICECHAN_FOREACH_BEGIN
700
701int16_t
702midisyn_vol2cB(uint_fast16_t vol)
703{
704	int16_t cB = 0;
705	int32_t v;
706
707	if ( 0 == vol )
708		return INT16_MIN;
709	/*
710	 * Adjust vol to fall in the range 8192..16383. Each doubling is
711	 * worth 12 dB.
712	 */
713	while ( vol < 8192 ) {
714		vol <<= 1;
715		cB -= 120;
716	}
717	v = vol; /* ensure evaluation in signed 32 bit below */
718	/*
719	 * The GM vol-to-dB formula is dB = 40 log ( v / 127 ) for 7-bit v.
720	 * The vol and expression controllers are in 14-bit space so the
721	 * equivalent is 40 log ( v / 16256 ) - that is, MSB 127 LSB 0 because
722	 * the LSB is commonly unused. MSB 127 LSB 127 would then be a tiny
723	 * bit over.
724	 * 1 dB resolution is a little coarser than we'd like, so let's shoot
725	 * for centibels, i.e. 400 log ( v / 16256 ), and shift everything left
726	 * as far as will fit in 32 bits, which turns out to be a shift of 22.
727	 * This minimax polynomial approximation is good to about a centibel
728	 * on the range 8192..16256, a shade worse (1.4 or so) above that.
729	 * 26385/10166 is the 6th convergent of the coefficient for v^2.
730	 */
731	cB += ( v * ( 124828 - ( v * 26385 ) / 10166 ) - 1347349038 ) >> 22;
732	return cB;
733}
734
735/*
736 * MIDI RP-012 constitutes a MIDI Tuning Specification. The units are
737 * fractional-MIDIkeys, that is, the key number 00 - 7f left shifted
738 * 14 bits to provide a 14-bit fraction that divides each semitone. The
739 * whole thing is just a 21-bit number that is bent and tuned simply by
740 * adding and subtracting--the same offset is the same pitch change anywhere
741 * on the scale. One downside is that a cent is 163.84 of these units, so
742 * you can't expect a lengthy integer sum of cents to come out in tune; if you
743 * do anything in cents it is best to use them only for local adjustment of
744 * a pitch.
745 *
746 * This function converts a pitch in MIDItune units to Hz left-shifted 18 bits.
747 * That should leave you enough to shift down to whatever precision the hardware
748 * supports.
749 *
750 * Its prototype is exposed in <sys/midiio.h>.
751 */
752midihz18_t
753midisyn_mp2hz18(midipitch_t mp)
754{
755	int64_t t64a, t64b;
756	uint_fast8_t shift;
757
758	/*
759	 * Scale from the logarithmic MIDI-Tuning units to Hz<<18. Uses the
760	 * continued-fraction form of a 2/2 rational function derived to
761	 * cover the highest octave (mt 1900544..2097151 or 74.00.00..7f.7f.7f
762	 * in RP-012-speak, the dotted bits are 7 wide) to produce Hz shifted
763	 * left just as far as the maximum Hz will fit in a uint32, which
764	 * turns out to be 18. Just shift off the result for lower octaves.
765	 * Fit is within 1/4 MIDI tuning unit throughout (disclaimer: the
766	 * comparison relied on the double-precision log in libm).
767	 */
768
769	if ( 0 == mp )
770		return 2143236;
771
772	for ( shift = 0; mp < 1900544; ++ shift )
773		mp += MIDIPITCH_OCTAVE;
774
775	if ( 1998848 == mp )
776		return UINT32_C(2463438621) >> shift;
777
778	t64a  = 0x5a1a0ee4; /* INT64_C(967879298788) gcc333: spurious warning */
779	t64a |= (int64_t)0xe1 << 32;
780	t64a /= mp - 1998848; /* here's why 1998848 is special-cased above ;) */
781	t64a += mp - 3704981;
782	t64b  = 0x6763759d; /* INT64_C(8405905567872413) goofy warning again */
783	t64b |= (int64_t)0x1ddd20 << 32;
784	t64b /= t64a;
785	t64b += UINT32_C(2463438619);
786	return (uint32_t)t64b >> shift;
787}
788