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