Fix gmsynth detection
[ardour.git] / libs / ardour / session_ltc.cc
1 /*
2   Copyright (C) 2012 Paul Davis
3   Written by Robin Gareus <robin@gareus.org>
4
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.
9
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.
14
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.
18
19 */
20
21 #include "temporal/time.h"
22
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/transport_master.h"
29 #include "ardour/transport_master_manager.h"
30
31 #include "pbd/i18n.h"
32
33 using namespace std;
34 using namespace ARDOUR;
35 using namespace PBD;
36 using namespace Timecode;
37
38 /* really verbose timing debug */
39 //#define LTC_GEN_FRAMEDBUG
40 //#define LTC_GEN_TXDBUG
41
42 #ifndef MAX
43 #define MAX(a,b) ( (a) > (b) ? (a) : (b) )
44 #endif
45 #ifndef MIN
46 #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
47 #endif
48
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.
55  *
56  * This filter is adaptive so that fast vari-speed signals
57  * will not be affected by it.
58  */
59 #define LTC_RISE_TIME(speed) MIN (100, MAX(40, (4000000 / ((speed==0)?1:speed) / engine().sample_rate())))
60
61 #define TV_STANDARD(tcf) \
62         (timecode_to_frames_per_second(tcf)==25.0 ? LTC_TV_625_50 : \
63          timecode_has_drop_frames(tcf)? LTC_TV_525_60 : LTC_TV_FILM_24)
64
65 void
66 Session::ltc_tx_initialize()
67 {
68         assert (!ltc_encoder && !ltc_enc_buf);
69         ltc_enc_tcformat = config.get_timecode_format();
70
71         ltc_tx_parse_offset();
72         DEBUG_TRACE (DEBUG::TXLTC, string_compose("LTC TX init sr: %1 fps: %2\n", nominal_sample_rate(), timecode_to_frames_per_second(ltc_enc_tcformat)));
73         ltc_encoder = ltc_encoder_create(nominal_sample_rate(),
74                         timecode_to_frames_per_second(ltc_enc_tcformat),
75                         TV_STANDARD(ltc_enc_tcformat), 0);
76
77         ltc_encoder_set_bufsize(ltc_encoder, nominal_sample_rate(), 23.0);
78         ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(1.0));
79
80         /* buffersize for 1 LTC sample: (1 + sample-rate / fps) bytes
81          * usually returned by ltc_encoder_get_buffersize(encoder)
82          *
83          * since the fps can change and A3's  min fps: 24000/1001 */
84         ltc_enc_buf = (ltcsnd_sample_t*) calloc((nominal_sample_rate() / 23), sizeof(ltcsnd_sample_t));
85         ltc_speed = 0;
86         ltc_prev_cycle = -1;
87         ltc_tx_reset();
88         ltc_tx_resync_latency();
89         Xrun.connect_same_thread (ltc_tx_connections, boost::bind (&Session::ltc_tx_reset, this));
90         engine().GraphReordered.connect_same_thread (ltc_tx_connections, boost::bind (&Session::ltc_tx_resync_latency, this));
91         restarting = false;
92 }
93
94 void
95 Session::ltc_tx_cleanup()
96 {
97         DEBUG_TRACE (DEBUG::TXLTC, "cleanup\n");
98         ltc_tx_connections.drop_connections ();
99         free(ltc_enc_buf);
100         ltc_enc_buf = NULL;
101         ltc_encoder_free(ltc_encoder);
102         ltc_encoder = NULL;
103 }
104
105 void
106 Session::ltc_tx_resync_latency()
107 {
108         DEBUG_TRACE (DEBUG::TXLTC, "resync latency\n");
109         if (!deletion_in_progress()) {
110                 boost::shared_ptr<Port> ltcport = ltc_output_port();
111                 if (ltcport) {
112                         ltcport->get_connected_latency_range(ltc_out_latency, true);
113                 }
114         }
115 }
116
117 void
118 Session::ltc_tx_reset()
119 {
120         DEBUG_TRACE (DEBUG::TXLTC, "reset\n");
121         assert (ltc_encoder);
122         ltc_enc_pos = -9999; // force re-start
123         ltc_buf_len = 0;
124         ltc_buf_off = 0;
125         ltc_enc_byte = 0;
126         ltc_enc_cnt = 0;
127
128         ltc_encoder_reset(ltc_encoder);
129 }
130
131 void
132 Session::ltc_tx_parse_offset() {
133         Timecode::Time offset_tc;
134         Timecode::parse_timecode_format(config.get_timecode_generator_offset(), offset_tc);
135         offset_tc.rate = timecode_frames_per_second();
136         offset_tc.drop = timecode_drop_frames();
137         timecode_to_sample(offset_tc, ltc_timecode_offset, false, false);
138         ltc_timecode_negative_offset = !offset_tc.negative;
139         ltc_prev_cycle = -1;
140 }
141
142 void
143 Session::ltc_tx_recalculate_position()
144 {
145         SMPTETimecode enctc;
146         Timecode::Time a3tc;
147         ltc_encoder_get_timecode(ltc_encoder, &enctc);
148
149         a3tc.hours   = enctc.hours;
150         a3tc.minutes = enctc.mins;
151         a3tc.seconds = enctc.secs;
152         a3tc.frames  = enctc.frame;
153         a3tc.rate = timecode_to_frames_per_second(ltc_enc_tcformat);
154         a3tc.drop = timecode_has_drop_frames(ltc_enc_tcformat);
155
156         Timecode::timecode_to_sample (a3tc, ltc_enc_pos, true, false,
157                 (double)sample_rate(),
158                 config.get_subframes_per_frame(),
159                 ltc_timecode_negative_offset, ltc_timecode_offset
160                 );
161         restarting = false;
162 }
163
164 void
165 Session::ltc_tx_send_time_code_for_cycle (samplepos_t start_sample, samplepos_t end_sample,
166                                           double target_speed, double current_speed,
167                                           pframes_t nframes)
168 {
169         assert (nframes > 0);
170
171         Sample *out;
172         pframes_t txf = 0;
173         boost::shared_ptr<Port> ltcport = ltc_output_port();
174
175         if (!ltcport) {
176                 assert (deletion_in_progress ());
177                 return;
178         }
179
180         /* marks buffer as not written */
181         Buffer& buf (ltcport->get_buffer (nframes));
182
183         if (!ltc_encoder || !ltc_enc_buf) {
184                 return;
185         }
186
187         SyncSource sync_src = TransportMasterManager::instance().current()->type();
188         if (engine().freewheeling() || !Config->get_send_ltc()
189             /* TODO
190              * decide which time-sources we can generated LTC from.
191              * Internal, JACK or sample-synced slaves should be fine.
192              * talk to oofus.
193              *
194              || (config.get_external_sync() && sync_src == LTC)
195              || (config.get_external_sync() && sync_src == MTC)
196             */
197              ||(config.get_external_sync() && sync_src == MIDIClock)
198                 ) {
199                 return;
200         }
201
202         out = dynamic_cast<AudioBuffer*>(&buf)->data ();
203
204         /* range from libltc (38..218) || - 128.0  -> (-90..90) */
205         const float ltcvol = Config->get_ltc_output_volume()/(90.0); // pow(10, db/20.0)/(90.0);
206
207         DEBUG_TRACE (DEBUG::TXLTC, string_compose("LTC TX %1 to %2 / %3 | lat: %4\n", start_sample, end_sample, nframes, ltc_out_latency.max));
208
209         /* all systems go. Now here's the plan:
210          *
211          *  1) check if fps has changed
212          *  2) check direction of encoding, calc speed, re-sample existing buffer
213          *  3) calculate sample and byte to send aligned to jack-period size
214          *  4) check if it's the sample/byte that is already in the queue
215          *  5) if (4) mismatch, re-calculate offset of LTC sample relative to period size
216          *  6) actual LTC audio output
217          *  6a) send remaining part of already queued sample; break on nframes
218          *  6b) encode new LTC-sample byte
219          *  6c) goto 6a
220          *  7) done
221          */
222
223         // (1) check fps
224         TimecodeFormat cur_timecode = config.get_timecode_format();
225         if (cur_timecode != ltc_enc_tcformat) {
226                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("1: TC format mismatch - reinit sr: %1 fps: %2\n", nominal_sample_rate(), timecode_to_frames_per_second(cur_timecode)));
227                 if (ltc_encoder_reinit(ltc_encoder, nominal_sample_rate(),
228                                         timecode_to_frames_per_second(cur_timecode),
229                                         TV_STANDARD(cur_timecode), 0
230                                         )) {
231                         PBD::error << _("LTC encoder: invalid framerate - LTC encoding is disabled for the remainder of this session.") << endmsg;
232                         ltc_tx_cleanup();
233                         return;
234                 }
235                 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(ltc_speed));
236                 ltc_enc_tcformat = cur_timecode;
237                 ltc_tx_parse_offset();
238                 ltc_tx_reset();
239         }
240
241         /* LTC is max. 30 fps */
242         if (timecode_to_frames_per_second(cur_timecode) > 30) {
243                 return;
244         }
245
246         // (2) speed & direction
247
248         /* speed 0 aka transport stopped is interpreted as rolling forward.
249          * keep repeating current sample
250          */
251 #define SIGNUM(a) ( (a) < 0 ? -1 : 1)
252         bool speed_changed = false;
253
254         /* port latency compensation:
255          * The _generated timecode_ is offset by the port-latency,
256          * therefore the offset depends on the direction of transport.
257          *
258          * latency is compensated by adding it to the timecode to
259          * be generated. e.g. if the signal will reach the output in
260          * N samples time from now, generate the timecode for (now + N).
261          *
262          * sample-sync is achieved by further calculating the difference
263          * between the timecode and the session-transport and offsetting the
264          * buffer.
265          *
266          * The timecode is generated directly in the Session process callback
267          * using _transport_sample (which is the audible frame at the
268          * output).
269          */
270         samplepos_t cycle_start_sample;
271
272         if (current_speed < 0) {
273                 cycle_start_sample = (start_sample + ltc_out_latency.max);
274         } else if (current_speed > 0) {
275                 cycle_start_sample = (start_sample - ltc_out_latency.max);
276         } else {
277                 /* There is no need to compensate for latency when not rolling
278                  * rather send the accurate NOW timecode
279                  * (LTC encoder compenates latency by sending earlier timecode)
280                  */
281                 cycle_start_sample = start_sample;
282         }
283
284         /* LTC TV standard offset */
285         if (current_speed != 0) {
286                 /* ditto - send "NOW" if not rolling */
287                 cycle_start_sample -= ltc_frame_alignment(samples_per_timecode_frame(), TV_STANDARD(cur_timecode));
288         }
289
290         /* cycle-start may become negative due to latency compensation */
291         if (cycle_start_sample < 0) { cycle_start_sample = 0; }
292
293         double new_ltc_speed = (double)(labs(end_sample - start_sample) * SIGNUM(current_speed)) / (double)nframes;
294         if (nominal_sample_rate() != sample_rate()) {
295                 new_ltc_speed *= (double)nominal_sample_rate() / (double)sample_rate();
296         }
297
298         if (SIGNUM(new_ltc_speed) != SIGNUM (ltc_speed)) {
299                 DEBUG_TRACE (DEBUG::TXLTC, "transport changed direction\n");
300                 ltc_tx_reset();
301         }
302
303         if (ltc_speed != new_ltc_speed
304                         /* but only once if, current_speed changes to 0. In that case
305                          * new_ltc_speed is > 0 because (end_sample - start_sample) == jack-period for no-roll
306                          * but ltc_speed will still be 0
307                          */
308                         && (current_speed != 0 || ltc_speed != current_speed)
309                         ) {
310                 /* check ./libs/ardour/interpolation.cc  CubicInterpolation::interpolate
311                  * if target_speed != current_speed we should interpolate, too.
312                  *
313                  * However, currency in A3 target_speed == current_speed for each process cycle
314                  * (except for the sign and if target_speed > 8.0).
315                  * Besides, above speed calculation uses the difference (end_sample - start_sample).
316                  * end_sample is calculated from 'samples_moved' which includes the interpolation.
317                  * so we're good.
318                  */
319                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: speed change old: %1 cur: %2 tgt: %3 ctd: %4\n", ltc_speed, current_speed, target_speed, fabs(current_speed) - target_speed, new_ltc_speed));
320                 speed_changed = true;
321                 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(new_ltc_speed));
322         }
323
324         if (end_sample == start_sample || fabs(current_speed) < 0.1 ) {
325                 DEBUG_TRACE (DEBUG::TXLTC, "transport is not rolling or absolute-speed < 0.1\n");
326                 /* keep repeating current sample
327                  *
328                  * an LTC generator must be able to continue generating LTC when Ardours transport is in stop
329                  * some machines do odd things if LTC goes away:
330                  * e.g. a tape based machine (video or audio), some think they have gone into park if LTC goes away,
331                  * so unspool the tape from the playhead. That might be inconvenient.
332                  * If LTC keeps arriving they remain in a stop position with the tape on the playhead.
333                  */
334                 new_ltc_speed = 0;
335                 if (!Config->get_ltc_send_continuously()) {
336                         ltc_speed = new_ltc_speed;
337                         return;
338                 }
339                 if (start_sample != ltc_prev_cycle) {
340                         DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: no-roll seek from %1 to %2 (%3)\n", ltc_prev_cycle, start_sample, cycle_start_sample));
341                         ltc_tx_reset();
342                 }
343         }
344
345         if (fabs(new_ltc_speed) > 10.0) {
346                 DEBUG_TRACE (DEBUG::TXLTC, "speed is out of bounds.\n");
347                 ltc_tx_reset();
348                 return;
349         }
350
351         if (ltc_speed == 0 && new_ltc_speed != 0) {
352                 DEBUG_TRACE (DEBUG::TXLTC, "transport started rolling - reset\n");
353                 ltc_tx_reset();
354         }
355
356         /* the timecode duration corresponding to the samples that are still
357          * in the buffer. Here, the speed of previous cycle is used to calculate
358          * the alignment at the beginning of this cycle later.
359          */
360         double poff = (ltc_buf_len - ltc_buf_off) * ltc_speed;
361
362         if (speed_changed && new_ltc_speed != 0) {
363                 /* we need to re-sample the existing buffer.
364                  * "make space for the en-coder to catch up to the new speed"
365                  *
366                  * since the LTC signal is a rectangular waveform we can simply squeeze it
367                  * by removing samples or duplicating samples /here and there/.
368                  *
369                  * There may be a more elegant way to do this, in fact one could
370                  * simply re-render the buffer using ltc_encoder_encode_byte()
371                  * but that'd require some timecode offset buffer magic,
372                  * which is left for later..
373                  */
374
375                 double oldbuflen = (double)(ltc_buf_len - ltc_buf_off);
376                 double newbuflen = (double)(ltc_buf_len - ltc_buf_off) * fabs(ltc_speed / new_ltc_speed);
377
378                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: bufOld %1 bufNew %2 | diff %3\n",
379                                         (ltc_buf_len - ltc_buf_off), newbuflen, newbuflen - oldbuflen
380                                         ));
381
382                 double bufrspdiff = rint(newbuflen - oldbuflen);
383
384                 if (abs(bufrspdiff) > newbuflen || abs(bufrspdiff) > oldbuflen) {
385                         DEBUG_TRACE (DEBUG::TXLTC, "resampling buffer would destroy information.\n");
386                         ltc_tx_reset();
387                         poff = 0;
388                 } else if (bufrspdiff != 0 && newbuflen > oldbuflen) {
389                         int incnt = 0;
390                         double samples_to_insert = ceil(newbuflen - oldbuflen);
391                         double avg_distance = newbuflen / samples_to_insert;
392                         DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: resample buffer insert: %1\n", samples_to_insert));
393
394                         for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
395                                 const int ro = rp - ltc_buf_off;
396                                 if (ro < (incnt*avg_distance)) continue;
397                                 const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
398                                 const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
399                                 if (v1 != v2 && ro < ((incnt+1)*avg_distance)) continue;
400                                 memmove(&ltc_enc_buf[rp+1], &ltc_enc_buf[rp], ltc_buf_len-rp);
401                                 incnt++;
402                                 ltc_buf_len++;
403                         }
404                 } else if (bufrspdiff != 0 && newbuflen < oldbuflen) {
405                         double samples_to_remove = ceil(oldbuflen - newbuflen);
406                         DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: resample buffer - remove: %1\n", samples_to_remove));
407                         if (oldbuflen <= samples_to_remove) {
408                                 ltc_buf_off = ltc_buf_len= 0;
409                         } else {
410                                 double avg_distance = newbuflen / samples_to_remove;
411                                 int rmcnt = 0;
412                                 for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
413                                         const int ro = rp - ltc_buf_off;
414                                         if (ro < (rmcnt*avg_distance)) continue;
415                                         const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
416                                         const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
417                                         if (v1 != v2 && ro < ((rmcnt+1)*avg_distance)) continue;
418                                         memmove(&ltc_enc_buf[rp], &ltc_enc_buf[rp+1], ltc_buf_len-rp-1);
419                                         ltc_buf_len--;
420                                         rmcnt++;
421                                 }
422                         }
423                 }
424         }
425
426         ltc_prev_cycle = start_sample;
427         ltc_speed = new_ltc_speed;
428         DEBUG_TRACE (DEBUG::TXLTC, string_compose("2: transport speed %1.\n", ltc_speed));
429
430         // (3) bit/sample alignment
431         Timecode::Time tc_start;
432         samplepos_t tc_sample_start;
433
434         /* calc timecode frame from current position - round down to nearest timecode */
435         Timecode::sample_to_timecode(cycle_start_sample, tc_start, true, false,
436                         timecode_frames_per_second(),
437                         timecode_drop_frames(),
438                         (double)sample_rate(),
439                         config.get_subframes_per_frame(),
440                         ltc_timecode_negative_offset, ltc_timecode_offset
441                         );
442
443         /* convert timecode back to sample-position */
444         Timecode::timecode_to_sample (tc_start, tc_sample_start, true, false,
445                 (double)sample_rate(),
446                 config.get_subframes_per_frame(),
447                 ltc_timecode_negative_offset, ltc_timecode_offset
448                 );
449
450         /* difference between current sample and TC sample in samples */
451         sampleoffset_t soff = cycle_start_sample - tc_sample_start;
452         if (current_speed == 0) {
453                 soff = 0;
454         }
455         DEBUG_TRACE (DEBUG::TXLTC, string_compose("3: A3cycle: %1 = A3tc: %2 +off: %3\n",
456                                 cycle_start_sample, tc_sample_start, soff));
457
458
459         // (4) check if alignment matches
460         const double fptcf = samples_per_timecode_frame();
461
462         /* maximum difference of bit alignment in audio-samples.
463          *
464          * if transport and LTC generator differs more than this, the LTC
465          * generator will be re-initialized
466          *
467          * due to rounding error and variations in LTC-bit duration depending
468          * on the speed, it can be off by +- ltc_speed audio-samples.
469          * When the playback speed changes, it can actually reach +- 2 * ltc_speed
470          * in the cycle _after_ the speed changed. The average delta however is 0.
471          */
472         double maxdiff;
473
474         if (transport_master_is_external()) {
475                 maxdiff = transport_master()->resolution();
476         } else {
477                 maxdiff = ceil(fabs(ltc_speed))*2.0;
478                 if (nominal_sample_rate() != sample_rate()) {
479                         maxdiff *= 3.0;
480                 }
481                 if (ltc_enc_tcformat == Timecode::timecode_23976 || ltc_enc_tcformat == Timecode::timecode_24976) {
482                         maxdiff *= 15.0;
483                 }
484         }
485
486         DEBUG_TRACE (DEBUG::TXLTC, string_compose("4: enc: %1 + %2 - %3 || buf-bytes: %4 enc-byte: %5\n",
487                                 ltc_enc_pos, ltc_enc_cnt, poff, (ltc_buf_len - ltc_buf_off), poff, ltc_enc_byte));
488
489         DEBUG_TRACE (DEBUG::TXLTC, string_compose("4: enc-pos: %1  | d: %2\n",
490                                 ltc_enc_pos + ltc_enc_cnt - poff,
491                                 rint(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_sample
492                                 ));
493
494         const samplecnt_t wrap24h = 86400. * sample_rate();
495         if (ltc_enc_pos < 0
496                         || (ltc_speed != 0 && fabs(fmod(ceil(ltc_enc_pos + ltc_enc_cnt - poff), wrap24h) - (cycle_start_sample % wrap24h)) > maxdiff)
497                         ) {
498
499                 // (5) re-align
500                 ltc_tx_reset();
501
502                 /* set sample to encode */
503                 SMPTETimecode tc;
504                 tc.hours = tc_start.hours % 24;
505                 tc.mins = tc_start.minutes;
506                 tc.secs = tc_start.seconds;
507                 tc.frame = tc_start.frames;
508                 ltc_encoder_set_timecode(ltc_encoder, &tc);
509
510                 /* workaround for libltc recognizing 29.97 and 30000/1001 as drop-sample TC.
511                  * In A3 30000/1001 or 30 fps can be drop-sample.
512                  */
513                 LTCFrame ltcframe;
514                 ltc_encoder_get_frame(ltc_encoder, &ltcframe);
515                 ltcframe.dfbit = timecode_has_drop_frames(cur_timecode)?1:0;
516                 ltc_encoder_set_frame(ltc_encoder, &ltcframe);
517
518
519                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("4: now: %1 trs: %2 toff %3\n", cycle_start_sample, tc_sample_start, soff));
520
521                 int32_t cyc_off;
522                 if (soff < 0 || soff >= fptcf) {
523                         /* session framerate change between (2) and now */
524                         ltc_tx_reset();
525                         return;
526                 }
527
528                 if (ltc_speed < 0 ) {
529                         /* calculate the byte that starts at or after the current position */
530                         ltc_enc_byte = floor((10.0 * soff) / (fptcf));
531                         ltc_enc_cnt = ltc_enc_byte * fptcf / 10.0;
532
533                         /* calculate difference between the current position and the byte to send */
534                         cyc_off = soff- ceil(ltc_enc_cnt);
535
536                 } else {
537                         /* calculate the byte that starts at or after the current position */
538                         ltc_enc_byte = ceil((10.0 * soff) / fptcf);
539                         ltc_enc_cnt = ltc_enc_byte * fptcf / 10.0;
540
541                         /* calculate difference between the current position and the byte to send */
542                         cyc_off = ceil(ltc_enc_cnt) - soff;
543
544                         if (ltc_enc_byte == 10) {
545                                 ltc_enc_byte = 0;
546                                 ltc_encoder_inc_timecode(ltc_encoder);
547                         }
548                 }
549
550                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("5 restart encoder: soff %1 byte %2 cycoff %3\n",
551                                         soff, ltc_enc_byte, cyc_off));
552
553                 if ( (ltc_speed < 0 && ltc_enc_byte !=9 ) || (ltc_speed >= 0 && ltc_enc_byte !=0 ) ) {
554                         restarting = true;
555                 }
556
557                 if (cyc_off >= 0 && cyc_off <= (int32_t) nframes) {
558                         /* offset in this cycle */
559                         txf= rint(cyc_off / fabs(ltc_speed));
560                         memset(out, 0, cyc_off * sizeof(Sample));
561                 } else {
562                         /* resync next cycle */
563                         memset(out, 0, nframes * sizeof(Sample));
564                         return;
565                 }
566
567                 ltc_enc_pos = tc_sample_start % wrap24h;
568
569                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("5 restart @ %1 + %2 - %3 |  byte %4\n",
570                                         ltc_enc_pos, ltc_enc_cnt, cyc_off, ltc_enc_byte));
571         }
572         else if (ltc_speed != 0 && (fptcf / ltc_speed / 80) > 3 ) {
573                 /* reduce (low freq) jitter.
574                  * The granularity of the LTC encoder speed is 1 byte =
575                  * (samples-per-timecode-sample / 10) audio-samples.
576                  * Thus, tiny speed changes [as produced by some transport masters]
577                  * may not have any effect in the cycle when they occur,
578                  * but they will add up over time.
579                  *
580                  * This is a linear approx to compensate for this jitter
581                  * and prempt re-sync when the drift builds up.
582                  *
583                  * However, for very fast speeds - when 1 LTC bit is
584                  * <= 3 audio-sample - adjusting speed may lead to
585                  * invalid samples.
586                  *
587                  * To do better than this, resampling (or a rewrite of the
588                  * encoder) is required.
589                  */
590                 ltc_speed -= fmod(((ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_sample), wrap24h) / engine().sample_rate();
591         }
592
593
594         // (6) encode and output
595         while (1) {
596 #ifdef LTC_GEN_TXDBUG
597                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("6.1 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
598 #endif
599                 // (6a) send remaining buffer
600                 while ((ltc_buf_off < ltc_buf_len) && (txf < nframes)) {
601                         const float v1 = ltc_enc_buf[ltc_buf_off++] - 128.0;
602                         const Sample val = (Sample) (v1*ltcvol);
603                         out[txf++] = val;
604                 }
605 #ifdef LTC_GEN_TXDBUG
606                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("6.2 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
607 #endif
608
609                 if (txf >= nframes) {
610                         DEBUG_TRACE (DEBUG::TXLTC, string_compose("7 enc: %1 [ %2 / %3 ] byte: %4 spd %5 fpp %6 || nf: %7\n",
611                                                 ltc_enc_pos, ltc_buf_off, ltc_buf_len, ltc_enc_byte, ltc_speed, nframes, txf));
612                         break;
613                 }
614
615                 ltc_buf_len = 0;
616                 ltc_buf_off = 0;
617
618                 // (6b) encode LTC, bump timecode
619
620                 if (ltc_speed < 0) {
621                         ltc_enc_byte = (ltc_enc_byte + 9)%10;
622                         if (ltc_enc_byte == 9) {
623                                 ltc_encoder_dec_timecode(ltc_encoder);
624                                 ltc_tx_recalculate_position();
625                                 ltc_enc_cnt = fptcf;
626                         }
627                 }
628
629                 int enc_samples;
630
631                 if (restarting) {
632                         /* write zero bytes -- don't touch encoder until we're at a sample-boundary
633                          * otherwise the biphase polarity may be inverted.
634                          */
635                         enc_samples = fptcf / 10.0;
636                         memset(&ltc_enc_buf[ltc_buf_len], 127, enc_samples * sizeof(ltcsnd_sample_t));
637                 } else {
638                         if (ltc_encoder_encode_byte(ltc_encoder, ltc_enc_byte, (ltc_speed==0)?1.0:(1.0/ltc_speed))) {
639                                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("6.3 encoder error byte %1\n", ltc_enc_byte));
640                                 ltc_encoder_buffer_flush(ltc_encoder);
641                                 ltc_tx_reset();
642                                 return;
643                         }
644                         enc_samples = ltc_encoder_get_buffer(ltc_encoder, &(ltc_enc_buf[ltc_buf_len]));
645                 }
646
647 #ifdef LTC_GEN_FRAMEDBUG
648                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("6.3 encoded %1 bytes for LTC-byte %2 at spd %3\n", enc_samples, ltc_enc_byte, ltc_speed));
649 #endif
650                 if (enc_samples <=0) {
651                         DEBUG_TRACE (DEBUG::TXLTC, "6.3 encoder empty buffer.\n");
652                         ltc_encoder_buffer_flush(ltc_encoder);
653                         ltc_tx_reset();
654                         return;
655                 }
656
657                 ltc_buf_len += enc_samples;
658                 if (ltc_speed < 0)
659                         ltc_enc_cnt -= fptcf/10.0;
660                 else
661                         ltc_enc_cnt += fptcf/10.0;
662
663                 if (ltc_speed >= 0) {
664                         ltc_enc_byte = (ltc_enc_byte + 1)%10;
665                         if (ltc_enc_byte == 0 && ltc_speed != 0) {
666                                 ltc_encoder_inc_timecode(ltc_encoder);
667 #if 0 /* force fixed parity -- scope debug */
668                                 LTCFrame f;
669                                 ltc_encoder_get_frame(ltc_encoder, &f);
670                                 f.biphase_mark_phase_correction=0;
671                                 ltc_encoder_set_frame(ltc_encoder, &f);
672 #endif
673                                 ltc_tx_recalculate_position();
674                                 ltc_enc_cnt = 0;
675                         } else if (ltc_enc_byte == 0) {
676                                 ltc_enc_cnt = 0;
677                                 restarting=false;
678                         }
679                 }
680 #ifdef LTC_GEN_FRAMEDBUG
681                 DEBUG_TRACE (DEBUG::TXLTC, string_compose("6.4 enc-pos: %1 + %2 [ %4 / %5 ] spd %6\n", ltc_enc_pos, ltc_enc_cnt, ltc_buf_off, ltc_buf_len, ltc_speed));
682 #endif
683         }
684
685         dynamic_cast<AudioBuffer*>(&buf)->set_written (true);
686         return;
687 }