7b182cfa64949a8bf2e5176327fc5d013f4f035e
[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 ( 1 * 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();
48         timecode.rate = session.timecode_frames_per_second();
49         timecode.drop  = session.timecode_drop_frames();
50
51         did_reset_tc_format = false;
52         delayedlocked = 10;
53         monotonic_cnt = 0;
54         fps_detected=false;
55
56         ltc_timecode = session.config.get_timecode_format();
57         a3e_timecode = session.config.get_timecode_format();
58         printed_timecode_warning = false;
59         ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
60         memset(&prev_frame, 0, sizeof(LTCFrameExt));
61
62         decoder = ltc_decoder_create((int) frames_per_ltc_frame, 128 /*queue size*/);
63
64         session.config.ParameterChanged.connect_same_thread (config_connection, boost::bind (&LTC_Slave::parameter_changed, this, _1));
65         parse_timecode_offset();
66         reset();
67         resync_latency();
68         session.Xrun.connect_same_thread (port_connections, boost::bind (&LTC_Slave::resync_xrun, this));
69         session.engine().GraphReordered.connect_same_thread (port_connections, boost::bind (&LTC_Slave::resync_latency, this));
70 }
71
72 LTC_Slave::~LTC_Slave()
73 {
74         port_connections.drop_connections();
75         config_connection.disconnect();
76
77         if (did_reset_tc_format) {
78                 session.config.set_timecode_format (saved_tc_format);
79         }
80
81         ltc_decoder_free(decoder);
82 }
83
84 void
85 LTC_Slave::parse_timecode_offset() {
86         Timecode::Time offset_tc;
87         Timecode::parse_timecode_format(session.config.get_slave_timecode_offset(), offset_tc);
88         offset_tc.rate = session.timecode_frames_per_second();
89         offset_tc.drop = session.timecode_drop_frames();
90         session.timecode_to_sample(offset_tc, timecode_offset, false, false);
91         timecode_negative_offset = offset_tc.negative;
92 }
93
94 void
95 LTC_Slave::parameter_changed (std::string const & p)
96 {
97         if (p == "slave-timecode-offset"
98                         || p == "subframes-per-frame"
99                         || p == "timecode-format"
100                         ) {
101                 parse_timecode_offset();
102         }
103 }
104
105 ARDOUR::framecnt_t
106 LTC_Slave::resolution () const
107 {
108         return (framecnt_t) (session.frame_rate() / 1000);
109 }
110
111 bool
112 LTC_Slave::locked () const
113 {
114         return (delayedlocked < 5);
115 }
116
117 bool
118 LTC_Slave::ok() const
119 {
120         return true;
121 }
122
123 void
124 LTC_Slave::resync_xrun()
125 {
126         DEBUG_TRACE (DEBUG::LTC, "LTC resync_xrun()\n");
127         engine_dll_initstate = 0;
128 }
129
130 void
131 LTC_Slave::resync_latency()
132 {
133         DEBUG_TRACE (DEBUG::LTC, "LTC resync_latency()\n");
134         engine_dll_initstate = 0;
135
136         if (!session.deletion_in_progress() && session.ltc_output_io()) { /* check if Port exits */
137                 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
138                 ltcport->get_connected_latency_range(ltc_slave_latency, false);
139         }
140 }
141
142 void
143 LTC_Slave::reset()
144 {
145         DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
146         last_timestamp = 0;
147         current_delta = 0;
148         transport_direction = 0;
149         ltc_speed = 0;
150         engine_dll_initstate = 0;
151 }
152
153 void
154 LTC_Slave::parse_ltc(const jack_nframes_t nframes, const jack_default_audio_sample_t * const in, const framecnt_t posinfo)
155 {
156         jack_nframes_t i;
157         unsigned char sound[8192];
158         if (nframes > 8192) {
159                 /* TODO warn once or wrap, loop conversion below
160                  * does jack/A3 support > 8192 spp anyway?
161                  */
162                 return;
163         }
164
165         for (i = 0; i < nframes; i++) {
166                 const int snd=(int)rint((127.0*in[i])+128.0);
167                 sound[i] = (unsigned char) (snd&0xff);
168         }
169         ltc_decoder_write(decoder, sound, nframes, posinfo);
170         return;
171 }
172
173 bool
174 LTC_Slave::equal_ltc_frame_time(LTCFrame *a, LTCFrame *b) {
175         if (       a->frame_units != b->frame_units
176                 || a->frame_tens  != b->frame_tens
177                 || a->dfbit       != b->dfbit
178                 || a->secs_units  != b->secs_units
179                 || a->secs_tens   != b->secs_tens
180                 || a->mins_units  != b->mins_units
181                 || a->mins_tens   != b->mins_tens
182                 || a->hours_units != b->hours_units
183                 || a->hours_tens  != b->hours_tens
184              ) {
185                 return false;
186         }
187         return true;
188 }
189
190 bool
191 LTC_Slave::detect_discontinuity(LTCFrameExt *frame, int fps, bool fuzzy) {
192         bool discontinuity_detected = false;
193
194         if (fuzzy && (
195                   ( frame->reverse && prev_frame.ltc.frame_units == 0)
196                 ||(!frame->reverse && frame->ltc.frame_units == 0)
197                 )) {
198                 memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
199                 return false;
200         }
201
202         if (frame->reverse) {
203                 ltc_frame_decrement(&prev_frame.ltc, fps , 0);
204         } else {
205                 ltc_frame_increment(&prev_frame.ltc, fps , 0);
206         }
207         if (!equal_ltc_frame_time(&prev_frame.ltc, &frame->ltc)) {
208                 discontinuity_detected = true;
209         }
210
211     memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
212     return discontinuity_detected;
213 }
214
215 bool
216 LTC_Slave::detect_ltc_fps(int frameno, bool df)
217 {
218         bool fps_changed = false;
219         double detected_fps = 0;
220         if (frameno > ltc_detect_fps_max)
221         {
222                 ltc_detect_fps_max = frameno;
223         }
224         ltc_detect_fps_cnt++;
225
226         if (ltc_detect_fps_cnt > 40) {
227                 if (ltc_detect_fps_cnt > ltc_detect_fps_max) {
228                         detected_fps = ltc_detect_fps_max + 1;
229                         if (df) {
230                                 /* LTC df -> indicates fractional framerate */
231                                 if (Config->get_timecode_source_2997()) {
232                                         detected_fps = detected_fps * 999.0 / 1000.0;
233                                 } else {
234                                         detected_fps = detected_fps * 1000.0 / 1001.0;
235                                 }
236                         }
237
238                         if (timecode.rate != detected_fps || timecode.drop != df) {
239                                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
240                         } else {
241                                 detected_fps = 0; /* no cange */
242                         }
243                 }
244                 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
245         }
246
247         /* when changed */
248         if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
249                 timecode.rate = detected_fps;
250                 timecode.drop = df;
251                 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
252                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
253                                 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
254                 fps_changed=true;
255         }
256
257         /* poll and check session TC */
258         TimecodeFormat tc_format = apparent_timecode_format();
259         TimecodeFormat cur_timecode = session.config.get_timecode_format();
260
261         if (Config->get_timecode_sync_frame_rate()) {
262                 /* enforce time-code */
263                 if (!did_reset_tc_format) {
264                         saved_tc_format = cur_timecode;
265                         did_reset_tc_format = true;
266                 }
267                 if (cur_timecode != tc_format) {
268                         if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
269                                 warning << string_compose(_("Session framerate adjusted from %1 to LTC's %2."),
270                                                 Timecode::timecode_format_name(cur_timecode),
271                                                 Timecode::timecode_format_name(tc_format))
272                                         << endmsg;
273                         }
274                         session.config.set_timecode_format (tc_format);
275                 }
276         } else {
277                 /* only warn about TC mismatch */
278                 if (ltc_timecode != tc_format) printed_timecode_warning = false;
279                 if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
280
281                 if (cur_timecode != tc_format && ! printed_timecode_warning) {
282                         if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
283                                 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
284                                                 Timecode::timecode_format_name(tc_format),
285                                                 Timecode::timecode_format_name(cur_timecode))
286                                         << endmsg;
287                         }
288                         printed_timecode_warning = true;
289                 }
290         }
291         ltc_timecode = tc_format;
292         a3e_timecode = cur_timecode;
293
294         return fps_changed;
295 }
296
297 void
298 LTC_Slave::process_ltc(framepos_t const now)
299 {
300         LTCFrameExt frame;
301         while (ltc_decoder_read(decoder, &frame)) {
302                 SMPTETimecode stime;
303
304                 ltc_frame_to_time(&stime, &frame.ltc, 0);
305                 timecode.negative  = false;
306                 timecode.subframes  = 0;
307
308                 /* set timecode.rate and timecode.drop: */
309                 bool ltc_is_static = equal_ltc_frame_time(&prev_frame.ltc, &frame.ltc);
310
311                 if (detect_discontinuity(&frame, ceil(timecode.rate), !fps_detected)) {
312                         if (fps_detected) { ltc_detect_fps_cnt = ltc_detect_fps_max = 0; }
313                         fps_detected=false;
314                 }
315
316                 if (!ltc_is_static && detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false)) {
317                         reset();
318                         fps_detected=true;
319                 }
320
321 #if 0 // Devel/Debug
322                 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
323                         stime.hours,
324                         stime.mins,
325                         stime.secs,
326                         (frame.ltc.dfbit) ? '.' : ':',
327                         stime.frame,
328                         frame.off_start,
329                         frame.off_end,
330                         frame.reverse ? " R" : "  "
331                         );
332 #endif
333
334                 /* when a full LTC frame is decoded, the timecode the LTC frame
335                  * is referring has just passed.
336                  * So we send the _next_ timecode which
337                  * is expected to start at the end of the current frame
338                  */
339                 int fps_i = ceil(timecode.rate);
340                 if (!frame.reverse) {
341                         ltc_frame_increment(&frame.ltc, fps_i , 0);
342                         ltc_frame_to_time(&stime, &frame.ltc, 0);
343                         transport_direction = 1;
344                 } else {
345                         ltc_frame_decrement(&frame.ltc, fps_i , 0);
346                         int off = frame.off_end - frame.off_start;
347                         frame.off_start += off;
348                         frame.off_end += off;
349                         transport_direction = -1;
350                 }
351
352                 timecode.hours   = stime.hours;
353                 timecode.minutes = stime.mins;
354                 timecode.seconds = stime.secs;
355                 timecode.frames  = stime.frame;
356
357                 /* map LTC timecode to session TC setting */
358                 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
359                 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
360                         double(session.frame_rate()),
361                         session.config.get_subframes_per_frame(),
362                         timecode_negative_offset, timecode_offset
363                         );
364
365                 framepos_t cur_timestamp = frame.off_end + 1;
366                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC F: %1 LF: %2  N: %3 L: %4\n", ltc_frame, last_ltc_frame, cur_timestamp, last_timestamp));
367                 if (frame.off_end + 1 <= last_timestamp || last_timestamp == 0) {
368                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: UNCHANGED: %1\n", ltc_speed));
369                 } else {
370                         ltc_speed = double(ltc_frame - last_ltc_frame) / double(cur_timestamp - last_timestamp);
371                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: %1\n", ltc_speed));
372                 }
373
374                 if (fabs(ltc_speed) > 10.0) {
375                         ltc_speed = 0;
376                 }
377
378                 last_timestamp = frame.off_end + 1;
379                 last_ltc_frame = ltc_frame;
380         } /* end foreach decoded LTC frame */
381 }
382
383 void
384 LTC_Slave::init_engine_dll (framepos_t pos, int32_t inc)
385 {
386         double omega = 2.0 * M_PI * double(inc) / double(session.frame_rate());
387         b = 1.4142135623730950488 * omega;
388         c = omega * omega;
389
390         e2 = double(ltc_speed * inc);
391         t0 = double(pos);
392         t1 = t0 + e2;
393         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", t0, t1, e2));
394 }
395
396 /* main entry point from session_process.cc
397  * called from jack_process callback context
398  * so it is OK to use jack_port_get_buffer()
399  */
400 bool
401 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
402 {
403         bool engine_init_called = false;
404         framepos_t now = session.engine().frame_time_at_cycle_start();
405         framepos_t sess_pos = session.transport_frame(); // corresponds to now
406         framecnt_t nframes = session.engine().frames_per_cycle();
407
408         jack_default_audio_sample_t *in;
409
410         boost::shared_ptr<Port> ltcport = session.ltc_input_port();
411
412         in = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
413
414         frameoffset_t skip = now - (monotonic_cnt + nframes);
415         monotonic_cnt = now;
416         DEBUG_TRACE (DEBUG::LTC, string_compose ("speed_and_position - TID:%1 | latency: %2 | skip %3\n", ::pthread_self(), ltc_slave_latency.max, skip));
417
418         if (last_timestamp == 0) {
419                 engine_dll_initstate = 0;
420                 delayedlocked++;
421         }
422         else if (engine_dll_initstate != transport_direction && ltc_speed != 0) {
423                 engine_dll_initstate = transport_direction;
424                 init_engine_dll(last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp)),
425                                 session.engine().frames_per_cycle());
426                 engine_init_called = true;
427         }
428
429         if (in) {
430                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
431                 /* when the jack-graph changes and if ardour performs
432                  * locates, the audioengine is stopped (skipping frames) while
433                  * jack [time] moves along.
434                  */
435                 if (skip > 0) {
436                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames. Feeding silence to LTC parser.\n", skip));
437                         if (skip >= 8192) skip = 8192;
438                         unsigned char sound[8192];
439                         memset(sound, 0, sizeof(char) * skip);
440                         ltc_decoder_write(decoder, sound, nframes, now);
441                 } else if (skip != 0) {
442                         /* this should never happen. it may if monotonic_cnt, now overflow on 64bit */
443                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames\n", skip));
444                         reset();
445                 }
446
447                 parse_ltc(nframes, in, now - ltc_slave_latency.max );
448                 process_ltc(now);
449         }
450
451         if (last_timestamp == 0) {
452                 DEBUG_TRACE (DEBUG::LTC, "last timestamp == 0\n");
453                 speed = 0;
454                 pos = session.transport_frame();
455                 return true;
456         } else if (ltc_speed != 0) {
457                 delayedlocked = 0;
458         }
459
460         if (abs(now - last_timestamp) > FLYWHEEL_TIMEOUT) {
461                 DEBUG_TRACE (DEBUG::LTC, "flywheel timeout\n");
462                 reset();
463                 speed = 0;
464                 pos = session.transport_frame();
465                 return true;
466         }
467
468         /* it take 2 cycles from naught to rolling.
469          * during these to initial cycles the speed == 0
470          *
471          * the first cycle:
472          * DEBUG::Slave: slave stopped, move to NNN
473          * DEBUG::Transport: Request forced locate to NNN
474          * DEBUG::Slave: slave state 0 @ NNN speed 0 cur delta VERY-LARGE-DELTA avg delta 1800
475          * DEBUG::Slave: silent motion
476          * DEBUG::Transport: realtime stop @ NNN
477          * DEBUG::Transport: Butler transport work, todo = PostTransportStop,PostTransportLocate,PostTransportClearSubstate
478          *
479          * [engine skips frames to locate, jack time keeps rolling on]
480          *
481          * the second cycle:
482          *
483          * DEBUG::LTC: [re-]init Engine DLL
484          * DEBUG::Slave: slave stopped, move to NNN+
485          * ...
486          *
487          * we need to seek two cycles ahead: 2 * nframes
488          */
489         if (engine_dll_initstate == 0) {
490                 DEBUG_TRACE (DEBUG::LTC, "engine DLL not initialized. ltc_speed\n");
491                 speed = 0;
492                 pos = last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp));
493                 return true;
494         }
495
496         /* interpolate position according to speed and time since last LTC-frame*/
497         double speed_flt = ltc_speed;
498         double elapsed = (now - last_timestamp) * speed_flt;
499
500         if (!engine_init_called) {
501                 const double e = elapsed + double (last_ltc_frame - sess_pos);
502                 t0 = t1;
503                 t1 += b * e + e2;
504                 e2 += c * e;
505                 speed_flt = (t1 - t0) / double(session.engine().frames_per_cycle());
506                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC engine DLL t0:%1 t1:%2 err:%3 spd:%4 ddt:%5\n", t0, t1, e, speed_flt, e2 - session.engine().frames_per_cycle() ));
507         } else {
508                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC adjusting elapsed (no DLL) from %1 by %2\n", elapsed, (2 * nframes * ltc_speed)));
509                 speed_flt = 0;
510                 elapsed += 2.0 * nframes * ltc_speed; /* see note above */
511         }
512
513         pos = last_ltc_frame + rint(elapsed);
514         speed = speed_flt;
515         current_delta = (pos - sess_pos);
516
517         if (((pos < 0) || (labs(current_delta) > 2 * session.frame_rate()))) {
518                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift: %1\n", current_delta));
519                 reset();
520                 speed = 0;
521                 pos = session.transport_frame();
522                 return true;
523         }
524
525         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
526                                                  speed, pos, last_ltc_frame, elapsed, current_delta));
527
528         /* provide a .1% deadzone to lock the speed */
529         if (fabs(speed - 1.0) <= 0.001) {
530                 speed = 1.0;
531         }
532
533         return true;
534 }
535
536 Timecode::TimecodeFormat
537 LTC_Slave::apparent_timecode_format () const
538 {
539         if      (timecode.rate == 24 && !timecode.drop)
540                 return timecode_24;
541         else if (timecode.rate == 25 && !timecode.drop)
542                 return timecode_25;
543         else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
544                 return (Config->get_timecode_source_2997() ? timecode_2997000 : timecode_2997);
545         else if (rint(timecode.rate * 100) == 2997 &&  timecode.drop)
546                 return (Config->get_timecode_source_2997() ? timecode_2997000drop : timecode_2997drop);
547         else if (timecode.rate == 30 &&  timecode.drop)
548                 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
549         else if (timecode.rate == 30 && !timecode.drop)
550                 return timecode_30;
551
552         /* XXX - unknown timecode format */
553         return session.config.get_timecode_format();
554 }
555
556 std::string
557 LTC_Slave::approximate_current_position() const
558 {
559         if (last_timestamp == 0) {
560                 return " \u2012\u2012:\u2012\u2012:\u2012\u2012:\u2012\u2012";
561         }
562         return Timecode::timecode_format_time(timecode);
563 }
564
565 std::string
566 LTC_Slave::approximate_current_delta() const
567 {
568         char delta[80];
569         if (last_timestamp == 0 || engine_dll_initstate == 0) {
570                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
571         } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
572                 snprintf(delta, sizeof(delta), _("flywheel"));
573         } else {
574                 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span> sm",
575                                 LEADINGZERO(abs(current_delta)), PLUSMINUS(-current_delta), abs(current_delta));
576         }
577         return std::string(delta);
578 }