record.c revision 1.21 1 /* $NetBSD: record.c,v 1.21 2002/01/15 23:48:53 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 const char *device;
56 const 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 if (conv_func)
332 encoding = AUDIO_ENCODING_SLINEAR_BE;
333 } else if (encoding == AUDIO_ENCODING_ULINEAR_BE) {
334 if (precision == 16)
335 conv_func = change_sign16_be;
336 else if (precision == 32)
337 conv_func = change_sign32_be;
338 if (conv_func)
339 encoding = AUDIO_ENCODING_SLINEAR_BE;
340 } else if (encoding == AUDIO_ENCODING_SLINEAR_LE) {
341 if (precision == 16)
342 conv_func = change_sign16_swap_bytes_le;
343 else if (precision == 32)
344 conv_func = change_sign32_swap_bytes_le;
345 if (conv_func)
346 encoding = AUDIO_ENCODING_SLINEAR_BE;
347 }
348
349 /* if we can't express this as a Sun header, don't write any */
350 if (audio_encoding_to_sun(encoding, precision, &sunenc) != 0) {
351 if (!qflag && !warned)
352 warnx("failed to convert to sun encoding from %d:%d; "
353 "Sun audio header not written",
354 oencoding, precision);
355 conv_func = 0;
356 warned = 1;
357 return -1;
358 }
359
360 auh.magic = htonl(AUDIO_FILE_MAGIC);
361 if (outfd == STDOUT_FILENO)
362 auh.data_size = htonl(AUDIO_UNKNOWN_SIZE);
363 else
364 auh.data_size = htonl(total_size);
365 auh.encoding = htonl(sunenc);
366 auh.sample_rate = htonl(sample_rate);
367 auh.channels = htonl(channels);
368 if (header_info) {
369 int len, infolen;
370
371 infolen = ((len = strlen(header_info)) + 7) & 0xfffffff8;
372 *leftp = infolen - len;
373 auh.hdr_size = htonl(sizeof(auh) + infolen);
374 } else {
375 *leftp = sizeof(default_info);
376 auh.hdr_size = htonl(sizeof(auh) + *leftp);
377 }
378 *(sun_audioheader **)hdrp = &auh;
379 *lenp = sizeof auh;
380 return 0;
381 }
382
383 int
384 write_header_wav(hdrp, lenp, leftp)
385 void **hdrp;
386 size_t *lenp;
387 int *leftp;
388 {
389 /*
390 * WAV header we write looks like this:
391 *
392 * bytes purpose
393 * 0-3 "RIFF"
394 * 4-7 file length (minus 8)
395 * 8-15 "WAVEfmt "
396 * 16-19 format size
397 * 20-21 format tag
398 * 22-23 number of channels
399 * 24-27 sample rate
400 * 28-31 average bytes per second
401 * 32-33 block alignment
402 * 34-35 bits per sample
403 *
404 * then for ULAW and ALAW outputs, we have an extended chunk size
405 * and a WAV "fact" to add:
406 *
407 * 36-37 length of extension (== 0)
408 * 38-41 "fact"
409 * 42-45 fact size
410 * 46-49 number of samples written
411 * 50-53 "data"
412 * 54-57 data length
413 * 58- raw audio data
414 *
415 * for PCM outputs we have just the data remaining:
416 *
417 * 36-39 "data"
418 * 40-43 data length
419 * 44- raw audio data
420 *
421 * RIFF\^@^C^@WAVEfmt ^P^@^@^@^A^@^B^@D<AC>^@^@^P<B1>^B^@^D^@^P^@data^@^@^C^@^@^@^@^@^@^@^@^@^@
422 */
423 char wavheaderbuf[64], *p = wavheaderbuf;
424 const char *riff = "RIFF",
425 *wavefmt = "WAVEfmt ",
426 *fact = "fact",
427 *data = "data";
428 u_int32_t filelen, fmtsz, sps, abps, factsz = 4, nsample, datalen;
429 u_int16_t fmttag, nchan, align, bps, extln = 0;
430
431 if (header_info)
432 warnx("header information not supported for WAV");
433 *leftp = NULL;
434
435 switch (precision) {
436 case 8:
437 bps = 8;
438 break;
439 case 16:
440 bps = 16;
441 break;
442 case 32:
443 bps = 32;
444 break;
445 default:
446 {
447 static int warned = 0;
448
449 if (warned == 0) {
450 warnx("can not support precision of %d\n", precision);
451 warned = 1;
452 }
453 }
454 return (-1);
455 }
456
457 switch (encoding) {
458 case AUDIO_ENCODING_ULAW:
459 fmttag = WAVE_FORMAT_MULAW;
460 fmtsz = 18;
461 align = channels;
462 break;
463 case AUDIO_ENCODING_ALAW:
464 fmttag = WAVE_FORMAT_ALAW;
465 fmtsz = 18;
466 align = channels;
467 break;
468 /*
469 * we could try to support RIFX but it seems to be more portable
470 * to output little-endian data for WAV files.
471 */
472 case AUDIO_ENCODING_ULINEAR_BE:
473 if (bps == 16)
474 conv_func = change_sign16_swap_bytes_be;
475 else if (bps == 32)
476 conv_func = change_sign32_swap_bytes_be;
477 goto fmt_pcm;
478 case AUDIO_ENCODING_SLINEAR_BE:
479 if (bps == 16)
480 conv_func = swap_bytes;
481 else if (bps == 32)
482 conv_func = swap_bytes32;
483 goto fmt_pcm;
484 case AUDIO_ENCODING_ULINEAR_LE:
485 if (bps == 16)
486 conv_func = change_sign16_le;
487 else if (bps == 32)
488 conv_func = change_sign32_le;
489 /* FALLTHROUGH */
490 case AUDIO_ENCODING_SLINEAR_LE:
491 case AUDIO_ENCODING_PCM16:
492 fmt_pcm:
493 fmttag = WAVE_FORMAT_PCM;
494 fmtsz = 16;
495 align = channels * (bps / 8);
496 break;
497 default:
498 {
499 static int warned = 0;
500
501 if (warned == 0) {
502 warnx("can not support encoding of %s\n", wav_enc_from_val(encoding));
503 warned = 1;
504 }
505 }
506 return (-1);
507 }
508
509 nchan = channels;
510 sps = sample_rate;
511
512 /* data length */
513 if (outfd == STDOUT_FILENO)
514 datalen = 0;
515 else
516 datalen = total_size;
517
518 /* file length */
519 filelen = 4 + (8 + fmtsz) + (8 + datalen);
520 if (fmttag != WAVE_FORMAT_PCM)
521 filelen += 8 + factsz;
522
523 abps = (double)align*sample_rate / (double)1 + 0.5;
524
525 nsample = (datalen / bps) / sample_rate;
526
527 /*
528 * now we've calculated the info, write it out!
529 */
530 #define put32(x) do { \
531 u_int32_t _f; \
532 putle32(_f, (x)); \
533 memcpy(p, &_f, 4); \
534 } while (0)
535 #define put16(x) do { \
536 u_int16_t _f; \
537 putle16(_f, (x)); \
538 memcpy(p, &_f, 2); \
539 } while (0)
540 memcpy(p, riff, 4);
541 p += 4; /* 4 */
542 put32(filelen);
543 p += 4; /* 8 */
544 memcpy(p, wavefmt, 8);
545 p += 8; /* 16 */
546 put32(fmtsz);
547 p += 4; /* 20 */
548 put16(fmttag);
549 p += 2; /* 22 */
550 put16(nchan);
551 p += 2; /* 24 */
552 put32(sps);
553 p += 4; /* 28 */
554 put32(abps);
555 p += 4; /* 32 */
556 put16(align);
557 p += 2; /* 34 */
558 put16(bps);
559 p += 2; /* 36 */
560 /* NON PCM formats have an extended chunk; write it */
561 if (fmttag != WAVE_FORMAT_PCM) {
562 put16(extln);
563 p += 2; /* 38 */
564 memcpy(p, fact, 4);
565 p += 4; /* 42 */
566 put32(factsz);
567 p += 4; /* 46 */
568 put32(nsample);
569 p += 4; /* 50 */
570 }
571 memcpy(p, data, 4);
572 p += 4; /* 40/54 */
573 put32(datalen);
574 p += 4; /* 44/58 */
575 #undef put32
576 #undef put16
577
578 *hdrp = wavheaderbuf;
579 *lenp = (p - wavheaderbuf);
580
581 return 0;
582 }
583
584 void
585 write_header()
586 {
587 struct iovec iv[3];
588 int veclen, left, tlen;
589 void *hdr;
590 size_t hdrlen;
591
592 switch (format) {
593 case AUDIO_FORMAT_SUN:
594 if (write_header_sun(&hdr, &hdrlen, &left) != 0)
595 return;
596 break;
597 case AUDIO_FORMAT_WAV:
598 if (write_header_wav(&hdr, &hdrlen, &left) != 0)
599 return;
600 break;
601 case AUDIO_FORMAT_NONE:
602 return;
603 default:
604 errx(1, "unknown audio format");
605 }
606
607 veclen = 0;
608 tlen = 0;
609
610 if (hdrlen != 0) {
611 iv[veclen].iov_base = hdr;
612 iv[veclen].iov_len = hdrlen;
613 tlen += iv[veclen++].iov_len;
614 }
615 if (header_info) {
616 iv[veclen].iov_base = header_info;
617 iv[veclen].iov_len = (int)strlen(header_info) + 1;
618 tlen += iv[veclen++].iov_len;
619 }
620 if (left) {
621 iv[veclen].iov_base = default_info;
622 iv[veclen].iov_len = left;
623 tlen += iv[veclen++].iov_len;
624 }
625
626 if (tlen == 0)
627 return;
628
629 if (writev(outfd, iv, veclen) != tlen)
630 err(1, "could not write audio header");
631 }
632
633 void
634 rewrite_header()
635 {
636
637 /* can't do this here! */
638 if (outfd == STDOUT_FILENO)
639 return;
640
641 if (lseek(outfd, SEEK_SET, 0) < 0)
642 err(1, "could not seek to start of file for header rewrite");
643 write_header();
644 }
645
646 void
647 usage()
648 {
649
650 fprintf(stderr, "Usage: %s [-afhqV] [options] {files ...|-}\n",
651 getprogname());
652 fprintf(stderr, "Options:\n\t"
653 "-C audio control device\n\t"
654 "-F format\n\t"
655 "-b balance (0-63)\n\t"
656 "-c channels\n\t"
657 "-d audio device\n\t"
658 "-e encoding\n\t"
659 "-i header information\n\t"
660 "-m monitor volume\n\t"
661 "-P precision bits (4, 8, 16, 24 or 32)\n\t"
662 "-p input port\n\t"
663 "-s sample rate\n\t"
664 "-t recording time\n\t"
665 "-v volume\n");
666 exit(EXIT_FAILURE);
667 }
668