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