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