Home | History | Annotate | Line # | Download | only in play
play.c revision 1.39
      1 /*	$NetBSD: play.c,v 1.39 2002/11/03 19:35:00 wiz 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 *, const char *);
     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;
     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 *defdevice = _PATH_SOUND;
     83 	const char *device = 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 			/* Ignore, compatibility */
     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");
    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");
    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 = defdevice;
    166 
    167 	audiofd = open(device, O_WRONLY);
    168 	if (audiofd < 0 && device == defdevice) {
    169 		device = _PATH_SOUND0;
    170 		audiofd = open(device, O_WRONLY);
    171 	}
    172 
    173 	if (audiofd < 0)
    174 		err(1, "failed to open %s", device);
    175 
    176 	if (ioctl(audiofd, AUDIO_GETINFO, &info) < 0)
    177 		err(1, "failed to get audio info");
    178 	bufsize = info.play.buffer_size;
    179 	if (bufsize < 32 * 1024)
    180 		bufsize = 32 * 1024;
    181 
    182 	signal(SIGINT, cleanup);
    183 	signal(SIGTERM, cleanup);
    184 	signal(SIGHUP, cleanup);
    185 
    186 	if (*argv)
    187 		do
    188 			play(*argv++);
    189 		while (*argv);
    190 	else
    191 		play_fd("standard input", STDIN_FILENO);
    192 
    193 	cleanup(0);
    194 }
    195 
    196 void
    197 cleanup(signo)
    198 	int signo;
    199 {
    200 
    201 	(void)ioctl(audiofd, AUDIO_FLUSH, NULL);
    202 	(void)ioctl(audiofd, AUDIO_SETINFO, &info);
    203 	close(audiofd);
    204 	exit(exitstatus);
    205 }
    206 
    207 void
    208 play(file)
    209 	char *file;
    210 {
    211 	struct stat sb;
    212 	void *addr, *oaddr;
    213 	off_t	filesize;
    214 	size_t datasize = 0;
    215 	ssize_t	hdrlen;
    216 	int fd;
    217 
    218 	if (file[0] == '-' && file[1] == 0) {
    219 		play_fd("standard input", STDIN_FILENO);
    220 		return;
    221 	}
    222 
    223 	fd = open(file, O_RDONLY);
    224 	if (fd < 0) {
    225 		if (!qflag)
    226 			warn("could not open %s", file);
    227 		exitstatus = EXIT_FAILURE;
    228 		return;
    229 	}
    230 
    231 	if (fstat(fd, &sb) < 0)
    232 		err(1, "could not fstat %s", file);
    233 	filesize = sb.st_size;
    234 
    235 	oaddr = addr = mmap(0, (size_t)filesize, PROT_READ,
    236 	    MAP_SHARED, fd, 0);
    237 
    238 	/*
    239 	 * if we failed to mmap the file, try to read it
    240 	 * instead, so that filesystems, etc, that do not
    241 	 * support mmap() work
    242 	 */
    243 	if (addr == MAP_FAILED) {
    244 		play_fd(file, fd);
    245 		close(fd);
    246 		return;
    247 	}
    248 
    249 	/*
    250 	 * give the VM system a bit of a hint about the type
    251 	 * of accesses we will make.
    252 	 */
    253 	if (madvise(addr, filesize, MADV_SEQUENTIAL) < 0 &&
    254 	    !qflag)
    255 		warn("madvise failed, ignoring");
    256 
    257 	/*
    258 	 * get the header length and set up the audio device
    259 	 */
    260 	if ((hdrlen = audioctl_write_fromhdr(addr,
    261 	    (size_t)filesize, audiofd, &datasize, file)) < 0) {
    262 		if (play_errstring)
    263 			errx(1, "%s: %s", play_errstring, file);
    264 		else
    265 			errx(1, "unknown audio file: %s", file);
    266 	}
    267 
    268 	filesize -= hdrlen;
    269 	addr = (char *)addr + hdrlen;
    270 	if (filesize < datasize || datasize == 0) {
    271 		if (filesize < datasize)
    272 			warnx("bogus datasize: %ld", (u_long)datasize);
    273 		datasize = filesize;
    274 	}
    275 
    276 	while (datasize > bufsize) {
    277 		if (write(audiofd, addr, bufsize) != bufsize)
    278 			err(1, "write failed");
    279 		addr = (char *)addr + bufsize;
    280 		datasize -= bufsize;
    281 	}
    282 	if (write(audiofd, addr, (size_t)datasize) != (ssize_t)datasize)
    283 		err(1, "final write failed");
    284 
    285 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    286 		warn("audio drain ioctl failed");
    287 	if (munmap(oaddr, (size_t)filesize) < 0)
    288 		err(1, "munmap failed");
    289 
    290 	close(fd);
    291 }
    292 
    293 /*
    294  * play the file on the file descriptor fd
    295  */
    296 void
    297 play_fd(file, fd)
    298 	const char *file;
    299 	int     fd;
    300 {
    301 	char    *buffer = malloc(bufsize);
    302 	ssize_t hdrlen;
    303 	int     nr, nw;
    304 	size_t	datasize = 0;
    305 	size_t	dataout = 0;
    306 
    307 	if (buffer == NULL)
    308 		err(1, "malloc of read buffer failed");
    309 
    310 	nr = read(fd, buffer, bufsize);
    311 	if (nr < 0)
    312 		goto read_error;
    313 	if (nr == 0) {
    314 		if (fflag)
    315 			return;
    316 		err(1, "unexpected EOF");
    317 	}
    318 	hdrlen = audioctl_write_fromhdr(buffer, nr, audiofd, &datasize, file);
    319 	if (hdrlen < 0) {
    320 		if (play_errstring)
    321 			errx(1, "%s: %s", play_errstring, file);
    322 		else
    323 			errx(1, "unknown audio file: %s", file);
    324 	}
    325 	if (hdrlen > 0) {
    326 		if (hdrlen >= nr)	/* shouldn't happen */
    327 			errx(1, "header seems really large");
    328 		memmove(buffer, buffer + hdrlen, nr - hdrlen);
    329 		nr -= hdrlen;
    330 	}
    331 	while (datasize == 0 || dataout < datasize) {
    332 		if (datasize != 0 && dataout + nr > datasize)
    333 			nr = datasize - dataout;
    334 		nw = write(audiofd, buffer, nr);
    335 		if (nw != nr)
    336 			goto write_error;
    337 		dataout += nw;
    338 		nr = read(fd, buffer, bufsize);
    339 		if (nr == -1)
    340 			goto read_error;
    341 		if (nr == 0)
    342 			break;
    343 	}
    344 	/* something to think about: no message given for dataout < datasize */
    345 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    346 		warn("audio drain ioctl failed");
    347 	return;
    348 read_error:
    349 	err(1, "read of standard input failed");
    350 write_error:
    351 	err(1, "audio device write failed");
    352 }
    353 
    354 /*
    355  * only support sun and wav audio files so far ...
    356  *
    357  * XXX this should probably be mostly part of libaudio, but it
    358  * uses the local "info" variable. blah... fix me!
    359  */
    360 ssize_t
    361 audioctl_write_fromhdr(hdr, fsz, fd, datasize, file)
    362 	void	*hdr;
    363 	size_t	fsz;
    364 	int	fd;
    365 	size_t	*datasize;
    366 	const char	*file;
    367 {
    368 	sun_audioheader	*sunhdr;
    369 	ssize_t	hdr_len;
    370 
    371 	AUDIO_INITINFO(&info);
    372 	sunhdr = hdr;
    373 	if (ntohl(sunhdr->magic) == AUDIO_FILE_MAGIC) {
    374 		if (audio_sun_to_encoding(ntohl(sunhdr->encoding),
    375 		    &info.play.encoding, &info.play.precision)) {
    376 			if (!qflag)
    377 				warnx("unknown unsupported Sun audio encoding"
    378 				      " format %d", ntohl(sunhdr->encoding));
    379 			if (fflag)
    380 				goto set_audio_mode;
    381 			return (-1);
    382 		}
    383 
    384 		info.play.sample_rate = ntohl(sunhdr->sample_rate);
    385 		info.play.channels = ntohl(sunhdr->channels);
    386 		hdr_len = ntohl(sunhdr->hdr_size);
    387 
    388 		*datasize = ntohl(sunhdr->data_size);
    389 		goto set_audio_mode;
    390 	}
    391 
    392 	hdr_len = audio_wav_parse_hdr(hdr, fsz, &info.play.encoding,
    393 	    &info.play.precision, &info.play.sample_rate, &info.play.channels,
    394 	    datasize);
    395 
    396 	switch (hdr_len) {
    397 	case AUDIO_ESHORTHDR:
    398 	case AUDIO_EWAVUNSUPP:
    399 	case AUDIO_EWAVBADPCM:
    400 	case AUDIO_EWAVNODATA:
    401 		play_errstring = audio_errstring(hdr_len);
    402 		/* FALL THROUGH */
    403 	case AUDIO_ENOENT:
    404 		break;
    405 	default:
    406 		if (hdr_len < 1)
    407 			break;
    408 		goto set_audio_mode;
    409 	}
    410 	/*
    411 	 * if we don't know it, bail unless we are forcing.
    412 	 */
    413 	if (fflag == 0)
    414 		return (-1);
    415 set_audio_mode:
    416 	if (port)
    417 		info.play.port = port;
    418 	if (volume)
    419 		info.play.gain = volume;
    420 	if (balance)
    421 		info.play.balance = balance;
    422 	if (fflag) {
    423 		if (sample_rate)
    424 			info.play.sample_rate = sample_rate;
    425 		if (channels)
    426 			info.play.channels = channels;
    427 		if (encoding)
    428 			info.play.encoding = encoding;
    429 		if (precision)
    430 			info.play.precision = precision;
    431 		hdr_len = 0;
    432 	}
    433 	info.mode = AUMODE_PLAY_ALL;
    434 
    435 	if (verbose) {
    436 		const char *enc = audio_enc_from_val(info.play.encoding);
    437 
    438 		printf("%s: sample_rate=%d channels=%d "
    439 		   "precision=%d%s%s\n", file,
    440 		   info.play.sample_rate,
    441 		   info.play.channels,
    442 		   info.play.precision,
    443 		   enc ? " encoding=" : "",
    444 		   enc ? enc : "");
    445 	}
    446 
    447 	if (ioctl(fd, AUDIO_SETINFO, &info) < 0)
    448 		err(1, "failed to set audio info");
    449 
    450 	return (hdr_len);
    451 }
    452 
    453 void
    454 usage()
    455 {
    456 
    457 	fprintf(stderr, "Usage: %s [-hiqV] [options] files\n", getprogname());
    458 	fprintf(stderr, "Options:\n\t"
    459 	    "-C audio control device\n\t"
    460 	    "-b balance (0-63)\n\t"
    461 	    "-d audio device\n\t"
    462 	    "-f force settings\n\t"
    463 	    "\t-c forced channels\n\t"
    464 	    "\t-e forced encoding\n\t"
    465 	    "\t-P forced precision\n\t"
    466 	    "\t-s forced sample rate\n\t"
    467 	    "-i header information\n\t"
    468 	    "-m monitor volume\n\t"
    469 	    "-p output port\n\t"
    470 	    "-v volume\n");
    471 	exit(EXIT_FAILURE);
    472 }
    473