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