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