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