record.c revision 1.23 1 /* $NetBSD: record.c,v 1.23 2002/02/02 20:20:26 jdolecek 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
94 while ((ch = getopt(argc, argv, "ab:C:F:c:d:e:fhi:m:P:p:qt:s:Vv:")) != -1) {
95 switch (ch) {
96 case 'a':
97 aflag++;
98 break;
99 case 'b':
100 decode_int(optarg, &balance);
101 if (balance < 0 || balance > 63)
102 errx(1, "balance must be between 0 and 63\n");
103 break;
104 case 'C':
105 /* Ignore, compatibility */
106 break;
107 case 'F':
108 format = audio_format_from_str(optarg);
109 if (format < 0)
110 errx(1, "Unknown audio format; "
111 "supported formats: \"sun\" and \"wav\"");
112 break;
113 case 'c':
114 decode_int(optarg, &channels);
115 if (channels < 0 || channels > 16)
116 errx(1, "channels must be between 0 and 16\n");
117 break;
118 case 'd':
119 device = optarg;
120 break;
121 case 'e':
122 encoding_str = optarg;
123 break;
124 case 'f':
125 fflag++;
126 break;
127 case 'i':
128 header_info = optarg;
129 break;
130 case 'm':
131 decode_int(optarg, &monitor_gain);
132 if (monitor_gain < 0 || monitor_gain > 255)
133 errx(1, "monitor volume must be between 0 and 255\n");
134 break;
135 case 'P':
136 decode_int(optarg, &precision);
137 if (precision != 4 && precision != 8 &&
138 precision != 16 && precision != 24 &&
139 precision != 32)
140 errx(1, "precision must be between 4, 8, 16, 24 or 32");
141 break;
142 case 'p':
143 len = strlen(optarg);
144
145 if (strncmp(optarg, "mic", len) == 0)
146 port |= AUDIO_MICROPHONE;
147 else if (strncmp(optarg, "cd", len) == 0 ||
148 strncmp(optarg, "internal-cd", len) == 0)
149 port |= AUDIO_CD;
150 else if (strncmp(optarg, "line", len) == 0)
151 port |= AUDIO_LINE_IN;
152 else
153 errx(1,
154 "port must be `cd', `internal-cd', `mic', or `line'");
155 break;
156 case 'q':
157 qflag++;
158 break;
159 case 's':
160 decode_int(optarg, &sample_rate);
161 if (sample_rate < 0 || sample_rate > 48000 * 2) /* XXX */
162 errx(1, "sample rate must be between 0 and 96000\n");
163 break;
164 case 't':
165 no_time_limit = 0;
166 decode_time(optarg, &record_time);
167 break;
168 case 'V':
169 verbose++;
170 break;
171 case 'v':
172 decode_int(optarg, &gain);
173 if (gain < 0 || gain > 255)
174 errx(1, "volume must be between 0 and 255\n");
175 break;
176 /* case 'h': */
177 default:
178 usage();
179 /* NOTREACHED */
180 }
181 }
182 argc -= optind;
183 argv += optind;
184
185 /*
186 * open the audio device, and control device
187 */
188 if (device == NULL && (device = getenv("AUDIODEVICE")) == NULL &&
189 (device = getenv("AUDIODEV")) == NULL) /* Sun compatibility */
190 device = _PATH_SOUND;
191
192 audiofd = open(device, O_RDONLY);
193 if (audiofd < 0 && device == _PATH_SOUND) {
194 device = _PATH_SOUND0;
195 audiofd = open(device, O_WRONLY);
196 }
197 if (audiofd < 0)
198 err(1, "failed to open %s", device);
199
200 /*
201 * work out the buffer size to use, and allocate it. also work out
202 * what the old monitor gain value is, so that we can reset it later.
203 */
204 if (ioctl(audiofd, AUDIO_GETINFO, &oinfo) < 0)
205 err(1, "failed to get audio info");
206 bufsize = oinfo.record.buffer_size;
207 if (bufsize < 32 * 1024)
208 bufsize = 32 * 1024;
209 omonitor_gain = oinfo.monitor_gain;
210
211 buffer = malloc(bufsize);
212 if (buffer == NULL)
213 err(1, "couldn't malloc buffer of %d size", (int)bufsize);
214
215 /*
216 * open the output file
217 */
218 if (argc != 1)
219 usage();
220 if (argv[0][0] != '-' && argv[0][1] != '\0') {
221 outfd = open(*argv, O_CREAT|(aflag ? O_APPEND : O_TRUNC)|O_WRONLY, 0666);
222 if (outfd < 0)
223 err(1, "could not open %s", *argv);
224 } else
225 outfd = STDOUT_FILENO;
226
227 /*
228 * convert the encoding string into a value.
229 */
230 if (encoding_str) {
231 encoding = audio_enc_to_val(encoding_str);
232 if (encoding == -1)
233 errx(1, "unknown encoding, bailing...");
234 }
235 else
236 encoding = AUDIO_ENCODING_ULAW;
237
238 /*
239 * set up audio device for recording with the speified parameters
240 */
241 AUDIO_INITINFO(&info);
242
243 /*
244 * for these, get the current values for stuffing into the header
245 */
246 #define SETINFO(x) if (x) info.record.x = x; else x = oinfo.record.x
247 SETINFO (sample_rate);
248 SETINFO (channels);
249 SETINFO (precision);
250 SETINFO (encoding);
251 SETINFO (gain);
252 SETINFO (port);
253 SETINFO (balance);
254 #undef SETINFO
255
256 if (monitor_gain)
257 info.monitor_gain = monitor_gain;
258 else
259 monitor_gain = oinfo.monitor_gain;
260
261 info.mode = AUMODE_RECORD;
262 if (ioctl(audiofd, AUDIO_SETINFO, &info) < 0)
263 err(1, "failed to reset audio info");
264
265 signal(SIGINT, cleanup);
266 write_header();
267 total_size = 0;
268
269 (void)gettimeofday(&start_time, NULL);
270 while (no_time_limit || timeleft(&start_time, &record_time)) {
271 if (read(audiofd, buffer, bufsize) != bufsize)
272 err(1, "read failed");
273 if (conv_func)
274 (*conv_func)(buffer, bufsize);
275 if (write(outfd, buffer, bufsize) != bufsize)
276 err(1, "write failed");
277 total_size += bufsize;
278 }
279 cleanup(0);
280 }
281
282 int
283 timeleft(start_tvp, record_tvp)
284 struct timeval *start_tvp;
285 struct timeval *record_tvp;
286 {
287 struct timeval now, diff;
288
289 (void)gettimeofday(&now, NULL);
290 timersub(&now, start_tvp, &diff);
291 timersub(record_tvp, &diff, &now);
292
293 return (now.tv_sec > 0 || (now.tv_sec == 0 && now.tv_usec > 0));
294 }
295
296 void
297 cleanup(signo)
298 int signo;
299 {
300
301 rewrite_header();
302 close(outfd);
303 if (omonitor_gain) {
304 AUDIO_INITINFO(&info);
305 info.monitor_gain = omonitor_gain;
306 if (ioctl(audiofd, AUDIO_SETINFO, &info) < 0)
307 err(1, "failed to reset audio info");
308 }
309 close(audiofd);
310 exit(0);
311 }
312
313 int
314 write_header_sun(hdrp, lenp, leftp)
315 void **hdrp;
316 size_t *lenp;
317 int *leftp;
318 {
319 static int warned = 0;
320 static sun_audioheader auh;
321 int sunenc, oencoding = encoding;
322
323 if (encoding == AUDIO_ENCODING_ULINEAR_LE) {
324 if (precision == 16)
325 conv_func = swap_bytes;
326 else if (precision == 32)
327 conv_func = swap_bytes32;
328 if (conv_func)
329 encoding = AUDIO_ENCODING_SLINEAR_BE;
330 } else if (encoding == AUDIO_ENCODING_ULINEAR_BE) {
331 if (precision == 16)
332 conv_func = change_sign16_be;
333 else if (precision == 32)
334 conv_func = change_sign32_be;
335 if (conv_func)
336 encoding = AUDIO_ENCODING_SLINEAR_BE;
337 } else if (encoding == AUDIO_ENCODING_SLINEAR_LE) {
338 if (precision == 16)
339 conv_func = change_sign16_swap_bytes_le;
340 else if (precision == 32)
341 conv_func = change_sign32_swap_bytes_le;
342 if (conv_func)
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 const char *riff = "RIFF",
422 *wavefmt = "WAVEfmt ",
423 *fact = "fact",
424 *data = "data";
425 u_int32_t filelen, fmtsz, sps, abps, factsz = 4, nsample, datalen;
426 u_int16_t fmttag, nchan, align, bps, extln = 0;
427
428 if (header_info)
429 warnx("header information not supported for WAV");
430 *leftp = NULL;
431
432 switch (precision) {
433 case 8:
434 bps = 8;
435 break;
436 case 16:
437 bps = 16;
438 break;
439 case 32:
440 bps = 32;
441 break;
442 default:
443 {
444 static int warned = 0;
445
446 if (warned == 0) {
447 warnx("can not support precision of %d\n", precision);
448 warned = 1;
449 }
450 }
451 return (-1);
452 }
453
454 switch (encoding) {
455 case AUDIO_ENCODING_ULAW:
456 fmttag = WAVE_FORMAT_MULAW;
457 fmtsz = 18;
458 align = channels;
459 break;
460 case AUDIO_ENCODING_ALAW:
461 fmttag = WAVE_FORMAT_ALAW;
462 fmtsz = 18;
463 align = channels;
464 break;
465 /*
466 * we could try to support RIFX but it seems to be more portable
467 * to output little-endian data for WAV files.
468 */
469 case AUDIO_ENCODING_ULINEAR_BE:
470 if (bps == 16)
471 conv_func = change_sign16_swap_bytes_be;
472 else if (bps == 32)
473 conv_func = change_sign32_swap_bytes_be;
474 goto fmt_pcm;
475 case AUDIO_ENCODING_SLINEAR_BE:
476 if (bps == 16)
477 conv_func = swap_bytes;
478 else if (bps == 32)
479 conv_func = swap_bytes32;
480 goto fmt_pcm;
481 case AUDIO_ENCODING_ULINEAR_LE:
482 if (bps == 16)
483 conv_func = change_sign16_le;
484 else if (bps == 32)
485 conv_func = change_sign32_le;
486 /* FALLTHROUGH */
487 case AUDIO_ENCODING_SLINEAR_LE:
488 case AUDIO_ENCODING_PCM16:
489 fmt_pcm:
490 fmttag = WAVE_FORMAT_PCM;
491 fmtsz = 16;
492 align = channels * (bps / 8);
493 break;
494 default:
495 {
496 static int warned = 0;
497
498 if (warned == 0) {
499 warnx("can not support encoding of %s\n", wav_enc_from_val(encoding));
500 warned = 1;
501 }
502 }
503 return (-1);
504 }
505
506 nchan = channels;
507 sps = sample_rate;
508
509 /* data length */
510 if (outfd == STDOUT_FILENO)
511 datalen = 0;
512 else
513 datalen = total_size;
514
515 /* file length */
516 filelen = 4 + (8 + fmtsz) + (8 + datalen);
517 if (fmttag != WAVE_FORMAT_PCM)
518 filelen += 8 + factsz;
519
520 abps = (double)align*sample_rate / (double)1 + 0.5;
521
522 nsample = (datalen / bps) / sample_rate;
523
524 /*
525 * now we've calculated the info, write it out!
526 */
527 #define put32(x) do { \
528 u_int32_t _f; \
529 putle32(_f, (x)); \
530 memcpy(p, &_f, 4); \
531 } while (0)
532 #define put16(x) do { \
533 u_int16_t _f; \
534 putle16(_f, (x)); \
535 memcpy(p, &_f, 2); \
536 } while (0)
537 memcpy(p, riff, 4);
538 p += 4; /* 4 */
539 put32(filelen);
540 p += 4; /* 8 */
541 memcpy(p, wavefmt, 8);
542 p += 8; /* 16 */
543 put32(fmtsz);
544 p += 4; /* 20 */
545 put16(fmttag);
546 p += 2; /* 22 */
547 put16(nchan);
548 p += 2; /* 24 */
549 put32(sps);
550 p += 4; /* 28 */
551 put32(abps);
552 p += 4; /* 32 */
553 put16(align);
554 p += 2; /* 34 */
555 put16(bps);
556 p += 2; /* 36 */
557 /* NON PCM formats have an extended chunk; write it */
558 if (fmttag != WAVE_FORMAT_PCM) {
559 put16(extln);
560 p += 2; /* 38 */
561 memcpy(p, fact, 4);
562 p += 4; /* 42 */
563 put32(factsz);
564 p += 4; /* 46 */
565 put32(nsample);
566 p += 4; /* 50 */
567 }
568 memcpy(p, data, 4);
569 p += 4; /* 40/54 */
570 put32(datalen);
571 p += 4; /* 44/58 */
572 #undef put32
573 #undef put16
574
575 *hdrp = wavheaderbuf;
576 *lenp = (p - wavheaderbuf);
577
578 return 0;
579 }
580
581 void
582 write_header()
583 {
584 struct iovec iv[3];
585 int veclen, left, tlen;
586 void *hdr;
587 size_t hdrlen;
588
589 switch (format) {
590 case AUDIO_FORMAT_SUN:
591 if (write_header_sun(&hdr, &hdrlen, &left) != 0)
592 return;
593 break;
594 case AUDIO_FORMAT_WAV:
595 if (write_header_wav(&hdr, &hdrlen, &left) != 0)
596 return;
597 break;
598 case AUDIO_FORMAT_NONE:
599 return;
600 default:
601 errx(1, "unknown audio format");
602 }
603
604 veclen = 0;
605 tlen = 0;
606
607 if (hdrlen != 0) {
608 iv[veclen].iov_base = hdr;
609 iv[veclen].iov_len = hdrlen;
610 tlen += iv[veclen++].iov_len;
611 }
612 if (header_info) {
613 iv[veclen].iov_base = header_info;
614 iv[veclen].iov_len = (int)strlen(header_info) + 1;
615 tlen += iv[veclen++].iov_len;
616 }
617 if (left) {
618 iv[veclen].iov_base = default_info;
619 iv[veclen].iov_len = left;
620 tlen += iv[veclen++].iov_len;
621 }
622
623 if (tlen == 0)
624 return;
625
626 if (writev(outfd, iv, veclen) != tlen)
627 err(1, "could not write audio header");
628 }
629
630 void
631 rewrite_header()
632 {
633
634 /* can't do this here! */
635 if (outfd == STDOUT_FILENO)
636 return;
637
638 if (lseek(outfd, SEEK_SET, 0) < 0)
639 err(1, "could not seek to start of file for header rewrite");
640 write_header();
641 }
642
643 void
644 usage()
645 {
646
647 fprintf(stderr, "Usage: %s [-afhqV] [options] {files ...|-}\n",
648 getprogname());
649 fprintf(stderr, "Options:\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