2 Copyright (C) 2012 Paul Davis
3 Written by Robin Gareus <robin@gareus.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #include "timecode/time.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/audio_port.h"
25 #include "ardour/debug.h"
26 #include "ardour/io.h"
27 #include "ardour/session.h"
28 #include "ardour/slave.h"
33 using namespace ARDOUR;
36 using namespace Timecode;
38 /* really verbose timing debug */
39 //#define LTC_GEN_FRAMEDBUG
40 //#define LTC_GEN_TXDBUG
43 #define MAX(a,b) ( (a) > (b) ? (a) : (b) )
46 #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
49 /* LTC signal should have a rise time of 25 us +/- 5 us.
50 * yet with most sound-cards a square-wave of 1-2 sample
51 * introduces ringing and small oscillations.
52 * https://en.wikipedia.org/wiki/Gibbs_phenomenon
53 * A low-pass filter in libltc can reduce this at
54 * the cost of being slightly out of spec WRT to rise-time.
56 * This filter is adaptive so that fast vari-speed signals
57 * will not be affected by it.
59 #define LTC_RISE_TIME(speed) MIN (100, MAX(25, (4000000 / ((speed==0)?1:speed) / engine().frame_rate())))
62 Session::ltc_tx_initialize()
64 ltc_enc_tcformat = config.get_timecode_format();
66 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX init sr: %1 fps: %2\n", nominal_frame_rate(), timecode_to_frames_per_second(ltc_enc_tcformat)));
67 ltc_encoder = ltc_encoder_create(nominal_frame_rate(),
68 timecode_to_frames_per_second(ltc_enc_tcformat),
71 ltc_encoder_set_bufsize(ltc_encoder, nominal_frame_rate(), 23.0);
72 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(1.0));
74 /* buffersize for 1 LTC frame: (1 + sample-rate / fps) bytes
75 * usually returned by ltc_encoder_get_buffersize(encoder)
77 * since the fps can change and A3's min fps: 24000/1001 */
78 ltc_enc_buf = (ltcsnd_sample_t*) calloc((nominal_frame_rate() / 23), sizeof(ltcsnd_sample_t));
81 ltc_tx_resync_latency();
82 Xrun.connect_same_thread (*this, boost::bind (&Session::ltc_tx_reset, this));
83 engine().GraphReordered.connect_same_thread (*this, boost::bind (&Session::ltc_tx_resync_latency, this));
87 Session::ltc_tx_cleanup()
89 DEBUG_TRACE (DEBUG::LTC, "LTC TX cleanup\n");
90 if (ltc_enc_buf) free(ltc_enc_buf);
91 ltc_encoder_free(ltc_encoder);
96 Session::ltc_tx_resync_latency()
98 DEBUG_TRACE (DEBUG::LTC, "LTC TX resync latency\n");
99 if (!deletion_in_progress()) {
100 boost::shared_ptr<Port> ltcport = ltc_output_port();
102 ltcport->get_connected_latency_range(ltc_out_latency, true);
108 Session::ltc_tx_reset()
110 DEBUG_TRACE (DEBUG::LTC, "LTC TX reset\n");
111 ltc_enc_pos = -9999; // force re-start
119 Session::ltc_tx_recalculate_position()
123 ltc_encoder_get_timecode(ltc_encoder, &enctc);
125 a3tc.hours = enctc.hours;
126 a3tc.minutes = enctc.mins;
127 a3tc.seconds = enctc.secs;
128 a3tc.frames = enctc.frame;
129 a3tc.rate = timecode_to_frames_per_second(ltc_enc_tcformat);
130 a3tc.drop = timecode_has_drop_frames(ltc_enc_tcformat);
132 Timecode::timecode_to_sample (a3tc, ltc_enc_pos, true, false,
133 double(frame_rate()),
134 config.get_subframes_per_frame(),
135 config.get_timecode_offset_negative(), config.get_timecode_offset()
140 Session::ltc_tx_send_time_code_for_cycle (framepos_t start_frame, framepos_t end_frame,
141 double target_speed, double current_speed,
144 assert (nframes > 0);
148 boost::shared_ptr<Port> ltcport = ltc_output_port();
150 Buffer& buf (ltcport->get_buffer (nframes));
152 if (!ltc_encoder || !ltc_enc_buf) {
156 SyncSource sync_src = Config->get_sync_source();
157 if (engine().freewheeling() || !Config->get_send_ltc()
159 * decide which time-sources we can generated LTC from.
160 * Internal, JACK or sample-synced slaves should be fine.
163 || (config.get_external_sync() && sync_src == LTC)
164 || (config.get_external_sync() && sync_src == MTC)
166 ||(config.get_external_sync() && sync_src == MIDIClock)
171 out = dynamic_cast<AudioBuffer*>(&buf)->data ();
173 /* range from libltc (38..218) || - 128.0 -> (-90..90) */
174 const float ltcvol = Config->get_ltc_output_volume()/(90.0); // pow(10, db/20.0)/(90.0);
176 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX %1 to %2 / %3 | lat: %4\n", start_frame, end_frame, nframes, ltc_out_latency.max));
178 /* all systems go. Now here's the plan:
180 * 1) check if fps has changed
181 * 2) check direction of encoding, calc speed, re-sample existing buffer
182 * 3) calculate frame and byte to send aligned to jack-period size
183 * 4) check if it's the frame/byte that is already in the queue
184 * 5) if (4) mismatch, re-calculate offset of LTC frame relative to period size
185 * 6) actual LTC audio output
186 * 6a) send remaining part of already queued frame; break on nframes
187 * 6b) encode new LTC-frame byte
193 TimecodeFormat cur_timecode = config.get_timecode_format();
194 if (cur_timecode != ltc_enc_tcformat) {
195 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX1: TC format mismatch - reinit sr: %1 fps: %2\n", nominal_frame_rate(), timecode_to_frames_per_second(cur_timecode)));
196 if (ltc_encoder_reinit(ltc_encoder, nominal_frame_rate(), timecode_to_frames_per_second(cur_timecode), 0)) {
197 PBD::error << _("LTC encoder: invalid framerate - LTC encoding is disabled for the remainder of this session.") << endmsg;
201 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(ltc_speed));
202 ltc_enc_tcformat = cur_timecode;
206 /* LTC is max. 30 fps */
207 if (timecode_to_frames_per_second(cur_timecode) > 30) {
211 // (2) speed & direction
213 /* speed 0 aka transport stopped is interpreted as rolling forward.
214 * keep repeating current frame
216 #define SIGNUM(a) ( (a) < 0 ? -1 : 1)
217 bool speed_changed = false;
219 /* port latency compensation:
220 * The _generated timecode_ is offset by the port-latency,
221 * therefore the offset depends on the direction of transport.
223 framepos_t cycle_start_frame = (current_speed < 0) ? (start_frame - ltc_out_latency.max) : (start_frame + ltc_out_latency.max);
225 /* cycle-start may become negative due to latency compensation */
226 if (cycle_start_frame < 0) { cycle_start_frame = 0; }
228 double new_ltc_speed = (double)(labs(end_frame - start_frame) * SIGNUM(current_speed)) / (double)nframes;
229 if (nominal_frame_rate() != frame_rate()) {
230 new_ltc_speed *= (double)nominal_frame_rate() / (double)frame_rate();
233 if (SIGNUM(new_ltc_speed) != SIGNUM (ltc_speed)) {
234 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport changed direction\n");
238 if (ltc_speed != new_ltc_speed) {
239 /* check ./libs/ardour/interpolation.cc CubicInterpolation::interpolate
240 * if target_speed != current_speed we should interpolate, too.
242 * However, currency in A3 target_speed == current_speed for each process cycle
243 * (except for the sign and if target_speed > 8.0).
244 * Besides, above speed calculation uses the difference (end_frame - start_frame).
245 * end_frame is calculated from 'frames_moved' which includes the interpolation.
248 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: speed change old: %1 cur: %2 tgt: %3 ctd: %4\n", ltc_speed, current_speed, target_speed, fabs(current_speed) - target_speed));
249 speed_changed = true;
250 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(new_ltc_speed));
253 if (end_frame == start_frame || fabs(current_speed) < 0.1 ) {
254 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport is not rolling or absolute-speed < 0.1\n");
255 /* keep repeating current frame
257 * an LTC generator must be able to continue generating LTC when Ardours transport is in stop
258 * some machines do odd things if LTC goes away:
259 * e.g. a tape based machine (video or audio), some think they have gone into park if LTC goes away,
260 * so unspool the tape from the playhead. That might be inconvenient.
261 * If LTC keeps arriving they remain in a stop position with the tape on the playhead.
264 if (!Config->get_ltc_send_continuously()) {
265 ltc_speed = new_ltc_speed;
270 if (fabs(new_ltc_speed) > 10.0) {
271 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: speed is out of bounds.\n");
276 if (ltc_speed == 0 && new_ltc_speed != 0) {
277 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport started rolling - reset\n");
281 /* the timecode duration corresponding to the samples that are still
282 * in the buffer. Here, the speed of previous cycle is used to calculate
283 * the alignment at the beginning of this cycle later.
285 double poff = (ltc_buf_len - ltc_buf_off) * ltc_speed;
287 if (speed_changed && new_ltc_speed != 0) {
288 /* we need to re-sample the existing buffer.
289 * "make space for the en-coder to catch up to the new speed"
291 * since the LTC signal is a rectangular waveform we can simply squeeze it
292 * by removing samples or duplicating samples /here and there/.
294 * There may be a more elegant way to do this, in fact one could
295 * simply re-render the buffer using ltc_encoder_encode_byte()
296 * but that'd require some timecode offset buffer magic,
297 * which is left for later..
300 double oldbuflen = double(ltc_buf_len - ltc_buf_off);
301 double newbuflen = double(ltc_buf_len - ltc_buf_off) * fabs(ltc_speed / new_ltc_speed);
303 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: bufOld %1 bufNew %2 | diff %3\n",
304 (ltc_buf_len - ltc_buf_off), newbuflen, newbuflen - oldbuflen
307 double bufrspdiff = rint(newbuflen - oldbuflen);
309 if (abs(bufrspdiff) > newbuflen || abs(bufrspdiff) > oldbuflen) {
310 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: resampling buffer would destroy information.\n");
313 } else if (bufrspdiff != 0 && newbuflen > oldbuflen) {
315 double samples_to_insert = ceil(newbuflen - oldbuflen);
316 double avg_distance = newbuflen / samples_to_insert;
317 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer insert: %1\n", samples_to_insert));
319 for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
320 const int ro = rp - ltc_buf_off;
321 if (ro < (incnt*avg_distance)) continue;
322 const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
323 const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
324 if (v1 != v2 && ro < ((incnt+1)*avg_distance)) continue;
325 memmove(<c_enc_buf[rp+1], <c_enc_buf[rp], ltc_buf_len-rp);
329 } else if (bufrspdiff != 0 && newbuflen < oldbuflen) {
330 double samples_to_remove = ceil(oldbuflen - newbuflen);
331 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer - remove: %1\n", samples_to_remove));
332 if (oldbuflen <= samples_to_remove) {
333 ltc_buf_off = ltc_buf_len= 0;
335 double avg_distance = newbuflen / samples_to_remove;
337 for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
338 const int ro = rp - ltc_buf_off;
339 if (ro < (rmcnt*avg_distance)) continue;
340 const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
341 const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
342 if (v1 != v2 && ro < ((rmcnt+1)*avg_distance)) continue;
343 memmove(<c_enc_buf[rp], <c_enc_buf[rp+1], ltc_buf_len-rp-1);
351 ltc_speed = new_ltc_speed;
352 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: transport speed %1.\n", ltc_speed));
354 // (3) bit/sample alignment
355 Timecode::Time tc_start;
356 framepos_t tc_sample_start;
358 /* calc timecode frame from current position - round down to nearest timecode */
359 Timecode::sample_to_timecode(cycle_start_frame, tc_start, true, false,
360 timecode_frames_per_second(),
361 timecode_drop_frames(),
362 (double)frame_rate(),
363 config.get_subframes_per_frame(),
364 config.get_timecode_offset_negative(), config.get_timecode_offset()
367 /* convert timecode back to sample-position */
368 Timecode::timecode_to_sample (tc_start, tc_sample_start, true, false,
369 double(frame_rate()),
370 config.get_subframes_per_frame(),
371 config.get_timecode_offset_negative(), config.get_timecode_offset()
374 /* difference between current frame and TC frame in samples */
375 frameoffset_t soff = cycle_start_frame - tc_sample_start;
376 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX3: A3cycle: %1 = A3tc: %2 +off: %3\n",
377 cycle_start_frame, tc_sample_start, soff));
380 // (4) check if alignment matches
381 const double fptcf = frames_per_timecode_frame();
383 /* maximum difference of bit alignment in audio-samples.
385 * if transport and LTC generator differs more than this, the LTC
386 * generator will be re-initialized
388 * due to rounding error and variations in LTC-bit duration depending
389 * on the speed, it can be off by +- ltc_speed audio-samples.
390 * When the playback speed changes, it can actually reach +- 2 * ltc_speed
391 * in the cycle _after_ the speed changed. The average delta however is 0.
395 if (config.get_external_sync() && slave()) {
396 maxdiff = slave()->resolution();
398 maxdiff = ceil(fabs(ltc_speed))*2.0;
401 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc: %1 + %2 - %3 || buf-bytes: %4 enc-byte: %5\n",
402 ltc_enc_pos, ltc_enc_cnt, poff, (ltc_buf_len - ltc_buf_off), poff, ltc_enc_byte));
404 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc-pos: %1 | d: %2\n",
405 ltc_enc_pos + ltc_enc_cnt - poff,
406 rint(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame
410 || (ltc_speed != 0 && fabs(ceil(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame) > maxdiff)
416 /* set frame to encode */
418 tc.hours = tc_start.hours;
419 tc.mins = tc_start.minutes;
420 tc.secs = tc_start.seconds;
421 tc.frame = tc_start.frames;
422 ltc_encoder_set_timecode(ltc_encoder, &tc);
424 /* workaround for libltc recognizing 29.97 and 30000/1001 as drop-frame TC.
425 * In A3 30000/1001 or 30 fps can be drop-frame.
428 ltc_encoder_get_frame(ltc_encoder, <cframe);
429 ltcframe.dfbit = timecode_has_drop_frames(cur_timecode)?1:0;
430 ltc_encoder_set_frame(ltc_encoder, <cframe);
433 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: now: %1 trs: %2 toff %3\n", cycle_start_frame, tc_sample_start, soff));
436 if (soff < 0 || soff >= fptcf) {
437 /* session framerate change between (2) and now */
442 if (ltc_speed < 0 ) {
443 /* calculate the byte that starts at or after the current position */
444 ltc_enc_byte = floor((10.0 * soff) / (fptcf));
445 ltc_enc_cnt = double(ltc_enc_byte * fptcf / 10.0);
447 /* calculate difference between the current position and the byte to send */
448 cyc_off = soff- ceil(ltc_enc_cnt);
451 /* calculate the byte that starts at or after the current position */
452 ltc_enc_byte = ceil((10.0 * soff) / fptcf);
453 ltc_enc_cnt = double(ltc_enc_byte * fptcf / 10.0);
455 /* calculate difference between the current position and the byte to send */
456 cyc_off = ceil(ltc_enc_cnt) - soff;
458 if (ltc_enc_byte == 10) {
460 ltc_encoder_inc_timecode(ltc_encoder);
464 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart encoder: soff %1 byte %2 cycoff %3\n",
465 soff, ltc_enc_byte, cyc_off));
467 if (cyc_off > 0 && cyc_off <= nframes) {
468 /* offset in this cycle */
469 txf= rint(cyc_off / fabs(ltc_speed));
470 memset(out, 0, cyc_off * sizeof(Sample));
472 /* resync next cycle */
473 memset(out, 0, nframes * sizeof(Sample));
477 ltc_enc_pos = tc_sample_start;
479 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart @ %1 + %2 - %3 | byte %4\n",
480 ltc_enc_pos, ltc_enc_cnt, cyc_off, ltc_enc_byte));
482 #if 1 /* experimental sample bit alignment */
483 else if (ltc_speed != 0 && (fptcf / ltc_speed / 80) > 3 ) {
484 /* We may get away without a DLL if speed-changes are uniform enough and
485 * no oscillation takes place, the linear approx here should reduce the
486 * jitter sufficiently when generating LTC from another LTC source or
487 * JACK-transport or ardour internal clock.
489 * Note that the granularity of the LTC encoder speed is 1 byte =
490 * (frames-per-timecode-frame / 10) audio-samples.
492 * Thus, tiny speed changes won't have any effect and larger ones
493 * may lead to oscillations.
494 * To be better than that, resampling (or a rewrite of the encoder) is
497 ltc_speed -= ((ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame) / engine().frame_rate();
502 // (6) encode and output
504 #ifdef LTC_GEN_TXDBUG
505 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.1 @%1 [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
507 // (6a) send remaining buffer
508 while ((ltc_buf_off < ltc_buf_len) && (txf < nframes)) {
509 const float v1 = ltc_enc_buf[ltc_buf_off++] - 128.0;
510 const Sample val = (Sample) (v1*ltcvol);
513 #ifdef LTC_GEN_TXDBUG
514 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.2 @%1 [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
517 if (txf >= nframes) {
518 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX7 enc: %1 [ %2 / %3 ] byte: %4 spd %5 fpp %6 || nf: %7\n",
519 ltc_enc_pos, ltc_buf_off, ltc_buf_len, ltc_enc_byte, ltc_speed, nframes, txf));
526 // (6b) encode LTC, bump timecode
529 ltc_enc_byte = (ltc_enc_byte + 9)%10;
530 if (ltc_enc_byte == 9) {
531 ltc_encoder_dec_timecode(ltc_encoder);
532 ltc_tx_recalculate_position();
537 if (ltc_encoder_encode_byte(ltc_encoder, ltc_enc_byte, (ltc_speed==0)?1.0:(1.0/ltc_speed))) {
538 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.3 encoder error byte %1\n", ltc_enc_byte));
539 ltc_encoder_buffer_flush(ltc_encoder);
543 int enc_frames = ltc_encoder_get_buffer(ltc_encoder, &(ltc_enc_buf[ltc_buf_len]));
544 #ifdef LTC_GEN_FRAMEDBUG
545 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.3 encoded %1 bytes for LTC-byte %2 at spd %3\n", enc_frames, ltc_enc_byte, ltc_speed));
547 if (enc_frames <=0) {
548 DEBUG_TRACE (DEBUG::LTC, "LTC TX6.3 encoder empty buffer.\n");
549 ltc_encoder_buffer_flush(ltc_encoder);
554 ltc_buf_len += enc_frames;
556 ltc_enc_cnt -= fptcf/10.0;
558 ltc_enc_cnt += fptcf/10.0;
560 if (ltc_speed >= 0) {
561 ltc_enc_byte = (ltc_enc_byte + 1)%10;
562 if (ltc_enc_byte == 0 && ltc_speed != 0) {
563 ltc_encoder_inc_timecode(ltc_encoder);
564 #if 0 /* force fixed parity -- scope debug */
566 ltc_encoder_get_frame(ltc_encoder, &f);
567 f.biphase_mark_phase_correction=0;
568 ltc_encoder_set_frame(ltc_encoder, &f);
570 ltc_tx_recalculate_position();
572 } else if (ltc_enc_byte == 0) {
576 #ifdef LTC_GEN_FRAMEDBUG
577 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.4 enc-pos: %1 + %2 [ %4 / %5 ] spd %6\n", ltc_enc_pos, ltc_enc_cnt, ltc_buf_off, ltc_buf_len, ltc_speed));
581 dynamic_cast<AudioBuffer*>(&buf)->set_written (true);