xref: /netbsd-src/usr.bin/audio/play/play.c (revision 413d532bcc3f62d122e56d92e13ac64825a40baf)
1 /*	$NetBSD: play.c,v 1.54 2011/08/28 01:17:48 joerg Exp $	*/
2 
3 /*
4  * Copyright (c) 1999, 2000, 2001, 2002, 2010 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.54 2011/08/28 01:17:48 joerg Exp $");
32 #endif
33 
34 
35 #include <sys/param.h>
36 #include <sys/audioio.h>
37 #include <sys/ioctl.h>
38 #include <sys/mman.h>
39 #include <sys/stat.h>
40 
41 #include <err.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <util.h>
49 
50 #include <paths.h>
51 
52 #include "libaudio.h"
53 
54 static void usage(void) __dead;
55 static void play(char *);
56 static void play_fd(const char *, int);
57 static ssize_t audioctl_write_fromhdr(void *, size_t, int, size_t *, const char *);
58 static void cleanup(int) __dead;
59 
60 static audio_info_t	info;
61 static int	volume;
62 static int	balance;
63 static int	port;
64 static int	fflag;
65 static int	qflag;
66 int	verbose;
67 static int	sample_rate;
68 static int	encoding;
69 static char	*encoding_str;
70 static int	precision;
71 static int	channels;
72 
73 static char	const *play_errstring = NULL;
74 static size_t	bufsize;
75 static int	audiofd;
76 static int	exitstatus = EXIT_SUCCESS;
77 
78 int
79 main(int argc, char *argv[])
80 {
81 	size_t	len;
82 	int	ch;
83 	int	iflag = 0;
84 	const char *defdevice = _PATH_SOUND;
85 	const char *device = NULL;
86 
87 	while ((ch = getopt(argc, argv, "b:B:C:c:d:e:fhip:P:qs:Vv:")) != -1) {
88 		switch (ch) {
89 		case 'b':
90 			decode_int(optarg, &balance);
91 			if (balance < 0 || balance > 64)
92 				errx(1, "balance must be between 0 and 63");
93 			break;
94 		case 'B':
95 			bufsize = strsuftoll("write buffer size", optarg,
96 					     1, UINT_MAX);
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 	if (bufsize == 0) {
185 		bufsize = info.play.buffer_size;
186 		if (bufsize < 32 * 1024)
187 			bufsize = 32 * 1024;
188 	}
189 
190 	signal(SIGINT, cleanup);
191 	signal(SIGTERM, cleanup);
192 	signal(SIGHUP, cleanup);
193 
194 	if (*argv)
195 		do
196 			play(*argv++);
197 		while (*argv);
198 	else
199 		play_fd("standard input", STDIN_FILENO);
200 
201 	cleanup(0);
202 }
203 
204 static void
205 cleanup(int signo)
206 {
207 
208 	(void)ioctl(audiofd, AUDIO_FLUSH, NULL);
209 	(void)ioctl(audiofd, AUDIO_SETINFO, &info);
210 	close(audiofd);
211 	if (signo != 0) {
212 		(void)raise_default_signal(signo);
213 	}
214 	exit(exitstatus);
215 }
216 
217 static void
218 play(char *file)
219 {
220 	struct stat sb;
221 	void *addr, *oaddr;
222 	off_t	filesize;
223 	size_t	sizet_filesize;
224 	size_t datasize = 0;
225 	ssize_t	hdrlen;
226 	int fd;
227 
228 	if (file[0] == '-' && file[1] == 0) {
229 		play_fd("standard input", STDIN_FILENO);
230 		return;
231 	}
232 
233 	fd = open(file, O_RDONLY);
234 	if (fd < 0) {
235 		if (!qflag)
236 			warn("could not open %s", file);
237 		exitstatus = EXIT_FAILURE;
238 		return;
239 	}
240 
241 	if (fstat(fd, &sb) < 0)
242 		err(1, "could not fstat %s", file);
243 	filesize = sb.st_size;
244 	sizet_filesize = (size_t)filesize;
245 
246 	/*
247 	 * if the file is not a regular file, doesn't fit in a size_t,
248 	 * or if we failed to mmap the file, try to read it instead, so
249 	 * that filesystems, etc, that do not support mmap() work
250 	 */
251 	if (S_ISREG(sb.st_rdev & S_IFMT) == 0 ||
252 	    ((off_t)sizet_filesize != filesize) ||
253 	    (oaddr = addr = mmap(0, sizet_filesize, PROT_READ,
254 	    MAP_SHARED, fd, 0)) == MAP_FAILED) {
255 		play_fd(file, fd);
256 		close(fd);
257 		return;
258 	}
259 
260 	/*
261 	 * give the VM system a bit of a hint about the type
262 	 * of accesses we will make.  we don't care about errors.
263 	 */
264 	madvise(addr, sizet_filesize, MADV_SEQUENTIAL);
265 
266 	/*
267 	 * get the header length and set up the audio device
268 	 */
269 	if ((hdrlen = audioctl_write_fromhdr(addr,
270 	    sizet_filesize, audiofd, &datasize, file)) < 0) {
271 		if (play_errstring)
272 			errx(1, "%s: %s", play_errstring, file);
273 		else
274 			errx(1, "unknown audio file: %s", file);
275 	}
276 
277 	filesize -= hdrlen;
278 	addr = (char *)addr + hdrlen;
279 	if ((uint64_t)filesize < datasize || datasize == 0) {
280 		if ((uint64_t)filesize < datasize)
281 			warnx("bogus datasize: %ld", (u_long)datasize);
282 		datasize = filesize;
283 	}
284 
285 	while (datasize > bufsize) {
286 		if ((size_t)write(audiofd, addr, bufsize) != bufsize)
287 			err(1, "write failed");
288 		addr = (char *)addr + bufsize;
289 		datasize -= bufsize;
290 	}
291 	if ((size_t)write(audiofd, addr, datasize) != datasize)
292 		err(1, "final write failed");
293 
294 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
295 		warn("audio drain ioctl failed");
296 	if (munmap(oaddr, sizet_filesize) < 0)
297 		err(1, "munmap failed");
298 
299 	close(fd);
300 }
301 
302 /*
303  * play the file on the file descriptor fd
304  */
305 static void
306 play_fd(const char *file, int fd)
307 {
308 	char    *buffer = malloc(bufsize);
309 	ssize_t hdrlen;
310 	int     nr, nw;
311 	size_t	datasize = 0;
312 	size_t	dataout = 0;
313 
314 	if (buffer == NULL)
315 		err(1, "malloc of read buffer failed");
316 
317 	nr = read(fd, buffer, bufsize);
318 	if (nr < 0)
319 		goto read_error;
320 	if (nr == 0) {
321 		if (fflag) {
322 			free(buffer);
323 			return;
324 		}
325 		err(1, "unexpected EOF");
326 	}
327 	hdrlen = audioctl_write_fromhdr(buffer, nr, audiofd, &datasize, file);
328 	if (hdrlen < 0) {
329 		if (play_errstring)
330 			errx(1, "%s: %s", play_errstring, file);
331 		else
332 			errx(1, "unknown audio file: %s", file);
333 	}
334 	if (hdrlen > 0) {
335 		if (hdrlen > nr)	/* shouldn't happen */
336 			errx(1, "header seems really large: %lld", (long long)hdrlen);
337 		memmove(buffer, buffer + hdrlen, nr - hdrlen);
338 		nr -= hdrlen;
339 	}
340 	while (datasize == 0 || dataout < datasize) {
341 		if (datasize != 0 && dataout + nr > datasize)
342 			nr = datasize - dataout;
343 		nw = write(audiofd, buffer, nr);
344 		if (nw != nr)
345 			goto write_error;
346 		dataout += nw;
347 		nr = read(fd, buffer, bufsize);
348 		if (nr == -1)
349 			goto read_error;
350 		if (nr == 0)
351 			break;
352 	}
353 	/* something to think about: no message given for dataout < datasize */
354 	if (ioctl(audiofd, AUDIO_DRAIN) < 0 && !qflag)
355 		warn("audio drain ioctl failed");
356 	return;
357 read_error:
358 	err(1, "read of standard input failed");
359 write_error:
360 	err(1, "audio device write failed");
361 }
362 
363 /*
364  * only support sun and wav audio files so far ...
365  *
366  * XXX this should probably be mostly part of libaudio, but it
367  * uses the local "info" variable. blah... fix me!
368  */
369 static ssize_t
370 audioctl_write_fromhdr(void *hdr, size_t fsz, int fd, size_t *datasize, const char *file)
371 {
372 	sun_audioheader	*sunhdr;
373 	ssize_t	hdr_len = 0;
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 		const char *enc = audio_enc_from_val(info.play.encoding);
441 
442 		printf("%s: sample_rate=%d channels=%d "
443 		   "datasize=%lld "
444 		   "precision=%d%s%s\n", file,
445 		   info.play.sample_rate,
446 		   info.play.channels,
447 		   (long long)*datasize,
448 		   info.play.precision,
449 		   enc ? " encoding=" : "",
450 		   enc ? enc : "");
451 	}
452 
453 	if (ioctl(fd, AUDIO_SETINFO, &info) < 0)
454 		err(1, "failed to set audio info");
455 
456 	return (hdr_len);
457 }
458 
459 static void
460 usage(void)
461 {
462 
463 	fprintf(stderr, "Usage: %s [-hiqV] [options] files\n", getprogname());
464 	fprintf(stderr, "Options:\n\t"
465 	    "-B buffer size\n\t"
466 	    "-b balance (0-63)\n\t"
467 	    "-d audio device\n\t"
468 	    "-f force settings\n\t"
469 	    "\t-c forced channels\n\t"
470 	    "\t-e forced encoding\n\t"
471 	    "\t-P forced precision\n\t"
472 	    "\t-s forced sample rate\n\t"
473 	    "-i header information\n\t"
474 	    "-p output port\n\t"
475 	    "-v volume\n");
476 	exit(EXIT_FAILURE);
477 }
478