xref: /freebsd/usr.sbin/cdcontrol/cdcontrol.c (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 /*
2  * Compact Disc Control Utility by Serge V. Vakulenko <vak@cronyx.ru>.
3  * Based on the non-X based CD player by Jean-Marc Zucconi and
4  * Andrey A. Chernov.
5  *
6  * Fixed and further modified on 5-Sep-1995 by Jukka Ukkonen <jau@funet.fi>.
7  *
8  * 11-Sep-1995: Jukka A. Ukkonen <jau@funet.fi>
9  *              A couple of further fixes to my own earlier "fixes".
10  *
11  * 18-Sep-1995: Jukka A. Ukkonen <jau@funet.fi>
12  *              Added an ability to specify addresses relative to the
13  *              beginning of a track. This is in fact a variation of
14  *              doing the simple play_msf() call.
15  *
16  * 11-Oct-1995: Serge V.Vakulenko <vak@cronyx.ru>
17  *              New eject algorithm.
18  *              Some code style reformatting.
19  *
20  * 13-Dec-1999: Knut A. Syed <kas@kas.no>
21  * 		Volume-command modified.  If used with only one
22  * 		parameter it now sets both channels.  If used without
23  * 		parameters it will print volume-info.
24  * 		Version 2.0.1
25  *
26  * 27-Jun-2008  Pietro Cerutti <gahr@FreeBSD.org>
27  * 		Further enhancement to volume. Values not in range 0-255
28  * 		are now reduced to be in range. This prevents overflow in
29  * 		the uchar storing the volume (256 -> 0, -20 -> 236, ...).
30  * 		Version 2.0.2
31  *
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/cdio.h>
38 #include <sys/cdrio.h>
39 #include <sys/file.h>
40 #include <sys/ioctl.h>
41 #include <sys/param.h>
42 #include <arpa/inet.h>
43 #include <ctype.h>
44 #include <err.h>
45 #include <errno.h>
46 #include <histedit.h>
47 #include <limits.h>
48 #include <paths.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <vis.h>
54 
55 #define VERSION "2.0.2"
56 
57 #define ASTS_INVALID	0x00  /* Audio status byte not valid */
58 #define ASTS_PLAYING	0x11  /* Audio play operation in progress */
59 #define ASTS_PAUSED	0x12  /* Audio play operation paused */
60 #define ASTS_COMPLETED	0x13  /* Audio play operation successfully completed */
61 #define ASTS_ERROR	0x14  /* Audio play operation stopped due to error */
62 #define ASTS_VOID	0x15  /* No current audio status to return */
63 
64 #ifdef DEFAULT_CD_DRIVE
65 #  error "Setting DEFAULT_CD_DRIVE is no longer supported"
66 #endif
67 
68 #define CMD_DEBUG	1
69 #define CMD_EJECT	2
70 #define CMD_HELP	3
71 #define CMD_INFO	4
72 #define CMD_PAUSE	5
73 #define CMD_PLAY	6
74 #define CMD_QUIT	7
75 #define CMD_RESUME	8
76 #define CMD_STOP	9
77 #define CMD_VOLUME	10
78 #define CMD_CLOSE	11
79 #define CMD_RESET	12
80 #define CMD_SET		13
81 #define CMD_STATUS	14
82 #define CMD_CDID	15
83 #define CMD_NEXT	16
84 #define CMD_PREVIOUS	17
85 #define CMD_SPEED	18
86 #define STATUS_AUDIO	0x1
87 #define STATUS_MEDIA	0x2
88 #define STATUS_VOLUME	0x4
89 
90 static struct cmdtab {
91 	int command;
92 	const char *name;
93 	unsigned min;
94 	const char *args;
95 } cmdtab[] = {
96 { CMD_CLOSE,	"close",	1, "" },
97 { CMD_DEBUG,	"debug",	1, "on | off" },
98 { CMD_EJECT,	"eject",	1, "" },
99 { CMD_HELP,	"?",		1, 0 },
100 { CMD_HELP,	"help",		1, "" },
101 { CMD_INFO,	"info",		1, "" },
102 { CMD_NEXT,	"next",		1, "" },
103 { CMD_PAUSE,	"pause",	2, "" },
104 { CMD_PLAY,	"play",		1, "min1:sec1[.fram1] [min2:sec2[.fram2]]" },
105 { CMD_PLAY,	"play",		1, "track1[.index1] [track2[.index2]]" },
106 { CMD_PLAY,	"play",		1, "tr1 m1:s1[.f1] [[tr2] [m2:s2[.f2]]]" },
107 { CMD_PLAY,	"play",		1, "[#block [len]]" },
108 { CMD_PREVIOUS,	"previous",	2, "" },
109 { CMD_QUIT,	"quit",		1, "" },
110 { CMD_RESET,	"reset",	4, "" },
111 { CMD_RESUME,	"resume",	1, "" },
112 { CMD_SET,	"set",		2, "msf | lba" },
113 { CMD_STATUS,	"status",	1, "[audio | media | volume]" },
114 { CMD_STOP,	"stop",		3, "" },
115 { CMD_VOLUME,	"volume",	1,
116       "<l&r> <l> <r> | left | right | mute | mono | stereo" },
117 { CMD_CDID,	"cdid",		2, "" },
118 { CMD_SPEED,	"speed",	2, "speed" },
119 { 0,		NULL,		0, NULL }
120 };
121 
122 static struct cd_toc_entry toc_buffer[100];
123 
124 static const char *cdname;
125 static int	fd = -1;
126 static int	verbose = 1;
127 static int	msf = 1;
128 
129 static int	 setvol(int, int);
130 static int	 read_toc_entrys(int);
131 static int	 play_msf(int, int, int, int, int, int);
132 static int	 play_track(int, int, int, int);
133 static int	 status(int *, int *, int *, int *);
134 static int	 open_cd(void);
135 static int	 next_prev(char *arg, int);
136 static int	 play(char *arg);
137 static int	 info(char *arg);
138 static int	 cdid(void);
139 static int	 pstatus(char *arg);
140 static char	*input(int *);
141 static void	 prtrack(struct cd_toc_entry *e, int lastflag);
142 static void	 lba2msf(unsigned long lba, u_char *m, u_char *s, u_char *f);
143 static unsigned int msf2lba(u_char m, u_char s, u_char f);
144 static int	 play_blocks(int blk, int len);
145 static int	 run(int cmd, char *arg);
146 static char	*parse(char *buf, int *cmd);
147 static void	 help(void);
148 static void	 usage(void);
149 static char	*use_cdrom_instead(const char *);
150 static const char *strstatus(int);
151 static u_int	 dbprog_discid(void);
152 static const char *cdcontrol_prompt(void);
153 
154 static void
155 help(void)
156 {
157 	struct cmdtab *c;
158 	const char *s;
159 	char n;
160 	int i;
161 
162 	for (c=cmdtab; c->name; ++c) {
163 		if (! c->args)
164 			continue;
165 		printf("\t");
166 		for (i = c->min, s = c->name; *s; s++, i--) {
167 			if (i > 0)
168 				n = toupper(*s);
169 			else
170 				n = *s;
171 			putchar(n);
172 		}
173 		if (*c->args)
174 			printf (" %s", c->args);
175 		printf ("\n");
176 	}
177 	printf ("\n\tThe word \"play\" is not required for the play commands.\n");
178 	printf ("\tThe plain target address is taken as a synonym for play.\n");
179 }
180 
181 static void
182 usage(void)
183 {
184 	fprintf (stderr, "usage: cdcontrol [-sv] [-f device] [command ...]\n");
185 	exit (1);
186 }
187 
188 static char *
189 use_cdrom_instead(const char *old_envvar)
190 {
191 	char *device;
192 
193 	device = getenv(old_envvar);
194 	if (device)
195 		warnx("%s environment variable deprecated, "
196 		    "please use CDROM in the future.", old_envvar);
197 	return device;
198 }
199 
200 
201 int
202 main(int argc, char **argv)
203 {
204 	int cmd;
205 	char *arg;
206 
207 	for (;;) {
208 		switch (getopt (argc, argv, "svhf:")) {
209 		case -1:
210 			break;
211 		case 's':
212 			verbose = 0;
213 			continue;
214 		case 'v':
215 			verbose = 2;
216 			continue;
217 		case 'f':
218 			cdname = optarg;
219 			continue;
220 		case 'h':
221 		default:
222 			usage ();
223 		}
224 		break;
225 	}
226 	argc -= optind;
227 	argv += optind;
228 
229 	if (argc > 0 && ! strcasecmp (*argv, "help"))
230 		usage ();
231 
232 	if (! cdname) {
233 		cdname = getenv("CDROM");
234 	}
235 
236 	if (! cdname)
237 		cdname = use_cdrom_instead("MUSIC_CD");
238 	if (! cdname)
239 		cdname = use_cdrom_instead("CD_DRIVE");
240 	if (! cdname)
241 		cdname = use_cdrom_instead("DISC");
242 	if (! cdname)
243 		cdname = use_cdrom_instead("CDPLAY");
244 
245 	if (argc > 0) {
246 		char buf[80], *p;
247 		int len, rc;
248 
249 		for (p=buf; argc-->0; ++argv) {
250 			len = strlen (*argv);
251 
252 			if (p + len >= buf + sizeof (buf) - 1)
253 				usage ();
254 
255 			if (p > buf)
256 				*p++ = ' ';
257 
258 			strcpy (p, *argv);
259 			p += len;
260 		}
261 		*p = 0;
262 		arg = parse (buf, &cmd);
263 		rc = run (cmd, arg);
264 		if (rc < 0 && verbose)
265 			warn(NULL);
266 
267 		return (rc);
268 	}
269 
270 	if (verbose == 1)
271 		verbose = isatty (0);
272 
273 	if (verbose) {
274 		printf ("Compact Disc Control utility, version %s\n", VERSION);
275 		printf ("Type `?' for command list\n\n");
276 	}
277 
278 	for (;;) {
279 		arg = input (&cmd);
280 		if (run (cmd, arg) < 0) {
281 			if (verbose)
282 				warn(NULL);
283 			close (fd);
284 			fd = -1;
285 		}
286 		fflush (stdout);
287 	}
288 }
289 
290 static int
291 run(int cmd, char *arg)
292 {
293 	long speed;
294 	int l, r, rc, count;
295 
296 	switch (cmd) {
297 
298 	case CMD_QUIT:
299 		exit (0);
300 
301 	case CMD_INFO:
302 		if (fd < 0 && ! open_cd ())
303 			return (0);
304 
305 		return info (arg);
306 
307 	case CMD_CDID:
308 		if (fd < 0 && ! open_cd ())
309 			return (0);
310 
311 		return cdid ();
312 
313 	case CMD_STATUS:
314 		if (fd < 0 && ! open_cd ())
315 			return (0);
316 
317 		return pstatus (arg);
318 
319 	case CMD_NEXT:
320 	case CMD_PREVIOUS:
321 		if (fd < 0 && ! open_cd ())
322 			return (0);
323 
324 		while (isspace (*arg))
325 			arg++;
326 
327 		return next_prev (arg, cmd);
328 
329 	case CMD_PAUSE:
330 		if (fd < 0 && ! open_cd ())
331 			return (0);
332 
333 		return ioctl (fd, CDIOCPAUSE);
334 
335 	case CMD_RESUME:
336 		if (fd < 0 && ! open_cd ())
337 			return (0);
338 
339 		return ioctl (fd, CDIOCRESUME);
340 
341 	case CMD_STOP:
342 		if (fd < 0 && ! open_cd ())
343 			return (0);
344 
345 		rc = ioctl (fd, CDIOCSTOP);
346 
347 		(void) ioctl (fd, CDIOCALLOW);
348 
349 		return (rc);
350 
351 	case CMD_RESET:
352 		if (fd < 0 && ! open_cd ())
353 			return (0);
354 
355 		rc = ioctl (fd, CDIOCRESET);
356 		if (rc < 0)
357 			return rc;
358 		close(fd);
359 		fd = -1;
360 		return (0);
361 
362 	case CMD_DEBUG:
363 		if (fd < 0 && ! open_cd ())
364 			return (0);
365 
366 		if (! strcasecmp (arg, "on"))
367 			return ioctl (fd, CDIOCSETDEBUG);
368 
369 		if (! strcasecmp (arg, "off"))
370 			return ioctl (fd, CDIOCCLRDEBUG);
371 
372 		warnx("invalid command arguments");
373 
374 		return (0);
375 
376 	case CMD_EJECT:
377 		if (fd < 0 && ! open_cd ())
378 			return (0);
379 
380 		(void) ioctl (fd, CDIOCALLOW);
381 		rc = ioctl (fd, CDIOCEJECT);
382 		if (rc < 0)
383 			return (rc);
384 		return (0);
385 
386 	case CMD_CLOSE:
387 		if (fd < 0 && ! open_cd ())
388 			return (0);
389 
390 		(void) ioctl (fd, CDIOCALLOW);
391 		rc = ioctl (fd, CDIOCCLOSE);
392 		if (rc < 0)
393 			return (rc);
394 		close(fd);
395 		fd = -1;
396 		return (0);
397 
398 	case CMD_PLAY:
399 		if (fd < 0 && ! open_cd ())
400 			return (0);
401 
402 		while (isspace (*arg))
403 			arg++;
404 
405 		return play (arg);
406 
407 	case CMD_SET:
408 		if (! strcasecmp (arg, "msf"))
409 			msf = 1;
410 		else if (! strcasecmp (arg, "lba"))
411 			msf = 0;
412 		else
413 			warnx("invalid command arguments");
414 		return (0);
415 
416 	case CMD_VOLUME:
417 		if (fd < 0 && !open_cd ())
418 			return (0);
419 
420 		if (! strlen (arg)) {
421 			char volume[] = "volume";
422 
423 		    	return pstatus (volume);
424 		}
425 
426 		if (! strncasecmp (arg, "left", strlen(arg)))
427 			return ioctl (fd, CDIOCSETLEFT);
428 
429 		if (! strncasecmp (arg, "right", strlen(arg)))
430 			return ioctl (fd, CDIOCSETRIGHT);
431 
432 		if (! strncasecmp (arg, "mono", strlen(arg)))
433 			return ioctl (fd, CDIOCSETMONO);
434 
435 		if (! strncasecmp (arg, "stereo", strlen(arg)))
436 			return ioctl (fd, CDIOCSETSTERIO);
437 
438 		if (! strncasecmp (arg, "mute", strlen(arg)))
439 			return ioctl (fd, CDIOCSETMUTE);
440 
441 		count = sscanf (arg, "%d %d", &l, &r);
442 		if (count == 1)
443 		    return setvol (l, l);
444 		if (count == 2)
445 		    return setvol (l, r);
446 		warnx("invalid command arguments");
447 		return (0);
448 
449 	case CMD_SPEED:
450 		if (fd < 0 && ! open_cd ())
451 			return (0);
452 
453 		errno = 0;
454 		if (strcasecmp("max", arg) == 0)
455 			speed = CDR_MAX_SPEED;
456 		else
457 			speed = strtol(arg, NULL, 10) * 177;
458 		if (speed <= 0 || speed > INT_MAX) {
459 			warnx("invalid command arguments %s", arg);
460 			return (0);
461 		}
462 		return ioctl(fd, CDRIOCREADSPEED, &speed);
463 
464 	default:
465 	case CMD_HELP:
466 		help ();
467 		return (0);
468 
469 	}
470 }
471 
472 static int
473 play(char *arg)
474 {
475 	struct ioc_toc_header h;
476 	unsigned int n;
477 	int rc, start, end = 0, istart = 1, iend = 1;
478 
479 	rc = ioctl (fd, CDIOREADTOCHEADER, &h);
480 
481 	if (rc < 0)
482 		return (rc);
483 
484 	n = h.ending_track - h.starting_track + 1;
485 	rc = read_toc_entrys ((n + 1) * sizeof (struct cd_toc_entry));
486 
487 	if (rc < 0)
488 		return (rc);
489 
490 	if (! arg || ! *arg) {
491 		/* Play the whole disc */
492 		if (msf)
493 			return play_blocks (0, msf2lba (toc_buffer[n].addr.msf.minute,
494 							toc_buffer[n].addr.msf.second,
495 							toc_buffer[n].addr.msf.frame));
496 		else
497 			return play_blocks (0, ntohl(toc_buffer[n].addr.lba));
498 	}
499 
500 	if (strchr (arg, '#')) {
501 		/* Play block #blk [ len ] */
502 		int blk, len = 0;
503 
504 		if (2 != sscanf (arg, "#%d%d", &blk, &len) &&
505 		    1 != sscanf (arg, "#%d", &blk))
506 			goto Clean_up;
507 
508 		if (len == 0) {
509 			if (msf)
510 				len = msf2lba (toc_buffer[n].addr.msf.minute,
511 					       toc_buffer[n].addr.msf.second,
512 					       toc_buffer[n].addr.msf.frame) - blk;
513 			else
514 				len = ntohl(toc_buffer[n].addr.lba) - blk;
515 		}
516 		return play_blocks (blk, len);
517 	}
518 
519 	if (strchr (arg, ':')) {
520 		/*
521 		 * Play MSF m1:s1 [ .f1 ] [ m2:s2 [ .f2 ] ]
522 		 *
523 		 * Will now also undestand timed addresses relative
524 		 * to the beginning of a track in the form...
525 		 *
526 		 *      tr1 m1:s1[.f1] [[tr2] [m2:s2[.f2]]]
527 		 */
528 		unsigned tr1, tr2;
529 		unsigned m1, m2, s1, s2, f1, f2;
530 		unsigned char tm, ts, tf;
531 
532 		tr2 = m2 = s2 = f2 = f1 = 0;
533 		if (8 == sscanf (arg, "%d %d:%d.%d %d %d:%d.%d",
534 		    &tr1, &m1, &s1, &f1, &tr2, &m2, &s2, &f2))
535 			goto Play_Relative_Addresses;
536 
537 		tr2 = m2 = s2 = f2 = f1 = 0;
538 		if (7 == sscanf (arg, "%d %d:%d %d %d:%d.%d",
539 		    &tr1, &m1, &s1, &tr2, &m2, &s2, &f2))
540 			goto Play_Relative_Addresses;
541 
542 		tr2 = m2 = s2 = f2 = f1 = 0;
543 		if (7 == sscanf (arg, "%d %d:%d.%d %d %d:%d",
544 		    &tr1, &m1, &s1, &f1, &tr2, &m2, &s2))
545 			goto Play_Relative_Addresses;
546 
547 		tr2 = m2 = s2 = f2 = f1 = 0;
548 		if (7 == sscanf (arg, "%d %d:%d.%d %d:%d.%d",
549 		    &tr1, &m1, &s1, &f1, &m2, &s2, &f2))
550 			goto Play_Relative_Addresses;
551 
552 		tr2 = m2 = s2 = f2 = f1 = 0;
553 		if (6 == sscanf (arg, "%d %d:%d.%d %d:%d",
554 		    &tr1, &m1, &s1, &f1, &m2, &s2))
555 			goto Play_Relative_Addresses;
556 
557 		tr2 = m2 = s2 = f2 = f1 = 0;
558 		if (6 == sscanf (arg, "%d %d:%d %d:%d.%d",
559 		    &tr1, &m1, &s1, &m2, &s2, &f2))
560 			goto Play_Relative_Addresses;
561 
562 		tr2 = m2 = s2 = f2 = f1 = 0;
563 		if (6 == sscanf (arg, "%d %d:%d.%d %d %d",
564 		    &tr1, &m1, &s1, &f1, &tr2, &m2))
565 			goto Play_Relative_Addresses;
566 
567 		tr2 = m2 = s2 = f2 = f1 = 0;
568 		if (5 == sscanf (arg, "%d %d:%d %d:%d", &tr1, &m1, &s1, &m2, &s2))
569 			goto Play_Relative_Addresses;
570 
571 		tr2 = m2 = s2 = f2 = f1 = 0;
572 		if (5 == sscanf (arg, "%d %d:%d %d %d",
573 		    &tr1, &m1, &s1, &tr2, &m2))
574 			goto Play_Relative_Addresses;
575 
576 		tr2 = m2 = s2 = f2 = f1 = 0;
577 		if (5 == sscanf (arg, "%d %d:%d.%d %d",
578 		    &tr1, &m1, &s1, &f1, &tr2))
579 			goto Play_Relative_Addresses;
580 
581 		tr2 = m2 = s2 = f2 = f1 = 0;
582 		if (4 == sscanf (arg, "%d %d:%d %d", &tr1, &m1, &s1, &tr2))
583 			goto Play_Relative_Addresses;
584 
585 		tr2 = m2 = s2 = f2 = f1 = 0;
586 		if (4 == sscanf (arg, "%d %d:%d.%d", &tr1, &m1, &s1, &f1))
587 			goto Play_Relative_Addresses;
588 
589 		tr2 = m2 = s2 = f2 = f1 = 0;
590 		if (3 == sscanf (arg, "%d %d:%d", &tr1, &m1, &s1))
591 			goto Play_Relative_Addresses;
592 
593 		tr2 = m2 = s2 = f2 = f1 = 0;
594 		goto Try_Absolute_Timed_Addresses;
595 
596 Play_Relative_Addresses:
597 		if (! tr1)
598 			tr1 = 1;
599 		else if (tr1 > n)
600 			tr1 = n;
601 
602 		tr1--;
603 
604 		if (msf) {
605 			tm = toc_buffer[tr1].addr.msf.minute;
606 			ts = toc_buffer[tr1].addr.msf.second;
607 			tf = toc_buffer[tr1].addr.msf.frame;
608 		} else
609 			lba2msf(ntohl(toc_buffer[tr1].addr.lba),
610 				&tm, &ts, &tf);
611 		if ((m1 > tm)
612 		    || ((m1 == tm)
613 		    && ((s1 > ts)
614 		    || ((s1 == ts)
615 		    && (f1 > tf))))) {
616 			printf ("Track %d is not that long.\n", tr1);
617 			return (0);
618 		}
619 
620 		f1 += tf;
621 		if (f1 >= 75) {
622 			s1 += f1 / 75;
623 			f1 %= 75;
624 		}
625 
626 		s1 += ts;
627 		if (s1 >= 60) {
628 			m1 += s1 / 60;
629 			s1 %= 60;
630 		}
631 
632 		m1 += tm;
633 
634 		if (! tr2) {
635 			if (m2 || s2 || f2) {
636 				tr2 = tr1;
637 				f2 += f1;
638 				if (f2 >= 75) {
639 					s2 += f2 / 75;
640 					f2 %= 75;
641 				}
642 
643 				s2 += s1;
644 				if (s2 > 60) {
645 					m2 += s2 / 60;
646 					s2 %= 60;
647 				}
648 
649 				m2 += m1;
650 			} else {
651 				tr2 = n;
652 				if (msf) {
653 					m2 = toc_buffer[n].addr.msf.minute;
654 					s2 = toc_buffer[n].addr.msf.second;
655 					f2 = toc_buffer[n].addr.msf.frame;
656 				} else {
657 					lba2msf(ntohl(toc_buffer[n].addr.lba),
658 						&tm, &ts, &tf);
659 					m2 = tm;
660 					s2 = ts;
661 					f2 = tf;
662 				}
663 			}
664 		} else if (tr2 > n) {
665 			tr2 = n;
666 			m2 = s2 = f2 = 0;
667 		} else {
668 			if (m2 || s2 || f2)
669 				tr2--;
670 			if (msf) {
671 				tm = toc_buffer[tr2].addr.msf.minute;
672 				ts = toc_buffer[tr2].addr.msf.second;
673 				tf = toc_buffer[tr2].addr.msf.frame;
674 			} else
675 				lba2msf(ntohl(toc_buffer[tr2].addr.lba),
676 					&tm, &ts, &tf);
677 			f2 += tf;
678 			if (f2 >= 75) {
679 				s2 += f2 / 75;
680 				f2 %= 75;
681 			}
682 
683 			s2 += ts;
684 			if (s2 > 60) {
685 				m2 += s2 / 60;
686 				s2 %= 60;
687 			}
688 
689 			m2 += tm;
690 		}
691 
692 		if (msf) {
693 			tm = toc_buffer[n].addr.msf.minute;
694 			ts = toc_buffer[n].addr.msf.second;
695 			tf = toc_buffer[n].addr.msf.frame;
696 		} else
697 			lba2msf(ntohl(toc_buffer[n].addr.lba),
698 				&tm, &ts, &tf);
699 		if ((tr2 < n)
700 		    && ((m2 > tm)
701 		    || ((m2 == tm)
702 		    && ((s2 > ts)
703 		    || ((s2 == ts)
704 		    && (f2 > tf)))))) {
705 			printf ("The playing time of the disc is not that long.\n");
706 			return (0);
707 		}
708 		return (play_msf (m1, s1, f1, m2, s2, f2));
709 
710 Try_Absolute_Timed_Addresses:
711 		if (6 != sscanf (arg, "%d:%d.%d%d:%d.%d",
712 			&m1, &s1, &f1, &m2, &s2, &f2) &&
713 		    5 != sscanf (arg, "%d:%d.%d%d:%d", &m1, &s1, &f1, &m2, &s2) &&
714 		    5 != sscanf (arg, "%d:%d%d:%d.%d", &m1, &s1, &m2, &s2, &f2) &&
715 		    3 != sscanf (arg, "%d:%d.%d", &m1, &s1, &f1) &&
716 		    4 != sscanf (arg, "%d:%d%d:%d", &m1, &s1, &m2, &s2) &&
717 		    2 != sscanf (arg, "%d:%d", &m1, &s1))
718 			goto Clean_up;
719 
720 		if (m2 == 0) {
721 			if (msf) {
722 				m2 = toc_buffer[n].addr.msf.minute;
723 				s2 = toc_buffer[n].addr.msf.second;
724 				f2 = toc_buffer[n].addr.msf.frame;
725 			} else {
726 				lba2msf(ntohl(toc_buffer[n].addr.lba),
727 					&tm, &ts, &tf);
728 				m2 = tm;
729 				s2 = ts;
730 				f2 = tf;
731 			}
732 		}
733 		return play_msf (m1, s1, f1, m2, s2, f2);
734 	}
735 
736 	/*
737 	 * Play track trk1 [ .idx1 ] [ trk2 [ .idx2 ] ]
738 	 */
739 	if (4 != sscanf (arg, "%d.%d%d.%d", &start, &istart, &end, &iend) &&
740 	    3 != sscanf (arg, "%d.%d%d", &start, &istart, &end) &&
741 	    3 != sscanf (arg, "%d%d.%d", &start, &end, &iend) &&
742 	    2 != sscanf (arg, "%d.%d", &start, &istart) &&
743 	    2 != sscanf (arg, "%d%d", &start, &end) &&
744 	    1 != sscanf (arg, "%d", &start))
745 		goto Clean_up;
746 
747 	if (end == 0)
748 		end = n;
749 	return (play_track (start, istart, end, iend));
750 
751 Clean_up:
752 	warnx("invalid command arguments");
753 	return (0);
754 }
755 
756 static int
757 next_prev(char *arg, int cmd)
758 {
759 	struct ioc_toc_header h;
760 	int dir, junk, n, off, rc, trk;
761 
762 	dir = (cmd == CMD_NEXT) ? 1 : -1;
763 	rc = ioctl (fd, CDIOREADTOCHEADER, &h);
764 	if (rc < 0)
765 		return (rc);
766 
767 	n = h.ending_track - h.starting_track + 1;
768 	rc = status (&trk, &junk, &junk, &junk);
769 	if (rc < 0)
770 		return (-1);
771 
772 	if (arg && *arg) {
773 		if (sscanf (arg, "%u", &off) != 1) {
774 		    warnx("invalid command argument");
775 		    return (0);
776 		} else
777 		    trk += off * dir;
778 	} else
779 		trk += dir;
780 
781 	if (trk > h.ending_track)
782 		trk = 1;
783 
784 	return (play_track (trk, 1, n, 1));
785 }
786 
787 static const char *
788 strstatus(int sts)
789 {
790 	switch (sts) {
791 	case ASTS_INVALID:	return ("invalid");
792 	case ASTS_PLAYING:	return ("playing");
793 	case ASTS_PAUSED:	return ("paused");
794 	case ASTS_COMPLETED:	return ("completed");
795 	case ASTS_ERROR:	return ("error");
796 	case ASTS_VOID:		return ("void");
797 	default:		return ("??");
798 	}
799 }
800 
801 static int
802 pstatus(char *arg)
803 {
804 	struct ioc_vol v;
805 	struct ioc_read_subchannel ss;
806 	struct cd_sub_channel_info data;
807 	int rc, trk, m, s, f;
808 	int what = 0;
809 	char *p, vmcn[(4 * 15) + 1];
810 
811 	while ((p = strtok(arg, " \t"))) {
812 	    arg = 0;
813 	    if (!strncasecmp(p, "audio", strlen(p)))
814 		what |= STATUS_AUDIO;
815 	    else if (!strncasecmp(p, "media", strlen(p)))
816 		what |= STATUS_MEDIA;
817 	    else if (!strncasecmp(p, "volume", strlen(p)))
818 		what |= STATUS_VOLUME;
819 	    else {
820 		warnx("invalid command arguments");
821 		return 0;
822 	    }
823 	}
824 	if (!what)
825 	    what = STATUS_AUDIO|STATUS_MEDIA|STATUS_VOLUME;
826 	if (what & STATUS_AUDIO) {
827 	    rc = status (&trk, &m, &s, &f);
828 	    if (rc >= 0)
829 		if (verbose)
830 		    printf ("Audio status = %d<%s>, current track = %d, current position = %d:%02d.%02d\n",
831 			    rc, strstatus (rc), trk, m, s, f);
832 		else
833 		    printf ("%d %d %d:%02d.%02d\n", rc, trk, m, s, f);
834 	    else
835 		printf ("No current status info available\n");
836 	}
837 	if (what & STATUS_MEDIA) {
838 	    bzero (&ss, sizeof (ss));
839 	    ss.data = &data;
840 	    ss.data_len = sizeof (data);
841 	    ss.address_format = msf ? CD_MSF_FORMAT : CD_LBA_FORMAT;
842 	    ss.data_format = CD_MEDIA_CATALOG;
843 	    rc = ioctl (fd, CDIOCREADSUBCHANNEL, (char *) &ss);
844 	    if (rc >= 0) {
845 		printf("Media catalog is %sactive",
846 		    ss.data->what.media_catalog.mc_valid ? "": "in");
847 		if (ss.data->what.media_catalog.mc_valid &&
848 		    ss.data->what.media_catalog.mc_number[0])
849 		{
850 		    strvisx (vmcn, ss.data->what.media_catalog.mc_number,
851 			    (sizeof (vmcn) - 1) / 4, VIS_OCTAL | VIS_NL);
852 		    printf(", number \"%.*s\"", (int)sizeof (vmcn), vmcn);
853 		}
854 		putchar('\n');
855 	    } else
856 		printf("No media catalog info available\n");
857 	}
858 	if (what & STATUS_VOLUME) {
859 	    rc = ioctl (fd, CDIOCGETVOL, &v);
860 	    if (rc >= 0)
861 		if (verbose)
862 		    printf ("Left volume = %d, right volume = %d\n",
863 			    v.vol[0], v.vol[1]);
864 		else
865 		    printf ("%d %d\n", v.vol[0], v.vol[1]);
866 	    else
867 		printf ("No volume level info available\n");
868 	}
869 	return(0);
870 }
871 
872 /*
873  * dbprog_sum
874  *	Convert an integer to its text string representation, and
875  *	compute its checksum.  Used by dbprog_discid to derive the
876  *	disc ID.
877  *
878  * Args:
879  *	n - The integer value.
880  *
881  * Return:
882  *	The integer checksum.
883  */
884 static int
885 dbprog_sum(int n)
886 {
887 	char	buf[12],
888 		*p;
889 	int	ret = 0;
890 
891 	/* For backward compatibility this algorithm must not change */
892 	sprintf(buf, "%u", n);
893 	for (p = buf; *p != '\0'; p++)
894 		ret += (*p - '0');
895 
896 	return(ret);
897 }
898 
899 
900 /*
901  * dbprog_discid
902  *	Compute a magic disc ID based on the number of tracks,
903  *	the length of each track, and a checksum of the string
904  *	that represents the offset of each track.
905  *
906  * Args:
907  *	s - Pointer to the curstat_t structure.
908  *
909  * Return:
910  *	The integer disc ID.
911  */
912 static u_int
913 dbprog_discid(void)
914 {
915 	struct	ioc_toc_header h;
916 	int	rc;
917 	int	i, ntr,
918 		t = 0,
919 		n = 0;
920 
921 	rc = ioctl (fd, CDIOREADTOCHEADER, &h);
922 	if (rc < 0)
923 		return 0;
924 	ntr = h.ending_track - h.starting_track + 1;
925 	i = msf;
926 	msf = 1;
927 	rc = read_toc_entrys ((ntr + 1) * sizeof (struct cd_toc_entry));
928 	msf = i;
929 	if (rc < 0)
930 		return 0;
931 	/* For backward compatibility this algorithm must not change */
932 	for (i = 0; i < ntr; i++) {
933 #define TC_MM(a) toc_buffer[a].addr.msf.minute
934 #define TC_SS(a) toc_buffer[a].addr.msf.second
935 		n += dbprog_sum((TC_MM(i) * 60) + TC_SS(i));
936 
937 		t += ((TC_MM(i+1) * 60) + TC_SS(i+1)) -
938 		    ((TC_MM(i) * 60) + TC_SS(i));
939 	}
940 
941 	return((n % 0xff) << 24 | t << 8 | ntr);
942 }
943 
944 static int
945 cdid(void)
946 {
947 	u_int	id;
948 
949 	id = dbprog_discid();
950 	if (id)
951 	{
952 		if (verbose)
953 			printf ("CDID=");
954 		printf ("%08x\n",id);
955 	}
956 	return id ? 0 : 1;
957 }
958 
959 static int
960 info(char *arg __unused)
961 {
962 	struct ioc_toc_header h;
963 	int rc, i, n;
964 
965 	rc = ioctl (fd, CDIOREADTOCHEADER, &h);
966 	if (rc >= 0) {
967 		if (verbose)
968 			printf ("Starting track = %d, ending track = %d, TOC size = %d bytes\n",
969 				h.starting_track, h.ending_track, h.len);
970 		else
971 			printf ("%d %d %d\n", h.starting_track,
972 				h.ending_track, h.len);
973 	} else {
974 		warn("getting toc header");
975 		return (rc);
976 	}
977 
978 	n = h.ending_track - h.starting_track + 1;
979 	rc = read_toc_entrys ((n + 1) * sizeof (struct cd_toc_entry));
980 	if (rc < 0)
981 		return (rc);
982 
983 	if (verbose) {
984 		printf ("track     start  duration   block  length   type\n");
985 		printf ("-------------------------------------------------\n");
986 	}
987 
988 	for (i = 0; i < n; i++) {
989 		printf ("%5d  ", toc_buffer[i].track);
990 		prtrack (toc_buffer + i, 0);
991 	}
992 	printf ("%5d  ", toc_buffer[n].track);
993 	prtrack (toc_buffer + n, 1);
994 	return (0);
995 }
996 
997 static void
998 lba2msf(unsigned long lba, u_char *m, u_char *s, u_char *f)
999 {
1000 	lba += 150;			/* block start offset */
1001 	lba &= 0xffffff;		/* negative lbas use only 24 bits */
1002 	*m = lba / (60 * 75);
1003 	lba %= (60 * 75);
1004 	*s = lba / 75;
1005 	*f = lba % 75;
1006 }
1007 
1008 static unsigned int
1009 msf2lba(u_char m, u_char s, u_char f)
1010 {
1011 	return (((m * 60) + s) * 75 + f) - 150;
1012 }
1013 
1014 static void
1015 prtrack(struct cd_toc_entry *e, int lastflag)
1016 {
1017 	int block, next, len;
1018 	u_char m, s, f;
1019 
1020 	if (msf) {
1021 		/* Print track start */
1022 		printf ("%2d:%02d.%02d  ", e->addr.msf.minute,
1023 			e->addr.msf.second, e->addr.msf.frame);
1024 
1025 		block = msf2lba (e->addr.msf.minute, e->addr.msf.second,
1026 			e->addr.msf.frame);
1027 	} else {
1028 		block = ntohl(e->addr.lba);
1029 		lba2msf(block, &m, &s, &f);
1030 		/* Print track start */
1031 		printf ("%2d:%02d.%02d  ", m, s, f);
1032 	}
1033 	if (lastflag) {
1034 		/* Last track -- print block */
1035 		printf ("       -  %6d       -      -\n", block);
1036 		return;
1037 	}
1038 
1039 	if (msf)
1040 		next = msf2lba (e[1].addr.msf.minute, e[1].addr.msf.second,
1041 			e[1].addr.msf.frame);
1042 	else
1043 		next = ntohl(e[1].addr.lba);
1044 	len = next - block;
1045 	/* Take into account a start offset time. */
1046 	lba2msf (len - 150, &m, &s, &f);
1047 
1048 	/* Print duration, block, length, type */
1049 	printf ("%2d:%02d.%02d  %6d  %6d  %5s\n", m, s, f, block, len,
1050 		(e->control & 4) ? "data" : "audio");
1051 }
1052 
1053 static int
1054 play_track(int tstart, int istart, int tend, int iend)
1055 {
1056 	struct ioc_play_track t;
1057 
1058 	t.start_track = tstart;
1059 	t.start_index = istart;
1060 	t.end_track = tend;
1061 	t.end_index = iend;
1062 
1063 	return ioctl (fd, CDIOCPLAYTRACKS, &t);
1064 }
1065 
1066 static int
1067 play_blocks(int blk, int len)
1068 {
1069 	struct ioc_play_blocks  t;
1070 
1071 	t.blk = blk;
1072 	t.len = len;
1073 
1074 	return ioctl (fd, CDIOCPLAYBLOCKS, &t);
1075 }
1076 
1077 static int
1078 setvol(int left, int right)
1079 {
1080 	struct ioc_vol  v;
1081 
1082 	left  = left  < 0 ? 0 : left  > 255 ? 255 : left;
1083 	right = right < 0 ? 0 : right > 255 ? 255 : right;
1084 
1085 	v.vol[0] = left;
1086 	v.vol[1] = right;
1087 	v.vol[2] = 0;
1088 	v.vol[3] = 0;
1089 
1090 	return ioctl (fd, CDIOCSETVOL, &v);
1091 }
1092 
1093 static int
1094 read_toc_entrys(int len)
1095 {
1096 	struct ioc_read_toc_entry t;
1097 
1098 	t.address_format = msf ? CD_MSF_FORMAT : CD_LBA_FORMAT;
1099 	t.starting_track = 0;
1100 	t.data_len = len;
1101 	t.data = toc_buffer;
1102 
1103 	return (ioctl (fd, CDIOREADTOCENTRYS, (char *) &t));
1104 }
1105 
1106 static int
1107 play_msf(int start_m, int start_s, int start_f,
1108 	int end_m, int end_s, int end_f)
1109 {
1110 	struct ioc_play_msf a;
1111 
1112 	a.start_m = start_m;
1113 	a.start_s = start_s;
1114 	a.start_f = start_f;
1115 	a.end_m = end_m;
1116 	a.end_s = end_s;
1117 	a.end_f = end_f;
1118 
1119 	return ioctl (fd, CDIOCPLAYMSF, (char *) &a);
1120 }
1121 
1122 static int
1123 status(int *trk, int *min, int *sec, int *frame)
1124 {
1125 	struct ioc_read_subchannel s;
1126 	struct cd_sub_channel_info data;
1127 	u_char mm, ss, ff;
1128 
1129 	bzero (&s, sizeof (s));
1130 	s.data = &data;
1131 	s.data_len = sizeof (data);
1132 	s.address_format = msf ? CD_MSF_FORMAT : CD_LBA_FORMAT;
1133 	s.data_format = CD_CURRENT_POSITION;
1134 
1135 	if (ioctl (fd, CDIOCREADSUBCHANNEL, (char *) &s) < 0)
1136 		return -1;
1137 
1138 	*trk = s.data->what.position.track_number;
1139 	if (msf) {
1140 		*min = s.data->what.position.reladdr.msf.minute;
1141 		*sec = s.data->what.position.reladdr.msf.second;
1142 		*frame = s.data->what.position.reladdr.msf.frame;
1143 	} else {
1144 		lba2msf(ntohl(s.data->what.position.reladdr.lba),
1145 			&mm, &ss, &ff);
1146 		*min = mm;
1147 		*sec = ss;
1148 		*frame = ff;
1149 	}
1150 
1151 	return s.data->header.audio_status;
1152 }
1153 
1154 static const char *
1155 cdcontrol_prompt(void)
1156 {
1157 	return ("cdcontrol> ");
1158 }
1159 
1160 static char *
1161 input(int *cmd)
1162 {
1163 #define MAXLINE 80
1164 	static EditLine *el = NULL;
1165 	static History *hist = NULL;
1166 	HistEvent he;
1167 	static char buf[MAXLINE];
1168 	int num = 0;
1169 	int len;
1170 	const char *bp = NULL;
1171 	char *p;
1172 
1173 	do {
1174 		if (verbose) {
1175 			if (!el) {
1176 				el = el_init("cdcontrol", stdin, stdout,
1177 				    stderr);
1178 				hist = history_init();
1179 				history(hist, &he, H_SETSIZE, 100);
1180 				el_set(el, EL_HIST, history, hist);
1181 				el_set(el, EL_EDITOR, "emacs");
1182 				el_set(el, EL_PROMPT, cdcontrol_prompt);
1183 				el_set(el, EL_SIGNAL, 1);
1184 				el_source(el, NULL);
1185 			}
1186 			if ((bp = el_gets(el, &num)) == NULL || num == 0) {
1187 				*cmd = CMD_QUIT;
1188 				fprintf (stderr, "\r\n");
1189 				return (0);
1190 			}
1191 
1192 			len = (num > MAXLINE) ? MAXLINE : num;
1193 			memcpy(buf, bp, len);
1194 			buf[len] = 0;
1195 			history(hist, &he, H_ENTER, bp);
1196 #undef MAXLINE
1197 
1198 		} else {
1199 			if (! fgets (buf, sizeof (buf), stdin)) {
1200 				*cmd = CMD_QUIT;
1201 				fprintf (stderr, "\r\n");
1202 				return (0);
1203 			}
1204 		}
1205 		p = parse (buf, cmd);
1206 	} while (! p);
1207 	return (p);
1208 }
1209 
1210 static char *
1211 parse(char *buf, int *cmd)
1212 {
1213 	struct cmdtab *c;
1214 	char *p;
1215 	unsigned int len;
1216 
1217 	for (p=buf; isspace (*p); p++)
1218 		continue;
1219 
1220 	if (isdigit (*p) || (p[0] == '#' && isdigit (p[1]))) {
1221 		*cmd = CMD_PLAY;
1222 		return (p);
1223 	} else if (*p == '+') {
1224 		*cmd = CMD_NEXT;
1225 		return (p + 1);
1226 	} else if (*p == '-') {
1227 		*cmd = CMD_PREVIOUS;
1228 		return (p + 1);
1229 	}
1230 
1231 	for (buf = p; *p && ! isspace (*p); p++)
1232 		continue;
1233 
1234 	len = p - buf;
1235 	if (! len)
1236 		return (0);
1237 
1238 	if (*p) {		/* It must be a spacing character! */
1239 		char *q;
1240 
1241 		*p++ = 0;
1242 		for (q=p; *q && *q != '\n' && *q != '\r'; q++)
1243 			continue;
1244 		*q = 0;
1245 	}
1246 
1247 	*cmd = -1;
1248 	for (c=cmdtab; c->name; ++c) {
1249 		/* Is it an exact match? */
1250 		if (! strcasecmp (buf, c->name)) {
1251   			*cmd = c->command;
1252   			break;
1253   		}
1254 
1255 		/* Try short hand forms then... */
1256 		if (len >= c->min && ! strncasecmp (buf, c->name, len)) {
1257 			if (*cmd != -1 && *cmd != c->command) {
1258 				warnx("ambiguous command");
1259 				return (0);
1260 			}
1261 			*cmd = c->command;
1262   		}
1263 	}
1264 
1265 	if (*cmd == -1) {
1266 		warnx("invalid command, enter ``help'' for commands");
1267 		return (0);
1268 	}
1269 
1270 	while (isspace (*p))
1271 		p++;
1272 	return p;
1273 }
1274 
1275 static int
1276 open_cd(void)
1277 {
1278 	char devbuf[MAXPATHLEN];
1279 	const char *dev;
1280 
1281 	if (fd > -1)
1282 		return (1);
1283 
1284 	if (cdname) {
1285 	    if (*cdname == '/') {
1286 		    snprintf (devbuf, MAXPATHLEN, "%s", cdname);
1287 	    } else {
1288 		    snprintf (devbuf, MAXPATHLEN, "%s%s", _PATH_DEV, cdname);
1289 	    }
1290 	    fd = open (dev = devbuf, O_RDONLY);
1291 	} else {
1292 	    fd = open(dev = "/dev/cdrom", O_RDONLY);
1293 	    if (fd < 0 && errno == ENOENT)
1294 		fd = open(dev = "/dev/cd0", O_RDONLY);
1295 	}
1296 
1297 	if (fd < 0) {
1298 		if (errno == ENXIO) {
1299 			/*  ENXIO has an overloaded meaning here.
1300 			 *  The original "Device not configured" should
1301 			 *  be interpreted as "No disc in drive %s". */
1302 			warnx("no disc in drive %s", dev);
1303 			return (0);
1304 		}
1305 		err(1, "%s", dev);
1306 	}
1307 	return (1);
1308 }
1309