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