8 #include <vorbis/vorbisfile.h>
9 #include <alsa/asoundlib.h>
12 static void __attribute__((noreturn)) die(char *msg, ...)
16 vfprintf(stderr, msg, args);
21 typedef long long s64;
23 #define MIN(a,b) ((a)<(b) ? (a) : (b))
24 #define MAX(a,b) ((a)>(b) ? (a) : (b))
25 #define TRIPLE(pos) (int)(((pos)/rate)/60), (int)(((pos)/rate)%60), (int)((pos)%rate)
27 static struct termios tios, tios_old;
29 static void key_init(void)
31 if (tcgetattr(0, &tios_old) < 0)
32 die("tcgetattr failed: %m");
34 tios.c_iflag = IGNBRK;
38 if (tcsetattr(0, 0, &tios) < 0)
39 die("tcsetattr failed: %m");
40 fcntl(0, F_SETFL, O_NONBLOCK);
43 static void key_cleanup(void)
45 tcsetattr(0, 0, &tios_old);
48 static int key_get(void)
51 static int esc_state, esc_num;
55 int e = read(0, keybuf, 1);
78 if (key >= '0' && key <= '9')
79 esc_num = 10*esc_num + key - '0';
83 return (esc_num << 16) + 0x200 + key;
91 enum { IN_WAV, IN_OGG } inmode;
92 static OggVorbis_File vf;
94 static unsigned int rate;
95 static char *find_title = "Toulky ceskou minulosti";
96 static s64 total_samples = 0;
97 static s64 start_pos = -1;
98 static s64 end_pos = -1;
99 double prefade = 1, postfade = 1;
101 static void scan_streams(void)
103 int nstr = ov_streams(&vf);
104 printf("OGG: Scanning %d logical streams:\n", nstr);
106 die("No streams found");
107 for (int i=0; i<nstr; i++)
110 vi = ov_info(&vf, i);
112 die("ov_info failed");
113 if (vi->channels != 2)
114 die("Stream %d has %d channels, which is not supported", i, vi->channels);
115 if ((unsigned int) vi->rate != rate)
118 die("Stream %d has sample rate %d, while the previous had %d", i, vi->rate, rate);
124 vc = ov_comment(&vf, i);
126 die("ov_comment failed");
129 for (int j=0; j<vc->comments; j++)
130 if (vc->comment_lengths[j] > 6 && !strncasecmp(vc->user_comments[j], "title=", 6))
132 int l = vc->comment_lengths[j] - 6;
133 memcpy(title, vc->user_comments[j]+6, l);
137 strcpy(title, "<none>");
139 s64 samples = ov_pcm_total(&vf, i);
140 int sec = (samples + rate - 1) / rate;
141 printf(" %d: `%s' (%d:%02d, %d bits/sec) @%Ld\n", i, title, sec/60, sec%60, (int)vi->bitrate_nominal, total_samples);
143 if (find_title && strstr(title, find_title))
146 start_pos = total_samples;
147 else if (end_pos != total_samples)
148 printf("WARNING: Gap encountered!\n");
149 end_pos = total_samples + samples;
152 total_samples += samples;
154 if (ov_pcm_total(&vf, -1) != total_samples)
155 die("ov_pcm_total mismatch");
160 printf("WARNING: Title not found, marking whole file");
162 end_pos = total_samples;
166 static void in_open(char *name)
168 infile = fopen(name, "r");
170 die("Cannot open %s: %m", name);
173 if (fread(s, 1, 4, infile) != 4)
174 die("Input file too short");
176 if (!memcmp(s, "RIFF", 4))
178 puts("INPUT: WAV file detected");
181 else if (!memcmp(s, "OggS", 4))
183 puts("INPUT: OGG file detected");
186 else if (!memcmp(s, "HTTP", 4))
188 puts("INPUT: HTTP header detected, expecting OGG inside");
192 die("Unable to identify input format");
194 if (inmode == IN_WAV)
197 bzero(&si, sizeof(si));
198 lseek(fileno(infile), 0, SEEK_SET);
199 sndf = sf_open_fd(fileno(infile), O_RDONLY, &si, 0);
201 die("sf_open_fd() failed: %s", sf_strerror(NULL));
202 total_samples = si.frames;
203 rate = si.samplerate;
204 if (si.channels != 2)
205 die("Got %d channels instead of 2", si.channels);
206 if (si.sections != 1)
207 die("Found %d sections, what does it mean?", si.sections);
208 printf("WAV: format id=%08x\n", si.format);
210 end_pos = total_samples;
214 int err = ov_open(infile, &vf, NULL, 0);
216 die("ov_open: error %d", err);
217 if (!ov_seekable(&vf))
218 die("Input is not seekable, how come?");
222 printf("INPUT: length %3d:%02d.%05d, %Ld samples at rate %d\n", TRIPLE(total_samples), total_samples, rate);
225 static void in_goto(s64 go)
227 if (inmode == IN_OGG)
228 ov_pcm_seek(&vf, go);
230 sf_seek(sndf, go, SEEK_SET);
233 static int in_read(s16 *buf, s64 pos, int nsamp)
235 if (inmode == IN_OGG)
237 if (ov_pcm_tell(&vf) != pos)
239 printf("!!! CONFUSED POSITION\n");
240 ov_pcm_seek(&vf, pos);
241 if (ov_pcm_tell(&vf) != pos)
242 printf(">>> unable to correct :(\n");
247 int e = ov_read(&vf, (char*)buf, 4*nsamp, 0, 2, 1, &bp);
249 printf("!!! HOLE DETECTED\n");
250 else if (e == OV_EBADLINK)
251 printf("!!! BAD LINK\n");
253 die("ov_read returned %d bytes, which means non-integer number of samples. Huh.", e);
255 die("ov_read returned %d. Huh!", e);
256 else if (e/4 <= nsamp)
259 die("ov_read returned %d samples, although we wanted %d", e/4, nsamp);
264 int e = sf_readf_short(sndf, buf, nsamp);
266 printf("!!!! sf_readf_short mismatch: %d != %d\n", e, nsamp);
271 static void in_close(void)
273 if (inmode == IN_OGG)
279 static s16 *prefader, *postfader;
281 static s16 *calc_fader(int len, int rev)
285 s16 *x = malloc(2*len);
286 for (int i=0; i<len; i++)
287 x[rev ? len-1-i : i] = (s64)i*32767/len;
291 static void recalc_faders(void)
293 // printf("FADERS: set to %g pre, %g post\n", prefade, postfade);
295 prefader = calc_fader(prefade*rate, 0);
297 postfader = calc_fader(postfade*rate, 1);
300 static void apply_fader(s16 *sig, int nsamp, s64 pos, s64 fstart, int flen, s16 *fader)
302 s64 relpos = pos - fstart;
303 if (relpos <= -nsamp || relpos >= flen)
313 while (nsamp > 0 && rel < flen)
315 sig[0] = (sig[0] * fader[rel]) >> 15;
316 sig[1] = (sig[1] * fader[rel]) >> 15;
323 static int cooked_read(s16 *buf, s64 pos, int nsamp, int apply_pre, int apply_post)
325 nsamp = in_read(buf, pos, nsamp);
326 int presamp = prefade * rate;
327 int postsamp = postfade * rate;
329 apply_fader(buf, nsamp, pos, start_pos, presamp, prefader);
331 apply_fader(buf, nsamp, pos, end_pos-postsamp, postsamp, postfader);
335 static char *cuename;
337 static int cue_load(void)
341 FILE *f = fopen(cuename, "r");
344 if (fscanf(f, "%Ld%lf%Ld%lf", &start_pos, &prefade, &end_pos, &postfade) != 4)
345 die("CUE: Invalid syntax");
347 printf("CUE: Loaded\n");
354 static void cue_save(void)
358 FILE *f = fopen(cuename, "w");
360 die("CUE: Cannot write");
361 fprintf(f, "%Ld %g %Ld %g\n", start_pos, prefade, end_pos, postfade);
366 static void editor(void)
368 printf("Initializing ALSA\n");
370 snd_pcm_hw_params_t *apars;
372 #define ALSACALL(f,args) if ((err = f args) < 0) die(#f " failed: %s", snd_strerror(err))
373 ALSACALL(snd_pcm_open, (&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0));
374 ALSACALL(snd_pcm_hw_params_malloc, (&apars));
375 ALSACALL(snd_pcm_hw_params_any, (pcm, apars));
376 ALSACALL(snd_pcm_hw_params_set_access, (pcm, apars, SND_PCM_ACCESS_RW_INTERLEAVED));
377 ALSACALL(snd_pcm_hw_params_set_format, (pcm, apars, SND_PCM_FORMAT_S16_LE));
378 unsigned int xrate = rate;
380 ALSACALL(snd_pcm_hw_params_set_rate_near, (pcm, apars, &xrate, &dir));
382 printf("WARNING: Rate set to %d instead of %d\n", xrate, rate);
383 ALSACALL(snd_pcm_hw_params_set_channels, (pcm, apars, 2));
384 ALSACALL(snd_pcm_hw_params, (pcm, apars));
385 snd_pcm_hw_params_free(apars);
386 ALSACALL(snd_pcm_prepare, (pcm));
391 #define CLAMP(x) (((x) < 0) ? 0 : ((x) >= total_samples) ? total_samples-1 : (x))
423 if (mode == M_START || mode == M_PRE)
429 else if (mode == M_END || mode == M_POST)
432 go = CLAMP(end_pos - lback);
445 fst = 1. / (16 >> (key - '0'));
449 fst = 1 << (key - '4');
455 start_pos = CLAMP(start_pos - step);
458 else if (mode == M_POST)
460 end_pos = CLAMP(end_pos - step);
461 go = CLAMP(end_pos - lback);
464 go = CLAMP(pos - step);
469 start_pos = CLAMP(start_pos + step);
472 else if (mode == M_POST)
474 end_pos = CLAMP(end_pos + step);
475 go = CLAMP(end_pos - lback);
478 go = CLAMP(pos + step);
487 else if (mode == M_POST)
489 go = CLAMP(end_pos - lback);
495 case 0x7027e: // Home
501 go = CLAMP(total_samples - lback);
503 case 0x5027e: // PgUp
505 go = CLAMP(pos - 60*rate);
507 case 0x6027e: // PgUp
509 go = CLAMP(pos + 60*rate);
511 case 0x2027e: // Insert
514 case 0x3027e: // Delete
516 go = end_pos - lback;
524 go = CLAMP(end_pos - lback);
533 if (mode == M_PRE || mode == M_POST)
535 double *f = (mode == M_PRE ? &prefade : &postfade);
541 *f = MIN(*f + fst, 10);
543 *f = MAX(*f - fst, 0);
548 go = CLAMP(end_pos - lback);
558 printf("KEY <%x>\n", key);
564 printf("%3d:%02d.%05d [%s %3d:%02d.%05d/%g -> %s %3d:%02d.%05d\\%g] step=%g%s\e[K\r",
566 (mode == M_START) ? "START" : (mode == M_PRE) ? "START>" : "start", TRIPLE(start_pos), prefade,
567 (mode == M_END) ? "END" : (mode == M_POST) ? ">END" : "end", TRIPLE(end_pos), postfade,
569 (silence < 0) ? " [STOP]" : "");
572 s64 end = (mode == M_POST) ? end_pos : total_samples;
574 if (pos >= end || silence)
580 nsamp = MIN(nsamp, silence);
587 nsamp = sizeof(buf)/4;
588 if (pos + nsamp > pos)
590 nsamp = cooked_read(buf, pos, nsamp, (mode == M_PRE), (mode == M_POST));
594 int err = snd_pcm_writei(pcm, buf, nsamp);
597 puts("[xrun detected]");
598 err = snd_pcm_prepare(pcm);
600 die("xrun recovery failed: error %d", err);
603 die("snd_pcm_writei failed: error %d", err);
613 static int nchildren;
615 static int add_filter(int fd, char **args)
630 execvp(args[0], args);
631 die("execvp(%s) failed: %m", args[0]);
636 printf("FILTER: Forked pid %d for %s\n", pid, args[0]);
643 static int orig_stdout;
645 static void render(char *name)
649 if (!strcmp(name, "-"))
656 sfix = strrchr(name, '.') ? : "";
657 fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
659 die("Unable to create %s: %m", name);
661 if (!strcmp(sfix, ".WAV"))
662 printf("RENDER: WAV output without sample rate conversion\n");
663 else if (!strcmp(sfix, ".wav"))
665 printf("RENDER: WAV output\n");
668 printf("RENDER: Adding resample filter\n");
669 char *f[] = { "sox", "-twav", "-", "-r44100", "-twav", "-", "vol", "0.9", "resample", NULL };
670 fd = add_filter(fd, f);
674 die("Unknown output file suffix");
676 s64 outlen = end_pos - start_pos;
679 /* GRRRR! libsndfile is unable to write WAV files to pipes! */
684 .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16,
688 SNDFILE *sf = sf_open_fd(fd, SFM_WRITE, &si, 0);
690 die("Output sf_open_fd() failed: %s", sf_strerror(NULL));
692 FILE *of = fdopen(fd, "w");
693 void wt(char *x) { fwrite(x, 4, 1, of); }
694 void wr(unsigned int x) { fwrite(&x, sizeof(x), 1, of); }
696 wr(8 + 0x10 + 8 + 4*outlen);
700 wr(0x00020001); // 2 channels, not compressed
703 wr(0x00100004); // 16-bit
712 printf("RENDER: Generating %d:%02d.%05d of output\n", TRIPLE(outlen));
715 int n = sizeof(buf) / 4;
716 if (pos + n > end_pos)
720 n = cooked_read(buf, pos, n, 1, 1);
724 if (sf_writef_short(sf, buf, n) != n)
726 if ((int)fwrite(buf, 4, n, of) != n)
728 die("Short write, oops!");
729 printf("RENDER: %3d:%02d.%05d\r", TRIPLE(outpos));
744 printf("wait(): %m\n");
751 printf("!!! pid %d failed with exit code %d\n", p, WEXITSTATUS(st));
753 printf("FILTER: pid %d finished OK\n", p);
756 printf("!!! pid %d failed with status %x\n", p, st);
759 printf("RENDER: Rendering successfully completed.\n");
762 int main(int argc, char **argv)
764 if (argc < 2 || argc > 4)
765 die("Usage: vorbiscut <infile> [<cuefile> [<outfile>|-]]");
769 orig_stdout = dup(1);
776 int cueok = cue_load();
781 printf("!!!!! Cue sheet not present, rendering with defaults !!!!!\n");