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;
158 printf("WARNING: Title not found, marking whole file");
160 end_pos = total_samples;
164 static void in_open(char *name)
166 infile = fopen(name, "r");
168 die("Cannot open %s: %m", name);
171 if (fread(s, 1, 4, infile) != 4)
172 die("Input file too short");
174 if (!memcmp(s, "RIFF", 4))
176 puts("INPUT: WAV file detected");
179 else if (!memcmp(s, "OggS", 4))
181 puts("INPUT: OGG file detected");
184 else if (!memcmp(s, "HTTP", 4))
186 puts("INPUT: HTTP header detected, expecting OGG inside");
190 die("Unable to identify input format");
192 if (inmode == IN_WAV)
195 bzero(&si, sizeof(si));
196 lseek(fileno(infile), 0, SEEK_SET);
197 sndf = sf_open_fd(fileno(infile), O_RDONLY, &si, 0);
199 die("sf_open_fd() failed: %s", sf_strerror(NULL));
200 total_samples = si.frames;
201 rate = si.samplerate;
202 if (si.channels != 2)
203 die("Got %d channels instead of 2", si.channels);
204 if (si.sections != 1)
205 die("Found %d sections, what does it mean?", si.sections);
206 printf("WAV: format id=%08x\n", si.format);
208 end_pos = total_samples;
212 int err = ov_open(infile, &vf, NULL, 0);
214 die("ov_open: error %d", err);
215 if (!ov_seekable(&vf))
216 die("Input is not seekable, how come?");
220 printf("INPUT: length %3d:%02d.%05d, %Ld samples at rate %d\n", TRIPLE(total_samples), total_samples, rate);
223 static void in_goto(s64 go)
225 if (inmode == IN_OGG)
226 ov_pcm_seek(&vf, go);
228 sf_seek(sndf, go, SEEK_SET);
231 static int in_read(s16 *buf, s64 pos, int nsamp)
233 if (inmode == IN_OGG)
235 if (ov_pcm_tell(&vf) != pos)
236 printf("!!! CONFUSED POSITION\n");
240 int e = ov_read(&vf, (char*)buf, 4*nsamp, 0, 2, 1, &bp);
242 printf("!!! HOLE DETECTED\n");
243 else if (e == OV_EBADLINK)
244 printf("!!! BAD LINK\n");
246 die("ov_read returned %d bytes, which means non-integer number of samples. Huh.", e);
247 else if (e/4 <= nsamp)
250 die("ov_read returned %d samples, although we wanted %d", e/4, nsamp);
255 int e = sf_readf_short(sndf, buf, nsamp);
257 printf("!!!! sf_readf_short mismatch: %d != %d\n", e, nsamp);
262 static void in_close(void)
264 if (inmode == IN_OGG)
270 static s16 *prefader, *postfader;
272 static s16 *calc_fader(int len, int rev)
276 s16 *x = malloc(2*len);
277 for (int i=0; i<len; i++)
278 x[rev ? len-1-i : i] = (s64)i*32767/len;
282 static void recalc_faders(void)
284 // printf("FADERS: set to %g pre, %g post\n", prefade, postfade);
286 prefader = calc_fader(prefade*rate, 0);
288 postfader = calc_fader(postfade*rate, 1);
291 static void apply_fader(s16 *sig, int nsamp, s64 pos, s64 fstart, int flen, s16 *fader)
293 s64 relpos = pos - fstart;
294 if (relpos <= -nsamp || relpos >= flen)
304 while (nsamp > 0 && rel < flen)
306 sig[0] = (sig[0] * fader[rel]) >> 15;
307 sig[1] = (sig[1] * fader[rel]) >> 15;
314 static int cooked_read(s16 *buf, s64 pos, int nsamp, int apply_pre, int apply_post)
316 nsamp = in_read(buf, pos, nsamp);
317 int presamp = prefade * rate;
318 int postsamp = postfade * rate;
320 apply_fader(buf, nsamp, pos, start_pos, presamp, prefader);
322 apply_fader(buf, nsamp, pos, end_pos-postsamp, postsamp, postfader);
326 static char *cuename;
328 static int cue_load(void)
332 FILE *f = fopen(cuename, "r");
335 if (fscanf(f, "%Ld%lf%Ld%lf", &start_pos, &prefade, &end_pos, &postfade) != 4)
336 die("CUE: Invalid syntax");
338 printf("CUE: Loaded\n");
345 static void cue_save(void)
349 FILE *f = fopen(cuename, "w");
351 die("CUE: Cannot write");
352 fprintf(f, "%Ld %g %Ld %g\n", start_pos, prefade, end_pos, postfade);
357 static void editor(void)
359 printf("Initializing ALSA\n");
361 snd_pcm_hw_params_t *apars;
363 #define ALSACALL(f,args) if ((err = f args) < 0) die(#f " failed: %s", snd_strerror(err))
364 ALSACALL(snd_pcm_open, (&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0));
365 ALSACALL(snd_pcm_hw_params_malloc, (&apars));
366 ALSACALL(snd_pcm_hw_params_any, (pcm, apars));
367 ALSACALL(snd_pcm_hw_params_set_access, (pcm, apars, SND_PCM_ACCESS_RW_INTERLEAVED));
368 ALSACALL(snd_pcm_hw_params_set_format, (pcm, apars, SND_PCM_FORMAT_S16_LE));
369 unsigned int xrate = rate;
371 ALSACALL(snd_pcm_hw_params_set_rate_near, (pcm, apars, &xrate, &dir));
373 printf("WARNING: Rate set to %d instead of %d\n", xrate, rate);
374 ALSACALL(snd_pcm_hw_params_set_channels, (pcm, apars, 2));
375 ALSACALL(snd_pcm_hw_params, (pcm, apars));
376 snd_pcm_hw_params_free(apars);
377 ALSACALL(snd_pcm_prepare, (pcm));
382 #define CLAMP(x) (((x) < 0) ? 0 : ((x) >= total_samples) ? total_samples-1 : (x))
414 if (mode == M_START || mode == M_PRE)
420 else if (mode == M_END || mode == M_POST)
423 go = CLAMP(end_pos - lback);
436 fst = 1. / (16 >> (key - '0'));
440 fst = 1 << (key - '4');
446 start_pos = CLAMP(start_pos - step);
449 else if (mode == M_POST)
451 end_pos = CLAMP(end_pos - step);
452 go = CLAMP(end_pos - lback);
455 go = CLAMP(pos - step);
460 start_pos = CLAMP(start_pos + step);
463 else if (mode == M_POST)
465 end_pos = CLAMP(end_pos + step);
466 go = CLAMP(end_pos - lback);
469 go = CLAMP(pos + step);
478 else if (mode == M_POST)
480 go = CLAMP(end_pos - lback);
486 case 0x7027e: // Home
492 go = CLAMP(total_samples - lback);
494 case 0x5027e: // PgUp
496 go = CLAMP(pos - 60*rate);
498 case 0x6027e: // PgUp
500 go = CLAMP(pos + 60*rate);
502 case 0x2027e: // Insert
505 case 0x3027e: // Delete
514 go = CLAMP(end_pos - lback);
523 if (mode == M_PRE || mode == M_POST)
525 double *f = (mode == M_PRE ? &prefade : &postfade);
531 *f = MIN(*f + fst, 10);
533 *f = MAX(*f - fst, 0);
538 go = CLAMP(end_pos - lback);
548 printf("KEY <%x>\n", key);
554 printf("%3d:%02d.%05d [%s %3d:%02d.%05d/%g -> %s %3d:%02d.%05d\\%g] step=%g%s\e[K\r",
556 (mode == M_START) ? "START" : (mode == M_PRE) ? "START>" : "start", TRIPLE(start_pos), prefade,
557 (mode == M_END) ? "END" : (mode == M_POST) ? ">END" : "end", TRIPLE(end_pos), postfade,
559 (silence < 0) ? " [STOP]" : "");
562 s64 end = (mode == M_POST) ? end_pos : total_samples;
564 if (pos >= end || silence)
570 nsamp = MIN(nsamp, silence);
577 nsamp = sizeof(buf)/4;
578 if (pos + nsamp > end_pos)
579 nsamp = end_pos - pos;
580 nsamp = cooked_read(buf, pos, nsamp, (mode == M_PRE), (mode == M_POST));
584 int err = snd_pcm_writei(pcm, buf, nsamp);
587 puts("[xrun detected]");
588 err = snd_pcm_prepare(pcm);
590 die("xrun recovery failed: error %d", err);
593 die("snd_pcm_writei failed: error %d", err);
603 static int nchildren;
605 static int add_filter(int fd, char **args)
620 execvp(args[0], args);
621 die("execvp(%s) failed: %m", args[0]);
626 printf("FILTER: Forked pid %d for %s\n", pid, args[0]);
633 static int orig_stdout;
635 static void render(char *name)
639 if (!strcmp(name, "-"))
646 sfix = strrchr(name, '.') ? : "";
647 fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
649 die("Unable to create %s: %m", name);
651 if (!strcmp(sfix, ".WAV"))
652 printf("RENDER: WAV output without sample rate conversion\n");
653 else if (!strcmp(sfix, ".wav"))
655 printf("RENDER: WAV output\n");
658 printf("RENDER: Adding resample filter\n");
659 char *f[] = { "sox", "-twav", "-", "-r44100", "-twav", "-", "vol", "0.9", "resample", NULL };
660 fd = add_filter(fd, f);
664 die("Unknown output file suffix");
666 s64 outlen = end_pos - start_pos;
669 /* GRRRR! libsndfile is unable to write WAV files to pipes! */
674 .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16,
678 SNDFILE *sf = sf_open_fd(fd, SFM_WRITE, &si, 0);
680 die("Output sf_open_fd() failed: %s", sf_strerror(NULL));
682 FILE *of = fdopen(fd, "w");
683 void wt(char *x) { fwrite(x, 4, 1, of); }
684 void wr(unsigned int x) { fwrite(&x, sizeof(x), 1, of); }
686 wr(8 + 0x10 + 8 + 4*outlen);
690 wr(0x00020001); // 2 channels, not compressed
693 wr(0x00100004); // 16-bit
702 printf("RENDER: Generating %d:%02d.%05d of output\n", TRIPLE(outlen));
705 int n = sizeof(buf) / 4;
706 if (pos + n > end_pos)
710 n = cooked_read(buf, pos, n, 1, 1);
714 if (sf_writef_short(sf, buf, n) != n)
716 if ((int)fwrite(buf, 4, n, of) != n)
718 die("Short write, oops!");
719 printf("RENDER: %3d:%02d.%05d\r", TRIPLE(outpos));
734 printf("wait(): %m\n");
741 printf("!!! pid %d failed with exit code %d\n", p, WEXITSTATUS(st));
743 printf("FILTER: pid %d finished OK\n", p);
746 printf("!!! pid %d failed with status %x\n", p, st);
749 printf("RENDER: Rendering successfully completed.\n");
752 int main(int argc, char **argv)
754 if (argc < 2 || argc > 4)
755 die("Usage: vorbiscut <infile> [<cuefile> [<outfile>|-]]");
759 orig_stdout = dup(1);
766 int cueok = cue_load();
771 printf("!!!!! Cue sheet not present, rendering with defaults !!!!!\n");