Merge remote-tracking branch 'remotes/origin/cairocanvas' into windows
[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 <sys/types.h>
23 #include <unistd.h>
24
25 #include "pbd/error.h"
26 #include "pbd/pthread_utils.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 == "timecode-format"
99                         ) {
100                 parse_timecode_offset();
101         }
102 }
103
104 ARDOUR::framecnt_t
105 LTC_Slave::resolution () const
106 {
107         return (framecnt_t) (session.frame_rate() / 1000);
108 }
109
110 bool
111 LTC_Slave::locked () const
112 {
113         return (delayedlocked < 5);
114 }
115
116 bool
117 LTC_Slave::ok() const
118 {
119         return true;
120 }
121
122 void
123 LTC_Slave::resync_xrun()
124 {
125         DEBUG_TRACE (DEBUG::LTC, "LTC resync_xrun()\n");
126         engine_dll_initstate = 0;
127 }
128
129 void
130 LTC_Slave::resync_latency()
131 {
132         DEBUG_TRACE (DEBUG::LTC, "LTC resync_latency()\n");
133         engine_dll_initstate = 0;
134
135         if (!session.deletion_in_progress() && session.ltc_output_io()) { /* check if Port exits */
136                 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
137                 ltcport->get_connected_latency_range (ltc_slave_latency, false);
138         }
139 }
140
141 void
142 LTC_Slave::reset()
143 {
144         DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
145         last_timestamp = 0;
146         current_delta = 0;
147         transport_direction = 0;
148         ltc_speed = 0;
149         engine_dll_initstate = 0;
150 }
151
152 void
153 LTC_Slave::parse_ltc(const ARDOUR::pframes_t nframes, const Sample* const in, const ARDOUR::framecnt_t posinfo)
154 {
155         pframes_t i;
156         unsigned char sound[8192];
157         if (nframes > 8192) {
158                 /* TODO warn once or wrap, loop conversion below
159                  * does jack/A3 support > 8192 spp anyway?
160                  */
161                 return;
162         }
163
164         for (i = 0; i < nframes; i++) {
165                 const int snd=(int)rint((127.0*in[i])+128.0);
166                 sound[i] = (unsigned char) (snd&0xff);
167         }
168         ltc_decoder_write(decoder, sound, nframes, posinfo);
169         return;
170 }
171
172 bool
173 LTC_Slave::equal_ltc_frame_time(LTCFrame *a, LTCFrame *b) {
174         if (       a->frame_units != b->frame_units
175                 || a->frame_tens  != b->frame_tens
176                 || a->dfbit       != b->dfbit
177                 || a->secs_units  != b->secs_units
178                 || a->secs_tens   != b->secs_tens
179                 || a->mins_units  != b->mins_units
180                 || a->mins_tens   != b->mins_tens
181                 || a->hours_units != b->hours_units
182                 || a->hours_tens  != b->hours_tens
183              ) {
184                 return false;
185         }
186         return true;
187 }
188
189 bool
190 LTC_Slave::detect_discontinuity(LTCFrameExt *frame, int fps, bool fuzzy) {
191         bool discontinuity_detected = false;
192
193         if (fuzzy && (
194                   ( frame->reverse && prev_frame.ltc.frame_units == 0)
195                 ||(!frame->reverse && frame->ltc.frame_units == 0)
196                 )) {
197                 memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
198                 return false;
199         }
200
201         if (frame->reverse) {
202                 ltc_frame_decrement(&prev_frame.ltc, fps, LTC_TV_525_60, 0);
203         } else {
204                 ltc_frame_increment(&prev_frame.ltc, fps, LTC_TV_525_60, 0);
205         }
206         if (!equal_ltc_frame_time(&prev_frame.ltc, &frame->ltc)) {
207                 discontinuity_detected = true;
208         }
209
210     memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
211     return discontinuity_detected;
212 }
213
214 bool
215 LTC_Slave::detect_ltc_fps(int frameno, bool df)
216 {
217         bool fps_changed = false;
218         double detected_fps = 0;
219         if (frameno > ltc_detect_fps_max)
220         {
221                 ltc_detect_fps_max = frameno;
222         }
223         ltc_detect_fps_cnt++;
224
225         if (ltc_detect_fps_cnt > 40) {
226                 if (ltc_detect_fps_cnt > ltc_detect_fps_max) {
227                         detected_fps = ltc_detect_fps_max + 1;
228                         if (df) {
229                                 /* LTC df -> indicates fractional framerate */
230                                 if (Config->get_timecode_source_2997()) {
231                                         detected_fps = detected_fps * 999.0 / 1000.0;
232                                 } else {
233                                         detected_fps = detected_fps * 1000.0 / 1001.0;
234                                 }
235                         }
236
237                         if (timecode.rate != detected_fps || timecode.drop != df) {
238                                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
239                         } else {
240                                 detected_fps = 0; /* no cange */
241                         }
242                 }
243                 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
244         }
245
246         /* when changed */
247         if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
248                 timecode.rate = detected_fps;
249                 timecode.drop = df;
250                 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
251                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
252                                 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
253                 fps_changed=true;
254         }
255
256         /* poll and check session TC */
257         TimecodeFormat tc_format = apparent_timecode_format();
258         TimecodeFormat cur_timecode = session.config.get_timecode_format();
259
260         if (Config->get_timecode_sync_frame_rate()) {
261                 /* enforce time-code */
262                 if (!did_reset_tc_format) {
263                         saved_tc_format = cur_timecode;
264                         did_reset_tc_format = true;
265                 }
266                 if (cur_timecode != tc_format) {
267                         if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
268                                 warning << string_compose(_("Session framerate adjusted from %1 to LTC's %2."),
269                                                 Timecode::timecode_format_name(cur_timecode),
270                                                 Timecode::timecode_format_name(tc_format))
271                                         << endmsg;
272                         }
273                         session.config.set_timecode_format (tc_format);
274                 }
275         } else {
276                 /* only warn about TC mismatch */
277                 if (ltc_timecode != tc_format) printed_timecode_warning = false;
278                 if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
279
280                 if (cur_timecode != tc_format && ! printed_timecode_warning) {
281                         if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
282                                 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
283                                                 Timecode::timecode_format_name(tc_format),
284                                                 Timecode::timecode_format_name(cur_timecode))
285                                         << endmsg;
286                         }
287                         printed_timecode_warning = true;
288                 }
289         }
290         ltc_timecode = tc_format;
291         a3e_timecode = cur_timecode;
292
293         return fps_changed;
294 }
295
296 void
297 LTC_Slave::process_ltc(framepos_t const /*now*/)
298 {
299         LTCFrameExt frame;
300         enum LTC_TV_STANDARD tv_standard = LTC_TV_625_50;
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
341                 switch(fps_i) {
342                         case 30:
343                                 if (timecode.drop) {
344                                         tv_standard = LTC_TV_525_60;
345                                 } else {
346                                         tv_standard = LTC_TV_1125_60;
347                                 }
348                                 break;
349                         case 25:
350                                 tv_standard = LTC_TV_625_50;
351                                 break;
352                         default:
353                                 tv_standard = LTC_TV_FILM_24; /* == LTC_TV_1125_60 == no offset, 24,30fps BGF */
354                                 break;
355                 }
356
357                 if (!frame.reverse) {
358                         ltc_frame_increment(&frame.ltc, fps_i, tv_standard, 0);
359                         ltc_frame_to_time(&stime, &frame.ltc, 0);
360                         transport_direction = 1;
361                         frame.off_start -= ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
362                         frame.off_end -= ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
363                 } else {
364                         ltc_frame_decrement(&frame.ltc, fps_i, tv_standard, 0);
365                         int off = frame.off_end - frame.off_start;
366                         frame.off_start += off - ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
367                         frame.off_end += off - ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
368                         transport_direction = -1;
369                 }
370
371                 timecode.hours   = stime.hours;
372                 timecode.minutes = stime.mins;
373                 timecode.seconds = stime.secs;
374                 timecode.frames  = stime.frame;
375
376                 /* map LTC timecode to session TC setting */
377                 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
378                 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
379                         double(session.frame_rate()),
380                         session.config.get_subframes_per_frame(),
381                         timecode_negative_offset, timecode_offset
382                         );
383
384                 framepos_t cur_timestamp = frame.off_end + 1;
385                 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));
386                 if (frame.off_end + 1 <= last_timestamp || last_timestamp == 0) {
387                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: UNCHANGED: %1\n", ltc_speed));
388                 } else {
389                         ltc_speed = double(ltc_frame - last_ltc_frame) / double(cur_timestamp - last_timestamp);
390                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: %1\n", ltc_speed));
391                 }
392
393                 if (fabs(ltc_speed) > 10.0) {
394                         ltc_speed = 0;
395                 }
396
397                 last_timestamp = frame.off_end + 1;
398                 last_ltc_frame = ltc_frame;
399         } /* end foreach decoded LTC frame */
400 }
401
402 void
403 LTC_Slave::init_engine_dll (framepos_t pos, int32_t inc)
404 {
405         double omega = 2.0 * M_PI * double(inc) / double(session.frame_rate());
406         b = 1.4142135623730950488 * omega;
407         c = omega * omega;
408
409         e2 = double(ltc_speed * inc);
410         t0 = double(pos);
411         t1 = t0 + e2;
412         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", t0, t1, e2));
413 }
414
415 /* main entry point from session_process.cc
416  * called from process callback context
417  * so it is OK to use get_buffer()
418  */
419 bool
420 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
421 {
422         bool engine_init_called = false;
423         framepos_t now = session.engine().sample_time_at_cycle_start();
424         framepos_t sess_pos = session.transport_frame(); // corresponds to now
425         framecnt_t nframes = session.engine().samples_per_cycle();
426
427         Sample* in;
428
429         boost::shared_ptr<Port> ltcport = session.ltc_input_port();
430
431         in = (Sample*) AudioEngine::instance()->port_engine().get_buffer (ltcport->port_handle(), nframes);
432
433         frameoffset_t skip = now - (monotonic_cnt + nframes);
434         monotonic_cnt = now;
435         DEBUG_TRACE (DEBUG::LTC, string_compose ("speed_and_position - TID:%1 | latency: %2 | skip %3\n", pthread_name(), ltc_slave_latency.max, skip));
436
437         if (last_timestamp == 0) {
438                 engine_dll_initstate = 0;
439                 delayedlocked++;
440         }
441         else if (engine_dll_initstate != transport_direction && ltc_speed != 0) {
442                 engine_dll_initstate = transport_direction;
443                 init_engine_dll(last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp)),
444                                 session.engine().samples_per_cycle());
445                 engine_init_called = true;
446         }
447
448         if (in) {
449                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
450                 /* when the jack-graph changes and if ardour performs
451                  * locates, the audioengine is stopped (skipping frames) while
452                  * jack [time] moves along.
453                  */
454                 if (skip > 0) {
455                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames. Feeding silence to LTC parser.\n", skip));
456                         if (skip >= 8192) skip = 8192;
457                         unsigned char sound[8192];
458                         memset(sound, 0, sizeof(char) * skip);
459                         ltc_decoder_write(decoder, sound, nframes, now);
460                 } else if (skip != 0) {
461                         /* this should never happen. it may if monotonic_cnt, now overflow on 64bit */
462                         DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames\n", skip));
463                         reset();
464                 }
465
466                 parse_ltc(nframes, in, now - ltc_slave_latency.max );
467                 process_ltc(now);
468         }
469
470         if (last_timestamp == 0) {
471                 DEBUG_TRACE (DEBUG::LTC, "last timestamp == 0\n");
472                 speed = 0;
473                 pos = session.transport_frame();
474                 return true;
475         } else if (ltc_speed != 0) {
476                 delayedlocked = 0;
477         }
478
479         if (abs(now - last_timestamp) > FLYWHEEL_TIMEOUT) {
480                 DEBUG_TRACE (DEBUG::LTC, "flywheel timeout\n");
481                 reset();
482                 speed = 0;
483                 pos = session.transport_frame();
484                 return true;
485         }
486
487         /* it take 2 cycles from naught to rolling.
488          * during these to initial cycles the speed == 0
489          *
490          * the first cycle:
491          * DEBUG::Slave: slave stopped, move to NNN
492          * DEBUG::Transport: Request forced locate to NNN
493          * DEBUG::Slave: slave state 0 @ NNN speed 0 cur delta VERY-LARGE-DELTA avg delta 1800
494          * DEBUG::Slave: silent motion
495          * DEBUG::Transport: realtime stop @ NNN
496          * DEBUG::Transport: Butler transport work, todo = PostTransportStop,PostTransportLocate,PostTransportClearSubstate
497          *
498          * [engine skips frames to locate, jack time keeps rolling on]
499          *
500          * the second cycle:
501          *
502          * DEBUG::LTC: [re-]init Engine DLL
503          * DEBUG::Slave: slave stopped, move to NNN+
504          * ...
505          *
506          * we need to seek two cycles ahead: 2 * nframes
507          */
508         if (engine_dll_initstate == 0) {
509                 DEBUG_TRACE (DEBUG::LTC, "engine DLL not initialized. ltc_speed\n");
510                 speed = 0;
511                 pos = last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp));
512                 return true;
513         }
514
515         /* interpolate position according to speed and time since last LTC-frame*/
516         double speed_flt = ltc_speed;
517         double elapsed = (now - last_timestamp) * speed_flt;
518
519         if (!engine_init_called) {
520                 const double e = elapsed + double (last_ltc_frame - sess_pos);
521                 t0 = t1;
522                 t1 += b * e + e2;
523                 e2 += c * e;
524                 speed_flt = (t1 - t0) / double(session.engine().samples_per_cycle());
525                 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().samples_per_cycle() ));
526         } else {
527                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC adjusting elapsed (no DLL) from %1 by %2\n", elapsed, (2 * nframes * ltc_speed)));
528                 speed_flt = 0;
529                 elapsed += 2.0 * nframes * ltc_speed; /* see note above */
530         }
531
532         pos = last_ltc_frame + rint(elapsed);
533         speed = speed_flt;
534         current_delta = (pos - sess_pos);
535
536         if (((pos < 0) || (labs(current_delta) > 2 * session.frame_rate()))) {
537                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift: %1\n", current_delta));
538                 reset();
539                 speed = 0;
540                 pos = session.transport_frame();
541                 return true;
542         }
543
544         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
545                                                  speed, pos, last_ltc_frame, elapsed, current_delta));
546
547         /* provide a .1% deadzone to lock the speed */
548         if (fabs(speed - 1.0) <= 0.001) {
549                 speed = 1.0;
550         }
551
552         return true;
553 }
554
555 Timecode::TimecodeFormat
556 LTC_Slave::apparent_timecode_format () const
557 {
558         if      (timecode.rate == 24 && !timecode.drop)
559                 return timecode_24;
560         else if (timecode.rate == 25 && !timecode.drop)
561                 return timecode_25;
562         else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
563                 return (Config->get_timecode_source_2997() ? timecode_2997000 : timecode_2997);
564         else if (rint(timecode.rate * 100) == 2997 &&  timecode.drop)
565                 return (Config->get_timecode_source_2997() ? timecode_2997000drop : timecode_2997drop);
566         else if (timecode.rate == 30 &&  timecode.drop)
567                 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
568         else if (timecode.rate == 30 && !timecode.drop)
569                 return timecode_30;
570
571         /* XXX - unknown timecode format */
572         return session.config.get_timecode_format();
573 }
574
575 std::string
576 LTC_Slave::approximate_current_position() const
577 {
578         if (last_timestamp == 0) {
579                 return " --:--:--:--";
580         }
581         return Timecode::timecode_format_time(timecode);
582 }
583
584 std::string
585 LTC_Slave::approximate_current_delta() const
586 {
587         char delta[80];
588         if (last_timestamp == 0 || engine_dll_initstate == 0) {
589                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
590         } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
591                 snprintf(delta, sizeof(delta), "%s", _("flywheel"));
592         } else {
593                 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
594                                 LEADINGZERO(llabs(current_delta)), PLUSMINUS(-current_delta), llabs(current_delta));
595         }
596         return std::string(delta);
597 }