Home | History | Annotate | Line # | Download | only in record
record.c revision 1.32
      1 /*	$NetBSD: record.c,v 1.32 2002/12/27 23:43:16 mrg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999, 2002 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 /*
     32  * SunOS compatible audiorecord(1)
     33  */
     34 
     35 #include <sys/types.h>
     36 #include <sys/audioio.h>
     37 #include <sys/ioctl.h>
     38 #include <sys/time.h>
     39 #include <sys/uio.h>
     40 
     41 #include <err.h>
     42 #include <fcntl.h>
     43 #include <paths.h>
     44 #include <signal.h>
     45 #include <stdio.h>
     46 #include <stdlib.h>
     47 #include <string.h>
     48 #include <unistd.h>
     49 
     50 #include "libaudio.h"
     51 #include "auconv.h"
     52 
     53 audio_info_t info, oinfo;
     54 ssize_t	total_size = -1;
     55 const char *device;
     56 int	format = AUDIO_FORMAT_DEFAULT;
     57 char	*header_info;
     58 char	default_info[8] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
     59 int	audiofd, outfd;
     60 int	qflag, aflag, fflag;
     61 int	verbose;
     62 int	monitor_gain, omonitor_gain;
     63 int	gain;
     64 int	balance;
     65 int	port;
     66 int	encoding;
     67 char	*encoding_str;
     68 int	precision;
     69 int	sample_rate;
     70 int	channels;
     71 struct timeval record_time;
     72 struct timeval start_time;
     73 
     74 void (*conv_func) (u_char *, size_t);
     75 
     76 void usage (void);
     77 int main (int, char *[]);
     78 int timeleft (struct timeval *, struct timeval *);
     79 void cleanup (int) __attribute__((__noreturn__));
     80 int write_header_sun (void **, size_t *, int *);
     81 int write_header_wav (void **, size_t *, int *);
     82 void write_header (void);
     83 void rewrite_header (void);
     84 
     85 int
     86 main(argc, argv)
     87 	int argc;
     88 	char *argv[];
     89 {
     90 	char	*buffer;
     91 	size_t	len, bufsize;
     92 	int	ch, no_time_limit = 1;
     93 	const char *defdevice = _PATH_SOUND;
     94 
     95 	while ((ch = getopt(argc, argv, "ab:C:F:c:d:e:fhi:m:P:p:qt:s:Vv:")) != -1) {
     96 		switch (ch) {
     97 		case 'a':
     98 			aflag++;
     99 			break;
    100 		case 'b':
    101 			decode_int(optarg, &balance);
    102 			if (balance < 0 || balance > 63)
    103 				errx(1, "balance must be between 0 and 63");
    104 			break;
    105 		case 'C':
    106 			/* Ignore, compatibility */
    107 			break;
    108 		case 'F':
    109 			format = audio_format_from_str(optarg);
    110 			if (format < 0)
    111 				errx(1, "Unknown audio format; supported "
    112 				    "formats: \"sun\", \"wav\", and \"none\"");
    113 			break;
    114 		case 'c':
    115 			decode_int(optarg, &channels);
    116 			if (channels < 0 || channels > 16)
    117 				errx(1, "channels must be between 0 and 16");
    118 			break;
    119 		case 'd':
    120 			device = optarg;
    121 			break;
    122 		case 'e':
    123 			encoding_str = optarg;
    124 			break;
    125 		case 'f':
    126 			fflag++;
    127 			break;
    128 		case 'i':
    129 			header_info = optarg;
    130 			break;
    131 		case 'm':
    132 			decode_int(optarg, &monitor_gain);
    133 			if (monitor_gain < 0 || monitor_gain > 255)
    134 				errx(1, "monitor volume must be between 0 and 255");
    135 			break;
    136 		case 'P':
    137 			decode_int(optarg, &precision);
    138 			if (precision != 4 && precision != 8 &&
    139 			    precision != 16 && precision != 24 &&
    140 			    precision != 32)
    141 				errx(1, "precision must be between 4, 8, 16, 24 or 32");
    142 			break;
    143 		case 'p':
    144 			len = strlen(optarg);
    145 
    146 			if (strncmp(optarg, "mic", len) == 0)
    147 				port |= AUDIO_MICROPHONE;
    148 			else if (strncmp(optarg, "cd", len) == 0 ||
    149 			           strncmp(optarg, "internal-cd", len) == 0)
    150 				port |= AUDIO_CD;
    151 			else if (strncmp(optarg, "line", len) == 0)
    152 				port |= AUDIO_LINE_IN;
    153 			else
    154 				errx(1,
    155 			    "port must be `cd', `internal-cd', `mic', or `line'");
    156 			break;
    157 		case 'q':
    158 			qflag++;
    159 			break;
    160 		case 's':
    161 			decode_int(optarg, &sample_rate);
    162 			if (sample_rate < 0 || sample_rate > 48000 * 2)	/* XXX */
    163 				errx(1, "sample rate must be between 0 and 96000");
    164 			break;
    165 		case 't':
    166 			no_time_limit = 0;
    167 			decode_time(optarg, &record_time);
    168 			break;
    169 		case 'V':
    170 			verbose++;
    171 			break;
    172 		case 'v':
    173 			decode_int(optarg, &gain);
    174 			if (gain < 0 || gain > 255)
    175 				errx(1, "volume must be between 0 and 255");
    176 			break;
    177 		/* case 'h': */
    178 		default:
    179 			usage();
    180 			/* NOTREACHED */
    181 		}
    182 	}
    183 	argc -= optind;
    184 	argv += optind;
    185 
    186 	/*
    187 	 * open the audio device, and control device
    188 	 */
    189 	if (device == NULL && (device = getenv("AUDIODEVICE")) == NULL &&
    190 	    (device = getenv("AUDIODEV")) == NULL) /* Sun compatibility */
    191 		device = defdevice;
    192 
    193 	audiofd = open(device, O_RDONLY);
    194 	if (audiofd < 0 && device == defdevice) {
    195 		device = _PATH_SOUND0;
    196 		audiofd = open(device, O_RDONLY);
    197 	}
    198 	if (audiofd < 0)
    199 		err(1, "failed to open %s", device);
    200 
    201 	/*
    202 	 * work out the buffer size to use, and allocate it.  also work out
    203 	 * what the old monitor gain value is, so that we can reset it later.
    204 	 */
    205 	if (ioctl(audiofd, AUDIO_GETINFO, &oinfo) < 0)
    206 		err(1, "failed to get audio info");
    207 	bufsize = oinfo.record.buffer_size;
    208 	if (bufsize < 32 * 1024)
    209 		bufsize = 32 * 1024;
    210 	omonitor_gain = oinfo.monitor_gain;
    211 
    212 	buffer = malloc(bufsize);
    213 	if (buffer == NULL)
    214 		err(1, "couldn't malloc buffer of %d size", (int)bufsize);
    215 
    216 	/*
    217 	 * open the output file
    218 	 */
    219 	if (argc != 1)
    220 		usage();
    221 	if (argv[0][0] != '-' && argv[0][1] != '\0') {
    222 		/* intuit the file type from the name */
    223 		if (format == AUDIO_FORMAT_DEFAULT)
    224 		{
    225 			size_t flen = strlen(*argv);
    226 			const char *arg = *argv;
    227 
    228 			if (strcasecmp(arg + flen - 3, ".au") == 0)
    229 				format = AUDIO_FORMAT_SUN;
    230 			else if (strcasecmp(arg + flen - 4, ".wav") == 0)
    231 				format = AUDIO_FORMAT_WAV;
    232 		}
    233 		outfd = open(*argv, O_CREAT|(aflag ? O_APPEND : O_TRUNC)|O_WRONLY, 0666);
    234 		if (outfd < 0)
    235 			err(1, "could not open %s", *argv);
    236 	} else
    237 		outfd = STDOUT_FILENO;
    238 
    239 	/*
    240 	 * convert the encoding string into a value.
    241 	 */
    242 	if (encoding_str) {
    243 		encoding = audio_enc_to_val(encoding_str);
    244 		if (encoding == -1)
    245 			errx(1, "unknown encoding, bailing...");
    246 	}
    247 	else
    248 		encoding = AUDIO_ENCODING_ULAW;
    249 
    250 	/*
    251 	 * set up audio device for recording with the speified parameters
    252 	 */
    253 	AUDIO_INITINFO(&info);
    254 
    255 	/*
    256 	 * for these, get the current values for stuffing into the header
    257 	 */
    258 #define SETINFO(x)	if (x) info.record.x = x; else x = oinfo.record.x
    259 	SETINFO (sample_rate);
    260 	SETINFO (channels);
    261 	SETINFO (precision);
    262 	SETINFO (encoding);
    263 	SETINFO (gain);
    264 	SETINFO (port);
    265 	SETINFO (balance);
    266 #undef SETINFO
    267 
    268 	if (monitor_gain)
    269 		info.monitor_gain = monitor_gain;
    270 	else
    271 		monitor_gain = oinfo.monitor_gain;
    272 
    273 	info.mode = AUMODE_RECORD;
    274 	if (ioctl(audiofd, AUDIO_SETINFO, &info) < 0)
    275 		err(1, "failed to set audio info");
    276 
    277 	signal(SIGINT, cleanup);
    278 	write_header();
    279 	total_size = 0;
    280 
    281 	if (verbose && conv_func) {
    282 		const char *s = NULL;
    283 
    284 		if (conv_func == swap_bytes)
    285 			s = "swap bytes (16 bit)";
    286 		else if (conv_func == swap_bytes32)
    287 			s = "swap bytes (32 bit)";
    288 		else if (conv_func == change_sign16_be)
    289 			s = "change sign (big-endian, 16 bit)";
    290 		else if (conv_func == change_sign16_le)
    291 			s = "change sign (little-endian, 16 bit)";
    292 		else if (conv_func == change_sign32_be)
    293 			s = "change sign (big-endian, 32 bit)";
    294 		else if (conv_func == change_sign32_le)
    295 			s = "change sign (little-endian, 32 bit)";
    296 		else if (conv_func == change_sign16_swap_bytes_be)
    297 			s = "change sign & swap bytes (big-endian, 16 bit)";
    298 		else if (conv_func == change_sign16_swap_bytes_le)
    299 			s = "change sign & swap bytes (little-endian, 16 bit)";
    300 		else if (conv_func == change_sign32_swap_bytes_be)
    301 			s = "change sign (big-endian, 32 bit)";
    302 		else if (conv_func == change_sign32_swap_bytes_le)
    303 			s = "change sign & swap bytes (little-endian, 32 bit)";
    304 
    305 		if (s)
    306 			fprintf(stderr, "%s: converting, using function: %s\n",
    307 			    getprogname(), s);
    308 		else
    309 			fprintf(stderr, "%s: using unnamed conversion "
    310 					"function\n", getprogname());
    311 	}
    312 
    313 	if (verbose)
    314 		fprintf(stderr,
    315 		   "sample_rate=%d channels=%d precision=%d encoding=%s\n",
    316 		   info.record.sample_rate, info.record.channels,
    317 		   info.record.precision,
    318 		   audio_enc_from_val(info.record.encoding));
    319 
    320 	if (!no_time_limit && verbose)
    321 		fprintf(stderr, "recording for %lu seconds, %lu microseconds\n",
    322 		    (u_long)record_time.tv_sec, (u_long)record_time.tv_usec);
    323 
    324 	(void)gettimeofday(&start_time, NULL);
    325 	while (no_time_limit || timeleft(&start_time, &record_time)) {
    326 		if (read(audiofd, buffer, bufsize) != bufsize)
    327 			err(1, "read failed");
    328 		if (conv_func)
    329 			(*conv_func)(buffer, bufsize);
    330 		if (write(outfd, buffer, bufsize) != bufsize)
    331 			err(1, "write failed");
    332 		total_size += bufsize;
    333 	}
    334 	cleanup(0);
    335 }
    336 
    337 int
    338 timeleft(start_tvp, record_tvp)
    339 	struct timeval *start_tvp;
    340 	struct timeval *record_tvp;
    341 {
    342 	struct timeval now, diff;
    343 
    344 	(void)gettimeofday(&now, NULL);
    345 	timersub(&now, start_tvp, &diff);
    346 	timersub(record_tvp, &diff, &now);
    347 
    348 	return (now.tv_sec > 0 || (now.tv_sec == 0 && now.tv_usec > 0));
    349 }
    350 
    351 void
    352 cleanup(signo)
    353 	int signo;
    354 {
    355 
    356 	rewrite_header();
    357 	close(outfd);
    358 	if (omonitor_gain) {
    359 		AUDIO_INITINFO(&info);
    360 		info.monitor_gain = omonitor_gain;
    361 		if (ioctl(audiofd, AUDIO_SETINFO, &info) < 0)
    362 			err(1, "failed to reset audio info");
    363 	}
    364 	close(audiofd);
    365 	exit(0);
    366 }
    367 
    368 int
    369 write_header_sun(hdrp, lenp, leftp)
    370 	void **hdrp;
    371 	size_t *lenp;
    372 	int *leftp;
    373 {
    374 	static int warned = 0;
    375 	static sun_audioheader auh;
    376 	int sunenc, oencoding = encoding;
    377 
    378 	/* only perform conversions if we don't specify the encoding */
    379 	switch (encoding) {
    380 	case AUDIO_ENCODING_ULINEAR_LE:
    381 #if BYTE_ORDER == LITTLE_ENDIAN
    382 	case AUDIO_ENCODING_ULINEAR:
    383 #endif
    384 		if (precision == 16)
    385 			conv_func = change_sign16_swap_bytes_le;
    386 		else if (precision == 32)
    387 			conv_func = change_sign32_swap_bytes_le;
    388 		if (conv_func)
    389 			encoding = AUDIO_ENCODING_SLINEAR_BE;
    390 		break;
    391 
    392 	case AUDIO_ENCODING_ULINEAR_BE:
    393 #if BYTE_ORDER == BIG_ENDIAN
    394 	case AUDIO_ENCODING_ULINEAR:
    395 #endif
    396 		if (precision == 16)
    397 			conv_func = change_sign16_be;
    398 		else if (precision == 32)
    399 			conv_func = change_sign32_be;
    400 		if (conv_func)
    401 			encoding = AUDIO_ENCODING_SLINEAR_BE;
    402 		break;
    403 
    404 	case AUDIO_ENCODING_SLINEAR_LE:
    405 #if BYTE_ORDER == LITTLE_ENDIAN
    406 	case AUDIO_ENCODING_SLINEAR:
    407 #endif
    408 		if (precision == 16)
    409 			conv_func = swap_bytes;
    410 		else if (precision == 32)
    411 			conv_func = swap_bytes32;
    412 		if (conv_func)
    413 			encoding = AUDIO_ENCODING_SLINEAR_BE;
    414 		break;
    415 
    416 #if BYTE_ORDER == BIG_ENDIAN
    417 	case AUDIO_ENCODING_SLINEAR:
    418 		encoding = AUDIO_ENCODING_SLINEAR_BE;
    419 		break;
    420 #endif
    421 	}
    422 
    423 	/* if we can't express this as a Sun header, don't write any */
    424 	if (audio_encoding_to_sun(encoding, precision, &sunenc) != 0) {
    425 		if (!qflag && !warned) {
    426 			const char *s = audio_enc_from_val(oencoding);
    427 
    428 			if (s == NULL)
    429 				s = "(unknown)";
    430 			warnx("failed to convert to sun encoding from %s "
    431 			      "(precision %d);\nSun audio header not written",
    432 			      s, precision);
    433 		}
    434 		format = AUDIO_FORMAT_NONE;
    435 		conv_func = 0;
    436 		warned = 1;
    437 		return -1;
    438 	}
    439 
    440 	auh.magic = htonl(AUDIO_FILE_MAGIC);
    441 	if (outfd == STDOUT_FILENO)
    442 		auh.data_size = htonl(AUDIO_UNKNOWN_SIZE);
    443 	else
    444 		auh.data_size = htonl(total_size);
    445 	auh.encoding = htonl(sunenc);
    446 	auh.sample_rate = htonl(sample_rate);
    447 	auh.channels = htonl(channels);
    448 	if (header_info) {
    449 		int 	len, infolen;
    450 
    451 		infolen = ((len = strlen(header_info)) + 7) & 0xfffffff8;
    452 		*leftp = infolen - len;
    453 		auh.hdr_size = htonl(sizeof(auh) + infolen);
    454 	} else {
    455 		*leftp = sizeof(default_info);
    456 		auh.hdr_size = htonl(sizeof(auh) + *leftp);
    457 	}
    458 	*(sun_audioheader **)hdrp = &auh;
    459 	*lenp = sizeof auh;
    460 	return 0;
    461 }
    462 
    463 int
    464 write_header_wav(hdrp, lenp, leftp)
    465 	void **hdrp;
    466 	size_t *lenp;
    467 	int *leftp;
    468 {
    469 	/*
    470 	 * WAV header we write looks like this:
    471 	 *
    472 	 *      bytes   purpose
    473 	 *      0-3     "RIFF"
    474 	 *      4-7     file length (minus 8)
    475 	 *      8-15    "WAVEfmt "
    476 	 *      16-19   format size
    477 	 *      20-21   format tag
    478 	 *      22-23   number of channels
    479 	 *      24-27   sample rate
    480 	 *      28-31   average bytes per second
    481 	 *      32-33   block alignment
    482 	 *      34-35   bits per sample
    483 	 *
    484 	 * then for ULAW and ALAW outputs, we have an extended chunk size
    485 	 * and a WAV "fact" to add:
    486 	 *
    487 	 *      36-37   length of extension (== 0)
    488 	 *      38-41   "fact"
    489 	 *      42-45   fact size
    490 	 *      46-49   number of samples written
    491 	 *      50-53   "data"
    492 	 *      54-57   data length
    493 	 *      58-     raw audio data
    494 	 *
    495 	 * for PCM outputs we have just the data remaining:
    496 	 *
    497 	 *      36-39   "data"
    498 	 *      40-43   data length
    499 	 *      44-     raw audio data
    500 	 *
    501 	 *	RIFF\^@^C^@WAVEfmt ^P^@^@^@^A^@^B^@D<AC>^@^@^P<B1>^B^@^D^@^P^@data^@^@^C^@^@^@^@^@^@^@^@^@^@
    502 	 */
    503 	char	wavheaderbuf[64], *p = wavheaderbuf;
    504 	const char *riff = "RIFF",
    505 	    *wavefmt = "WAVEfmt ",
    506 	    *fact = "fact",
    507 	    *data = "data";
    508 	u_int32_t filelen, fmtsz, sps, abps, factsz = 4, nsample, datalen;
    509 	u_int16_t fmttag, nchan, align, bps, extln = 0;
    510 
    511 	if (header_info)
    512 		warnx("header information not supported for WAV");
    513 	*leftp = NULL;
    514 
    515 	switch (precision) {
    516 	case 8:
    517 		bps = 8;
    518 		break;
    519 	case 16:
    520 		bps = 16;
    521 		break;
    522 	case 32:
    523 		bps = 32;
    524 		break;
    525 	default:
    526 		{
    527 			static int warned = 0;
    528 
    529 			if (warned == 0) {
    530 				warnx("can not support precision of %d", precision);
    531 				warned = 1;
    532 			}
    533 		}
    534 		return (-1);
    535 	}
    536 
    537 	switch (encoding) {
    538 	case AUDIO_ENCODING_ULAW:
    539 		fmttag = WAVE_FORMAT_MULAW;
    540 		fmtsz = 18;
    541 		align = channels;
    542 		break;
    543 
    544 	case AUDIO_ENCODING_ALAW:
    545 		fmttag = WAVE_FORMAT_ALAW;
    546 		fmtsz = 18;
    547 		align = channels;
    548 		break;
    549 
    550 	/*
    551 	 * we could try to support RIFX but it seems to be more portable
    552 	 * to output little-endian data for WAV files.
    553 	 */
    554 	case AUDIO_ENCODING_ULINEAR_BE:
    555 #if BYTE_ORDER == BIG_ENDIAN
    556 	case AUDIO_ENCODING_ULINEAR:
    557 #endif
    558 		if (bps == 16)
    559 			conv_func = change_sign16_swap_bytes_be;
    560 		else if (bps == 32)
    561 			conv_func = change_sign32_swap_bytes_be;
    562 		goto fmt_pcm;
    563 
    564 	case AUDIO_ENCODING_SLINEAR_BE:
    565 #if BYTE_ORDER == BIG_ENDIAN
    566 	case AUDIO_ENCODING_SLINEAR:
    567 #endif
    568 		if (bps == 16)
    569 			conv_func = swap_bytes;
    570 		else if (bps == 32)
    571 			conv_func = swap_bytes32;
    572 		goto fmt_pcm;
    573 
    574 	case AUDIO_ENCODING_ULINEAR_LE:
    575 #if BYTE_ORDER == LITTLE_ENDIAN
    576 	case AUDIO_ENCODING_ULINEAR:
    577 #endif
    578 		if (bps == 16)
    579 			conv_func = change_sign16_le;
    580 		else if (bps == 32)
    581 			conv_func = change_sign32_le;
    582 		/* FALLTHROUGH */
    583 
    584 	case AUDIO_ENCODING_SLINEAR_LE:
    585 	case AUDIO_ENCODING_PCM16:
    586 #if BYTE_ORDER == LITTLE_ENDIAN
    587 	case AUDIO_ENCODING_SLINEAR:
    588 #endif
    589 fmt_pcm:
    590 		fmttag = WAVE_FORMAT_PCM;
    591 		fmtsz = 16;
    592 		align = channels * (bps / 8);
    593 		break;
    594 
    595 	default:
    596 		{
    597 			static int warned = 0;
    598 
    599 			if (warned == 0) {
    600 				const char *s = wav_enc_from_val(encoding);
    601 
    602 				if (s == NULL)
    603 					warnx("can not support encoding of %s", s);
    604 				else
    605 					warnx("can not support encoding of %d", encoding);
    606 				warned = 1;
    607 			}
    608 		}
    609 		format = AUDIO_FORMAT_NONE;
    610 		return (-1);
    611 	}
    612 
    613 	nchan = channels;
    614 	sps = sample_rate;
    615 
    616 	/* data length */
    617 	if (outfd == STDOUT_FILENO)
    618 		datalen = 0;
    619 	else
    620 		datalen = total_size;
    621 
    622 	/* file length */
    623 	filelen = 4 + (8 + fmtsz) + (8 + datalen);
    624 	if (fmttag != WAVE_FORMAT_PCM)
    625 		filelen += 8 + factsz;
    626 
    627 	abps = (double)align*sample_rate / (double)1 + 0.5;
    628 
    629 	nsample = (datalen / bps) / sample_rate;
    630 
    631 	/*
    632 	 * now we've calculated the info, write it out!
    633 	 */
    634 #define put32(x) do { \
    635 	u_int32_t _f; \
    636 	putle32(_f, (x)); \
    637 	memcpy(p, &_f, 4); \
    638 } while (0)
    639 #define put16(x) do { \
    640 	u_int16_t _f; \
    641 	putle16(_f, (x)); \
    642 	memcpy(p, &_f, 2); \
    643 } while (0)
    644 	memcpy(p, riff, 4);
    645 	p += 4;				/* 4 */
    646 	put32(filelen);
    647 	p += 4;				/* 8 */
    648 	memcpy(p, wavefmt, 8);
    649 	p += 8;				/* 16 */
    650 	put32(fmtsz);
    651 	p += 4;				/* 20 */
    652 	put16(fmttag);
    653 	p += 2;				/* 22 */
    654 	put16(nchan);
    655 	p += 2;				/* 24 */
    656 	put32(sps);
    657 	p += 4;				/* 28 */
    658 	put32(abps);
    659 	p += 4;				/* 32 */
    660 	put16(align);
    661 	p += 2;				/* 34 */
    662 	put16(bps);
    663 	p += 2;				/* 36 */
    664 	/* NON PCM formats have an extended chunk; write it */
    665 	if (fmttag != WAVE_FORMAT_PCM) {
    666 		put16(extln);
    667 		p += 2;			/* 38 */
    668 		memcpy(p, fact, 4);
    669 		p += 4;			/* 42 */
    670 		put32(factsz);
    671 		p += 4;			/* 46 */
    672 		put32(nsample);
    673 		p += 4;			/* 50 */
    674 	}
    675 	memcpy(p, data, 4);
    676 	p += 4;				/* 40/54 */
    677 	put32(datalen);
    678 	p += 4;				/* 44/58 */
    679 #undef put32
    680 #undef put16
    681 
    682 	*hdrp = wavheaderbuf;
    683 	*lenp = (p - wavheaderbuf);
    684 
    685 	return 0;
    686 }
    687 
    688 void
    689 write_header()
    690 {
    691 	struct iovec iv[3];
    692 	int veclen, left, tlen;
    693 	void *hdr;
    694 	size_t hdrlen;
    695 
    696 	switch (format) {
    697 	case AUDIO_FORMAT_DEFAULT:
    698 	case AUDIO_FORMAT_SUN:
    699 		if (write_header_sun(&hdr, &hdrlen, &left) != 0)
    700 			return;
    701 		break;
    702 	case AUDIO_FORMAT_WAV:
    703 		if (write_header_wav(&hdr, &hdrlen, &left) != 0)
    704 			return;
    705 		break;
    706 	case AUDIO_FORMAT_NONE:
    707 		return;
    708 	default:
    709 		errx(1, "unknown audio format");
    710 	}
    711 
    712 	veclen = 0;
    713 	tlen = 0;
    714 
    715 	if (hdrlen != 0) {
    716 		iv[veclen].iov_base = hdr;
    717 		iv[veclen].iov_len = hdrlen;
    718 		tlen += iv[veclen++].iov_len;
    719 	}
    720 	if (header_info) {
    721 		iv[veclen].iov_base = header_info;
    722 		iv[veclen].iov_len = (int)strlen(header_info) + 1;
    723 		tlen += iv[veclen++].iov_len;
    724 	}
    725 	if (left) {
    726 		iv[veclen].iov_base = default_info;
    727 		iv[veclen].iov_len = left;
    728 		tlen += iv[veclen++].iov_len;
    729 	}
    730 
    731 	if (tlen == 0)
    732 		return;
    733 
    734 	if (writev(outfd, iv, veclen) != tlen)
    735 		err(1, "could not write audio header");
    736 }
    737 
    738 void
    739 rewrite_header()
    740 {
    741 
    742 	/* can't do this here! */
    743 	if (outfd == STDOUT_FILENO)
    744 		return;
    745 
    746 	if (lseek(outfd, SEEK_SET, 0) < 0)
    747 		err(1, "could not seek to start of file for header rewrite");
    748 	write_header();
    749 }
    750 
    751 void
    752 usage()
    753 {
    754 
    755 	fprintf(stderr, "Usage: %s [-afhqV] [options] {files ...|-}\n",
    756 	    getprogname());
    757 	fprintf(stderr, "Options:\n\t"
    758 	    "-F format\n\t"
    759 	    "-b balance (0-63)\n\t"
    760 	    "-c channels\n\t"
    761 	    "-d audio device\n\t"
    762 	    "-e encoding\n\t"
    763 	    "-i header information\n\t"
    764 	    "-m monitor volume\n\t"
    765 	    "-P precision bits (4, 8, 16, 24 or 32)\n\t"
    766 	    "-p input port\n\t"
    767 	    "-s sample rate\n\t"
    768 	    "-t recording time\n\t"
    769 	    "-v volume\n");
    770 	exit(EXIT_FAILURE);
    771 }
    772