spkr.c revision 7090
1/*
2 * spkr.c -- device driver for console speaker
3 *
4 * v1.4 by Eric S. Raymond (esr@snark.thyrsus.com) Aug 1993
5 * modified for FreeBSD by Andrew A. Chernov <ache@astral.msk.su>
6 *
7 *    $Id: spkr.c,v 1.11 1995/02/03 10:19:38 ache Exp $
8 */
9
10#include "speaker.h"
11
12#if NSPEAKER > 0
13
14#include <sys/param.h>
15#include <sys/systm.h>
16#include <sys/kernel.h>
17#include <sys/errno.h>
18#include <sys/buf.h>
19#include <sys/proc.h>
20#include <sys/uio.h>
21#include <i386/isa/isa.h>
22#include <i386/isa/timerreg.h>
23#include <machine/clock.h>
24#include <machine/speaker.h>
25
26/**************** MACHINE DEPENDENT PART STARTS HERE *************************
27 *
28 * This section defines a function tone() which causes a tone of given
29 * frequency and duration from the 80x86's console speaker.
30 * Another function endtone() is defined to force sound off, and there is
31 * also a rest() entry point to do pauses.
32 *
33 * Audible sound is generated using the Programmable Interval Timer (PIT) and
34 * Programmable Peripheral Interface (PPI) attached to the 80x86's speaker. The
35 * PPI controls whether sound is passed through at all; the PIT's channel 2 is
36 * used to generate clicks (a square wave) of whatever frequency is desired.
37 */
38
39/*
40 * PIT and PPI port addresses and control values
41 *
42 * Most of the magic is hidden in the TIMER_PREP value, which selects PIT
43 * channel 2, frequency LSB first, square-wave mode and binary encoding.
44 * The encoding is as follows:
45 *
46 * +----------+----------+---------------+-----+
47 * |  1    0  |  1    1  |  0    1    1  |  0  |
48 * | SC1  SC0 | RW1  RW0 | M2   M1   M0  | BCD |
49 * +----------+----------+---------------+-----+
50 *   Counter     Write        Mode 3      Binary
51 *  Channel 2  LSB first,  (Square Wave) Encoding
52 *             MSB second
53 */
54#define PPI_SPKR	0x03	/* turn these PPI bits on to pass sound */
55#define PIT_MODE	0xB6	/* set timer mode for sound generation */
56
57/*
58 * Magic numbers for timer control.
59 */
60#define TIMER_CLK	1193180L	/* corresponds to 18.2 MHz tick rate */
61
62#define SPKRPRI PSOCK
63static char endtone, endrest;
64
65static void tone(thz, ticks)
66/* emit tone of frequency thz for given number of ticks */
67unsigned int thz, ticks;
68{
69    unsigned int divisor = TIMER_CLK / thz;
70    int sps;
71
72#ifdef DEBUG
73    (void) printf("tone: thz=%d ticks=%d\n", thz, ticks);
74#endif /* DEBUG */
75
76    /* set timer to generate clicks at given frequency in Hertz */
77    sps = spltty();
78
79    if (acquire_timer2(PIT_MODE)) {
80	/* enter list of waiting procs ??? */
81	return;
82    }
83    outb(TIMER_CNTR2, (divisor & 0xff));	/* send lo byte */
84    outb(TIMER_CNTR2, (divisor >> 8));	/* send hi byte */
85    splx(sps);
86
87    /* turn the speaker on */
88    outb(IO_PPI, inb(IO_PPI) | PPI_SPKR);
89
90    /*
91     * Set timeout to endtone function, then give up the timeslice.
92     * This is so other processes can execute while the tone is being
93     * emitted.
94     */
95    if (ticks > 0)
96	tsleep((caddr_t)&endtone, SPKRPRI | PCATCH, "spkrtn", ticks);
97    outb(IO_PPI, inb(IO_PPI) & ~PPI_SPKR);
98    release_timer2();
99}
100
101static void rest(ticks)
102/* rest for given number of ticks */
103int	ticks;
104{
105    /*
106     * Set timeout to endrest function, then give up the timeslice.
107     * This is so other processes can execute while the rest is being
108     * waited out.
109     */
110#ifdef DEBUG
111    (void) printf("rest: %d\n", ticks);
112#endif /* DEBUG */
113    if (ticks > 0)
114	tsleep((caddr_t)&endrest, SPKRPRI | PCATCH, "spkrrs", ticks);
115}
116
117/**************** PLAY STRING INTERPRETER BEGINS HERE **********************
118 *
119 * Play string interpretation is modelled on IBM BASIC 2.0's PLAY statement;
120 * M[LNS] are missing; the ~ synonym and the _ slur mark and the octave-
121 * tracking facility are added.
122 * Requires tone(), rest(), and endtone(). String play is not interruptible
123 * except possibly at physical block boundaries.
124 */
125
126typedef int	bool;
127#define TRUE	1
128#define FALSE	0
129
130#define toupper(c)	((c) - ' ' * (((c) >= 'a') && ((c) <= 'z')))
131#define isdigit(c)	(((c) >= '0') && ((c) <= '9'))
132#define dtoi(c)		((c) - '0')
133
134static int octave;	/* currently selected octave */
135static int whole;	/* whole-note time at current tempo, in ticks */
136static int value;	/* whole divisor for note time, quarter note = 1 */
137static int fill;	/* controls spacing of notes */
138static bool octtrack;	/* octave-tracking on? */
139static bool octprefix;	/* override current octave-tracking state? */
140
141/*
142 * Magic number avoidance...
143 */
144#define SECS_PER_MIN	60	/* seconds per minute */
145#define WHOLE_NOTE	4	/* quarter notes per whole note */
146#define MIN_VALUE	64	/* the most we can divide a note by */
147#define DFLT_VALUE	4	/* default value (quarter-note) */
148#define FILLTIME	8	/* for articulation, break note in parts */
149#define STACCATO	6	/* 6/8 = 3/4 of note is filled */
150#define NORMAL		7	/* 7/8ths of note interval is filled */
151#define LEGATO		8	/* all of note interval is filled */
152#define DFLT_OCTAVE	4	/* default octave */
153#define MIN_TEMPO	32	/* minimum tempo */
154#define DFLT_TEMPO	120	/* default tempo */
155#define MAX_TEMPO	255	/* max tempo */
156#define NUM_MULT	3	/* numerator of dot multiplier */
157#define DENOM_MULT	2	/* denominator of dot multiplier */
158
159/* letter to half-tone:  A   B  C  D  E  F  G */
160static int notetab[8] = {9, 11, 0, 2, 4, 5, 7};
161
162/*
163 * This is the American Standard A440 Equal-Tempered scale with frequencies
164 * rounded to nearest integer. Thank Goddess for the good ol' CRC Handbook...
165 * our octave 0 is standard octave 2.
166 */
167#define OCTAVE_NOTES	12	/* semitones per octave */
168static int pitchtab[] =
169{
170/*        C     C#    D     D#    E     F     F#    G     G#    A     A#    B*/
171/* 0 */   65,   69,   73,   78,   82,   87,   93,   98,  103,  110,  117,  123,
172/* 1 */  131,  139,  147,  156,  165,  175,  185,  196,  208,  220,  233,  247,
173/* 2 */  262,  277,  294,  311,  330,  349,  370,  392,  415,  440,  466,  494,
174/* 3 */  523,  554,  587,  622,  659,  698,  740,  784,  831,  880,  932,  988,
175/* 4 */ 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1975,
176/* 5 */ 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951,
177/* 6 */ 4186, 4435, 4698, 4978, 5274, 5588, 5920, 6272, 6644, 7040, 7459, 7902,
178};
179
180static void playinit()
181{
182    octave = DFLT_OCTAVE;
183    whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / DFLT_TEMPO;
184    fill = NORMAL;
185    value = DFLT_VALUE;
186    octtrack = FALSE;
187    octprefix = TRUE;	/* act as though there was an initial O(n) */
188}
189
190static void playtone(pitch, value, sustain)
191/* play tone of proper duration for current rhythm signature */
192int	pitch, value, sustain;
193{
194    register int	sound, silence, snum = 1, sdenom = 1;
195
196    /* this weirdness avoids floating-point arithmetic */
197    for (; sustain; sustain--)
198    {
199	/* See the BUGS section in the man page for discussion */
200	snum *= NUM_MULT;
201	sdenom *= DENOM_MULT;
202    }
203
204    if (pitch == -1)
205	rest(whole * snum / (value * sdenom));
206    else
207    {
208	sound = (whole * snum) / (value * sdenom)
209		- (whole * (FILLTIME - fill)) / (value * FILLTIME);
210	silence = whole * (FILLTIME-fill) * snum / (FILLTIME * value * sdenom);
211
212#ifdef DEBUG
213	(void) printf("playtone: pitch %d for %d ticks, rest for %d ticks\n",
214			pitch, sound, silence);
215#endif /* DEBUG */
216
217	tone(pitchtab[pitch], sound);
218	if (fill != LEGATO)
219	    rest(silence);
220    }
221}
222
223static int abs(n)
224int n;
225{
226    if (n < 0)
227	return(-n);
228    else
229	return(n);
230}
231
232static void playstring(cp, slen)
233/* interpret and play an item from a notation string */
234char	*cp;
235size_t	slen;
236{
237    int		pitch, oldfill, lastpitch = OCTAVE_NOTES * DFLT_OCTAVE;
238
239#define GETNUM(cp, v)	for(v=0; isdigit(cp[1]) && slen > 0; ) \
240				{v = v * 10 + (*++cp - '0'); slen--;}
241    for (; slen--; cp++)
242    {
243	int		sustain, timeval, tempo;
244	register char	c = toupper(*cp);
245
246#ifdef DEBUG
247	(void) printf("playstring: %c (%x)\n", c, c);
248#endif /* DEBUG */
249
250	switch (c)
251	{
252	case 'A':  case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
253
254	    /* compute pitch */
255	    pitch = notetab[c - 'A'] + octave * OCTAVE_NOTES;
256
257	    /* this may be followed by an accidental sign */
258	    if (cp[1] == '#' || cp[1] == '+')
259	    {
260		++pitch;
261		++cp;
262		slen--;
263	    }
264	    else if (cp[1] == '-')
265	    {
266		--pitch;
267		++cp;
268		slen--;
269	    }
270
271	    /*
272	     * If octave-tracking mode is on, and there has been no octave-
273	     * setting prefix, find the version of the current letter note
274	     * closest to the last regardless of octave.
275	     */
276	    if (octtrack && !octprefix)
277	    {
278		if (abs(pitch-lastpitch) > abs(pitch+OCTAVE_NOTES-lastpitch))
279		{
280		    ++octave;
281		    pitch += OCTAVE_NOTES;
282		}
283
284		if (abs(pitch-lastpitch) > abs((pitch-OCTAVE_NOTES)-lastpitch))
285		{
286		    --octave;
287		    pitch -= OCTAVE_NOTES;
288		}
289	    }
290	    octprefix = FALSE;
291	    lastpitch = pitch;
292
293	    /* ...which may in turn be followed by an override time value */
294	    GETNUM(cp, timeval);
295	    if (timeval <= 0 || timeval > MIN_VALUE)
296		timeval = value;
297
298	    /* ...and/or sustain dots */
299	    for (sustain = 0; cp[1] == '.'; cp++)
300	    {
301		slen--;
302		sustain++;
303	    }
304
305	    /* ...and/or a slur mark */
306	    oldfill = fill;
307	    if (cp[1] == '_')
308	    {
309		fill = LEGATO;
310		++cp;
311		slen--;
312	    }
313
314	    /* time to emit the actual tone */
315	    playtone(pitch, timeval, sustain);
316
317	    fill = oldfill;
318	    break;
319
320	case 'O':
321	    if (cp[1] == 'N' || cp[1] == 'n')
322	    {
323		octprefix = octtrack = FALSE;
324		++cp;
325		slen--;
326	    }
327	    else if (cp[1] == 'L' || cp[1] == 'l')
328	    {
329		octtrack = TRUE;
330		++cp;
331		slen--;
332	    }
333	    else
334	    {
335		GETNUM(cp, octave);
336		if (octave >= sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES)
337		    octave = DFLT_OCTAVE;
338		octprefix = TRUE;
339	    }
340	    break;
341
342	case '>':
343	    if (octave < sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES - 1)
344		octave++;
345	    octprefix = TRUE;
346	    break;
347
348	case '<':
349	    if (octave > 0)
350		octave--;
351	    octprefix = TRUE;
352	    break;
353
354	case 'N':
355	    GETNUM(cp, pitch);
356	    for (sustain = 0; cp[1] == '.'; cp++)
357	    {
358		slen--;
359		sustain++;
360	    }
361	    oldfill = fill;
362	    if (cp[1] == '_')
363	    {
364		fill = LEGATO;
365		++cp;
366		slen--;
367	    }
368	    playtone(pitch - 1, value, sustain);
369	    fill = oldfill;
370	    break;
371
372	case 'L':
373	    GETNUM(cp, value);
374	    if (value <= 0 || value > MIN_VALUE)
375		value = DFLT_VALUE;
376	    break;
377
378	case 'P':
379	case '~':
380	    /* this may be followed by an override time value */
381	    GETNUM(cp, timeval);
382	    if (timeval <= 0 || timeval > MIN_VALUE)
383		timeval = value;
384	    for (sustain = 0; cp[1] == '.'; cp++)
385	    {
386		slen--;
387		sustain++;
388	    }
389	    playtone(-1, timeval, sustain);
390	    break;
391
392	case 'T':
393	    GETNUM(cp, tempo);
394	    if (tempo < MIN_TEMPO || tempo > MAX_TEMPO)
395		tempo = DFLT_TEMPO;
396	    whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / tempo;
397	    break;
398
399	case 'M':
400	    if (cp[1] == 'N' || cp[1] == 'n')
401	    {
402		fill = NORMAL;
403		++cp;
404		slen--;
405	    }
406	    else if (cp[1] == 'L' || cp[1] == 'l')
407	    {
408		fill = LEGATO;
409		++cp;
410		slen--;
411	    }
412	    else if (cp[1] == 'S' || cp[1] == 's')
413	    {
414		fill = STACCATO;
415		++cp;
416		slen--;
417	    }
418	    break;
419	}
420    }
421}
422
423/******************* UNIX DRIVER HOOKS BEGIN HERE **************************
424 *
425 * This section implements driver hooks to run playstring() and the tone(),
426 * endtone(), and rest() functions defined above.
427 */
428
429static int spkr_active = FALSE; /* exclusion flag */
430static struct buf *spkr_inbuf;  /* incoming buf */
431
432int spkropen(dev)
433dev_t	dev;
434{
435#ifdef DEBUG
436    (void) printf("spkropen: entering with dev = %x\n", dev);
437#endif /* DEBUG */
438
439    if (minor(dev) != 0)
440	return(ENXIO);
441    else if (spkr_active)
442	return(EBUSY);
443    else
444    {
445#ifdef DEBUG
446	(void) printf("spkropen: about to perform play initialization\n");
447#endif /* DEBUG */
448	playinit();
449	spkr_inbuf = geteblk(DEV_BSIZE);
450	spkr_active = TRUE;
451	return(0);
452    }
453}
454
455int spkrwrite(dev, uio)
456dev_t		dev;
457struct uio	*uio;
458{
459#ifdef DEBUG
460    printf("spkrwrite: entering with dev = %x, count = %d\n",
461		dev, uio->uio_resid);
462#endif /* DEBUG */
463
464    if (minor(dev) != 0)
465	return(ENXIO);
466    else if (uio->uio_resid > DEV_BSIZE)     /* prevent system crashes */
467	return(E2BIG);
468    else
469    {
470	unsigned n;
471	char *cp;
472	int error;
473
474	n = uio->uio_resid;
475	cp = spkr_inbuf->b_un.b_addr;
476	if (!(error = uiomove(cp, n, uio)))
477		playstring(cp, n);
478	return(error);
479    }
480}
481
482int spkrclose(dev)
483dev_t	dev;
484{
485#ifdef DEBUG
486    (void) printf("spkrclose: entering with dev = %x\n", dev);
487#endif /* DEBUG */
488
489    if (minor(dev) != 0)
490	return(ENXIO);
491    else
492    {
493	wakeup((caddr_t)&endtone);
494	wakeup((caddr_t)&endrest);
495	brelse(spkr_inbuf);
496	spkr_active = FALSE;
497	return(0);
498    }
499}
500
501int spkrioctl(dev, cmd, cmdarg)
502dev_t	dev;
503int	cmd;
504caddr_t	cmdarg;
505{
506#ifdef DEBUG
507    (void) printf("spkrioctl: entering with dev = %x, cmd = %x\n");
508#endif /* DEBUG */
509
510    if (minor(dev) != 0)
511	return(ENXIO);
512    else if (cmd == SPKRTONE)
513    {
514	tone_t	*tp = (tone_t *)cmdarg;
515
516	if (tp->frequency == 0)
517	    rest(tp->duration);
518	else
519	    tone(tp->frequency, tp->duration);
520	return 0;
521    }
522    else if (cmd == SPKRTUNE)
523    {
524	tone_t  *tp = (tone_t *)(*(caddr_t *)cmdarg);
525	tone_t ttp;
526	int error;
527
528	for (; ; tp++) {
529	    error = copyin(tp, &ttp, sizeof(tone_t));
530	    if (error)
531		    return(error);
532	    if (ttp.duration == 0)
533		    break;
534	    if (ttp.frequency == 0)
535		 rest(ttp.duration);
536	    else
537		 tone(ttp.frequency, ttp.duration);
538	}
539	return(0);
540    }
541    return(EINVAL);
542}
543
544#endif  /* NSPEAKER > 0 */
545/* spkr.c ends here */
546