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