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