Home | History | Annotate | Line # | Download | only in play
play.c revision 1.33
      1 /*	$NetBSD: play.c,v 1.33 2002/01/31 00:33:10 augustss Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999 Matthew R. Green
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. The name of the author may not be used to endorse or promote products
     16  *    derived from this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     28  * SUCH DAMAGE.
     29  */
     30 
     31 #include <sys/param.h>
     32 #include <sys/audioio.h>
     33 #include <sys/ioctl.h>
     34 #include <sys/mman.h>
     35 #include <sys/stat.h>
     36 
     37 #include <err.h>
     38 #include <fcntl.h>
     39 #include <signal.h>
     40 #include <stdio.h>
     41 #include <stdlib.h>
     42 #include <string.h>
     43 #include <unistd.h>
     44 
     45 #include <paths.h>
     46 
     47 #include "libaudio.h"
     48 
     49 int main(int, char *[]);
     50 void usage(void);
     51 void play(char *);
     52 void play_fd(const char *, int);
     53 ssize_t audioctl_write_fromhdr(void *, size_t, int, size_t *);
     54 void cleanup(int) __attribute__((__noreturn__));
     55 
     56 audio_info_t	info;
     57 int	volume;
     58 int	balance;
     59 int	port;
     60 int	fflag;
     61 int	qflag;
     62 int	verbose;
     63 int	sample_rate;
     64 int	encoding;
     65 char	*encoding_str;
     66 int	precision;
     67 int	channels;
     68 
     69 char	const *play_errstring = NULL;
     70 size_t	bufsize;
     71 int	audiofd, ctlfd;
     72 int	exitstatus = EXIT_SUCCESS;
     73 
     74 int
     75 main(argc, argv)
     76 	int argc;
     77 	char *argv[];
     78 {
     79 	size_t	len;
     80 	int	ch;
     81 	int	iflag = 0;
     82 	const char *device = NULL;
     83 	const char *ctldev = NULL;
     84 
     85 	while ((ch = getopt(argc, argv, "b:C:c:d:e:fhip:P:qs:Vv:")) != -1) {
     86 		switch (ch) {
     87 		case 'b':
     88 			decode_int(optarg, &balance);
     89 			if (balance < 0 || balance > 64)
     90 				errx(1, "balance must be between 0 and 64");
     91 			break;
     92 		case 'c':
     93 			decode_int(optarg, &channels);
     94 			if (channels < 0)
     95 				errx(1, "channels must be positive");
     96 			break;
     97 		case 'C':
     98 			ctldev = optarg;
     99 			break;
    100 		case 'd':
    101 			device = optarg;
    102 			break;
    103 		case 'e':
    104 			encoding_str = optarg;
    105 			break;
    106 		case 'f':
    107 			fflag = 1;
    108 			break;
    109 		case 'i':
    110 			iflag++;
    111 			break;
    112 		case 'q':
    113 			qflag++;
    114 			break;
    115 		case 'P':
    116 			decode_int(optarg, &precision);
    117 			if (precision != 4 && precision != 8 &&
    118 			    precision != 16 && precision != 24 &&
    119 			    precision != 32)
    120 				errx(1, "precision must be between 4, 8, 16, 24 or 32");
    121 			break;
    122 		case 'p':
    123 			len = strlen(optarg);
    124 
    125 			if (strncmp(optarg, "speaker", len) == 0)
    126 				port |= AUDIO_SPEAKER;
    127 			else if (strncmp(optarg, "headphone", len) == 0)
    128 				port |= AUDIO_HEADPHONE;
    129 			else if (strncmp(optarg, "line", len) == 0)
    130 				port |= AUDIO_LINE_OUT;
    131 			else
    132 				errx(1,
    133 			    "port must be `speaker', `headphone', or `line'");
    134 			break;
    135 		case 's':
    136 			decode_int(optarg, &sample_rate);
    137 			if (sample_rate < 0 || sample_rate > 48000 * 2)	/* XXX */
    138 				errx(1, "sample rate must be between 0 and 96000\n");
    139 			break;
    140 		case 'V':
    141 			verbose++;
    142 			break;
    143 		case 'v':
    144 			volume = atoi(optarg);
    145 			if (volume < 0 || volume > 255)
    146 				errx(1, "volume must be between 0 and 255\n");
    147 			break;
    148 		/* case 'h': */
    149 		default:
    150 			usage();
    151 			/* NOTREACHED */
    152 		}
    153 	}
    154 	argc -= optind;
    155 	argv += optind;
    156 
    157 	if (encoding_str) {
    158 		encoding = audio_enc_to_val(encoding_str);
    159 		if (encoding == -1)
    160 			errx(1, "unknown encoding, bailing...");
    161 	}
    162 
    163 	if (device == NULL && (device = getenv("AUDIODEVICE")) == NULL &&
    164 	    (device = getenv("AUDIODEV")) == NULL) /* Sun compatibility */
    165 		device = _PATH_SOUND;
    166 	if (ctldev == NULL && (ctldev = getenv("AUDIOCTLDEVICE")) == NULL)
    167 		ctldev = _PATH_AUDIOCTL;
    168 
    169 	audiofd = open(device, O_WRONLY);
    170 	if (audiofd < 0 && device == _PATH_SOUND) {
    171 		device = _PATH_SOUND0;
    172 		ctldev = _PATH_AUDIOCTL0;
    173 		audiofd = open(device, O_WRONLY);
    174 	}
    175 
    176 	if (audiofd < 0)
    177 		err(1, "failed to open %s", device);
    178 	ctlfd = open(ctldev, O_RDWR);
    179 	if (ctlfd < 0)
    180 		err(1, "failed to open %s", ctldev);
    181 
    182 	if (ioctl(ctlfd, AUDIO_GETINFO, &info) < 0)
    183 		err(1, "failed to get audio info");
    184 	bufsize = info.play.buffer_size;
    185 	if (bufsize < 32 * 1024)
    186 		bufsize = 32 * 1024;
    187 
    188 	signal(SIGINT, cleanup);
    189 	signal(SIGTERM, cleanup);
    190 	signal(SIGHUP, cleanup);
    191 
    192 	if (*argv)
    193 		do
    194 			play(*argv++);
    195 		while (*argv);
    196 	else
    197 		play_fd("standard input", STDIN_FILENO);
    198 
    199 	cleanup(0);
    200 }
    201 
    202 void
    203 cleanup(signo)
    204 	int signo;
    205 {
    206 
    207 	close(audiofd);
    208 	(void)ioctl(audiofd, AUDIO_FLUSH, NULL);
    209 	(void)ioctl(ctlfd, AUDIO_SETINFO, &info);
    210 	exit(exitstatus);
    211 }
    212 
    213 void
    214 play(file)
    215 	char *file;
    216 {
    217 	struct stat sb;
    218 	void *addr, *oaddr;
    219 	off_t	filesize;
    220 	size_t datasize;
    221 	ssize_t	hdrlen;
    222 	int fd;
    223 
    224 	if (file[0] == '-' && file[1] == 0) {
    225 		play_fd("standard input", STDIN_FILENO);
    226 		return;
    227 	}
    228 
    229 	fd = open(file, O_RDONLY);
    230 	if (fd < 0) {
    231 		if (!qflag)
    232 			warn("could not open %s", file);
    233 		exitstatus = EXIT_FAILURE;
    234 		return;
    235 	}
    236 
    237 	if (fstat(fd, &sb) < 0)
    238 		err(1, "could not fstat %s", file);
    239 	filesize = sb.st_size;
    240 
    241 	oaddr = addr = mmap(0, (size_t)filesize, PROT_READ,
    242 	    MAP_SHARED, fd, 0);
    243 
    244 	/*
    245 	 * if we failed to mmap the file, try to read it
    246 	 * instead, so that filesystems, etc, that do not
    247 	 * support mmap() work
    248 	 */
    249 	if (addr == MAP_FAILED) {
    250 		play_fd(file, fd);
    251 		close(fd);
    252 		return;
    253 	}
    254 
    255 	/*
    256 	 * give the VM system a bit of a hint about the type
    257 	 * of accesses we will make.
    258 	 */
    259 	if (madvise(addr, filesize, MADV_SEQUENTIAL) < 0 &&
    260 	    !qflag)
    261 		warn("madvise failed, ignoring");
    262 
    263 	/*
    264 	 * get the header length and set up the audio device
    265 	 */
    266 	if ((hdrlen = audioctl_write_fromhdr(addr,
    267 	    (size_t)filesize, ctlfd, &datasize)) < 0) {
    268 		if (play_errstring)
    269 			errx(1, "%s: %s", play_errstring, file);
    270 		else
    271 			errx(1, "unknown audio file: %s", file);
    272 	}
    273 
    274 	filesize -= hdrlen;
    275 	addr = (char *)addr + hdrlen;
    276 	if (filesize < datasize || datasize == 0) {
    277 		warnx("bogus datasize: %lu", (long)datasize);
    278 		datasize = filesize;
    279 	}
    280 
    281 	while (datasize > bufsize) {
    282 		if (write(audiofd, addr, bufsize) != bufsize)
    283 			err(1, "write failed");
    284 		addr = (char *)addr + bufsize;
    285 		datasize -= bufsize;
    286 	}
    287 	if (write(audiofd, addr, (size_t)datasize) != (ssize_t)datasize)
    288 		err(1, "final write failed");
    289 
    290 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    291 		warn("audio drain ioctl failed");
    292 	if (munmap(oaddr, (size_t)filesize) < 0)
    293 		err(1, "munmap failed");
    294 
    295 	close(fd);
    296 }
    297 
    298 /*
    299  * play the file on on the file descriptor fd
    300  */
    301 void
    302 play_fd(file, fd)
    303 	const char *file;
    304 	int     fd;
    305 {
    306 	char    *buffer = malloc(bufsize);
    307 	ssize_t hdrlen;
    308 	int     nr, nw;
    309 	size_t	datasize = 0;
    310 	size_t	dataout = 0;
    311 
    312 	if (buffer == NULL)
    313 		err(1, "malloc of read buffer failed");
    314 
    315 	nr = read(fd, buffer, bufsize);
    316 	if (nr < 0)
    317 		goto read_error;
    318 	if (nr == 0) {
    319 		if (fflag)
    320 			return;
    321 		err(1, "unexpected EOF");
    322 	}
    323 	hdrlen = audioctl_write_fromhdr(buffer, nr, ctlfd, &datasize);
    324 	if (hdrlen < 0) {
    325 		if (play_errstring)
    326 			errx(1, "%s: %s", play_errstring, file);
    327 		else
    328 			errx(1, "unknown audio file: %s", file);
    329 	}
    330 	if (hdrlen > 0) {
    331 		if (hdrlen >= nr)	/* shouldn't happen */
    332 			errx(1, "header seems really large");
    333 		memmove(buffer, buffer + hdrlen, nr - hdrlen);
    334 		nr -= hdrlen;
    335 	}
    336 	while (datasize == 0 || dataout < datasize) {
    337 		if (datasize != 0 && dataout + nr > datasize)
    338 			nr = datasize - dataout;
    339 		nw = write(audiofd, buffer, nr);
    340 		if (nw != nr)
    341 			goto write_error;
    342 		dataout += nw;
    343 		nr = read(fd, buffer, bufsize);
    344 		if (nr == -1)
    345 			goto read_error;
    346 		if (nr == 0)
    347 			break;
    348 	}
    349 	/* something to think about: no message given for dataout < datasize */
    350 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    351 		warn("audio drain ioctl failed");
    352 	return;
    353 read_error:
    354 	err(1, "read of standard input failed");
    355 write_error:
    356 	err(1, "audio device write failed");
    357 }
    358 
    359 /*
    360  * only support sun and wav audio files so far ...
    361  *
    362  * XXX this should probably be mostly part of libaudio, but it
    363  * uses the local "info" variable. blah... fix me!
    364  */
    365 ssize_t
    366 audioctl_write_fromhdr(hdr, fsz, fd, datasize)
    367 	void	*hdr;
    368 	size_t	fsz;
    369 	int	fd;
    370 	size_t	*datasize;
    371 {
    372 	sun_audioheader	*sunhdr;
    373 	ssize_t	hdr_len;
    374 
    375 	AUDIO_INITINFO(&info);
    376 	sunhdr = hdr;
    377 	if (ntohl(sunhdr->magic) == AUDIO_FILE_MAGIC) {
    378 		if (audio_sun_to_encoding(ntohl(sunhdr->encoding),
    379 		    &info.play.encoding, &info.play.precision)) {
    380 			if (!qflag)
    381 				warnx("unknown unsupported Sun audio encoding"
    382 				      " format %d", ntohl(sunhdr->encoding));
    383 			if (fflag)
    384 				goto set_audio_mode;
    385 			return (-1);
    386 		}
    387 
    388 		info.play.sample_rate = ntohl(sunhdr->sample_rate);
    389 		info.play.channels = ntohl(sunhdr->channels);
    390 		hdr_len = ntohl(sunhdr->hdr_size);
    391 
    392 		*datasize = ntohl(sunhdr->data_size);
    393 		goto set_audio_mode;
    394 	}
    395 
    396 	hdr_len = audio_wav_parse_hdr(hdr, fsz, &info.play.encoding,
    397 	    &info.play.precision, &info.play.sample_rate, &info.play.channels,
    398 	    datasize);
    399 
    400 	switch (hdr_len) {
    401 	case AUDIO_ESHORTHDR:
    402 	case AUDIO_EWAVUNSUPP:
    403 	case AUDIO_EWAVBADPCM:
    404 	case AUDIO_EWAVNODATA:
    405 		play_errstring = audio_errstring(hdr_len);
    406 		/* FALL THROUGH */
    407 	case AUDIO_ENOENT:
    408 		break;
    409 	default:
    410 		if (hdr_len < 1)
    411 			break;
    412 		goto set_audio_mode;
    413 	}
    414 	/*
    415 	 * if we don't know it, bail unless we are forcing.
    416 	 */
    417 	if (fflag == 0)
    418 		return (-1);
    419 set_audio_mode:
    420 	if (port)
    421 		info.play.port = port;
    422 	if (volume)
    423 		info.play.gain = volume;
    424 	if (balance)
    425 		info.play.balance = balance;
    426 	if (fflag) {
    427 		if (sample_rate)
    428 			info.play.sample_rate = sample_rate;
    429 		if (channels)
    430 			info.play.channels = channels;
    431 		if (encoding)
    432 			info.play.encoding = encoding;
    433 		if (precision)
    434 			info.play.precision = precision;
    435 		hdr_len = 0;
    436 	}
    437 	info.mode = AUMODE_PLAY_ALL;
    438 
    439 	if (verbose)
    440 		printf("sample_rate=%d channels=%d precision=%d encoding=%s\n",
    441 		   info.play.sample_rate, info.play.channels,
    442 		   info.play.precision, audio_enc_from_val(info.play.encoding));
    443 
    444 	if (ioctl(fd, AUDIO_SETINFO, &info) < 0)
    445 		err(1, "failed to set audio info");
    446 
    447 	return (hdr_len);
    448 }
    449 
    450 void
    451 usage()
    452 {
    453 
    454 	fprintf(stderr, "Usage: %s [-hiqV] [options] files\n", getprogname());
    455 	fprintf(stderr, "Options:\n\t"
    456 	    "-C audio control device\n\t"
    457 	    "-b balance (0-63)\n\t"
    458 	    "-d audio device\n\t"
    459 	    "-f force settings\n\t"
    460 	    "\t-c forced channels\n\t"
    461 	    "\t-e forced encoding\n\t"
    462 	    "\t-P forced precision\n\t"
    463 	    "\t-s forced sample rate\n\t"
    464 	    "-i header information\n\t"
    465 	    "-m monitor volume\n\t"
    466 	    "-p output port\n\t"
    467 	    "-v volume\n");
    468 	exit(EXIT_FAILURE);
    469 }
    470