update to libltc-1.1.0
[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, LTC_TV_525_60, 0);
204         } else {
205                 ltc_frame_increment(&prev_frame.ltc, fps, LTC_TV_525_60, 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         enum LTC_TV_STANDARD tv_standard = LTC_TV_625_50;
302         while (ltc_decoder_read(decoder, &frame)) {
303                 SMPTETimecode stime;
304
305                 ltc_frame_to_time(&stime, &frame.ltc, 0);
306                 timecode.negative  = false;
307                 timecode.subframes  = 0;
308
309                 /* set timecode.rate and timecode.drop: */
310                 bool ltc_is_static = equal_ltc_frame_time(&prev_frame.ltc, &frame.ltc);
311
312                 if (detect_discontinuity(&frame, ceil(timecode.rate), !fps_detected)) {
313                         if (fps_detected) { ltc_detect_fps_cnt = ltc_detect_fps_max = 0; }
314                         fps_detected=false;
315                 }
316
317                 if (!ltc_is_static && detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false)) {
318                         reset();
319                         fps_detected=true;
320                 }
321
322 #if 0 // Devel/Debug
323                 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
324                         stime.hours,
325                         stime.mins,
326                         stime.secs,
327                         (frame.ltc.dfbit) ? '.' : ':',
328                         stime.frame,
329                         frame.off_start,
330                         frame.off_end,
331                         frame.reverse ? " R" : "  "
332                         );
333 #endif
334
335                 /* when a full LTC frame is decoded, the timecode the LTC frame
336                  * is referring has just passed.
337                  * So we send the _next_ timecode which
338                  * is expected to start at the end of the current frame
339                  */
340                 int fps_i = ceil(timecode.rate);
341
342                 switch(fps_i) {
343                         case 30:
344                                 if (timecode.drop) {
345                                         tv_standard = LTC_TV_525_60;
346                                 } else {
347                                         tv_standard = LTC_TV_1125_60;
348                                 }
349                                 break;
350                         case 25:
351                                 tv_standard = LTC_TV_625_50;
352                                 break;
353                         default:
354                                 tv_standard = LTC_TV_FILM_24; /* == LTC_TV_1125_60 == no offset, 24,30fps BGF */
355                                 break;
356                 }
357
358                 if (!frame.reverse) {
359                         ltc_frame_increment(&frame.ltc, fps_i, tv_standard, 0);
360                         ltc_frame_to_time(&stime, &frame.ltc, 0);
361                         transport_direction = 1;
362                         frame.off_start -= ltc_frame_alignment(session.frame_rate(), tv_standard);
363                         frame.off_end -= ltc_frame_alignment(session.frame_rate(), tv_standard);
364                 } else {
365                         ltc_frame_decrement(&frame.ltc, fps_i, tv_standard, 0);
366                         int off = frame.off_end - frame.off_start;
367                         frame.off_start += off - ltc_frame_alignment(session.frame_rate(), tv_standard);
368                         frame.off_end += off - ltc_frame_alignment(session.frame_rate(), tv_standard);
369                         transport_direction = -1;
370                 }
371
372                 timecode.hours   = stime.hours;
373                 timecode.minutes = stime.mins;
374                 timecode.seconds = stime.secs;
375                 timecode.frames  = stime.frame;
376
377                 /* map LTC timecode to session TC setting */
378                 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
379                 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
380                         double(session.frame_rate()),
381                         session.config.get_subframes_per_frame(),
382                         timecode_negative_offset, timecode_offset
383                         );
384
385                 framepos_t cur_timestamp = frame.off_end + 1;
386                 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));
387                 if (frame.off_end + 1 <= last_timestamp || last_timestamp == 0) {
388                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: UNCHANGED: %1\n", ltc_speed));
389                 } else {
390                         ltc_speed = double(ltc_frame - last_ltc_frame) / double(cur_timestamp - last_timestamp);
391                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: %1\n", ltc_speed));
392                 }
393
394                 if (fabs(ltc_speed) > 10.0) {
395                         ltc_speed = 0;
396                 }
397
398                 last_timestamp = frame.off_end + 1;
399                 last_ltc_frame = ltc_frame;
400         } /* end foreach decoded LTC frame */
401 }
402
403 void
404 LTC_Slave::init_engine_dll (framepos_t pos, int32_t inc)
405 {
406         double omega = 2.0 * M_PI * double(inc) / double(session.frame_rate());
407         b = 1.4142135623730950488 * omega;
408         c = omega * omega;
409
410         e2 = double(ltc_speed * inc);
411         t0 = double(pos);
412         t1 = t0 + e2;
413         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", t0, t1, e2));
414 }
415
416 /* main entry point from session_process.cc
417  * called from jack_process callback context
418  * so it is OK to use jack_port_get_buffer()
419  */
420 bool
421 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
422 {
423         bool engine_init_called = false;
424         framepos_t now = session.engine().frame_time_at_cycle_start();
425         framepos_t sess_pos = session.transport_frame(); // corresponds to now
426         framecnt_t nframes = session.engine().frames_per_cycle();
427
428         jack_default_audio_sample_t *in;
429
430         boost::shared_ptr<Port> ltcport = session.ltc_input_port();
431
432         in = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
433
434         frameoffset_t skip = now - (monotonic_cnt + nframes);
435         monotonic_cnt = now;
436         DEBUG_TRACE (DEBUG::LTC, string_compose ("speed_and_position - TID:%1 | latency: %2 | skip %3\n", ::pthread_self(), ltc_slave_latency.max, skip));
437
438         if (last_timestamp == 0) {
439                 engine_dll_initstate = 0;
440                 delayedlocked++;
441         }
442         else if (engine_dll_initstate != transport_direction && ltc_speed != 0) {
443                 engine_dll_initstate = transport_direction;
444                 init_engine_dll(last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp)),
445                                 session.engine().frames_per_cycle());
446                 engine_init_called = true;
447         }
448
449         if (in) {
450                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
451                 /* when the jack-graph changes and if ardour performs
452                  * locates, the audioengine is stopped (skipping frames) while
453                  * jack [time] moves along.
454                  */
455                 if (skip > 0) {
456                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames. Feeding silence to LTC parser.\n", skip));
457                         if (skip >= 8192) skip = 8192;
458                         unsigned char sound[8192];
459                         memset(sound, 0, sizeof(char) * skip);
460                         ltc_decoder_write(decoder, sound, nframes, now);
461                 } else if (skip != 0) {
462                         /* this should never happen. it may if monotonic_cnt, now overflow on 64bit */
463                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames\n", skip));
464                         reset();
465                 }
466
467                 parse_ltc(nframes, in, now - ltc_slave_latency.max );
468                 process_ltc(now);
469         }
470
471         if (last_timestamp == 0) {
472                 DEBUG_TRACE (DEBUG::LTC, "last timestamp == 0\n");
473                 speed = 0;
474                 pos = session.transport_frame();
475                 return true;
476         } else if (ltc_speed != 0) {
477                 delayedlocked = 0;
478         }
479
480         if (abs(now - last_timestamp) > FLYWHEEL_TIMEOUT) {
481                 DEBUG_TRACE (DEBUG::LTC, "flywheel timeout\n");
482                 reset();
483                 speed = 0;
484                 pos = session.transport_frame();
485                 return true;
486         }
487
488         /* it take 2 cycles from naught to rolling.
489          * during these to initial cycles the speed == 0
490          *
491          * the first cycle:
492          * DEBUG::Slave: slave stopped, move to NNN
493          * DEBUG::Transport: Request forced locate to NNN
494          * DEBUG::Slave: slave state 0 @ NNN speed 0 cur delta VERY-LARGE-DELTA avg delta 1800
495          * DEBUG::Slave: silent motion
496          * DEBUG::Transport: realtime stop @ NNN
497          * DEBUG::Transport: Butler transport work, todo = PostTransportStop,PostTransportLocate,PostTransportClearSubstate
498          *
499          * [engine skips frames to locate, jack time keeps rolling on]
500          *
501          * the second cycle:
502          *
503          * DEBUG::LTC: [re-]init Engine DLL
504          * DEBUG::Slave: slave stopped, move to NNN+
505          * ...
506          *
507          * we need to seek two cycles ahead: 2 * nframes
508          */
509         if (engine_dll_initstate == 0) {
510                 DEBUG_TRACE (DEBUG::LTC, "engine DLL not initialized. ltc_speed\n");
511                 speed = 0;
512                 pos = last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp));
513                 return true;
514         }
515
516         /* interpolate position according to speed and time since last LTC-frame*/
517         double speed_flt = ltc_speed;
518         double elapsed = (now - last_timestamp) * speed_flt;
519
520         if (!engine_init_called) {
521                 const double e = elapsed + double (last_ltc_frame - sess_pos);
522                 t0 = t1;
523                 t1 += b * e + e2;
524                 e2 += c * e;
525                 speed_flt = (t1 - t0) / double(session.engine().frames_per_cycle());
526                 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() ));
527         } else {
528                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC adjusting elapsed (no DLL) from %1 by %2\n", elapsed, (2 * nframes * ltc_speed)));
529                 speed_flt = 0;
530                 elapsed += 2.0 * nframes * ltc_speed; /* see note above */
531         }
532
533         pos = last_ltc_frame + rint(elapsed);
534         speed = speed_flt;
535         current_delta = (pos - sess_pos);
536
537         if (((pos < 0) || (labs(current_delta) > 2 * session.frame_rate()))) {
538                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift: %1\n", current_delta));
539                 reset();
540                 speed = 0;
541                 pos = session.transport_frame();
542                 return true;
543         }
544
545         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
546                                                  speed, pos, last_ltc_frame, elapsed, current_delta));
547
548         /* provide a .1% deadzone to lock the speed */
549         if (fabs(speed - 1.0) <= 0.001) {
550                 speed = 1.0;
551         }
552
553         return true;
554 }
555
556 Timecode::TimecodeFormat
557 LTC_Slave::apparent_timecode_format () const
558 {
559         if      (timecode.rate == 24 && !timecode.drop)
560                 return timecode_24;
561         else if (timecode.rate == 25 && !timecode.drop)
562                 return timecode_25;
563         else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
564                 return (Config->get_timecode_source_2997() ? timecode_2997000 : timecode_2997);
565         else if (rint(timecode.rate * 100) == 2997 &&  timecode.drop)
566                 return (Config->get_timecode_source_2997() ? timecode_2997000drop : timecode_2997drop);
567         else if (timecode.rate == 30 &&  timecode.drop)
568                 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
569         else if (timecode.rate == 30 && !timecode.drop)
570                 return timecode_30;
571
572         /* XXX - unknown timecode format */
573         return session.config.get_timecode_format();
574 }
575
576 std::string
577 LTC_Slave::approximate_current_position() const
578 {
579         if (last_timestamp == 0) {
580                 return " \u2012\u2012:\u2012\u2012:\u2012\u2012:\u2012\u2012";
581         }
582         return Timecode::timecode_format_time(timecode);
583 }
584
585 std::string
586 LTC_Slave::approximate_current_delta() const
587 {
588         char delta[80];
589         if (last_timestamp == 0 || engine_dll_initstate == 0) {
590                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
591         } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
592                 snprintf(delta, sizeof(delta), _("flywheel"));
593         } else {
594                 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span> sm",
595                                 LEADINGZERO(abs(current_delta)), PLUSMINUS(-current_delta), abs(current_delta));
596         }
597         return std::string(delta);
598 }