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