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.
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,
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 */
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
{
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
[] = {
72 desc
: "Serato 2nd Ed., side A",
74 polarity
: POLARITY_POSITIVE
,
77 tap
: {2, 5, 6, 7, 8, 13, 14, 16, 17},
85 desc
: "Serato 2nd Ed., side B",
88 polarity
: POLARITY_POSITIVE
,
90 tap
: {3, 4, 6, 7, 12, 13, 14, 15, 18}, /* reverse of side A */
100 polarity
: POLARITY_POSITIVE
,
103 tap
: {2, 4, 6, 8, 10, 11, 14, 16, 17},
111 desc
: "Traktor Scratch, side A",
113 polarity
: POLARITY_POSITIVE
,
124 desc
: "Traktor Scratch, side B",
126 polarity
: POLARITY_POSITIVE
,
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
)
150 if(g_ascii_strcasecmp(timecode_def
[index
].name
, value
) == 0)
157 *error
= g_error_new(157, G_OPTION_ERROR_BAD_VALUE
, "Timecode definition '%s' is not known.", value
);
161 gchar
* get_timecode_names()
163 gchar
* names
= timecode_def
[0].name
;
166 for(guint index
= 1; ; index
++)
168 if(timecode_def
[index
].name
== NULL
)
171 temp
= g_strjoin(", ", names
, timecode_def
[index
].name
, NULL
);
179 static GOptionEntry timecodeOptions
[] =
181 { "timecode", 't', 0, G_OPTION_ARG_CALLBACK
, &parse_timecode
, NULL
, NULL
},
185 GOptionGroup
* get_timecode_option_group()
187 GOptionGroup
* group
= g_option_group_new
191 "Show timecode help options",
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
);
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
)
217 for(n
= 0; n
< def
->ntaps
; n
++) {
219 r
+= (code
& (1 << s
)) >> s
;
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
)
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
;
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) {
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));
267 for(n
= 0; n
< ((unsigned int)2 << def
->bits
); n
++)
272 for(n
= 0; n
< def
->length
; n
++) {
273 if(def
->lookup
[current
] != -1) {
274 fprintf(stderr
, "Timecode has wrapped; finishing here.\n");
278 def
->lookup
[current
] = n
;
279 current
= (current
>> 1) + (lfsr(current
) << (def
->bits
- 1));
286 /* Free the timecoder lookup table when it is no longer needed */
288 void timecoder_free_lookup(void) {
293 static void init_channel(struct timecoder_channel_t
*ch
)
297 ch
->crossing_ticker
= 0;
301 /* Initialise a timecode decoder */
303 void timecoder_init(struct timecoder_t
*tc
)
312 tc
->signal_level
= 0;
314 init_channel(&tc
->mono
);
315 for(c
= 0; c
< TIMECODER_CHANNELS
; c
++)
316 init_channel(&tc
->channel
[c
]);
319 tc
->pitch_ticker
= 0;
323 tc
->valid_counter
= 0;
324 tc
->timecode_ticker
= 0;
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
343 void timecoder_monitor_init(struct timecoder_t
*tc
, int size
, int scale
)
346 tc
->mon_scale
= scale
;
347 tc
->mon
= malloc(SQ(tc
->mon_size
));
348 memset(tc
->mon
, 0, SQ(tc
->mon_size
));
353 /* Clear the monitor on the given timecoder */
355 void timecoder_monitor_clear(struct timecoder_t
*tc
)
364 static int detect_zero_crossing(int v
, struct timecoder_channel_t
*ch
)
368 ch
->crossing_ticker
++;
371 if(v
>= ch
->zero
+ ZERO_THRESHOLD
&& !ch
->positive
) {
374 ch
->crossing_ticker
= 0;
375 } else if(v
< ch
->zero
- ZERO_THRESHOLD
&& ch
->positive
) {
378 ch
->crossing_ticker
= 0;
381 ch
->zero
= (ch
->zero
* (ZERO_AVG
- 1) + v
) / ZERO_AVG
;
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 */
393 x
, y
, p
, /* monitor coordinates */
397 signed int v
, w
; /* pcm sample value, sum of two short channels */
403 mask
= ((1 << def
->bits
) - 1);
404 monitor_centre
= tc
->mon_size
/ 2;
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 */
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
;
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 */
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
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));
461 l
= lfsr_rev(tc
->timecode
);
463 tc
->bitstream
= ((tc
->bitstream
<< 1) & mask
) + b
;
464 tc
->timecode
= ((tc
->timecode
<< 1) & mask
) + l
;
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
481 if(tc
->ref_level
== -1)
482 tc
->ref_level
= tc
->half_peak
+ tc
->wave_peak
;
484 tc
->ref_level
= (tc
->ref_level
* (REF_PEAKS_AVG
- 1)
485 + tc
->half_peak
+ tc
->wave_peak
)
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
)
504 tc
->pitch_ticker
+= tc
->crossing_ticker
;
505 tc
->crossing_ticker
= 0;
510 tc
->crossing_ticker
++;
511 tc
->timecode_ticker
++;
513 /* Find the zero-normalised sample of the peak value from
516 w
= abs(v
- tc
->mono
.zero
);
517 if(w
> tc
->wave_peak
)
520 /* Take a rolling average of zero and signal level */
522 tc
->signal_level
= (tc
->signal_level
* (SIGNAL_AVG
- 1) + w
)
525 /* Update the monitor to add the incoming sample */
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
++) {
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 */
557 fprintf(stderr
, "%+6d +/%4d -/%4d (%d)\t= %d (%d) %c %d"
558 "\t[crossings: %d %d]",
563 b
, l
, b
== l
? ' ' : 'x',
568 if(tc
->pitch_ticker
) {
569 fprintf(stderr
, " = %d",
570 TIMECODER_RATE
* tc
->crossings
/ tc
->pitch_ticker
);
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)
591 /* Value of tc->crossings may be negative in reverse */
593 *pitch
= TIMECODER_RATE
* (float)tc
->crossings
/ tc
->pitch_ticker
594 / (def
->resolution
* 2);
597 tc
->pitch_ticker
= 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
)
612 if(tc
->valid_counter
> VALID_BITS
) {
613 r
= def
->lookup
[tc
->bitstream
];
617 *when
= tc
->timecode_ticker
;
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
)
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
)
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
;