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