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