Home | History | Annotate | Line # | Download | only in play
play.c revision 1.59
      1 /*	$NetBSD: play.c,v 1.59 2019/11/09 12:54:34 mrg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999, 2000, 2001, 2002, 2010, 2015, 2019 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  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 #include <sys/cdefs.h>
     29 
     30 #ifndef lint
     31 __RCSID("$NetBSD: play.c,v 1.59 2019/11/09 12:54:34 mrg Exp $");
     32 #endif
     33 
     34 #include <sys/param.h>
     35 #include <sys/audioio.h>
     36 #include <sys/ioctl.h>
     37 #include <sys/mman.h>
     38 #include <sys/stat.h>
     39 
     40 #include <err.h>
     41 #include <fcntl.h>
     42 #include <signal.h>
     43 #include <stdio.h>
     44 #include <stdlib.h>
     45 #include <string.h>
     46 #include <unistd.h>
     47 #include <util.h>
     48 
     49 #include <paths.h>
     50 
     51 #include "libaudio.h"
     52 
     53 typedef size_t (*convert)(void *inbuf, void *outbuf, size_t len);
     54 
     55 static void usage(void) __dead;
     56 static void play(char *);
     57 static void play_fd(const char *, int);
     58 static ssize_t audioctl_write_fromhdr(void *, size_t, int,
     59 				      off_t *, const char *,
     60 				      convert *);
     61 static void cleanup(int) __dead;
     62 
     63 static audio_info_t	info;
     64 static int	volume;
     65 static int	balance;
     66 static int	port;
     67 static int	fflag;
     68 static int	qflag;
     69 int	verbose;
     70 static int	sample_rate;
     71 static int	encoding;
     72 static char	*encoding_str;
     73 static int	precision;
     74 static int	channels;
     75 
     76 static char	const *play_errstring = NULL;
     77 static size_t	bufsize;
     78 static int	audiofd;
     79 static int	exitstatus = EXIT_SUCCESS;
     80 
     81 int
     82 main(int argc, char *argv[])
     83 {
     84 	size_t	len;
     85 	int	ch;
     86 	int	iflag = 0;
     87 	const char *defdevice = _PATH_SOUND;
     88 	const char *device = NULL;
     89 
     90 	while ((ch = getopt(argc, argv, "b:B:C:c:d:e:fhip:P:qs:Vv:")) != -1) {
     91 		switch (ch) {
     92 		case 'b':
     93 			decode_int(optarg, &balance);
     94 			if (balance < 0 || balance > 64)
     95 				errx(1, "balance must be between 0 and 63");
     96 			break;
     97 		case 'B':
     98 			bufsize = strsuftoll("write buffer size", optarg,
     99 					     1, UINT_MAX);
    100 			break;
    101 		case 'c':
    102 			decode_int(optarg, &channels);
    103 			if (channels < 0)
    104 				errx(1, "channels must be positive");
    105 			break;
    106 		case 'C':
    107 			/* Ignore, compatibility */
    108 			break;
    109 		case 'd':
    110 			device = optarg;
    111 			break;
    112 		case 'e':
    113 			encoding_str = optarg;
    114 			break;
    115 		case 'f':
    116 			fflag = 1;
    117 			break;
    118 		case 'i':
    119 			iflag++;
    120 			break;
    121 		case 'q':
    122 			qflag++;
    123 			break;
    124 		case 'P':
    125 			decode_int(optarg, &precision);
    126 			if (precision != 4 && precision != 8 &&
    127 			    precision != 16 && precision != 24 &&
    128 			    precision != 32)
    129 				errx(1, "precision must be between 4, 8, 16, 24 or 32");
    130 			break;
    131 		case 'p':
    132 			len = strlen(optarg);
    133 
    134 			if (strncmp(optarg, "speaker", len) == 0)
    135 				port |= AUDIO_SPEAKER;
    136 			else if (strncmp(optarg, "headphone", len) == 0)
    137 				port |= AUDIO_HEADPHONE;
    138 			else if (strncmp(optarg, "line", len) == 0)
    139 				port |= AUDIO_LINE_OUT;
    140 			else
    141 				errx(1,
    142 			    "port must be `speaker', `headphone', or `line'");
    143 			break;
    144 		case 's':
    145 			decode_int(optarg, &sample_rate);
    146 			if (sample_rate < 0 || sample_rate > 48000 * 2)	/* XXX */
    147 				errx(1, "sample rate must be between 0 and 96000");
    148 			break;
    149 		case 'V':
    150 			verbose++;
    151 			break;
    152 		case 'v':
    153 			volume = atoi(optarg);
    154 			if (volume < 0 || volume > 255)
    155 				errx(1, "volume must be between 0 and 255");
    156 			break;
    157 		/* case 'h': */
    158 		default:
    159 			usage();
    160 			/* NOTREACHED */
    161 		}
    162 	}
    163 	argc -= optind;
    164 	argv += optind;
    165 
    166 	if (encoding_str) {
    167 		encoding = audio_enc_to_val(encoding_str);
    168 		if (encoding == -1)
    169 			errx(1, "unknown encoding, bailing...");
    170 	}
    171 
    172 	if (device == NULL && (device = getenv("AUDIODEVICE")) == NULL &&
    173 	    (device = getenv("AUDIODEV")) == NULL) /* Sun compatibility */
    174 		device = defdevice;
    175 
    176 	audiofd = open(device, O_WRONLY);
    177 	if (audiofd < 0 && device == defdevice) {
    178 		device = _PATH_SOUND0;
    179 		audiofd = open(device, O_WRONLY);
    180 	}
    181 
    182 	if (audiofd < 0)
    183 		err(1, "failed to open %s", device);
    184 
    185 	if (ioctl(audiofd, AUDIO_GETINFO, &info) < 0)
    186 		err(1, "failed to get audio info");
    187 	if (bufsize == 0) {
    188 		bufsize = info.play.buffer_size;
    189 		if (bufsize < 32 * 1024)
    190 			bufsize = 32 * 1024;
    191 	}
    192 
    193 	signal(SIGINT, cleanup);
    194 	signal(SIGTERM, cleanup);
    195 	signal(SIGHUP, cleanup);
    196 
    197 	if (*argv)
    198 		do
    199 			play(*argv++);
    200 		while (*argv);
    201 	else
    202 		play_fd("standard input", STDIN_FILENO);
    203 
    204 	cleanup(0);
    205 }
    206 
    207 static void
    208 cleanup(int signo)
    209 {
    210 
    211 	(void)ioctl(audiofd, AUDIO_FLUSH, NULL);
    212 	(void)ioctl(audiofd, AUDIO_SETINFO, &info);
    213 	close(audiofd);
    214 	if (signo != 0) {
    215 		(void)raise_default_signal(signo);
    216 	}
    217 	exit(exitstatus);
    218 }
    219 
    220 #ifndef __vax__
    221 static size_t
    222 float32_to_linear32(void *inbuf, void *outbuf, size_t len)
    223 {
    224 	uint8_t *inbuf8 = inbuf, *end = inbuf8 + len;
    225 	uint8_t *outbuf8 = outbuf;
    226 	float f;
    227 	int32_t i;
    228 
    229 	while (inbuf8 + sizeof f <= end) {
    230 		memcpy(&f, inbuf8, sizeof f);
    231 
    232 		/* saturate */
    233 		if (f < -1.0)
    234 			f = -1.0;
    235 		if (f > 1.0)
    236 			f = 1.0;
    237 
    238 		/* Convert -1.0 to +1.0 into a 32 bit signed value */
    239 		i = f * ((1u << 31) - 1);
    240 
    241 		memcpy(outbuf8, &i, sizeof i);
    242 
    243 		inbuf8 += sizeof f;
    244 		outbuf8 += sizeof i;
    245 	}
    246 
    247 	return len;
    248 }
    249 
    250 static size_t
    251 float64_to_linear32(void *inbuf, void *outbuf, size_t len)
    252 {
    253 	uint8_t *inbuf8 = inbuf, *end = inbuf8 + len;
    254 	uint8_t *outbuf8 = outbuf;
    255 	double f;
    256 	int32_t i;
    257 
    258 	while (inbuf8 + sizeof f <= end) {
    259 		memcpy(&f, inbuf8, sizeof f);
    260 
    261 		/* saturate */
    262 		if (f < -1.0)
    263 			f = -1.0;
    264 		if (f > 1.0)
    265 			f = 1.0;
    266 
    267 		/* Convert -1.0 to +1.0 into a 32 bit signed value */
    268 		i = f * ((1u << 31) - 1);
    269 
    270 		memcpy(outbuf8, &i, sizeof i);
    271 
    272 		inbuf8 += sizeof f;
    273 		outbuf8 += sizeof i;
    274 	}
    275 
    276 	return len / 2;
    277 }
    278 #endif /* __vax__ */
    279 
    280 static size_t
    281 audio_write(int fd, void *buf, size_t len, convert conv)
    282 {
    283 	static void *convert_buffer;
    284 	static size_t convert_buffer_size;
    285 
    286 	if (conv == NULL)
    287 		return write(fd, buf, len);
    288 
    289 	if (convert_buffer == NULL || convert_buffer_size < len) {
    290 		free(convert_buffer);
    291 		convert_buffer = malloc(len);
    292 		if (convert_buffer == NULL)
    293 			err(1, "malloc of convert buffer failed");
    294 		convert_buffer_size = len;
    295 	}
    296 	len = conv(buf, convert_buffer, len);
    297 	return write(fd, convert_buffer, len);
    298 }
    299 
    300 static void
    301 play(char *file)
    302 {
    303 	convert conv = NULL;
    304 	struct stat sb;
    305 	void *addr, *oaddr;
    306 	off_t	filesize;
    307 	size_t	sizet_filesize;
    308 	off_t datasize = 0;
    309 	ssize_t	hdrlen;
    310 	int fd;
    311 	int nw;
    312 
    313 	if (file[0] == '-' && file[1] == 0) {
    314 		play_fd("standard input", STDIN_FILENO);
    315 		return;
    316 	}
    317 
    318 	fd = open(file, O_RDONLY);
    319 	if (fd < 0) {
    320 		if (!qflag)
    321 			warn("could not open %s", file);
    322 		exitstatus = EXIT_FAILURE;
    323 		return;
    324 	}
    325 
    326 	if (fstat(fd, &sb) < 0)
    327 		err(1, "could not fstat %s", file);
    328 	filesize = sb.st_size;
    329 	sizet_filesize = (size_t)filesize;
    330 
    331 	/*
    332 	 * if the file is not a regular file, doesn't fit in a size_t,
    333 	 * or if we failed to mmap the file, try to read it instead, so
    334 	 * that filesystems, etc, that do not support mmap() work
    335 	 */
    336 	if (!S_ISREG(sb.st_mode) ||
    337 	    ((off_t)sizet_filesize != filesize) ||
    338 	    (oaddr = addr = mmap(0, sizet_filesize, PROT_READ,
    339 	    MAP_SHARED, fd, 0)) == MAP_FAILED) {
    340 		play_fd(file, fd);
    341 		close(fd);
    342 		return;
    343 	}
    344 
    345 	/*
    346 	 * give the VM system a bit of a hint about the type
    347 	 * of accesses we will make.  we don't care about errors.
    348 	 */
    349 	madvise(addr, sizet_filesize, MADV_SEQUENTIAL);
    350 
    351 	/*
    352 	 * get the header length and set up the audio device, and
    353 	 * determine any conversion needed.
    354 	 */
    355 	if ((hdrlen = audioctl_write_fromhdr(addr,
    356 	    sizet_filesize, audiofd, &datasize, file, &conv)) < 0) {
    357 		if (play_errstring)
    358 			errx(1, "%s: %s", play_errstring, file);
    359 		else
    360 			errx(1, "unknown audio file: %s", file);
    361 	}
    362 
    363 	filesize -= hdrlen;
    364 	addr = (char *)addr + hdrlen;
    365 	if (filesize < datasize || datasize == 0) {
    366 		if (filesize < datasize)
    367 			warnx("bogus datasize: %ld", (u_long)datasize);
    368 		datasize = filesize;
    369 	}
    370 
    371 	while ((uint64_t)datasize > bufsize) {
    372 		nw = audio_write(audiofd, addr, bufsize, conv);
    373 		if (nw == -1)
    374 			err(1, "write failed");
    375 		if ((size_t)nw != bufsize)
    376 			errx(1, "write failed");
    377 		addr = (char *)addr + bufsize;
    378 		datasize -= bufsize;
    379 	}
    380 	nw = audio_write(audiofd, addr, datasize, conv);
    381 	if (nw == -1)
    382 		err(1, "final write failed");
    383 	if ((off_t)nw != datasize)
    384 		errx(1, "final write failed");
    385 
    386 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    387 		warn("audio drain ioctl failed");
    388 	if (munmap(oaddr, sizet_filesize) < 0)
    389 		err(1, "munmap failed");
    390 
    391 	close(fd);
    392 }
    393 
    394 /*
    395  * play the file on the file descriptor fd
    396  */
    397 static void
    398 play_fd(const char *file, int fd)
    399 {
    400 	convert conv = NULL;
    401 	char    *buffer = malloc(bufsize);
    402 	ssize_t hdrlen;
    403 	int     nr, nw;
    404 	off_t	datasize = 0;
    405 	off_t	dataout = 0;
    406 
    407 	if (buffer == NULL)
    408 		err(1, "malloc of read buffer failed");
    409 
    410 	nr = read(fd, buffer, bufsize);
    411 	if (nr < 0)
    412 		goto read_error;
    413 	if (nr == 0) {
    414 		if (fflag) {
    415 			free(buffer);
    416 			return;
    417 		}
    418 		err(1, "unexpected EOF");
    419 	}
    420 	hdrlen = audioctl_write_fromhdr(buffer, nr, audiofd, &datasize, file, &conv);
    421 	if (hdrlen < 0) {
    422 		if (play_errstring)
    423 			errx(1, "%s: %s", play_errstring, file);
    424 		else
    425 			errx(1, "unknown audio file: %s", file);
    426 	}
    427 	if (hdrlen > 0) {
    428 		if (hdrlen > nr)	/* shouldn't happen */
    429 			errx(1, "header seems really large: %lld", (long long)hdrlen);
    430 		memmove(buffer, buffer + hdrlen, nr - hdrlen);
    431 		nr -= hdrlen;
    432 	}
    433 	while (datasize == 0 || dataout < datasize) {
    434 		if (datasize != 0 && dataout + nr > datasize)
    435 			nr = datasize - dataout;
    436 		nw = audio_write(audiofd, buffer, nr, conv);
    437 		if (nw == -1)
    438 			err(1, "audio device write failed");
    439 		if (nw != nr)
    440 			errx(1, "audio device write failed");
    441 		dataout += nw;
    442 		nr = read(fd, buffer, bufsize);
    443 		if (nr == -1)
    444 			goto read_error;
    445 		if (nr == 0)
    446 			break;
    447 	}
    448 	/* something to think about: no message given for dataout < datasize */
    449 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
    450 		warn("audio drain ioctl failed");
    451 	return;
    452 read_error:
    453 	err(1, "read of standard input failed");
    454 }
    455 
    456 /*
    457  * only support sun and wav audio files so far ...
    458  *
    459  * XXX this should probably be mostly part of libaudio, but it
    460  * uses the local "info" variable. blah... fix me!
    461  */
    462 static ssize_t
    463 audioctl_write_fromhdr(void *hdr, size_t fsz, int fd, off_t *datasize, const char *file, convert *conv)
    464 {
    465 	sun_audioheader	*sunhdr;
    466 	ssize_t	hdr_len = 0;
    467 
    468 	*conv = NULL;
    469 
    470 	AUDIO_INITINFO(&info);
    471 	sunhdr = hdr;
    472 	if (ntohl(sunhdr->magic) == AUDIO_FILE_MAGIC) {
    473 		if (audio_sun_to_encoding(ntohl(sunhdr->encoding),
    474 		    &info.play.encoding, &info.play.precision)) {
    475 			if (!qflag)
    476 				warnx("unknown unsupported Sun audio encoding"
    477 				      " format %d", ntohl(sunhdr->encoding));
    478 			if (fflag)
    479 				goto set_audio_mode;
    480 			return (-1);
    481 		}
    482 
    483 		info.play.sample_rate = ntohl(sunhdr->sample_rate);
    484 		info.play.channels = ntohl(sunhdr->channels);
    485 		hdr_len = ntohl(sunhdr->hdr_size);
    486 
    487 		*datasize = (off_t)ntohl(sunhdr->data_size);
    488 		goto set_audio_mode;
    489 	}
    490 
    491 	hdr_len = audio_wav_parse_hdr(hdr, fsz, &info.play.encoding,
    492 	    &info.play.precision, &info.play.sample_rate, &info.play.channels,
    493 	    datasize);
    494 
    495 	switch (hdr_len) {
    496 	case AUDIO_ESHORTHDR:
    497 	case AUDIO_EWAVUNSUPP:
    498 	case AUDIO_EWAVBADPCM:
    499 	case AUDIO_EWAVNODATA:
    500 		play_errstring = audio_errstring(hdr_len);
    501 		/* FALL THROUGH */
    502 	case AUDIO_ENOENT:
    503 		break;
    504 	default:
    505 		if (hdr_len < 1)
    506 			break;
    507 		goto set_audio_mode;
    508 	}
    509 	/*
    510 	 * if we don't know it, bail unless we are forcing.
    511 	 */
    512 	if (fflag == 0)
    513 		return (-1);
    514 set_audio_mode:
    515 	if (port)
    516 		info.play.port = port;
    517 	if (volume)
    518 		info.play.gain = volume;
    519 	if (balance)
    520 		info.play.balance = balance;
    521 	if (fflag) {
    522 		if (sample_rate)
    523 			info.play.sample_rate = sample_rate;
    524 		if (channels)
    525 			info.play.channels = channels;
    526 		if (encoding)
    527 			info.play.encoding = encoding;
    528 		if (precision)
    529 			info.play.precision = precision;
    530 		hdr_len = 0;
    531 	}
    532 	info.mode = AUMODE_PLAY_ALL;
    533 
    534 	if (verbose) {
    535 		const char *enc = audio_enc_from_val(info.play.encoding);
    536 
    537 		printf("%s: sample_rate=%d channels=%d "
    538 		   "datasize=%lld "
    539 		   "precision=%d%s%s\n", file,
    540 		   info.play.sample_rate,
    541 		   info.play.channels,
    542 		   (long long)*datasize,
    543 		   info.play.precision,
    544 		   enc ? " encoding=" : "",
    545 		   enc ? enc : "");
    546 	}
    547 
    548 #ifndef __vax__
    549 	if (info.play.encoding == AUDIO_ENCODING_LIBAUDIO_FLOAT32 ||
    550 	    info.play.encoding == AUDIO_ENCODING_LIBAUDIO_FLOAT64) {
    551 		const char *msg;
    552 
    553 		if (info.play.encoding == AUDIO_ENCODING_LIBAUDIO_FLOAT32) {
    554 			if (sizeof(float) * CHAR_BIT != 32)
    555 				return -1;
    556 			*conv = float32_to_linear32;
    557 			msg = "32";
    558 		} else {
    559 			if (sizeof(double) * CHAR_BIT != 64)
    560 				return -1;
    561 			*conv = float64_to_linear32;
    562 			msg = "32";
    563 		}
    564 		info.play.encoding = AUDIO_ENCODING_SLINEAR_LE;
    565 		info.play.precision = 32;
    566 		if (verbose)
    567 			printf("%s: converting IEEE float%s to precision=%d "
    568 			       "encoding=%s\n", file, msg,
    569 			       info.play.precision,
    570 			       audio_enc_from_val(info.play.encoding));
    571 	}
    572 #endif /* __vax__ */
    573 
    574 	if (ioctl(fd, AUDIO_SETINFO, &info) < 0)
    575 		err(1, "failed to set audio info");
    576 
    577 	return (hdr_len);
    578 }
    579 
    580 static void
    581 usage(void)
    582 {
    583 
    584 	fprintf(stderr, "Usage: %s [-hiqV] [options] files\n", getprogname());
    585 	fprintf(stderr, "Options:\n\t"
    586 	    "-B buffer size\n\t"
    587 	    "-b balance (0-63)\n\t"
    588 	    "-d audio device\n\t"
    589 	    "-f force settings\n\t"
    590 	    "\t-c forced channels\n\t"
    591 	    "\t-e forced encoding\n\t"
    592 	    "\t-P forced precision\n\t"
    593 	    "\t-s forced sample rate\n\t"
    594 	    "-i header information\n\t"
    595 	    "-p output port\n\t"
    596 	    "-v volume\n");
    597 	exit(EXIT_FAILURE);
    598 }
    599