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