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