Add a 1% speed deadzone around speed=1.0 for LTC, MTC slaves
[ardour.git] / libs / ardour / ltc_slave.cc
1 /*
2     Copyright (C) 2012 Paul Davis
3     Witten by 2012 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 <iostream>
21 #include <errno.h>
22 #include <poll.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include "pbd/error.h"
27
28 #include "ardour/debug.h"
29 #include "ardour/slave.h"
30 #include "ardour/session.h"
31 #include "ardour/audioengine.h"
32 #include "ardour/audio_port.h"
33
34 #include "i18n.h"
35
36 using namespace std;
37 using namespace ARDOUR;
38 using namespace MIDI;
39 using namespace PBD;
40 using namespace Timecode;
41
42 #define FLYWHEEL_TIMEOUT ( 3 * session.frame_rate() )
43
44 LTC_Slave::LTC_Slave (Session& s)
45         : session (s)
46 {
47         frames_per_ltc_frame = session.frames_per_timecode_frame(); // XXX at most 30fps ?
48         timecode.rate = session.timecode_frames_per_second();
49         timecode.drop  = session.timecode_drop_frames();
50
51         ltc_transport_pos = 0;
52         did_reset_tc_format = false;
53         delayedlocked = 10;
54         engine_dll_initstate = 0;
55         monotonic_cnt = 0;
56
57         memset(&prev_ltc_frame, 0, sizeof(LTCFrame));
58
59         ltc_timecode = timecode_60; // track changes of LTC timecode
60         a3e_timecode = timecode_60; // track canges of Ardour's timecode
61         printed_timecode_warning = false;
62
63         decoder = ltc_decoder_create((int) frames_per_ltc_frame, 128 /*queue size*/);
64         reset();
65         //session.engine().Xrun.connect_same_thread (*this, boost::bind (&LTC_Slave::reset, this));
66 }
67
68 LTC_Slave::~LTC_Slave()
69 {
70         if (did_reset_tc_format) {
71                 session.config.set_timecode_format (saved_tc_format);
72         }
73
74         ltc_decoder_free(decoder);
75 }
76
77 bool
78 LTC_Slave::give_slave_full_control_over_transport_speed() const
79 {
80         return true; // DLL align to engine transport
81         // return false; // for Session-level computed varispeed
82 }
83
84 ARDOUR::framecnt_t
85 LTC_Slave::resolution () const
86 {
87         return (framecnt_t) (frames_per_ltc_frame);
88 }
89
90 ARDOUR::framecnt_t
91 LTC_Slave::seekahead_distance () const
92 {
93         return 0;
94 }
95
96 bool
97 LTC_Slave::locked () const
98 {
99         return (delayedlocked < 5);
100 }
101
102 bool
103 LTC_Slave::ok() const
104 {
105         return true;
106 }
107
108 void
109 LTC_Slave::reset()
110 {
111         DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
112         frames_in_sequence = 0;
113         ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
114         last_timestamp = 0;
115         current_delta = 0;
116         transport_direction = 0;
117         ltc_speed = 0;
118         ltc_decoder_queue_flush(decoder);
119 }
120
121 int
122 LTC_Slave::parse_ltc(const jack_nframes_t nframes, const jack_default_audio_sample_t * const in, const framecnt_t posinfo)
123 {
124         jack_nframes_t i;
125         unsigned char sound[8192];
126         if (nframes > 8192) return 1;
127
128         for (i = 0; i < nframes; i++) {
129                 const int snd=(int)rint((127.0*in[i])+128.0);
130                 sound[i] = (unsigned char) (snd&0xff);
131         }
132         ltc_decoder_write(decoder, sound, nframes, posinfo);
133         return 0;
134 }
135
136 bool
137 LTC_Slave::detect_ltc_fps(int frameno, bool df)
138 {
139         double detected_fps = 0;
140         if (frameno > ltc_detect_fps_max)
141         {
142                 ltc_detect_fps_max = frameno;
143         }
144         ltc_detect_fps_cnt++;
145         if (ltc_detect_fps_cnt > 60)
146         {
147                 if (ltc_detect_fps_cnt > ltc_detect_fps_max
148                     && (   ceil(timecode.rate) != (ltc_detect_fps_max + 1)
149                         || timecode.drop != df
150                         )
151                     )
152                 {
153                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS %1%2",
154                                         ltc_detect_fps_max + 1, timecode.drop ? "df" : ""));
155                         detected_fps = ltc_detect_fps_max + 1;
156                         if (df) {
157                                 /* LTC df -> indicates fractional framerate */
158                                 detected_fps = detected_fps * 1000.0 / 1001.0;
159                         }
160                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
161                 }
162                 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
163         }
164
165         /* when changed */
166         if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
167                 timecode.rate = detected_fps;
168                 timecode.drop = df;
169                 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
170                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
171                                 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
172                 return true; // reset()
173         }
174
175         /* poll and check session TC */
176         if (1) {
177                 TimecodeFormat tc_format = apparent_timecode_format();
178                 TimecodeFormat cur_timecode = session.config.get_timecode_format();
179                 if (Config->get_timecode_sync_frame_rate()) {
180                         /* enforce time-code */
181                         if (!did_reset_tc_format) {
182                                 saved_tc_format = cur_timecode;
183                                 did_reset_tc_format = true;
184                         }
185                         if (cur_timecode != tc_format) {
186                                 warning << string_compose(_("Session framerate adjusted from %1 TO: LTC's %2."),
187                                                 Timecode::timecode_format_name(cur_timecode),
188                                                 Timecode::timecode_format_name(tc_format))
189                                         << endmsg;
190                         }
191                         session.config.set_timecode_format (tc_format);
192                 } else {
193                         /* only warn about TC mismatch */
194                         if (ltc_timecode != tc_format) printed_timecode_warning = false;
195                         if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
196
197                         if (cur_timecode != tc_format && ! printed_timecode_warning) {
198                                 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
199                                                 Timecode::timecode_format_name(tc_format),
200                                                 Timecode::timecode_format_name(cur_timecode))
201                                         << endmsg;
202                                 printed_timecode_warning = true;
203                         }
204                 }
205                 ltc_timecode = tc_format;
206                 a3e_timecode = cur_timecode;
207         }
208         return false;
209 }
210
211 bool
212 LTC_Slave::detect_ltc_discontinuity(LTCFrameExt *frame) {
213         bool discontinuity_detected = false;
214         /* detect discontinuities */
215         if (frame->reverse) {
216                 ltc_frame_decrement(&prev_ltc_frame, ceil(timecode.rate), 0);
217         } else {
218                 ltc_frame_increment(&prev_ltc_frame, ceil(timecode.rate), 0);
219         }
220
221         if (memcmp(&prev_ltc_frame, &frame->ltc, sizeof(LTCFrame))) {
222                 discontinuity_detected = true;
223         }
224         memcpy(&prev_ltc_frame, &frame->ltc, sizeof(LTCFrame));
225
226         /* notfify about discontinuities */
227         if (frames_in_sequence > 0 && discontinuity_detected) {
228                 DEBUG_TRACE (DEBUG::LTC, "# LTC DISCONTINUITY\n");
229                 frames_in_sequence=0;
230                 return true;
231         }
232         frames_in_sequence++;
233
234         return false;
235 }
236
237 bool
238 LTC_Slave::process_ltc(framepos_t const now, framepos_t const sess_pos, framecnt_t const nframes)
239 {
240         bool have_frame = false;
241         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
242
243         LTCFrameExt frame;
244         while (ltc_decoder_read(decoder,&frame)) {
245                 bool reinitialize_ltc_dll = false;
246                 SMPTETimecode stime;
247
248                 ltc_frame_to_time(&stime, &frame.ltc, 0);
249                 timecode.negative  = false;
250                 timecode.subframes  = 0;
251                 /* set timecode.rate and timecode.drop: */
252                 if (detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false)) {
253                         reset();
254                         break;
255                 }
256                 if (detect_ltc_discontinuity(&frame)) {
257                         ltc_discontinuity = true;
258                 }
259
260 #if 0 // Devel/Debug
261                 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
262                         stime.hours,
263                         stime.mins,
264                         stime.secs,
265                         (frame.ltc.dfbit) ? '.' : ':',
266                         stime.frame,
267                         frame.off_start,
268                         frame.off_end,
269                         frame.reverse ? " R" : "  "
270                         );
271
272                 if (frames_in_sequence < 1) {
273                         fprintf(stdout, " ####### FIRST LTC FRAME in SEQ #######\n");
274                 }
275
276                 if (ltc_discontinuity) {
277                         fprintf(stdout, " ####### LTC DISCONTINUITY #######\n");
278                 }
279 #endif
280
281                 if (frames_in_sequence < 1) {
282                         continue;
283                 }
284
285                 /* when a full LTC frame is decoded, the timecode the LTC frame
286                  * is referring has just passed.
287                  * So we send the _next_ timecode which
288                  * is expected to start at the end of the current frame
289                  */
290                 int fps_i = ceil(timecode.rate);
291                 if (!frame.reverse) {
292                         ltc_frame_increment(&frame.ltc, fps_i , 0);
293                         ltc_frame_to_time(&stime, &frame.ltc, 0);
294                 } else {
295                         ltc_frame_decrement(&frame.ltc, fps_i , 0);
296                         int off = frame.off_end - frame.off_start;
297                         frame.off_start += off;
298                         frame.off_end += off;
299                 }
300
301                 timecode.hours   = stime.hours;
302                 timecode.minutes = stime.mins;
303                 timecode.seconds = stime.secs;
304                 timecode.frames  = stime.frame;
305
306                 /* map LTC timecode to session TC setting */
307                 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
308                 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
309                         double(session.frame_rate()),
310                         session.config.get_subframes_per_frame(),
311                         session.config.get_timecode_offset_negative(), session.config.get_timecode_offset()
312                         );
313
314                 /* (frame.off_end + 1) = start of next LTC frame */
315                 double poff = (frame.off_end + 1 - now);
316                 ltc_transport_pos = ltc_frame - poff;
317
318 #if 0 // vari-speed LTC, no DLL
319                         frames_per_ltc_frame = 1 + frame.off_end - frame.off_start;
320 #else
321                         frames_per_ltc_frame = (double(session.frame_rate()) / timecode.rate);
322 #endif
323
324                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC frame: %1 poff: %2 pos: %3\n", ltc_frame, poff, ltc_transport_pos));
325
326                 if (ltc_discontinuity) {
327                         ltc_discontinuity=false;
328                         if (ltc_speed==0
329                                         || !locked()
330                                         || (ltc_transport_pos - sess_pos) > FLYWHEEL_TIMEOUT)
331                         {
332                                 engine_dll_initstate = 0;
333                                 reset();
334                         }
335                         reinitialize_ltc_dll = true;
336                 }
337
338                 if (last_timestamp == 0
339                         || ((now - last_timestamp) > FLYWHEEL_TIMEOUT)
340                         || (abs(current_delta) >  FLYWHEEL_TIMEOUT) // TODO LTC-delta not engine delta
341                         || (frame.reverse && transport_direction != -1)
342                         || (!frame.reverse && transport_direction != 1)
343                         ) {
344                         reinitialize_ltc_dll = true;
345                         engine_dll_initstate = 0;
346                         reset();
347                 }
348
349                 if (reinitialize_ltc_dll) {
350                         init_ltc_dll(ltc_transport_pos, frames_per_ltc_frame);
351
352                         if (ltc_speed==0 || !locked()) {
353                                 if (frame.reverse) {
354                                         transport_direction = -1;
355                                         ltc_transport_pos -= nframes * rint((2 * frames_per_ltc_frame + poff)/nframes);
356                                 } else {
357                                         transport_direction = 1;
358                                         ltc_transport_pos += nframes * rint((2 * frames_per_ltc_frame + poff)/nframes);
359                                 }
360                         }
361
362                 } else {
363                         // update DLL
364                         double e = (double(ltc_frame) - poff - double(sess_pos));
365                         t0 = t1;
366                         t1 += b * e + e2;
367                         e2 += c * e;
368
369                         ltc_speed = (t1 - t0) / frames_per_ltc_frame;
370                         current_delta = (ltc_transport_pos - sess_pos);
371                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC DLL t0:%1 t1:%2 err:%3 spd:%4 ddt:%5\n", t0, t1, e, ltc_speed, e2 - frames_per_ltc_frame));
372
373                 }
374
375                 /* the are equivalent
376                  * TODO: choose the value with larger diff ->
377                  * minimize roundig errors when extrapolating
378                  */
379 #if 1
380                 last_timestamp = now;
381                 last_ltc_frame = ltc_transport_pos;
382 #else
383                 last_timestamp = frame.off_end + 1;
384                 last_ltc_frame = ltc_frame;
385 #endif
386
387                 have_frame = true;
388         } /* end foreach decoded LTC frame */
389
390         return have_frame;
391 }
392
393 void
394 LTC_Slave::init_ltc_dll(framepos_t const tme, double const dt)
395 {
396         omega = 2.0 * M_PI * dt / double(session.frame_rate());
397         b = 1.4142135623730950488 * omega;
398         c = omega * omega;
399
400         e2 = dt;
401         t0 = double(tme);
402         t1 = t0 + e2;
403         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init LTC DLL %1 %2 %3\n", t0, t1, e2));
404 }
405
406 void
407 LTC_Slave::init_engine_dll (framepos_t pos, framepos_t inc)
408 {
409         /* the bandwidth of the DLL is a trade-off,
410          * because the max-speed of the transport in ardour is
411          * limited to +-8.0, a larger bandwidth would cause oscillations
412          *
413          * But this is only really a problem if the user performs manual
414          * seeks while transport is running and slaved to LTC.
415          */
416         oe = 2.0 * M_PI * double(inc/2.0) / double(session.frame_rate());
417         be = 1.4142135623730950488 * oe;
418         ce = oe * oe;
419
420         ee2 = double(transport_direction * inc);
421         te0 = double(pos);
422         te1 = te0 + ee2;
423         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", te0, te1, ee2));
424 }
425
426 /* main entry point from session_process.cc
427  * called from jack_process callback context
428  * so it is OK to use jack_port_get_buffer() etc
429  */
430 bool
431 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
432 {
433         //framepos_t now = session.engine().frame_time_at_cycle_start();
434         //framepos_t now = session.engine().processed_frames();
435         framepos_t now = monotonic_cnt;
436         framepos_t sess_pos = session.transport_frame(); // corresponds to now
437         framecnt_t nframes = session.engine().frames_per_cycle();
438         jack_default_audio_sample_t *in;
439         jack_latency_range_t ltc_latency;
440
441         monotonic_cnt += nframes;
442
443         boost::shared_ptr<Port> ltcport = session.engine().ltc_input_port();
444         ltcport->get_connected_latency_range(ltc_latency, false);
445         in = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
446
447         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC_Slave::speed_and_position - TID:%1 | latency: %2\n", ::pthread_self(), ltc_latency.max));
448
449         if (last_timestamp == 0) {
450                 engine_dll_initstate = 0;
451                 delayedlocked++;
452         }
453         else if (engine_dll_initstate != transport_direction) {
454                 engine_dll_initstate = transport_direction;
455                 init_engine_dll(last_ltc_frame, session.engine().frames_per_cycle());
456         }
457
458         if (in) {
459                 parse_ltc(nframes, in, now  + ltc_latency.max );
460                 if (!process_ltc(now, sess_pos, nframes) && ltc_speed != 0) {
461                 }
462         }
463
464         /* interpolate position according to speed and time since last LTC-frame*/
465         double speed_flt = ltc_speed;
466         framecnt_t elapsed;
467         if (speed_flt == 0.0f) {
468                 elapsed = 0;
469         } else {
470                 /* scale elapsed time by the current LTC speed */
471                 if (last_timestamp && (now > last_timestamp)) {
472                         elapsed = (now - last_timestamp) * speed_flt;
473                 } else {
474                         elapsed = 0;
475                 }
476                 /* update engine DLL and calculate speed */
477                 const double e = double (last_ltc_frame + elapsed - sess_pos);
478                 te0 = te1;
479                 te1 += be * e + ee2;
480                 ee2 += ce * e;
481                 speed_flt = (te1 - te0) / double(session.engine().frames_per_cycle());
482                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC engine DLL t0:%1 t1:%2 err:%3 spd:%4 ddt:%5\n", te0, te1, e, speed_flt, ee2 - session.engine().frames_per_cycle() ));
483         }
484
485         pos = last_ltc_frame + elapsed;
486         speed = speed_flt;
487         current_delta = (pos - sess_pos);
488
489         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
490                                                  speed, pos, last_ltc_frame, elapsed, current_delta));
491
492         if (last_timestamp != 0 /* && frames_in_sequence > 8*/) {
493                 delayedlocked = 0;
494         }
495
496         if (last_timestamp == 0 || ((now - last_timestamp) > FLYWHEEL_TIMEOUT)) {
497                 DEBUG_TRACE (DEBUG::LTC, "LTC no-signal - reset\n");
498                 reset();
499                 engine_dll_initstate = 0;
500                 speed = 0;
501                 pos = session.transport_frame();
502                 return true;
503         }
504
505         if (last_timestamp != 0  && ltc_speed != 0 && ((ltc_transport_pos < 0) || (labs(current_delta) > 10 * session.frame_rate()))) {
506                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift. %1\n", current_delta));
507                 // XXX only re-init engine DLL ?
508                 reset();
509                 engine_dll_initstate = 0;
510                 speed = 0;
511                 pos = session.transport_frame();
512                 return true;
513         }
514
515 #if 1
516         /* provide a 1% deadzone to lock the speed */
517         if (fabs(speed - 1.0) <= 0.01)
518                 speed = 1.0;
519 #endif
520
521         return true;
522 }
523
524 Timecode::TimecodeFormat
525 LTC_Slave::apparent_timecode_format () const
526 {
527         if      (timecode.rate == 24 && !timecode.drop)
528                 return timecode_24;
529         else if (timecode.rate == 25 && !timecode.drop)
530                 return timecode_25;
531         else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
532                 return timecode_2997;
533         else if (rint(timecode.rate * 100) == 2997 &&  timecode.drop)
534                 return timecode_2997drop;
535         else if (timecode.rate == 30 &&  timecode.drop)
536                 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
537         else if (timecode.rate == 30 && !timecode.drop)
538                 return timecode_30;
539
540         /* XXX - unknown timecode format */
541         return session.config.get_timecode_format();
542 }
543
544 std::string
545 LTC_Slave::approximate_current_position() const
546 {
547         if (last_timestamp == 0) {
548                 return " --:--:--:--";
549         }
550         return Timecode::timecode_format_time(timecode);
551 }
552
553 std::string
554 LTC_Slave::approximate_current_delta() const
555 {
556         char delta[24];
557         if (last_timestamp == 0 || frames_in_sequence < 2) {
558                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
559         } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
560                 snprintf(delta, sizeof(delta), "flywheel");
561         } else {
562                 // TODO if current_delta > 1 frame -> display timecode.
563                 // delta >0 if A3's transport is _behind_ LTC
564                 snprintf(delta, sizeof(delta), "%s%4" PRIi64 " sm",
565                                 PLUSMINUS(-current_delta), abs(current_delta));
566         }
567         return std::string(delta);
568 }