Replace manual option handling by use of glib
[lcid-xwax.git] / timecoder.c
blob45f90c657602706993d637390b5cd3857233343f
1 /*
2 * Copyright (C) 2008 Mark Hills <mark@pogo.org.uk>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * version 2, as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License version 2 for more details.
13 * You should have received a copy of the GNU General Public License
14 * version 2 along with this program; if not, write to the Free
15 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
16 * MA 02110-1301, USA.
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
25 #include "timecoder.h"
27 #define ZERO_THRESHOLD 128
28 #define SIGNAL_THRESHOLD 256
30 #define ZERO_AVG (TIMECODER_RATE / 1024)
31 #define SIGNAL_AVG (TIMECODER_RATE / 256)
33 #define MAX_BITS 32 /* bits in an int */
35 #define REF_PEAKS_AVG 48 /* in wave cycles */
37 /* The number of correct bits which come in before the timecode
38 * is declared valid. Set this too low, and risk the record skipping around
39 * (often to blank areas of track) during scratching */
41 #define VALID_BITS 24
43 #define MONITOR_DECAY_EVERY 512 /* in samples */
45 #define SQ(x) ((x)*(x))
47 #define DEFAULT_TIMECODE 0
49 static guint timecode = DEFAULT_TIMECODE;
51 /* Timecode definitions */
54 #define POLARITY_NEGATIVE 0
55 #define POLARITY_POSITIVE 1
57 struct timecode_def_t {
58 char *name, *desc;
59 int bits, /* number of bits in string */
60 resolution, /* wave cycles per second */
61 tap[MAX_BITS], ntaps, /* LFSR taps */
62 polarity; /* cycle begins POLARITY_POSITIVE or POLARITY_NEGATIVE */
63 unsigned int seed, /* LFSR value at timecode zero */
64 length, /* in cycles */
65 safe; /* last 'safe' timecode number (for auto disconnect) */
66 signed int *lookup; /* pointer to built lookup table */
69 struct timecode_def_t timecode_def[] = {
71 name: "serato_2a",
72 desc: "Serato 2nd Ed., side A",
73 resolution: 1000,
74 polarity: POLARITY_POSITIVE,
75 bits: 20,
76 seed: 0x59017,
77 tap: {2, 5, 6, 7, 8, 13, 14, 16, 17},
78 ntaps: 9,
79 length: 712000,
80 safe: 707000,
81 lookup: NULL
84 name: "serato_2b",
85 desc: "Serato 2nd Ed., side B",
86 seed: 0x8f3c6,
87 resolution: 1000,
88 polarity: POLARITY_POSITIVE,
89 bits: 20,
90 tap: {3, 4, 6, 7, 12, 13, 14, 15, 18}, /* reverse of side A */
91 ntaps: 9,
92 length: 922000,
93 safe: 917000,
94 lookup: NULL
97 name: "serato_cd",
98 desc: "Serato CD",
99 resolution: 1000,
100 polarity: POLARITY_POSITIVE,
101 bits: 20,
102 seed: 0x84c0c,
103 tap: {2, 4, 6, 8, 10, 11, 14, 16, 17},
104 ntaps: 9,
105 length: 940000,
106 safe: 930000,
107 lookup: NULL
110 name: "traktor_a",
111 desc: "Traktor Scratch, side A",
112 resolution: 2000,
113 polarity: POLARITY_POSITIVE,
114 bits: 23,
115 seed: 0x134503,
116 tap: {6, 12, 18},
117 ntaps: 3,
118 length: 1500000,
119 safe: 1480000,
120 lookup: NULL
123 name: "traktor_b",
124 desc: "Traktor Scratch, side B",
125 resolution: 2000,
126 polarity: POLARITY_POSITIVE,
127 bits: 23,
128 seed: 0x32066c,
129 tap: {6, 12, 18},
130 ntaps: 3,
131 length: 2110000,
132 safe: 2090000,
133 lookup: NULL
136 name: NULL
141 struct timecode_def_t *def;
143 static gboolean parse_timecode(const gchar *option_name, const gchar *value, gpointer data, GError **error)
145 for(guint index = 0; ; index++)
147 if(timecode_def[index].name == NULL)
148 break;
150 if(g_ascii_strcasecmp(timecode_def[index].name, value) == 0)
152 timecode = index;
153 return TRUE;
157 *error = g_error_new(157, G_OPTION_ERROR_BAD_VALUE, "Timecode definition '%s' is not known.", value);
158 return FALSE;
161 gchar* get_timecode_names()
163 gchar* names = timecode_def[0].name;
164 gchar* temp = NULL;
166 for(guint index = 1; ; index++)
168 if(timecode_def[index].name == NULL)
169 break;
171 temp = g_strjoin(", ", names, timecode_def[index].name, NULL);
172 names = temp;
173 temp = NULL;
176 return names;
179 static GOptionEntry timecodeOptions[] =
181 { "timecode", 't', 0, G_OPTION_ARG_CALLBACK, &parse_timecode, NULL, NULL},
182 { NULL }
185 GOptionGroup* get_timecode_option_group()
187 GOptionGroup* group = g_option_group_new
189 "timecode",
190 "Timecode options",
191 "Show timecode help options",
192 NULL,
193 NULL
196 if(timecodeOptions[0].description == NULL)
197 timecodeOptions[0].description = g_strdup_printf("Name of timecode to use (available: %s)", get_timecode_names());
199 if(timecodeOptions[0].arg_description == NULL)
200 timecodeOptions[0].arg_description = timecode_def[DEFAULT_TIMECODE].name;
202 g_option_group_add_entries(group, timecodeOptions);
203 return group;
207 /* Linear Feeback Shift Register in the forward direction. New values
208 * are generated at the least-significant bit. */
210 static inline int lfsr(unsigned int code)
212 unsigned int r;
213 char s, n;
215 r = code & 1;
217 for(n = 0; n < def->ntaps; n++) {
218 s = *(def->tap + n);
219 r += (code & (1 << s)) >> s;
222 return r & 0x1;
226 /* Linear Feeback Shift Register in the reverse direction. New values
227 * are generated at the most-significant bit. */
229 static inline int lfsr_rev(unsigned int code)
231 unsigned int r;
232 char s, n;
234 r = (code & (1 << (def->bits - 1))) >> (def->bits - 1);
236 for(n = 0; n < def->ntaps; n++) {
237 s = *(def->tap + n) - 1;
238 r += (code & (1 << s)) >> s;
241 return r & 0x1;
245 /* Setup globally, for a chosen timecode definition */
247 int timecoder_build_lookup() {
248 unsigned int n, current;
250 def = &timecode_def[0];
252 int timecodeCount = timecode;
253 while(--timecodeCount > 0) {
254 def++;
257 fprintf(stderr, "Allocating %d slots (%zuKb) for %d bit timecode (%s)\n",
258 2 << def->bits, (2 << def->bits) * sizeof(unsigned int) / 1024,
259 def->bits, def->desc);
261 def->lookup = malloc((2 << def->bits) * sizeof(unsigned int));
262 if(!def->lookup) {
263 perror("malloc");
264 return 0;
267 for(n = 0; n < ((unsigned int)2 << def->bits); n++)
268 def->lookup[n] = -1;
270 current = def->seed;
272 for(n = 0; n < def->length; n++) {
273 if(def->lookup[current] != -1) {
274 fprintf(stderr, "Timecode has wrapped; finishing here.\n");
275 return -1;
278 def->lookup[current] = n;
279 current = (current >> 1) + (lfsr(current) << (def->bits - 1));
282 return 0;
286 /* Free the timecoder lookup table when it is no longer needed */
288 void timecoder_free_lookup(void) {
289 free(def->lookup);
293 static void init_channel(struct timecoder_channel_t *ch)
295 ch->positive = 0;
296 ch->zero = 0;
297 ch->crossing_ticker = 0;
301 /* Initialise a timecode decoder */
303 void timecoder_init(struct timecoder_t *tc)
305 int c;
307 tc->forwards = 1;
309 tc->half_peak = 0;
310 tc->wave_peak = 0;
311 tc->ref_level = -1;
312 tc->signal_level = 0;
314 init_channel(&tc->mono);
315 for(c = 0; c < TIMECODER_CHANNELS; c++)
316 init_channel(&tc->channel[c]);
318 tc->crossings = 0;
319 tc->pitch_ticker = 0;
321 tc->bitstream = 0;
322 tc->timecode = 0;
323 tc->valid_counter = 0;
324 tc->timecode_ticker = 0;
326 tc->mon = NULL;
327 tc->log_fd = -1;
331 /* Clear a timecode decoder */
333 void timecoder_clear(struct timecoder_t *tc)
335 timecoder_monitor_clear(tc);
339 /* The monitor (otherwise known as 'scope' in the interface) is the
340 * display of the incoming audio. Initialise one for the given
341 * timecoder */
343 void timecoder_monitor_init(struct timecoder_t *tc, int size, int scale)
345 tc->mon_size = size;
346 tc->mon_scale = scale;
347 tc->mon = malloc(SQ(tc->mon_size));
348 memset(tc->mon, 0, SQ(tc->mon_size));
349 tc->mon_counter = 0;
353 /* Clear the monitor on the given timecoder */
355 void timecoder_monitor_clear(struct timecoder_t *tc)
357 if(tc->mon) {
358 free(tc->mon);
359 tc->mon = NULL;
364 static int detect_zero_crossing(int v, struct timecoder_channel_t *ch)
366 int swapped;
368 ch->crossing_ticker++;
370 swapped = 0;
371 if(v >= ch->zero + ZERO_THRESHOLD && !ch->positive) {
372 swapped = 1;
373 ch->positive = 1;
374 ch->crossing_ticker = 0;
375 } else if(v < ch->zero - ZERO_THRESHOLD && ch->positive) {
376 swapped = 1;
377 ch->positive = 0;
378 ch->crossing_ticker = 0;
381 ch->zero = (ch->zero * (ZERO_AVG - 1) + v) / ZERO_AVG;
383 return swapped;
387 /* Submit and decode a block of PCM audio data to the timecoder */
389 int timecoder_submit(struct timecoder_t *tc, signed short *pcm, int samples)
391 int b, l, /* bitstream and timecode bits */
392 s, c,
393 x, y, p, /* monitor coordinates */
394 offset,
395 swapped,
396 monitor_centre;
397 signed int v, w; /* pcm sample value, sum of two short channels */
398 unsigned int mask;
400 b = 0;
401 l = 0;
403 mask = ((1 << def->bits) - 1);
404 monitor_centre = tc->mon_size / 2;
406 offset = 0;
408 for(s = 0; s < samples; s++) {
410 for(c = 0; c < TIMECODER_CHANNELS; c++)
411 detect_zero_crossing(pcm[offset + c], &tc->channel[c]);
413 /* Read from the mono channel */
415 v = pcm[offset] + pcm[offset + 1];
416 swapped = detect_zero_crossing(v, &tc->mono);
418 /* If a sign change in the (zero corrected) audio has
419 * happened, log the peak information */
421 if(swapped) {
423 /* Work out whether half way through a cycle we are
424 * looking for the wave to be positive or negative */
426 if(tc->mono.positive == (def->polarity ^ tc->forwards)) {
428 /* Entering the second half of a wave cycle */
430 tc->half_peak = tc->wave_peak;
432 } else {
434 /* Completed a full wave cycle, so time to analyse the
435 * level and work out whether it's a 1 or 0 */
437 b = tc->wave_peak + tc->half_peak > tc->ref_level;
439 /* Log binary timecode */
441 if(tc->log_fd != -1)
442 write(tc->log_fd, b ? "1" : "0", 1);
444 /* Add it to the bitstream, and work out what we were
445 * expecting (timecode). */
447 /* tc->bitstream is always in the order it is
448 * physically placed on the vinyl, regardless of the
449 * direction. */
451 if(tc->forwards) {
452 l = lfsr(tc->timecode);
454 tc->bitstream = (tc->bitstream >> 1)
455 + (b << (def->bits - 1));
457 tc->timecode = (tc->timecode >> 1)
458 + (l << (def->bits - 1));
460 } else {
461 l = lfsr_rev(tc->timecode);
463 tc->bitstream = ((tc->bitstream << 1) & mask) + b;
464 tc->timecode = ((tc->timecode << 1) & mask) + l;
467 if(b == l) {
468 tc->valid_counter++;
469 } else {
470 tc->timecode = tc->bitstream;
471 tc->valid_counter = 0;
474 /* Take note of the last time we read a valid timecode */
476 tc->timecode_ticker = 0;
478 /* Adjust the reference level based on the peaks seen
479 * in this cycle */
481 if(tc->ref_level == -1)
482 tc->ref_level = tc->half_peak + tc->wave_peak;
483 else {
484 tc->ref_level = (tc->ref_level * (REF_PEAKS_AVG - 1)
485 + tc->half_peak + tc->wave_peak)
486 / REF_PEAKS_AVG;
491 /* Calculate the immediate direction from phase difference,
492 * based on the last channel to cross zero */
494 if(tc->channel[0].crossing_ticker > tc->channel[1].crossing_ticker)
495 tc->forwards = 1;
496 else
497 tc->forwards = 0;
499 if(tc->forwards)
500 tc->crossings++;
501 else
502 tc->crossings--;
504 tc->pitch_ticker += tc->crossing_ticker;
505 tc->crossing_ticker = 0;
506 tc->wave_peak = 0;
508 } /* swapped */
510 tc->crossing_ticker++;
511 tc->timecode_ticker++;
513 /* Find the zero-normalised sample of the peak value from
514 * the input */
516 w = abs(v - tc->mono.zero);
517 if(w > tc->wave_peak)
518 tc->wave_peak = w;
520 /* Take a rolling average of zero and signal level */
522 tc->signal_level = (tc->signal_level * (SIGNAL_AVG - 1) + w)
523 / SIGNAL_AVG;
525 /* Update the monitor to add the incoming sample */
527 if(tc->mon) {
529 /* Decay the pixels already in the montior */
531 if(++tc->mon_counter % MONITOR_DECAY_EVERY == 0) {
532 for(p = 0; p < SQ(tc->mon_size); p++) {
533 if(tc->mon[p])
534 tc->mon[p] = tc->mon[p] * 7 / 8;
538 v = pcm[offset]; /* first channel */
539 w = pcm[offset + 1]; /* second channel */
541 x = monitor_centre + (v * tc->mon_size * tc->mon_scale >> 16);
542 y = monitor_centre + (w * tc->mon_size * tc->mon_scale >> 16);
544 /* Set the pixel value to white */
546 if(x > 0 && x < tc->mon_size && y > 0 && y < tc->mon_size)
547 tc->mon[y * tc->mon_size + x] = 0xff;
550 offset += TIMECODER_CHANNELS;
552 } /* for each sample */
554 /* Print debugging information */
556 #if 0
557 fprintf(stderr, "%+6d +/%4d -/%4d (%d)\t= %d (%d) %c %d"
558 "\t[crossings: %d %d]",
559 tc->mono.zero,
560 tc->half_peak,
561 tc->wave_peak,
562 tc->ref_level >> 1,
563 b, l, b == l ? ' ' : 'x',
564 tc->valid_counter,
565 tc->crossings,
566 tc->pitch_ticker);
568 if(tc->pitch_ticker) {
569 fprintf(stderr, " = %d",
570 TIMECODER_RATE * tc->crossings / tc->pitch_ticker);
573 fputc('\n', stderr);
574 #endif
576 return 0;
580 /* Return the timecode pitch, based on cycles of the sine wave. This
581 * function can only be called by one context, at it resets the state
582 * of the counter in the timecoder. */
584 int timecoder_get_pitch(struct timecoder_t *tc, float *pitch)
586 /* Let the caller know if there's no data to gather pitch from */
588 if(tc->crossings == 0)
589 return -1;
591 /* Value of tc->crossings may be negative in reverse */
593 *pitch = TIMECODER_RATE * (float)tc->crossings / tc->pitch_ticker
594 / (def->resolution * 2);
596 tc->crossings = 0;
597 tc->pitch_ticker = 0;
599 return 0;
603 /* Return the known position in the timecode, or -1 if not known. If
604 * two few bits have been error-checked, then this also counts as
605 * invalid. If 'when' is given, return the time, in input samples since
606 * this value was read. */
608 signed int timecoder_get_position(struct timecoder_t *tc, int *when)
610 signed int r;
612 if(tc->valid_counter > VALID_BITS) {
613 r = def->lookup[tc->bitstream];
615 if(r >= 0) {
616 if(when)
617 *when = tc->timecode_ticker;
618 return r;
622 return -1;
626 /* Return non-zero if there is any timecode signal available */
628 int timecoder_get_alive(struct timecoder_t *tc)
630 if(tc->signal_level < SIGNAL_THRESHOLD)
631 return 0;
633 return 1;
637 /* Return the last 'safe' timecode value on the record. Beyond this
638 * value, we probably want to ignore the timecode values, as we will
639 * hit the label of the record. */
641 unsigned int timecoder_get_safe(struct timecoder_t *tc)
643 return def->safe;
647 /* Return the resolution of the timecode. This is the number of bits
648 * per second, which corresponds to the frequency of the sine wave */
650 int timecoder_get_resolution(struct timecoder_t *tc)
652 return def->resolution;