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