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