MTC Slave: allow >2 sec for re-sync, format delta
[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 LTC_Slave::LTC_Slave (Session& s)
43         : session (s)
44 {
45         frames_per_ltc_frame = session.frames_per_timecode_frame();
46         timecode.rate = session.timecode_frames_per_second();
47         timecode.drop  = session.timecode_drop_frames();
48
49         printf("LTC initial rate: %f %f\n", timecode.rate, frames_per_ltc_frame);
50
51         ltc_transport_pos = 0;
52         ltc_speed = 1.0;
53         last_timestamp = 0;
54         ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
55
56         ltc_timecode = timecode_60; // track changes of LTC timecode
57         a3e_timecode = timecode_60; // track canges of Ardour's timecode
58         printed_timecode_warning = false;
59
60         decoder = ltc_decoder_create((int) frames_per_ltc_frame, 128 /*queue size*/);
61 }
62
63 LTC_Slave::~LTC_Slave()
64 {
65         if (did_reset_tc_format) {
66                 session.config.set_timecode_format (saved_tc_format);
67         }
68
69         ltc_decoder_free(decoder);
70 }
71
72 bool
73 LTC_Slave::give_slave_full_control_over_transport_speed() const
74 {
75         return true; // DLL align to engine transport
76         // return false; // for Session-level computed varispeed
77 }
78
79 ARDOUR::framecnt_t
80 LTC_Slave::resolution () const
81 {
82         return (framecnt_t) (frames_per_ltc_frame);
83 }
84
85 ARDOUR::framecnt_t
86 LTC_Slave::seekahead_distance () const
87 {
88         return (framecnt_t) (frames_per_ltc_frame * 2);
89 }
90
91 bool
92 LTC_Slave::locked () const
93 {
94         return true; // TODO check if >2 sequential LTC frames have been received
95 }
96
97 bool
98 LTC_Slave::ok() const
99 {
100         return true;
101 }
102
103 int
104 LTC_Slave::parse_ltc(const jack_nframes_t nframes, const jack_default_audio_sample_t * const in, const framecnt_t posinfo)
105 {
106         jack_nframes_t i;
107         unsigned char sound[8192];
108         if (nframes > 8192) return 1;
109
110         for (i = 0; i < nframes; i++) {
111                 const int snd=(int)rint((127.0*in[i])+128.0);
112                 sound[i] = (unsigned char) (snd&0xff);
113         }
114         ltc_decoder_write(decoder, sound, nframes, posinfo);
115         return 0;
116 }
117
118 void
119 LTC_Slave::detect_ltc_fps(int frameno, bool df)
120 {
121         double detected_fps = 0;
122         if (frameno > ltc_detect_fps_max)
123         {
124                 ltc_detect_fps_max = frameno;
125         }
126         ltc_detect_fps_cnt++;
127         if (ltc_detect_fps_cnt > 60)
128         {
129                 if (ltc_detect_fps_cnt > ltc_detect_fps_max
130                     && (   ceil(timecode.rate) != (ltc_detect_fps_max + 1)
131                         || timecode.drop != df
132                         )
133                     )
134                 {
135                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS %1%2",
136                                         ltc_detect_fps_max + 1, timecode.drop ? "df" : ""));
137                         detected_fps = ltc_detect_fps_max + 1;
138                         if (df) {
139                                 /* LTC df -> indicates fractional framerate */
140                                 detected_fps = detected_fps * 1000.0 / 1001.0;
141                         }
142                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
143                 }
144                 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
145         }
146
147         /* when changed */
148         if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
149                 timecode.rate = detected_fps;
150                 timecode.drop = df;
151                 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
152                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
153                                 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
154                 last_timestamp = 0; // re-init
155         }
156
157         /* poll and check session TC */
158         if (1) {
159                 TimecodeFormat tc_format = apparent_timecode_format();
160                 TimecodeFormat cur_timecode = session.config.get_timecode_format();
161                 if (Config->get_timecode_sync_frame_rate()) {
162                         /* enforce time-code */
163                         if (!did_reset_tc_format) {
164                                 saved_tc_format = cur_timecode;
165                                 did_reset_tc_format = true;
166                         }
167                         if (cur_timecode != tc_format) {
168                                 warning << string_compose(_("Session framerate adjusted from %1 TO: LTC's %2."),
169                                                 Timecode::timecode_format_name(cur_timecode),
170                                                 Timecode::timecode_format_name(tc_format))
171                                         << endmsg;
172                         }
173                         session.config.set_timecode_format (tc_format);
174                 } else {
175                         /* only warn about TC mismatch */
176                         if (ltc_timecode != tc_format) printed_timecode_warning = false;
177                         if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
178
179                         if (cur_timecode != tc_format && ! printed_timecode_warning) {
180                                 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
181                                                 Timecode::timecode_format_name(tc_format),
182                                                 Timecode::timecode_format_name(cur_timecode))
183                                         << endmsg;
184                                 printed_timecode_warning = true;
185                         }
186                 }
187                 ltc_timecode = tc_format;
188                 a3e_timecode = cur_timecode;
189         }
190
191 }
192
193 bool
194 LTC_Slave::process_ltc(framepos_t now, framecnt_t nframes)
195 {
196         bool have_frame = false;
197
198         framepos_t sess_pos = session.transport_frame(); // corresponds to now
199         //sess_pos -= session.engine().frames_since_cycle_start();
200
201         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
202
203         LTCFrameExt frame;
204         while (ltc_decoder_read(decoder,&frame)) {
205                 SMPTETimecode stime;
206                 ltc_frame_to_time(&stime, &frame.ltc, 0);
207
208 #if 0 // Devel/Debug
209                 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
210                         stime.hours,
211                         stime.mins,
212                         stime.secs,
213                         (frame.ltc.dfbit) ? '.' : ':',
214                         stime.frame,
215                         frame.off_start,
216                         frame.off_end,
217                         frame.reverse ? " R" : "  "
218                         );
219 #endif
220
221                 timecode.negative  = false;
222                 timecode.subframes  = 0;
223                 /* set timecode.rate and timecode.drop: */
224                 detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false);
225
226                 /* when a full LTC frame is decoded, the timecode the LTC frame
227                  * is referring has just passed.
228                  * So we send the _next_ timecode which
229                  * is expected to start at the end of the current frame
230                  */
231                 int fps_i = ceil(timecode.rate);
232                 if (!frame.reverse) {
233                         ltc_frame_increment(&frame.ltc, fps_i , 0);
234                         ltc_frame_to_time(&stime, &frame.ltc, 0);
235                 } else {
236                         ltc_frame_decrement(&frame.ltc, fps_i , 0);
237                         int off = frame.off_end - frame.off_start;
238                         frame.off_start += off;
239                         frame.off_end += off;
240                 }
241
242                 timecode.hours   = stime.hours;
243                 timecode.minutes = stime.mins;
244                 timecode.seconds = stime.secs;
245                 timecode.frames  = stime.frame;
246
247                 framepos_t ltc_frame;
248                 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
249                         double(session.frame_rate()),
250                         session.config.get_subframes_per_frame(),
251                         session.config.get_timecode_offset_negative(), session.config.get_timecode_offset()
252                         );
253
254                 double poff = (frame.off_end - now);
255
256                 ltc_transport_pos = ltc_frame - poff;
257                 frames_per_ltc_frame = (double(session.frame_rate()) / timecode.rate);
258                 //frames_per_ltc_frame = frame.off_end - frame.off_start; // the first one is off.
259
260                 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC frame: %1 poff: %2 pos :%3\n", ltc_frame, poff, ltc_transport_pos));
261
262                 if (last_timestamp == 0 || ((now - last_timestamp) > 4 * frames_per_ltc_frame) ) {
263                         init_ltc_dll(ltc_frame, frames_per_ltc_frame);
264                         ltc_speed = 1.0; // XXX
265                 } else {
266
267                         double e = (double(ltc_frame) - poff - double(sess_pos));
268                         // update DLL
269                         t0 = t1;
270                         t1 += b * e + e2;
271                         e2 += c * e;
272
273                         ltc_speed = (t1 - t0) / frames_per_ltc_frame;
274                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC DLL t0:%1 t1:%2 err:%3 spd:%4 ddt:%5\n", t0, t1, e, ltc_speed, e2 - frames_per_ltc_frame));
275
276                 }
277                 last_timestamp = now;
278                 last_ltc_frame = ltc_frame;
279                 have_frame = true;
280         }
281         return have_frame;
282 }
283
284 void
285 LTC_Slave::init_ltc_dll(framepos_t tme, double dt)
286 {
287         omega = 2.0 * M_PI * dt / double(session.frame_rate());
288         b = 1.4142135623730950488 * omega;
289         c = omega * omega;
290
291         e2 = dt;
292         t0 = double(tme);
293         t1 = t0 + e2;
294         DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init LTC DLL %1 %2 %3\n", t0, t1, e2));
295 }
296
297 /* main entry point from session_process.cc
298  * called from jack_process callback context
299  * so it is OK to use jack_port_get_buffer() etc
300  */
301 bool
302 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
303 {
304
305         framepos_t now = session.engine().frame_time_at_cycle_start();
306         framecnt_t nframes = session.engine().frames_per_cycle();
307         jack_default_audio_sample_t *in;
308         jack_latency_range_t ltc_latency;
309
310         boost::shared_ptr<Port> ltcport = session.engine().ltc_input_port();
311         ltcport->get_connected_latency_range(ltc_latency, false);
312         in = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
313
314         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC_Slave::speed_and_position - TID:%1 | latency: %2\n", ::pthread_self(), ltc_latency.max));
315
316         if (in) {
317                 parse_ltc(nframes, in, now  + ltc_latency.max );
318                 if (!process_ltc(now, nframes)) {
319                         /* fly wheel */
320                         double elapsed = (now - last_timestamp) * ltc_speed;
321                         ltc_transport_pos = last_ltc_frame + elapsed;
322                         DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC fly wheel elapsed: %1 @speed %2\n", elapsed, ltc_speed));
323                 }
324         }
325
326         if (((now - last_timestamp) > 4 * frames_per_ltc_frame) ) {
327                 DEBUG_TRACE (DEBUG::LTC, "LTC no-signal - reset\n");
328                 speed = ltc_speed = 0;
329                 pos = session.transport_frame();
330                 last_timestamp = 0;
331                 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
332                 return true;
333         }
334
335         pos = ltc_transport_pos;
336         speed = ltc_speed;
337
338         return true;
339 }
340
341 Timecode::TimecodeFormat
342 LTC_Slave::apparent_timecode_format () const
343 {
344         if      (timecode.rate == 24 && !timecode.drop)
345                 return timecode_24;
346         else if (timecode.rate == 25 && !timecode.drop)
347                 return timecode_25;
348         else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
349                 return timecode_2997;
350         else if (rint(timecode.rate * 100) == 2997 &&  timecode.drop)
351                 return timecode_2997drop;
352         else if (timecode.rate == 30 &&  timecode.drop)
353                 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
354         else if (timecode.rate == 30 && !timecode.drop)
355                 return timecode_30;
356
357         /* XXX - unknown timecode format */
358         return session.config.get_timecode_format();
359 }
360
361 std::string 
362 LTC_Slave::approximate_current_position() const
363 {
364         if (last_timestamp == 0) {
365                 return "--:--:--:--";
366         }
367         return Timecode::timecode_format_time(timecode);
368 }