Home | History | Annotate | Line # | Download | only in play
play.c revision 1.42.4.1
      1 /*	$NetBSD: play.c,v 1.42.4.1 2005/07/18 04:11:03 riz 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 #include <sys/cdefs.h>
     31 
     32 #ifndef lint
     33 __RCSID("$NetBSD: play.c,v 1.42.4.1 2005/07/18 04:11:03 riz Exp $");
     34 #endif
     35 
     36 
     37 #include <sys/param.h>
     38 #include <sys/audioio.h>
     39 #include <sys/ioctl.h>
     40 #include <sys/mman.h>
     41 #include <sys/stat.h>
     42 
     43 #include <err.h>
     44 #include <fcntl.h>
     45 #include <signal.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <unistd.h>
     50 
     51 #include <paths.h>
     52 
     53 #include "libaudio.h"
     54 
     55 int main(int, char *[]);
     56 void usage(void);
     57 void play(char *);
     58 void play_fd(const char *, int);
     59 ssize_t audioctl_write_fromhdr(void *, size_t, int, size_t *, const char *);
     60 void cleanup(int) __attribute__((__noreturn__));
     61 
     62 audio_info_t	info;
     63 int	volume;
     64 int	balance;
     65 int	port;
     66 int	fflag;
     67 int	qflag;
     68 int	verbose;
     69 int	sample_rate;
     70 int	encoding;
     71 char	*encoding_str;
     72 int	precision;
     73 int	channels;
     74 
     75 char	const *play_errstring = NULL;
     76 size_t	bufsize;
     77 int	audiofd;
     78 int	exitstatus = EXIT_SUCCESS;
     79 
     80 int
     81 main(argc, argv)
     82 	int argc;
     83 	char *argv[];
     84 {
     85 	size_t	len;
     86 	int	ch;
     87 	int	iflag = 0;
     88 	const char *defdevice = _PATH_SOUND;
     89 	const char *device = NULL;
     90 
     91 	while ((ch = getopt(argc, argv, "b:C:c:d:e:fhip:P:qs:Vv:")) != -1) {
     92 		switch (ch) {
     93 		case 'b':
     94 			decode_int(optarg, &balance);
     95 			if (balance < 0 || balance > 64)
     96 				errx(1, "balance must be between 0 and 63");
     97 			break;
     98 		case 'c':
     99 			decode_int(optarg, &channels);
    100 			if (channels < 0)
    101 				errx(1, "channels must be positive");
    102 			break;
    103 		case 'C':
    104 			/* Ignore, compatibility */
    105 			break;
    106 		case 'd':
    107 			device = optarg;
    108 			break;
    109 		case 'e':
    110 			encoding_str = optarg;
    111 			break;
    112 		case 'f':
    113 			fflag = 1;
    114 			break;
    115 		case 'i':
    116 			iflag++;
    117 			break;
    118 		case 'q':
    119 			qflag++;
    120 			break;
    121 		case 'P':
    122 			decode_int(optarg, &precision);
    123 			if (precision != 4 && precision != 8 &&
    124 			    precision != 16 && precision != 24 &&
    125 			    precision != 32)
    126 				errx(1, "precision must be between 4, 8, 16, 24 or 32");
    127 			break;
    128 		case 'p':
    129 			len = strlen(optarg);
    130 
    131 			if (strncmp(optarg, "speaker", len) == 0)
    132 				port |= AUDIO_SPEAKER;
    133 			else if (strncmp(optarg, "headphone", len) == 0)
    134 				port |= AUDIO_HEADPHONE;
    135 			else if (strncmp(optarg, "line", len) == 0)
    136 				port |= AUDIO_LINE_OUT;
    137 			else
    138 				errx(1,
    139 			    "port must be `speaker', `headphone', or `line'");
    140 			break;
    141 		case 's':
    142 			decode_int(optarg, &sample_rate);
    143 			if (sample_rate < 0 || sample_rate > 48000 * 2)	/* XXX */
    144 				errx(1, "sample rate must be between 0 and 96000");
    145 			break;
    146 		case 'V':
    147 			verbose++;
    148 			break;
    149 		case 'v':
    150 			volume = atoi(optarg);
    151 			if (volume < 0 || volume > 255)
    152 				errx(1, "volume must be between 0 and 255");
    153 			break;
    154 		/* case 'h': */
    155 		default:
    156 			usage();
    157 			/* NOTREACHED */
    158 		}
    159 	}
    160 	argc -= optind;
    161 	argv += optind;
    162 
    163 	if (encoding_str) {
    164 		encoding = audio_enc_to_val(encoding_str);
    165 		if (encoding == -1)
    166 			errx(1, "unknown encoding, bailing...");
    167 	}
    168 
    169 	if (device == NULL && (device = getenv("AUDIODEVICE")) == NULL &&
    170 	    (device = getenv("AUDIODEV")) == NULL) /* Sun compatibility */
    171 		device = defdevice;
    172 
    173 	audiofd = open(device, O_WRONLY);
    174 	if (audiofd < 0 && device == defdevice) {
    175 		device = _PATH_SOUND0;
    176 		audiofd = open(device, O_WRONLY);
    177 	}
    178 
    179 	if (audiofd < 0)
    180 		err(1, "failed to open %s", device);
    181 
    182 	if (ioctl(audiofd, 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 	(void)ioctl(audiofd, AUDIO_FLUSH, NULL);
    208 	(void)ioctl(audiofd, AUDIO_SETINFO, &info);
    209 	close(audiofd);
    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	sizet_filesize;
    221 	size_t datasize = 0;
    222 	ssize_t	hdrlen;
    223 	int fd;
    224 
    225 	if (file[0] == '-' && file[1] == 0) {
    226 		play_fd("standard input", STDIN_FILENO);
    227 		return;
    228 	}
    229 
    230 	fd = open(file, O_RDONLY);
    231 	if (fd < 0) {
    232 		if (!qflag)
    233 			warn("could not open %s", file);
    234 		exitstatus = EXIT_FAILURE;
    235 		return;
    236 	}
    237 
    238 	if (fstat(fd, &sb) < 0)
    239 		err(1, "could not fstat %s", file);
    240 	filesize = sb.st_size;
    241 	sizet_filesize = (size_t)filesize;
    242 
    243 	/*
    244 	 * if the file is not a regular file, doesn't fit in a size_t,
    245 	 * or if we failed to mmap the file, try to read it instead, so
    246 	 * that filesystems, etc, that do not support mmap() work
    247 	 */
    248 	if (S_ISREG(sb.st_rdev & S_IFMT) == 0 ||
    249 	    ((off_t)sizet_filesize != filesize) ||
    250 	    (oaddr = addr = mmap(0, sizet_filesize, PROT_READ,
    251 	    MAP_SHARED, fd, 0)) == MAP_FAILED) {
    252 		play_fd(file, fd);
    253 		close(fd);
    254 		return;
    255 	}
    256 
    257 	/*
    258 	 * give the VM system a bit of a hint about the type
    259 	 * of accesses we will make.
    260 	 */
    261 	if (madvise(addr, sizet_filesize, MADV_SEQUENTIAL) < 0 &&
    262 	    !qflag)
    263 		warn("madvise failed, ignoring");
    264 
    265 	/*
    266 	 * get the header length and set up the audio device
    267 	 */
    268 	if ((hdrlen = audioctl_write_fromhdr(addr,
    269 	    sizet_filesize, audiofd, &datasize, file)) < 0) {
    270 		if (play_errstring)
    271 			errx(1, "%s: %s", play_errstring, file);
    272 		else
    273 			errx(1, "unknown audio file: %s", file);
    274 	}
    275 
    276 	filesize -= hdrlen;
    277 	addr = (char *)addr + hdrlen;
    278 	if (filesize < datasize || datasize == 0) {
    279 		if (filesize < datasize)
    280 			warnx("bogus datasize: %ld", (u_long)datasize);
    281 		datasize = filesize;
    282 	}
    283 
    284 	while (datasize > bufsize) {
    285 		if (write(audiofd, addr, bufsize) != bufsize)
    286 			err(1, "write failed");
    287 		addr = (char *)addr + bufsize;
    288 		datasize -= bufsize;
    289 	}
    290 	if (write(audiofd, addr, (size_t)datasize) != (ssize_t)datasize)
    291 		err(1, "final write failed");
    292 
    293 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    294 		warn("audio drain ioctl failed");
    295 	if (munmap(oaddr, sizet_filesize) < 0)
    296 		err(1, "munmap failed");
    297 
    298 	close(fd);
    299 }
    300 
    301 /*
    302  * play the file on the file descriptor fd
    303  */
    304 void
    305 play_fd(file, fd)
    306 	const char *file;
    307 	int     fd;
    308 {
    309 	char    *buffer = malloc(bufsize);
    310 	ssize_t hdrlen;
    311 	int     nr, nw;
    312 	size_t	datasize = 0;
    313 	size_t	dataout = 0;
    314 
    315 	if (buffer == NULL)
    316 		err(1, "malloc of read buffer failed");
    317 
    318 	nr = read(fd, buffer, bufsize);
    319 	if (nr < 0)
    320 		goto read_error;
    321 	if (nr == 0) {
    322 		if (fflag)
    323 			return;
    324 		err(1, "unexpected EOF");
    325 	}
    326 	hdrlen = audioctl_write_fromhdr(buffer, nr, audiofd, &datasize, file);
    327 	if (hdrlen < 0) {
    328 		if (play_errstring)
    329 			errx(1, "%s: %s", play_errstring, file);
    330 		else
    331 			errx(1, "unknown audio file: %s", file);
    332 	}
    333 	if (hdrlen > 0) {
    334 		if (hdrlen > nr)	/* shouldn't happen */
    335 			errx(1, "header seems really large: %lld", (long long)hdrlen);
    336 		memmove(buffer, buffer + hdrlen, nr - hdrlen);
    337 		nr -= hdrlen;
    338 	}
    339 	while (datasize == 0 || dataout < datasize) {
    340 		if (datasize != 0 && dataout + nr > datasize)
    341 			nr = datasize - dataout;
    342 		nw = write(audiofd, buffer, nr);
    343 		if (nw != nr)
    344 			goto write_error;
    345 		dataout += nw;
    346 		nr = read(fd, buffer, bufsize);
    347 		if (nr == -1)
    348 			goto read_error;
    349 		if (nr == 0)
    350 			break;
    351 	}
    352 	/* something to think about: no message given for dataout < datasize */
    353 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    354 		warn("audio drain ioctl failed");
    355 	return;
    356 read_error:
    357 	err(1, "read of standard input failed");
    358 write_error:
    359 	err(1, "audio device write failed");
    360 }
    361 
    362 /*
    363  * only support sun and wav audio files so far ...
    364  *
    365  * XXX this should probably be mostly part of libaudio, but it
    366  * uses the local "info" variable. blah... fix me!
    367  */
    368 ssize_t
    369 audioctl_write_fromhdr(hdr, fsz, fd, datasize, file)
    370 	void	*hdr;
    371 	size_t	fsz;
    372 	int	fd;
    373 	size_t	*datasize;
    374 	const char	*file;
    375 {
    376 	sun_audioheader	*sunhdr;
    377 	ssize_t	hdr_len;
    378 
    379 	AUDIO_INITINFO(&info);
    380 	sunhdr = hdr;
    381 	if (ntohl(sunhdr->magic) == AUDIO_FILE_MAGIC) {
    382 		if (audio_sun_to_encoding(ntohl(sunhdr->encoding),
    383 		    &info.play.encoding, &info.play.precision)) {
    384 			if (!qflag)
    385 				warnx("unknown unsupported Sun audio encoding"
    386 				      " format %d", ntohl(sunhdr->encoding));
    387 			if (fflag)
    388 				goto set_audio_mode;
    389 			return (-1);
    390 		}
    391 
    392 		info.play.sample_rate = ntohl(sunhdr->sample_rate);
    393 		info.play.channels = ntohl(sunhdr->channels);
    394 		hdr_len = ntohl(sunhdr->hdr_size);
    395 
    396 		*datasize = ntohl(sunhdr->data_size);
    397 		goto set_audio_mode;
    398 	}
    399 
    400 	hdr_len = audio_wav_parse_hdr(hdr, fsz, &info.play.encoding,
    401 	    &info.play.precision, &info.play.sample_rate, &info.play.channels,
    402 	    datasize);
    403 
    404 	switch (hdr_len) {
    405 	case AUDIO_ESHORTHDR:
    406 	case AUDIO_EWAVUNSUPP:
    407 	case AUDIO_EWAVBADPCM:
    408 	case AUDIO_EWAVNODATA:
    409 		play_errstring = audio_errstring(hdr_len);
    410 		/* FALL THROUGH */
    411 	case AUDIO_ENOENT:
    412 		break;
    413 	default:
    414 		if (hdr_len < 1)
    415 			break;
    416 		goto set_audio_mode;
    417 	}
    418 	/*
    419 	 * if we don't know it, bail unless we are forcing.
    420 	 */
    421 	if (fflag == 0)
    422 		return (-1);
    423 set_audio_mode:
    424 	if (port)
    425 		info.play.port = port;
    426 	if (volume)
    427 		info.play.gain = volume;
    428 	if (balance)
    429 		info.play.balance = balance;
    430 	if (fflag) {
    431 		if (sample_rate)
    432 			info.play.sample_rate = sample_rate;
    433 		if (channels)
    434 			info.play.channels = channels;
    435 		if (encoding)
    436 			info.play.encoding = encoding;
    437 		if (precision)
    438 			info.play.precision = precision;
    439 		hdr_len = 0;
    440 	}
    441 	info.mode = AUMODE_PLAY_ALL;
    442 
    443 	if (verbose) {
    444 		const char *enc = audio_enc_from_val(info.play.encoding);
    445 
    446 		printf("%s: sample_rate=%d channels=%d "
    447 		   "datasize=%lld "
    448 		   "precision=%d%s%s\n", file,
    449 		   info.play.sample_rate,
    450 		   info.play.channels,
    451 		   (long long)*datasize,
    452 		   info.play.precision,
    453 		   enc ? " encoding=" : "",
    454 		   enc ? enc : "");
    455 	}
    456 
    457 	if (ioctl(fd, AUDIO_SETINFO, &info) < 0)
    458 		err(1, "failed to set audio info");
    459 
    460 	return (hdr_len);
    461 }
    462 
    463 void
    464 usage()
    465 {
    466 
    467 	fprintf(stderr, "Usage: %s [-hiqV] [options] files\n", getprogname());
    468 	fprintf(stderr, "Options:\n\t"
    469 	    "-C audio control device\n\t"
    470 	    "-b balance (0-63)\n\t"
    471 	    "-d audio device\n\t"
    472 	    "-f force settings\n\t"
    473 	    "\t-c forced channels\n\t"
    474 	    "\t-e forced encoding\n\t"
    475 	    "\t-P forced precision\n\t"
    476 	    "\t-s forced sample rate\n\t"
    477 	    "-i header information\n\t"
    478 	    "-m monitor volume\n\t"
    479 	    "-p output port\n\t"
    480 	    "-v volume\n");
    481 	exit(EXIT_FAILURE);
    482 }
    483