LTC generator update
[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 #include "ardour/debug.h"
21 #include "timecode/time.h"
22 #include "ardour/session.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/audio_port.h"
25
26 #include "i18n.h"
27
28 using namespace std;
29 using namespace ARDOUR;
30 using namespace MIDI;
31 using namespace PBD;
32 using namespace Timecode;
33
34 /* really verbose timing debug */
35 //#define LTC_GEN_FRAMEDBUG
36 //#define LTC_GEN_TXDBUG
37
38 void
39 Session::ltc_tx_initialize()
40 {
41         ltc_enc_tcformat = config.get_timecode_format();
42
43         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)));
44         ltc_encoder = ltc_encoder_create(nominal_frame_rate(),
45                         timecode_to_frames_per_second(ltc_enc_tcformat),
46                         0);
47
48         ltc_encoder_set_bufsize(ltc_encoder, nominal_frame_rate(), 23.0);
49
50         /* buffersize for 1 LTC frame: (1 + sample-rate / fps) bytes
51          * usually returned by ltc_encoder_get_buffersize(encoder)
52          *
53          * since the fps can change and A3's  min fps: 24000/1001 */
54         ltc_enc_buf = (ltcsnd_sample_t*) calloc((nominal_frame_rate() / 23), sizeof(ltcsnd_sample_t));
55         ltc_speed = 0;
56         ltc_tx_reset();
57 }
58
59 void
60 Session::ltc_tx_cleanup()
61 {
62         DEBUG_TRACE (DEBUG::LTC, "LTC TX cleanup\n");
63         if (ltc_enc_buf) free(ltc_enc_buf);
64         ltc_encoder_free(ltc_encoder);
65         ltc_encoder = NULL;
66 }
67
68 void
69 Session::ltc_tx_reset()
70 {
71         DEBUG_TRACE (DEBUG::LTC, "LTC TX reset\n");
72         ltc_enc_pos = -9999; // force re-start
73         ltc_buf_len = 0;
74         ltc_buf_off = 0;
75         ltc_enc_byte = 0;
76         ltc_enc_cnt = 0;
77 }
78
79 void
80 Session::ltc_tx_recalculate_position()
81 {
82         SMPTETimecode enctc;
83         Timecode::Time a3tc;
84         ltc_encoder_get_timecode(ltc_encoder, &enctc);
85
86         a3tc.hours   = enctc.hours;
87         a3tc.minutes = enctc.mins;
88         a3tc.seconds = enctc.secs;
89         a3tc.frames  = enctc.frame;
90         a3tc.rate = timecode_to_frames_per_second(ltc_enc_tcformat);
91         a3tc.drop = timecode_has_drop_frames(ltc_enc_tcformat);
92
93         Timecode::timecode_to_sample (a3tc, ltc_enc_pos, true, false,
94                 double(frame_rate()),
95                 config.get_subframes_per_frame(),
96                 config.get_timecode_offset_negative(), config.get_timecode_offset()
97                 );
98 }
99
100 int
101 Session::ltc_tx_send_time_code_for_cycle (framepos_t start_frame, framepos_t end_frame,
102                 double target_speed, double current_speed,
103                 pframes_t nframes)
104 {
105         assert(nframes > 0);
106
107         jack_default_audio_sample_t *out;
108         pframes_t txf = 0;
109         boost::shared_ptr<Port> ltcport = engine().ltc_output_port();
110
111         if (!ltc_encoder || !ltc_enc_buf || !ltcport || ! ltcport->jack_port()) return 0;
112
113         out = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
114         if (!out) return 0;
115
116         if (engine().freewheeling()|| !Config->get_send_ltc()
117                         /* TODO
118                          * we can relax this a bit, JACK or sample-synced slaves should be fine.
119                          * test before allowing it, do the same for MTC generator in
120                          * libs/ardour/session_midi.cc
121                          * */
122                 //      || config.get_external_sync()  // XXX XXX
123                         ) {
124                 memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
125                 return nframes;
126         }
127
128         /* range from libltc (38..218) || - 128.0  -> (-90..90) */
129         const float ltcvol = Config->get_ltc_output_volume()/(90.0); // pow(10, db/20.0)/(90.0);
130
131         jack_latency_range_t ltc_latency;
132         ltcport->get_connected_latency_range(ltc_latency, true);
133         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX %1 to %2 / %3 | lat: %4\n", start_frame, end_frame, nframes, ltc_latency.max));
134
135         /* all systems go. Now here's the plan:
136          *
137          *  1) check if fps has changed
138          *  2) check direction of encoding, calc speed, resample existing buffer
139          *  3) calculate frame and byte to send aligned to jack-period size
140          *  4) check if it's the frame/byte that is already in the queue
141          *  5) if (4) mismatch, re-calculate offset of LTC frame relative to period size
142          *  6) actual LTC audio output
143          *  6a) send remaining part of already queued frame; break on nframes
144          *  6b) encode new LTC-frame byte
145          *  6c) goto 6a
146          *  7) done
147          */
148
149         // (1) check fps
150         TimecodeFormat cur_timecode = config.get_timecode_format();
151         if (cur_timecode != ltc_enc_tcformat) {
152                 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)));
153                 if (ltc_encoder_reinit(ltc_encoder, nominal_frame_rate(), timecode_to_frames_per_second(cur_timecode), 0)) {
154                         PBD::error << _("LTC encoder: invalid framerate - LTC encoding is disabled for the remainder of this session.") << endmsg;
155                         ltc_tx_cleanup();
156                         return 0;
157                 }
158                 ltc_enc_tcformat = cur_timecode;
159                 ltc_tx_reset();
160         }
161
162         /* LTC is max. 30 fps */
163         if (timecode_to_frames_per_second(cur_timecode) > 30) {
164                 memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
165                 return nframes;
166         }
167
168         // (2) speed & direction
169 #define SIGNUM(a) ( (a) < 0 ? -1 : 1)
170         bool speed_changed = false;
171
172         // XXX
173         //framepos_t cycle_start_frame = (current_speed < 0) ? (start_frame - ltc_latency.max) : (start_frame + ltc_latency.max);
174         framepos_t cycle_start_frame = start_frame;
175
176         /* cycle-start may become negative due to latency comensation */
177         if (cycle_start_frame < 0) { cycle_start_frame = 0; }
178
179         double new_ltc_speed = double(labs(end_frame - start_frame) * SIGNUM(current_speed)) / double(nframes);
180
181         if (SIGNUM(new_ltc_speed) != SIGNUM (ltc_speed)) {
182                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport changed direction\n");
183                 ltc_tx_reset();
184         }
185
186         if (ltc_speed != new_ltc_speed) {
187                 /* check ./libs/ardour/interpolation.cc  CubicInterpolation::interpolate
188                  * if target_speed != current_speed we should interpolate, too.
189                  *
190                  * However, currenly in A3 target_speed == current_speed for each process cycle
191                  * (except for the sign and if target_speed > 8.0).
192                  * Besides, above speed calulation uses the difference (end_frame - start_frame).
193                  * end_frame is calculated from 'frames_moved' which includes the interpolation.
194                  * so we're good.
195                  */
196                 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));
197                 speed_changed = true;
198         }
199
200         if (end_frame == start_frame || fabs(current_speed) < 0.1 ) {
201                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport is not rolling or absolute-speed < 0.1\n");
202                 /* keep repeating current frame
203                  *
204                  * an LTC generator must be able to continue generating LTC when Ardours transport is in stop
205                  * some machines do odd things if LTC goes away:
206                  * e.g. a tape based machine (video or audio), some think they have gone into park if LTC goes away,
207                  * so unspool the tape from the playhead. That might be inconvenient.
208                  * If LTC keeps arriving they remain in a stop position with the tape on the playhead.
209                  */
210                 new_ltc_speed = 0;
211                 if (!Config->get_ltc_send_continuously()) {
212                         ltc_speed = new_ltc_speed;
213                         memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
214                         return nframes;
215                 }
216         }
217
218         if (fabs(new_ltc_speed) > 10.0) {
219                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: speed is out of bounds.\n");
220                 ltc_tx_reset();
221                 memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
222                 return nframes;
223         }
224
225         if (ltc_speed == 0 && new_ltc_speed != 0) {
226                 DEBUG_TRACE (DEBUG::LTC, "LTC TX2: transport started rolling - reset\n");
227                 ltc_tx_reset();
228         }
229
230         /* the timecode duration corresponding to the samples still in the buffer
231          * here we use prev. speed to match the begining of this cycle for aligment.
232          */
233         double poff = (ltc_buf_len - ltc_buf_off) * ltc_speed;
234
235         if (speed_changed && new_ltc_speed != 0) {
236                 /* we need to re-sample the existing buffer.
237                  * "make space for the en-coder to catch up to the new speed"
238                  *
239                  * since the LTC signal is a rect waveform we can simply squeeze it
240                  * by removing samples or duplicating /here and there/.
241                  *
242                  * There may be a more elegant way to do this, in fact one could
243                  * simply re-render the buffer using ltc_encoder_encode_byte()
244                  * but that'd require some timecode offset buffer magic,
245                  * which is left for later..
246                  */
247
248                 double oldbuflen = double(ltc_buf_len - ltc_buf_off);
249                 double newbuflen = double(ltc_buf_len - ltc_buf_off) * fabs(ltc_speed / new_ltc_speed);
250
251                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: bufOld %1 bufNew %2 | diff %3\n",
252                                         (ltc_buf_len - ltc_buf_off), newbuflen, newbuflen - oldbuflen
253                                         ));
254
255                 double bufrspdiff = rint(newbuflen - oldbuflen);
256
257                 if (abs(bufrspdiff) > newbuflen || abs(bufrspdiff) > oldbuflen) {
258                         DEBUG_TRACE (DEBUG::LTC, "LTC TX2: resampling buffer would destroy information.\n");
259                         ltc_tx_reset();
260                         poff = 0;
261                 } else if (bufrspdiff != 0 && newbuflen > oldbuflen) {
262                         int incnt = 0;
263                         double samples_to_insert = ceil(newbuflen - oldbuflen);
264                         double avg_distance = newbuflen / samples_to_insert;
265                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer insert: %1\n", samples_to_insert));
266
267                         for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
268                                 const int ro = rp - ltc_buf_off;
269                                 if (ro < (incnt*avg_distance)) continue;
270                                 const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
271                                 const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
272                                 if (v1 != v2 && ro < ((incnt+1)*avg_distance)) continue;
273                                 memmove(&ltc_enc_buf[rp+1], &ltc_enc_buf[rp], ltc_buf_len-rp);
274                                 incnt++;
275                                 ltc_buf_len++;
276                         }
277                 } else if (bufrspdiff != 0 && newbuflen < oldbuflen) {
278                         double samples_to_remove = ceil(oldbuflen - newbuflen);
279                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: resample buffer - remove: %1\n", samples_to_remove));
280                         if (oldbuflen <= samples_to_remove) {
281                                 ltc_buf_off = ltc_buf_len= 0;
282                         } else {
283                                 double avg_distance = newbuflen / samples_to_remove;
284                                 int rmcnt = 0;
285                                 for (int rp = ltc_buf_off; rp < ltc_buf_len - 1; ++rp) {
286                                         const int ro = rp - ltc_buf_off;
287                                         if (ro < (rmcnt*avg_distance)) continue;
288                                         const ltcsnd_sample_t v1 = ltc_enc_buf[rp];
289                                         const ltcsnd_sample_t v2 = ltc_enc_buf[rp+1];
290                                         if (v1 != v2 && ro < ((rmcnt+1)*avg_distance)) continue;
291                                         memmove(&ltc_enc_buf[rp], &ltc_enc_buf[rp+1], ltc_buf_len-rp-1);
292                                         ltc_buf_len--;
293                                         rmcnt++;
294                                 }
295                         }
296                 }
297         }
298
299         ltc_speed = new_ltc_speed;
300         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX2: transport speed %1.\n", ltc_speed));
301
302
303         // (3) bit/sample aligment
304         Timecode::Time tc_start;
305         framepos_t tc_sample_start;
306
307         /* calc timecode frame from current position - round down to nearest timecode */
308         sample_to_timecode(cycle_start_frame, tc_start, true, false);
309
310         /* convert timecode back to sample-position */
311         Timecode::timecode_to_sample (tc_start, tc_sample_start, true, false,
312                 double(frame_rate()),
313                 config.get_subframes_per_frame(),
314                 config.get_timecode_offset_negative(), config.get_timecode_offset()
315                 );
316
317         /* difference between current frame and TC frame in samples */
318         frameoffset_t soff = cycle_start_frame - tc_sample_start;
319         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX3: A3cycle: %1 = A3tc: %2 +off: %3\n",
320                                 cycle_start_frame, tc_sample_start, soff));
321
322
323         // (4) check if aligment matches
324         const double fptcf = frames_per_timecode_frame(); // convenient, used a lot below.
325         double maxdiff;
326
327         /* due to rounding error and variations in LTC-bit duration depending
328          * on the speed, we can be off by +- speed samples.
329          * during speed-changes we can acually ready += 2*speed audio-samples
330          * in the cycle after the speed change.  The average delta however is 0.
331          */
332         if (config.get_external_sync()) {
333                 maxdiff = fptcf; // TODO get slave max delta
334         } else {
335                 maxdiff = ceil(fabs(ltc_speed))*2.0;
336         }
337
338         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc: %1 + %2 - %3 || buf-bytes: %4 enc-byte: %5\n",
339                                 ltc_enc_pos, ltc_enc_cnt, poff, (ltc_buf_len - ltc_buf_off), poff, ltc_enc_byte));
340
341         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: enc-pos: %1  | d: %2\n",
342                                 ltc_enc_pos + ltc_enc_cnt - poff,
343                                 rint(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame
344                                 ));
345
346         if (fabs(ceil(ltc_enc_pos + ltc_enc_cnt - poff) - cycle_start_frame) > maxdiff)
347         {
348                 // (5) re-align
349                 ltc_tx_reset();
350
351                 /* set frame to encode */
352                 SMPTETimecode tc;
353                 tc.hours = tc_start.hours;
354                 tc.mins = tc_start.minutes;
355                 tc.secs = tc_start.seconds;
356                 tc.frame = tc_start.frames;
357                 ltc_encoder_set_timecode(ltc_encoder, &tc);
358
359                 /* workaround for libltc recognizing 29.97 and 30000/1001 as drop-frame TC.
360                  * in A3 only 30000/1001 is drop-frame and there are also other questionable
361                  * DF timecodes  such as 24k/1001 and 25k/1001.
362                  */
363                 LTCFrame ltcframe;
364                 ltc_encoder_get_frame(ltc_encoder, &ltcframe);
365                 ltcframe.dfbit = timecode_has_drop_frames(cur_timecode)?1:0;
366                 ltc_encoder_set_frame(ltc_encoder, &ltcframe);
367
368
369                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX4: now: %1 trs: %2 toff %3\n", cycle_start_frame, tc_sample_start, soff));
370
371                 uint32_t cyc_off;
372                 assert(soff >= 0 && soff < fptcf);
373
374                 if (ltc_speed < 0 ) {
375                         /* calculate the byte that starts at or after the current position */
376                         ltc_enc_byte = floor((10.0 * soff) / (fptcf));
377                         ltc_enc_cnt = double(ltc_enc_byte * fptcf / 10.0);
378
379                         /* calculate difference between the current position and the byte to send */
380                         cyc_off = soff- ceil(ltc_enc_cnt);
381
382                 } else {
383                         /* calculate the byte that starts at or after the current position */
384                         ltc_enc_byte = ceil((10.0 * soff) / fptcf);
385                         ltc_enc_cnt = double(ltc_enc_byte * fptcf / 10.0);
386
387                         /* calculate difference between the current position and the byte to send */
388                         cyc_off = ceil(ltc_enc_cnt) - soff;
389
390                         if (ltc_enc_byte == 10) {
391                                 ltc_enc_byte = 0;
392                                 ltc_encoder_inc_timecode(ltc_encoder);
393                         }
394                 }
395
396                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart encoder: soff %1 byte %2 cycoff %3\n",
397                                         soff, ltc_enc_byte, cyc_off));
398
399                 if (ltc_speed == 0) {
400                         /* don't bother to align non-moving loops */
401                 } else if (cyc_off > 0 && cyc_off <= nframes) {
402                         /* offset in this cycle */
403                         txf= rint(cyc_off / fabs(ltc_speed));
404                         memset(out, 0, cyc_off * sizeof(jack_default_audio_sample_t));
405                 } else if (cyc_off > 0) {
406                         /* resync next cycle */
407                         memset(out, 0, cyc_off * sizeof(jack_default_audio_sample_t));
408                         return nframes;
409                 }
410
411                 ltc_enc_pos = tc_sample_start;
412
413                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX5 restart @ %1 + %2 - %3 |  byte %4\n",
414                                         ltc_enc_pos, ltc_enc_cnt, cyc_off, ltc_enc_byte));
415         }
416
417
418         // (6) encode and output
419         while (1) {
420 #ifdef LTC_GEN_TXDBUG
421                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.1 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
422 #endif
423                 // (6a) send remaining buffer
424                 while ((ltc_buf_off < ltc_buf_len) && (txf < nframes)) {
425                         const float v1 = ltc_enc_buf[ltc_buf_off++] - 128.0;
426                         const jack_default_audio_sample_t val = (jack_default_audio_sample_t) (v1*ltcvol);
427                         out[txf++] = val;
428                 }
429 #ifdef LTC_GEN_TXDBUG
430                 DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.2 @%1  [ %2 / %3 ]\n", txf, ltc_buf_off, ltc_buf_len));
431 #endif
432
433                 if (txf >= nframes) {
434                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX7 enc: %1 [ %2 / %3 ] byte: %4 spd %5 fpp %6 || nf: %7\n",
435                                                 ltc_enc_pos, ltc_buf_off, ltc_buf_len, ltc_enc_byte, ltc_speed, nframes, txf));
436                         return nframes;
437                 }
438
439                 ltc_buf_len = 0;
440                 ltc_buf_off = 0;
441
442                 // (6b) encode LTC, bump timecode
443
444                 if (ltc_speed < 0) {
445                         ltc_enc_byte = (ltc_enc_byte + 9)%10;
446                         if (ltc_enc_byte == 9) {
447                                 ltc_encoder_dec_timecode(ltc_encoder);
448                                 ltc_tx_recalculate_position();
449                                 ltc_enc_cnt = fptcf;
450                         }
451                 }
452
453                 if (ltc_encoder_encode_byte(ltc_encoder, ltc_enc_byte, (ltc_speed==0)?1.0:(1.0/ltc_speed))) {
454                         DEBUG_TRACE (DEBUG::LTC, string_compose("LTC TX6.3 encoder error byte %1\n", ltc_enc_byte));
455                         ltc_encoder_buffer_flush(ltc_encoder);
456                         ltc_tx_reset();
457                         memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
458                         return -1;
459                 }
460                 int enc_frames = ltc_encoder_get_buffer(ltc_encoder, &(ltc_enc_buf[ltc_buf_len]));
461 #ifdef LTC_GEN_FRAMEDBUG
462                 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));
463 #endif
464                 if (enc_frames <=0) {
465                         DEBUG_TRACE (DEBUG::LTC, "LTC TX6.3 encoder empty buffer.\n");
466                         ltc_encoder_buffer_flush(ltc_encoder);
467                         ltc_tx_reset();
468                         memset(out, 0, nframes * sizeof(jack_default_audio_sample_t));
469                         return -1;
470                 }
471
472                 ltc_buf_len += enc_frames;
473                 if (ltc_speed < 0)
474                         ltc_enc_cnt -= fptcf/10.0; //enc_frames * ltc_speed;
475                 else
476                         ltc_enc_cnt += fptcf/10.0; //enc_frames * ltc_speed;
477
478                 if (ltc_speed >= 0) {
479                         ltc_enc_byte = (ltc_enc_byte + 1)%10;
480                         if (ltc_enc_byte == 0 && ltc_speed != 0) {
481                                 ltc_encoder_inc_timecode(ltc_encoder);
482                                 ltc_tx_recalculate_position();
483                                 ltc_enc_cnt = 0;
484                         } else if (ltc_enc_byte == 0) {
485                                 ltc_enc_cnt = 0;
486                         }
487                 }
488 #ifdef LTC_GEN_FRAMEDBUG
489                 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));
490 #endif
491         }
492
493         return nframes;
494 }