free buffer then set it to 0
[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().frame_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_tx_reset();
86         ltc_tx_resync_latency();
87         Xrun.connect_same_thread (*this, boost::bind (&Session::ltc_tx_reset, this));
88         engine().GraphReordered.connect_same_thread (*this, boost::bind (&Session::ltc_tx_resync_latency, this));
89         restarting = false;
90 }
91
92 void
93 Session::ltc_tx_cleanup()
94 {
95         DEBUG_TRACE (DEBUG::LTC, "LTC TX cleanup\n");
96         if (ltc_enc_buf) {
97                 free(ltc_enc_buf);
98                 ltc_enc_buf = 0;
99         }
100         ltc_encoder_free(ltc_encoder);
101         ltc_encoder = NULL;
102 }
103
104 void
105 Session::ltc_tx_resync_latency()
106 {
107         DEBUG_TRACE (DEBUG::LTC, "LTC TX resync latency\n");
108         if (!deletion_in_progress()) {
109                 boost::shared_ptr<Port> ltcport = ltc_output_port();
110                 if (ltcport) {
111                         ltcport->get_connected_latency_range(ltc_out_latency, true);
112                 }
113         }
114 }
115
116 void
117 Session::ltc_tx_reset()
118 {
119         DEBUG_TRACE (DEBUG::LTC, "LTC TX reset\n");
120         ltc_enc_pos = -9999; // force re-start
121         ltc_buf_len = 0;
122         ltc_buf_off = 0;
123         ltc_enc_byte = 0;
124         ltc_enc_cnt = 0;
125
126         ltc_encoder_reset(ltc_encoder);
127 }
128
129 void
130 Session::ltc_tx_parse_offset() {
131         Timecode::Time offset_tc;
132         Timecode::parse_timecode_format(config.get_timecode_generator_offset(), offset_tc);
133         offset_tc.rate = timecode_frames_per_second();
134         offset_tc.drop = timecode_drop_frames();
135         timecode_to_sample(offset_tc, ltc_timecode_offset, false, false);
136         ltc_timecode_negative_offset = !offset_tc.negative;
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 = (current_speed < 0) ? (start_frame - ltc_out_latency.max) : (start_frame + ltc_out_latency.max);
250
251         /* LTC TV standard offset */
252         cycle_start_frame -= ltc_frame_alignment(frames_per_timecode_frame(), TV_STANDARD(cur_timecode));
253
254         /* cycle-start may become negative due to latency compensation */
255         if (cycle_start_frame < 0) { cycle_start_frame = 0; }
256
257         double new_ltc_speed = (double)(labs(end_frame - start_frame) * SIGNUM(current_speed)) / (double)nframes;
258         if (nominal_frame_rate() != frame_rate()) {
259                 new_ltc_speed *= (double)nominal_frame_rate() / (double)frame_rate();
260         }
261
262         if (SIGNUM(new_ltc_speed) != SIGNUM (ltc_speed)) {
263                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport changed direction\n");
264                 ltc_tx_reset();
265         }
266
267         if (ltc_speed != new_ltc_speed) {
268                 /* check ./libs/ardour/interpolation.cc  CubicInterpolation::interpolate
269                  * if target_speed != current_speed we should interpolate, too.
270                  *
271                  * However, currency in A3 target_speed == current_speed for each process cycle
272                  * (except for the sign and if target_speed > 8.0).
273                  * Besides, above speed calculation uses the difference (end_frame - start_frame).
274                  * end_frame is calculated from 'frames_moved' which includes the interpolation.
275                  * so we're good.
276                  */
277                 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));
278                 speed_changed = true;
279                 ltc_encoder_set_filter(ltc_encoder, LTC_RISE_TIME(new_ltc_speed));
280         }
281
282         if (end_frame == start_frame || fabs(current_speed) < 0.1 ) {
283                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport is not rolling or absolute-speed < 0.1\n");
284                 /* keep repeating current frame
285                  *
286                  * an LTC generator must be able to continue generating LTC when Ardours transport is in stop
287                  * some machines do odd things if LTC goes away:
288                  * e.g. a tape based machine (video or audio), some think they have gone into park if LTC goes away,
289                  * so unspool the tape from the playhead. That might be inconvenient.
290                  * If LTC keeps arriving they remain in a stop position with the tape on the playhead.
291                  */
292                 new_ltc_speed = 0;
293                 if (!Config->get_ltc_send_continuously()) {
294                         ltc_speed = new_ltc_speed;
295                         return;
296                 }
297         }
298
299         if (fabs(new_ltc_speed) > 10.0) {
300                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: speed is out of bounds.\n");
301                 ltc_tx_reset();
302                 return;
303         }
304
305         if (ltc_speed == 0 && new_ltc_speed != 0) {
306                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport started rolling - reset\n");
307                 ltc_tx_reset();
308         }
309
310         /* the timecode duration corresponding to the samples that are still
311          * in the buffer. Here, the speed of previous cycle is used to calculate
312          * the alignment at the beginning of this cycle later.
313          */
314         double poff = (ltc_buf_len - ltc_buf_off) * ltc_speed;
315
316         if (speed_changed && new_ltc_speed != 0) {
317                 /* we need to re-sample the existing buffer.
318                  * "make space for the en-coder to catch up to the new speed"
319                  *
320                  * since the LTC signal is a rectangular waveform we can simply squeeze it
321                  * by removing samples or duplicating samples /here and there/.
322                  *
323                  * There may be a more elegant way to do this, in fact one could
324                  * simply re-render the buffer using ltc_encoder_encode_byte()
325                  * but that'd require some timecode offset buffer magic,
326                  * which is left for later..
327                  */
328
329                 double oldbuflen = (double)(ltc_buf_len - ltc_buf_off);
330                 double newbuflen = (double)(ltc_buf_len - ltc_buf_off) * fabs(ltc_speed / new_ltc_speed);
331
332                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: bufOld %1 bufNew %2 | diff %3\n",
333                                         (ltc_buf_len - ltc_buf_off), newbuflen, newbuflen - oldbuflen
334                                         ));
335
336                 double bufrspdiff = rint(newbuflen - oldbuflen);
337
338                 if (abs(bufrspdiff) > newbuflen || abs(bufrspdiff) > oldbuflen) {
339                         DEBUG_TRACE (DEBUG::LTC, "LTC TX2: resampling buffer would destroy information.\n");
340                         ltc_tx_reset();
341                         poff = 0;
342                 } else if (bufrspdiff != 0 && newbuflen > oldbuflen) {
343                         int incnt = 0;
344                         double samples_to_insert = ceil(newbuflen - oldbuflen);
345                         double avg_distance = newbuflen / samples_to_insert;
346                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer insert: %1\n", samples_to_insert));
347
348                         for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
349                                 const int ro = rp - ltc_buf_off;
350                                 if (ro < (incnt*avg_distance)) continue;
351                                 const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
352                                 const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
353                                 if (v1 != v2 && ro < ((incnt+1)*avg_distance)) continue;
354                                 memmove(&ltc_enc_buf[rp+1], &ltc_enc_buf[rp], ltc_buf_len-rp);
355                                 incnt++;
356                                 ltc_buf_len++;
357                         }
358                 } else if (bufrspdiff != 0 && newbuflen < oldbuflen) {
359                         double samples_to_remove = ceil(oldbuflen - newbuflen);
360                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer - remove: %1\n", samples_to_remove));
361                         if (oldbuflen <= samples_to_remove) {
362                                 ltc_buf_off = ltc_buf_len= 0;
363                         } else {
364                                 double avg_distance = newbuflen / samples_to_remove;
365                                 int rmcnt = 0;
366                                 for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
367                                         const int ro = rp - ltc_buf_off;
368                                         if (ro < (rmcnt*avg_distance)) continue;
369                                         const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
370                                         const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
371                                         if (v1 != v2 && ro < ((rmcnt+1)*avg_distance)) continue;
372                                         memmove(&ltc_enc_buf[rp], &ltc_enc_buf[rp+1], ltc_buf_len-rp-1);
373                                         ltc_buf_len--;
374                                         rmcnt++;
375                                 }
376                         }
377                 }
378         }
379
380         ltc_speed = new_ltc_speed;
381         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: transport speed %1.\n", ltc_speed));
382
383         // (3) bit/sample alignment
384         Timecode::Time tc_start;
385         framepos_t tc_sample_start;
386
387         /* calc timecode frame from current position - round down to nearest timecode */
388         Timecode::sample_to_timecode(cycle_start_frame, tc_start, true, false,
389                         timecode_frames_per_second(),
390                         timecode_drop_frames(),
391                         (double)frame_rate(),
392                         config.get_subframes_per_frame(),
393                         ltc_timecode_negative_offset, ltc_timecode_offset
394                         );
395
396         /* convert timecode back to sample-position */
397         Timecode::timecode_to_sample (tc_start, tc_sample_start, true, false,
398                 (double)frame_rate(),
399                 config.get_subframes_per_frame(),
400                 ltc_timecode_negative_offset, ltc_timecode_offset
401                 );
402
403         /* difference between current frame and TC frame in samples */
404         frameoffset_t soff = cycle_start_frame - tc_sample_start;
405         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX3: A3cycle: %1 = A3tc: %2 +off: %3\n",
406                                 cycle_start_frame, tc_sample_start, soff));
407
408
409         // (4) check if alignment matches
410         const double fptcf = frames_per_timecode_frame();
411
412         /* maximum difference of bit alignment in audio-samples.
413          *
414          * if transport and LTC generator differs more than this, the LTC
415          * generator will be re-initialized
416          *
417          * due to rounding error and variations in LTC-bit duration depending
418          * on the speed, it can be off by +- ltc_speed audio-samples.
419          * When the playback speed changes, it can actually reach +- 2 * ltc_speed
420          * in the cycle _after_ the speed changed. The average delta however is 0.
421          */
422         double maxdiff;
423
424         if (config.get_external_sync() && slave()) {
425                 maxdiff = slave()->resolution();
426         } else {
427                 maxdiff = ceil(fabs(ltc_speed))*2.0;
428                 if (nominal_frame_rate() != frame_rate()) {
429                         maxdiff *= 3.0;
430                 }
431                 if (ltc_enc_tcformat == Timecode::timecode_23976 || ltc_enc_tcformat == Timecode::timecode_24976) {
432                         maxdiff *= 15.0;
433                 }
434         }
435
436         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc: %1 + %2 - %3 || buf-bytes: %4 enc-byte: %5\n",
437                                 ltc_enc_pos, ltc_enc_cnt, poff, (ltc_buf_len - ltc_buf_off), poff, ltc_enc_byte));
438
439         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc-pos: %1  | d: %2\n",
440                                 ltc_enc_pos + ltc_enc_cnt - poff,
441                                 rint(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame
442                                 ));
443
444         if (ltc_enc_pos < 0
445                         || (ltc_speed != 0 && fabs(ceil(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame) > maxdiff)
446                         ) {
447
448                 // (5) re-align
449                 ltc_tx_reset();
450
451                 /* set frame to encode */
452                 SMPTETimecode tc;
453                 tc.hours = tc_start.hours;
454                 tc.mins = tc_start.minutes;
455                 tc.secs = tc_start.seconds;
456                 tc.frame = tc_start.frames;
457                 ltc_encoder_set_timecode(ltc_encoder, &tc);
458
459                 /* workaround for libltc recognizing 29.97 and 30000/1001 as drop-frame TC.
460                  * In A3 30000/1001 or 30 fps can be drop-frame.
461                  */
462                 LTCFrame ltcframe;
463                 ltc_encoder_get_frame(ltc_encoder, &ltcframe);
464                 ltcframe.dfbit = timecode_has_drop_frames(cur_timecode)?1:0;
465                 ltc_encoder_set_frame(ltc_encoder, &ltcframe);
466
467
468                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: now: %1 trs: %2 toff %3\n", cycle_start_frame, tc_sample_start, soff));
469
470                 uint32_t cyc_off;
471                 if (soff < 0 || soff >= fptcf) {
472                         /* session framerate change between (2) and now */
473                         ltc_tx_reset();
474                         return;
475                 }
476
477                 if (ltc_speed < 0 ) {
478                         /* calculate the byte that starts at or after the current position */
479                         ltc_enc_byte = floor((10.0 * soff) / (fptcf));
480                         ltc_enc_cnt = ltc_enc_byte * fptcf / 10.0;
481
482                         /* calculate difference between the current position and the byte to send */
483                         cyc_off = soff- ceil(ltc_enc_cnt);
484
485                 } else {
486                         /* calculate the byte that starts at or after the current position */
487                         ltc_enc_byte = ceil((10.0 * soff) / fptcf);
488                         ltc_enc_cnt = ltc_enc_byte * fptcf / 10.0;
489
490                         /* calculate difference between the current position and the byte to send */
491                         cyc_off = ceil(ltc_enc_cnt) - soff;
492
493                         if (ltc_enc_byte == 10) {
494                                 ltc_enc_byte = 0;
495                                 ltc_encoder_inc_timecode(ltc_encoder);
496                         }
497                 }
498
499                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart encoder: soff %1 byte %2 cycoff %3\n",
500                                         soff, ltc_enc_byte, cyc_off));
501
502                 if ( (ltc_speed < 0 && ltc_enc_byte !=9 ) || (ltc_speed >= 0 && ltc_enc_byte !=0 ) ) {
503                         restarting = true;
504                 }
505
506                 if (cyc_off > 0 && cyc_off <= nframes) {
507                         /* offset in this cycle */
508                         txf= rint(cyc_off / fabs(ltc_speed));
509                         memset(out, 0, cyc_off * sizeof(Sample));
510                 } else {
511                         /* resync next cycle */
512                         memset(out, 0, nframes * sizeof(Sample));
513                         return;
514                 }
515
516                 ltc_enc_pos = tc_sample_start;
517
518                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart @ %1 + %2 - %3 |  byte %4\n",
519                                         ltc_enc_pos, ltc_enc_cnt, cyc_off, ltc_enc_byte));
520         }
521         else if (ltc_speed != 0 && (fptcf / ltc_speed / 80) > 3 ) {
522                 /* reduce (low freq) jitter.
523                  * The granularity of the LTC encoder speed is 1 byte =
524                  * (frames-per-timecode-frame / 10) audio-samples.
525                  * Thus, tiny speed changes [as produced by some slaves]
526                  * may not have any effect in the cycle when they occur,
527                  * but they will add up over time.
528                  *
529                  * This is a linear approx to compensate for this jitter
530                  * and prempt re-sync when the drift builds up.
531                  *
532                  * However, for very fast speeds - when 1 LTC bit is
533                  * <= 3 audio-sample - adjusting speed may lead to
534                  * invalid frames.
535                  *
536                  * To do better than this, resampling (or a rewrite of the
537                  * encoder) is required.
538                  */
539                 ltc_speed -= ((ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame) / engine().frame_rate();
540         }
541
542
543         // (6) encode and output
544         while (1) {
545 #ifdef LTC_GEN_TXDBUG
546                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.1 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
547 #endif
548                 // (6a) send remaining buffer
549                 while ((ltc_buf_off < ltc_buf_len) && (txf < nframes)) {
550                         const float v1 = ltc_enc_buf[ltc_buf_off++] - 128.0;
551                         const Sample val = (Sample) (v1*ltcvol);
552                         out[txf++] = val;
553                 }
554 #ifdef LTC_GEN_TXDBUG
555                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.2 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
556 #endif
557
558                 if (txf >= nframes) {
559                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX7 enc: %1 [ %2 / %3 ] byte: %4 spd %5 fpp %6 || nf: %7\n",
560                                                 ltc_enc_pos, ltc_buf_off, ltc_buf_len, ltc_enc_byte, ltc_speed, nframes, txf));
561                         break;
562                 }
563
564                 ltc_buf_len = 0;
565                 ltc_buf_off = 0;
566
567                 // (6b) encode LTC, bump timecode
568
569                 if (ltc_speed < 0) {
570                         ltc_enc_byte = (ltc_enc_byte + 9)%10;
571                         if (ltc_enc_byte == 9) {
572                                 ltc_encoder_dec_timecode(ltc_encoder);
573                                 ltc_tx_recalculate_position();
574                                 ltc_enc_cnt = fptcf;
575                         }
576                 }
577
578                 int enc_frames;
579
580                 if (restarting) {
581                         /* write zero bytes -- don't touch encoder until we're at a frame-boundary
582                          * otherwise the biphase polarity may be inverted.
583                          */
584                         enc_frames = fptcf / 10.0;
585                         memset(&ltc_enc_buf[ltc_buf_len], 127, enc_frames * sizeof(ltcsnd_sample_t));
586                 } else {
587                         if (ltc_encoder_encode_byte(ltc_encoder, ltc_enc_byte, (ltc_speed==0)?1.0:(1.0/ltc_speed))) {
588                                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.3 encoder error byte %1\n", ltc_enc_byte));
589                                 ltc_encoder_buffer_flush(ltc_encoder);
590                                 ltc_tx_reset();
591                                 return;
592                         }
593                         enc_frames = ltc_encoder_get_buffer(ltc_encoder, &(ltc_enc_buf[ltc_buf_len]));
594                 }
595
596 #ifdef LTC_GEN_FRAMEDBUG
597                 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));
598 #endif
599                 if (enc_frames <=0) {
600                         DEBUG_TRACE (DEBUG::LTC, "LTC TX6.3 encoder empty buffer.\n");
601                         ltc_encoder_buffer_flush(ltc_encoder);
602                         ltc_tx_reset();
603                         return;
604                 }
605
606                 ltc_buf_len += enc_frames;
607                 if (ltc_speed < 0)
608                         ltc_enc_cnt -= fptcf/10.0;
609                 else
610                         ltc_enc_cnt += fptcf/10.0;
611
612                 if (ltc_speed >= 0) {
613                         ltc_enc_byte = (ltc_enc_byte + 1)%10;
614                         if (ltc_enc_byte == 0 && ltc_speed != 0) {
615                                 ltc_encoder_inc_timecode(ltc_encoder);
616 #if 0 /* force fixed parity -- scope debug */
617                                 LTCFrame f;
618                                 ltc_encoder_get_frame(ltc_encoder, &f);
619                                 f.biphase_mark_phase_correction=0;
620                                 ltc_encoder_set_frame(ltc_encoder, &f);
621 #endif
622                                 ltc_tx_recalculate_position();
623                                 ltc_enc_cnt = 0;
624                         } else if (ltc_enc_byte == 0) {
625                                 ltc_enc_cnt = 0;
626                                 restarting=false;
627                         }
628                 }
629 #ifdef LTC_GEN_FRAMEDBUG
630                 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));
631 #endif
632         }
633
634         dynamic_cast<AudioBuffer*>(&buf)->set_written (true);
635         return;
636 }