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