8 #include <vorbis/vorbisfile.h>
9 #include <alsa/asoundlib.h>
12 static void key_cleanup(void);
14 static void __attribute__((noreturn)) die(char *msg, ...)
18 vfprintf(stderr, msg, args);
24 typedef long long s64;
26 #define MIN(a,b) ((a)<(b) ? (a) : (b))
27 #define MAX(a,b) ((a)>(b) ? (a) : (b))
28 #define TRIPLE(pos) (int)(((pos)/rate)/60), (int)(((pos)/rate)%60), (int)((pos)%rate)
30 static struct termios tios, tios_old;
31 static int tios_inited;
33 static void key_init(void)
35 if (tcgetattr(0, &tios_old) < 0)
36 die("tcgetattr failed: %m");
38 tios.c_iflag = IGNBRK;
42 if (tcsetattr(0, 0, &tios) < 0)
43 die("tcsetattr failed: %m");
44 fcntl(0, F_SETFL, O_NONBLOCK);
48 static void key_cleanup(void)
52 tcsetattr(0, 0, &tios_old);
57 static int key_get(void)
60 static int esc_state, esc_num;
64 int e = read(0, keybuf, 1);
87 if (key >= '0' && key <= '9')
88 esc_num = 10*esc_num + key - '0';
92 return (esc_num << 16) + 0x200 + key;
100 enum { IN_WAV, IN_OGG } inmode;
101 static OggVorbis_File vf;
102 static SNDFILE *sndf;
103 static unsigned int rate;
104 static char *find_title = "Toulky ceskou minulosti";
105 static s64 total_samples = 0;
106 static s64 start_pos = -1;
107 static s64 end_pos = -1;
108 double prefade = 1, postfade = 1;
110 static void scan_streams(void)
112 int nstr = ov_streams(&vf);
113 printf("OGG: Scanning %d logical streams:\n", nstr);
115 die("No streams found");
116 for (int i=0; i<nstr; i++)
119 vi = ov_info(&vf, i);
121 die("ov_info failed");
122 if (vi->channels != 2)
123 die("Stream %d has %d channels, which is not supported", i, vi->channels);
124 if ((unsigned int) vi->rate != rate)
127 die("Stream %d has sample rate %d, while the previous had %d", i, vi->rate, rate);
133 vc = ov_comment(&vf, i);
135 die("ov_comment failed");
138 for (int j=0; j<vc->comments; j++)
139 if (vc->comment_lengths[j] > 6 && !strncasecmp(vc->user_comments[j], "title=", 6))
141 int l = vc->comment_lengths[j] - 6;
142 memcpy(title, vc->user_comments[j]+6, l);
146 strcpy(title, "<none>");
148 s64 samples = ov_pcm_total(&vf, i);
149 int sec = (samples + rate - 1) / rate;
150 printf(" %d: `%s' (%d:%02d, %d bits/sec) @%Ld\n", i, title, sec/60, sec%60, (int)vi->bitrate_nominal, total_samples);
152 if (find_title && strstr(title, find_title))
155 start_pos = total_samples;
156 else if (end_pos != total_samples)
157 printf("WARNING: Gap encountered!\n");
158 end_pos = total_samples + samples;
161 total_samples += samples;
163 if (ov_pcm_total(&vf, -1) != total_samples)
164 die("ov_pcm_total mismatch");
169 printf("WARNING: Title not found, marking whole file\n");
171 end_pos = total_samples;
175 static void in_open(char *name)
177 infile = fopen(name, "r");
179 die("Cannot open %s: %m", name);
182 if (fread(s, 1, 4, infile) != 4)
183 die("Input file too short");
185 if (!memcmp(s, "RIFF", 4))
187 puts("INPUT: WAV file detected");
190 else if (!memcmp(s, "OggS", 4))
192 puts("INPUT: OGG file detected");
195 else if (!memcmp(s, "HTTP", 4))
197 puts("INPUT: HTTP header detected, expecting OGG inside");
201 die("Unable to identify input format");
203 if (inmode == IN_WAV)
206 bzero(&si, sizeof(si));
207 lseek(fileno(infile), 0, SEEK_SET);
208 sndf = sf_open_fd(fileno(infile), SFM_READ, &si, 0);
210 die("sf_open_fd() failed: %s", sf_strerror(NULL));
211 total_samples = si.frames;
212 rate = si.samplerate;
213 if (si.channels != 2)
214 die("Got %d channels instead of 2", si.channels);
215 if (si.sections != 1)
216 die("Found %d sections, what does it mean?", si.sections);
217 printf("WAV: format id=%08x\n", si.format);
219 end_pos = total_samples;
223 int err = ov_open(infile, &vf, NULL, 0);
225 die("ov_open: error %d", err);
226 if (!ov_seekable(&vf))
227 die("Input is not seekable, how come?");
231 printf("INPUT: length %3d:%02d.%05d, %Ld samples at rate %d\n", TRIPLE(total_samples), total_samples, rate);
234 static void in_goto(s64 go)
236 if (inmode == IN_OGG)
237 ov_pcm_seek(&vf, go);
239 sf_seek(sndf, go, SEEK_SET);
242 static int in_read(s16 *buf, s64 pos, int nsamp)
244 if (inmode == IN_OGG)
246 if (ov_pcm_tell(&vf) != pos)
248 printf("\n!!! CONFUSED POSITION\n");
249 //ov_pcm_seek(&vf, pos);
250 //if (ov_pcm_tell(&vf) != pos)
251 //printf(">>> unable to correct :(\n");
256 int e = ov_read(&vf, (char*)buf, 4*nsamp, 0, 2, 1, &bp);
258 printf("!!! HOLE DETECTED\n");
259 else if (e == OV_EBADLINK)
260 printf("!!! BAD LINK\n");
262 die("ov_read returned %d bytes, which means non-integer number of samples. Huh.", e);
264 die("ov_read returned %d. Huh!", e);
265 else if (e/4 <= nsamp)
268 die("ov_read returned %d samples, although we wanted %d", e/4, nsamp);
273 int e = sf_readf_short(sndf, buf, nsamp);
275 printf("!!!! sf_readf_short mismatch: %d != %d\n", e, nsamp);
280 static void in_close(void)
282 if (inmode == IN_OGG)
288 static s16 *prefader, *postfader;
290 static s16 *calc_fader(int len, int rev)
294 s16 *x = malloc(2*len);
295 for (int i=0; i<len; i++)
296 x[rev ? len-1-i : i] = (s64)i*32767/len;
300 static void recalc_faders(void)
302 // printf("FADERS: set to %g pre, %g post\n", prefade, postfade);
304 prefader = calc_fader(prefade*rate, 0);
306 postfader = calc_fader(postfade*rate, 1);
309 static void apply_fader(s16 *sig, int nsamp, s64 pos, s64 fstart, int flen, s16 *fader)
311 s64 relpos = pos - fstart;
312 if (relpos <= -nsamp || relpos >= flen)
322 while (nsamp > 0 && rel < flen)
324 sig[0] = (sig[0] * fader[rel]) >> 15;
325 sig[1] = (sig[1] * fader[rel]) >> 15;
332 static int cooked_read(s16 *buf, s64 pos, int nsamp, int apply_pre, int apply_post)
334 nsamp = in_read(buf, pos, nsamp);
335 int presamp = prefade * rate;
336 int postsamp = postfade * rate;
338 apply_fader(buf, nsamp, pos, start_pos, presamp, prefader);
340 apply_fader(buf, nsamp, pos, end_pos-postsamp, postsamp, postfader);
344 static char *cuename;
346 static int cue_load(void)
350 FILE *f = fopen(cuename, "r");
353 if (fscanf(f, "%Ld%lf%Ld%lf", &start_pos, &prefade, &end_pos, &postfade) != 4)
354 die("CUE: Invalid syntax");
356 printf("CUE: Loaded\n");
363 static void cue_save(void)
367 FILE *f = fopen(cuename, "w");
369 die("CUE: Cannot write");
370 fprintf(f, "%Ld %g %Ld %g\n", start_pos, prefade, end_pos, postfade);
375 static void editor(void)
377 printf("Initializing ALSA\n");
379 snd_pcm_hw_params_t *apars;
381 #define ALSACALL(f,args) if ((err = f args) < 0) die(#f " failed: %s", snd_strerror(err))
382 ALSACALL(snd_pcm_open, (&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0));
383 ALSACALL(snd_pcm_hw_params_malloc, (&apars));
384 ALSACALL(snd_pcm_hw_params_any, (pcm, apars));
385 ALSACALL(snd_pcm_hw_params_set_access, (pcm, apars, SND_PCM_ACCESS_RW_INTERLEAVED));
386 ALSACALL(snd_pcm_hw_params_set_format, (pcm, apars, SND_PCM_FORMAT_S16_LE));
387 unsigned int xrate = rate;
389 ALSACALL(snd_pcm_hw_params_set_rate_near, (pcm, apars, &xrate, &dir));
391 printf("WARNING: Rate set to %d instead of %d\n", xrate, rate);
392 ALSACALL(snd_pcm_hw_params_set_channels, (pcm, apars, 2));
393 ALSACALL(snd_pcm_hw_params, (pcm, apars));
394 snd_pcm_hw_params_free(apars);
395 ALSACALL(snd_pcm_prepare, (pcm));
400 #define CLAMP(x) (((x) < 0) ? 0 : ((x) >= total_samples) ? total_samples-1 : (x))
432 if (mode == M_START || mode == M_PRE)
438 else if (mode == M_END || mode == M_POST)
441 go = CLAMP(end_pos - lback);
454 fst = 1. / (16 >> (key - '0'));
458 fst = 1 << (key - '4');
464 start_pos = CLAMP(start_pos - step);
467 else if (mode == M_POST)
469 end_pos = CLAMP(end_pos - step);
470 go = CLAMP(end_pos - lback);
473 go = CLAMP(pos - step);
478 start_pos = CLAMP(start_pos + step);
481 else if (mode == M_POST)
483 end_pos = CLAMP(end_pos + step);
484 go = CLAMP(end_pos - lback);
487 go = CLAMP(pos + step);
496 else if (mode == M_POST)
498 go = CLAMP(end_pos - lback);
504 case 0x7027e: // Home
510 go = CLAMP(total_samples - lback);
512 case 0x5027e: // PgUp
514 go = CLAMP(pos - 60*rate);
516 case 0x6027e: // PgUp
518 go = CLAMP(pos + 60*rate);
520 case 0x2027e: // Insert
523 case 0x3027e: // Delete
525 go = end_pos - lback;
533 go = CLAMP(end_pos - lback);
542 if (mode == M_PRE || mode == M_POST)
544 double *f = (mode == M_PRE ? &prefade : &postfade);
550 *f = MIN(*f + fst, 10);
552 *f = MAX(*f - fst, 0);
557 go = CLAMP(end_pos - lback);
567 printf("KEY <%x>\n", key);
573 printf("%3d:%02d.%05d [%s %3d:%02d.%05d/%g -> %s %3d:%02d.%05d\\%g] step=%g%s\e[K\r",
575 (mode == M_START) ? "START" : (mode == M_PRE) ? "START>" : "start", TRIPLE(start_pos), prefade,
576 (mode == M_END) ? "END" : (mode == M_POST) ? ">END" : "end", TRIPLE(end_pos), postfade,
578 (silence < 0) ? " [STOP]" : "");
581 s64 end = (mode == M_POST) ? end_pos : total_samples;
583 if (pos >= end || silence)
589 nsamp = MIN(nsamp, silence);
596 nsamp = sizeof(buf)/4;
597 if (pos + nsamp > end)
599 nsamp = cooked_read(buf, pos, nsamp, (mode == M_PRE), (mode == M_POST));
603 int err = snd_pcm_writei(pcm, buf, nsamp);
606 puts("[xrun detected]");
607 err = snd_pcm_prepare(pcm);
609 die("xrun recovery failed: error %d", err);
612 die("snd_pcm_writei failed: error %d", err);
622 static int nchildren;
624 static int add_filter(int fd, char **args)
639 execvp(args[0], args);
640 die("execvp(%s) failed: %m", args[0]);
645 printf("FILTER: Forked pid %d for %s\n", pid, args[0]);
652 static int orig_stdout;
654 static void render(char *name)
658 if (!strcmp(name, "-"))
665 sfix = strrchr(name, '.') ? : "";
666 fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
668 die("Unable to create %s: %m", name);
670 if (!strcmp(sfix, ".WAV"))
671 printf("RENDER: WAV output without sample rate conversion\n");
672 else if (!strcmp(sfix, ".wav"))
674 printf("RENDER: WAV output\n");
677 printf("RENDER: Adding resample filter\n");
678 char *f[] = { "sox", "-twav", "-", "-r44100", "-twav", "-", "vol", "0.9", "resample", NULL };
679 fd = add_filter(fd, f);
683 die("Unknown output file suffix");
685 s64 outlen = end_pos - start_pos;
688 /* GRRRR! libsndfile is unable to write WAV files to pipes! */
693 .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16,
697 SNDFILE *sf = sf_open_fd(fd, SFM_WRITE, &si, 0);
699 die("Output sf_open_fd() failed: %s", sf_strerror(NULL));
701 FILE *of = fdopen(fd, "w");
702 void wt(char *x) { fwrite(x, 4, 1, of); }
703 void wr(unsigned int x) { fwrite(&x, sizeof(x), 1, of); }
705 wr(8 + 0x10 + 8 + 4*outlen);
709 wr(0x00020001); // 2 channels, not compressed
712 wr(0x00100004); // 16-bit
721 printf("RENDER: Generating %d:%02d.%05d of output\n", TRIPLE(outlen));
724 int n = sizeof(buf) / 4;
725 if (end_pos - pos < n)
729 n = cooked_read(buf, pos, n, 1, 1);
733 if (sf_writef_short(sf, buf, n) != n)
735 if ((int)fwrite(buf, 4, n, of) != n)
737 die("Short write, oops!");
738 printf("RENDER: %3d:%02d.%05d\r", TRIPLE(outpos));
753 printf("wait(): %m\n");
760 printf("!!! pid %d failed with exit code %d\n", p, WEXITSTATUS(st));
762 printf("FILTER: pid %d finished OK\n", p);
765 printf("!!! pid %d failed with status %x\n", p, st);
768 printf("RENDER: Rendering successfully completed.\n");
771 int main(int argc, char **argv)
773 if (argc < 2 || argc > 4)
774 die("Usage: vorbiscut <infile> [<cuefile> [<outfile>|-]]");
778 orig_stdout = dup(1);
785 int cueok = cue_load();
790 printf("!!!!! Cue sheet not present, rendering with defaults !!!!!\n");