record.c revision 1.20 1 /* $NetBSD: record.c,v 1.20 2002/01/15 17:17:13 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 case AUDIO_ENCODING_ULINEAR_BE:
467 if (bps == 16)
468 conv_func = change_sign16_swap_bytes_be;
469 else if (bps == 32)
470 conv_func = change_sign32_swap_bytes_be;
471 goto fmt_pcm;
472 case AUDIO_ENCODING_SLINEAR_BE:
473 if (bps == 16)
474 conv_func = swap_bytes;
475 else if (bps == 32)
476 conv_func = swap_bytes32;
477 goto fmt_pcm;
478 case AUDIO_ENCODING_ULINEAR_LE:
479 if (bps == 16)
480 conv_func = change_sign16_le;
481 else if (bps == 32)
482 conv_func = change_sign32_le;
483 /* FALLTHROUGH */
484 case AUDIO_ENCODING_SLINEAR_LE:
485 case AUDIO_ENCODING_PCM16:
486 fmt_pcm:
487 fmttag = WAVE_FORMAT_PCM;
488 fmtsz = 16;
489 align = channels * (bps / 8);
490 break;
491 default:
492 {
493 static int warned = 0;
494
495 if (warned == 0) {
496 warnx("can not support encoding of %s\n", wav_enc_from_val(encoding));
497 warned = 1;
498 }
499 }
500 return (-1);
501 }
502
503 nchan = channels;
504 sps = sample_rate;
505
506 /* data length */
507 if (outfd == STDOUT_FILENO)
508 datalen = 0;
509 else
510 datalen = total_size;
511
512 /* file length */
513 filelen = 4 + (8 + fmtsz) + (8 + datalen);
514 if (fmttag != WAVE_FORMAT_PCM)
515 filelen += 8 + factsz;
516
517 abps = (double)align*sample_rate / (double)1 + 0.5;
518
519 nsample = (datalen / bps) / sample_rate;
520
521 /*
522 * now we've calculated the info, write it out!
523 */
524 #define put32(x) do { \
525 u_int32_t _f; \
526 putle32(_f, (x)); \
527 memcpy(p, &_f, 4); \
528 } while (0)
529 #define put16(x) do { \
530 u_int16_t _f; \
531 putle16(_f, (x)); \
532 memcpy(p, &_f, 2); \
533 } while (0)
534 memcpy(p, riff, 4);
535 p += 4; /* 4 */
536 put32(filelen);
537 p += 4; /* 8 */
538 memcpy(p, wavefmt, 8);
539 p += 8; /* 16 */
540 put32(fmtsz);
541 p += 4; /* 20 */
542 put16(fmttag);
543 p += 2; /* 22 */
544 put16(nchan);
545 p += 2; /* 24 */
546 put32(sps);
547 p += 4; /* 28 */
548 put32(abps);
549 p += 4; /* 32 */
550 put16(align);
551 p += 2; /* 34 */
552 put16(bps);
553 p += 2; /* 36 */
554 /* NON PCM formats have an extended chunk; write it */
555 if (fmttag != WAVE_FORMAT_PCM) {
556 put16(extln);
557 p += 2; /* 38 */
558 memcpy(p, fact, 4);
559 p += 4; /* 42 */
560 put32(factsz);
561 p += 4; /* 46 */
562 put32(nsample);
563 p += 4; /* 50 */
564 }
565 memcpy(p, data, 4);
566 p += 4; /* 40/54 */
567 put32(datalen);
568 p += 4; /* 44/58 */
569 #undef put32
570 #undef put16
571
572 *hdrp = wavheaderbuf;
573 *lenp = (p - wavheaderbuf);
574
575 return 0;
576 }
577
578 void
579 write_header()
580 {
581 struct iovec iv[3];
582 int veclen, left, tlen;
583 void *hdr;
584 size_t hdrlen;
585
586 switch (format) {
587 case AUDIO_FORMAT_SUN:
588 if (write_header_sun(&hdr, &hdrlen, &left) != 0)
589 return;
590 break;
591 case AUDIO_FORMAT_WAV:
592 if (write_header_wav(&hdr, &hdrlen, &left) != 0)
593 return;
594 break;
595 case AUDIO_FORMAT_NONE:
596 return;
597 default:
598 errx(1, "unknown audio format");
599 }
600
601 veclen = 0;
602 tlen = 0;
603
604 if (hdrlen != 0) {
605 iv[veclen].iov_base = hdr;
606 iv[veclen].iov_len = hdrlen;
607 tlen += iv[veclen++].iov_len;
608 }
609 if (header_info) {
610 iv[veclen].iov_base = header_info;
611 iv[veclen].iov_len = (int)strlen(header_info) + 1;
612 tlen += iv[veclen++].iov_len;
613 }
614 if (left) {
615 iv[veclen].iov_base = default_info;
616 iv[veclen].iov_len = left;
617 tlen += iv[veclen++].iov_len;
618 }
619
620 if (tlen == 0)
621 return;
622
623 if (writev(outfd, iv, veclen) != tlen)
624 err(1, "could not write audio header");
625 }
626
627 void
628 rewrite_header()
629 {
630
631 /* can't do this here! */
632 if (outfd == STDOUT_FILENO)
633 return;
634
635 if (lseek(outfd, SEEK_SET, 0) < 0)
636 err(1, "could not seek to start of file for header rewrite");
637 write_header();
638 }
639
640 void
641 usage()
642 {
643
644 fprintf(stderr, "Usage: %s [-afhqV] [options] {files ...|-}\n",
645 getprogname());
646 fprintf(stderr, "Options:\n\t"
647 "-C audio control device\n\t"
648 "-F format\n\t"
649 "-b balance (0-63)\n\t"
650 "-c channels\n\t"
651 "-d audio device\n\t"
652 "-e encoding\n\t"
653 "-i header information\n\t"
654 "-m monitor volume\n\t"
655 "-P precision bits (4, 8, 16, 24 or 32)\n\t"
656 "-p input port\n\t"
657 "-s sample rate\n\t"
658 "-t recording time\n\t"
659 "-v volume\n");
660 exit(EXIT_FAILURE);
661 }
662