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