2 Copyright (C) 2012 Paul Davis
3 Witten by 2012 Robin Gareus <robin@gareus.org>
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.
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.
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.
23 #include <sys/types.h>
26 #include "pbd/error.h"
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"
37 using namespace ARDOUR;
40 using namespace Timecode;
42 #define FLYWHEEL_TIMEOUT ( 3 * session.frame_rate() )
44 LTC_Slave::LTC_Slave (Session& s)
47 frames_per_ltc_frame = session.frames_per_timecode_frame(); // XXX at most 30fps ?
48 timecode.rate = session.timecode_frames_per_second();
49 timecode.drop = session.timecode_drop_frames();
51 ltc_transport_pos = 0;
52 did_reset_tc_format = false;
54 engine_dll_initstate = 0;
57 memset(&prev_ltc_frame, 0, sizeof(LTCFrame));
59 ltc_timecode = timecode_60; // track changes of LTC timecode
60 a3e_timecode = timecode_60; // track canges of Ardour's timecode
61 printed_timecode_warning = false;
63 decoder = ltc_decoder_create((int) frames_per_ltc_frame, 128 /*queue size*/);
65 //session.engine().Xrun.connect_same_thread (*this, boost::bind (<C_Slave::reset, this));
68 LTC_Slave::~LTC_Slave()
70 if (did_reset_tc_format) {
71 session.config.set_timecode_format (saved_tc_format);
74 ltc_decoder_free(decoder);
78 LTC_Slave::give_slave_full_control_over_transport_speed() const
80 return true; // DLL align to engine transport
81 // return false; // for Session-level computed varispeed
85 LTC_Slave::resolution () const
87 return (framecnt_t) (frames_per_ltc_frame);
91 LTC_Slave::seekahead_distance () const
97 LTC_Slave::locked () const
99 return (delayedlocked < 5);
103 LTC_Slave::ok() const
111 DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
112 frames_in_sequence = 0;
113 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
116 transport_direction = 0;
118 ltc_decoder_queue_flush(decoder);
122 LTC_Slave::parse_ltc(const jack_nframes_t nframes, const jack_default_audio_sample_t * const in, const framecnt_t posinfo)
125 unsigned char sound[8192];
126 if (nframes > 8192) return 1;
128 for (i = 0; i < nframes; i++) {
129 const int snd=(int)rint((127.0*in[i])+128.0);
130 sound[i] = (unsigned char) (snd&0xff);
132 ltc_decoder_write(decoder, sound, nframes, posinfo);
137 LTC_Slave::detect_ltc_fps(int frameno, bool df)
139 double detected_fps = 0;
140 if (frameno > ltc_detect_fps_max)
142 ltc_detect_fps_max = frameno;
144 ltc_detect_fps_cnt++;
145 if (ltc_detect_fps_cnt > 60)
147 if (ltc_detect_fps_cnt > ltc_detect_fps_max
148 && ( ceil(timecode.rate) != (ltc_detect_fps_max + 1)
149 || timecode.drop != df
153 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS %1%2",
154 ltc_detect_fps_max + 1, timecode.drop ? "df" : ""));
155 detected_fps = ltc_detect_fps_max + 1;
157 /* LTC df -> indicates fractional framerate */
158 detected_fps = detected_fps * 1000.0 / 1001.0;
160 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
162 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
166 if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
167 timecode.rate = detected_fps;
169 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
170 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
171 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
172 return true; // reset()
175 /* poll and check session TC */
177 TimecodeFormat tc_format = apparent_timecode_format();
178 TimecodeFormat cur_timecode = session.config.get_timecode_format();
179 if (Config->get_timecode_sync_frame_rate()) {
180 /* enforce time-code */
181 if (!did_reset_tc_format) {
182 saved_tc_format = cur_timecode;
183 did_reset_tc_format = true;
185 if (cur_timecode != tc_format) {
186 warning << string_compose(_("Session framerate adjusted from %1 TO: LTC's %2."),
187 Timecode::timecode_format_name(cur_timecode),
188 Timecode::timecode_format_name(tc_format))
191 session.config.set_timecode_format (tc_format);
193 /* only warn about TC mismatch */
194 if (ltc_timecode != tc_format) printed_timecode_warning = false;
195 if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
197 if (cur_timecode != tc_format && ! printed_timecode_warning) {
198 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
199 Timecode::timecode_format_name(tc_format),
200 Timecode::timecode_format_name(cur_timecode))
202 printed_timecode_warning = true;
205 ltc_timecode = tc_format;
206 a3e_timecode = cur_timecode;
212 LTC_Slave::detect_ltc_discontinuity(LTCFrameExt *frame) {
213 bool discontinuity_detected = false;
214 /* detect discontinuities */
215 if (frame->reverse) {
216 ltc_frame_decrement(&prev_ltc_frame, ceil(timecode.rate), 0);
218 ltc_frame_increment(&prev_ltc_frame, ceil(timecode.rate), 0);
221 if (memcmp(&prev_ltc_frame, &frame->ltc, sizeof(LTCFrame))) {
222 discontinuity_detected = true;
224 memcpy(&prev_ltc_frame, &frame->ltc, sizeof(LTCFrame));
226 /* notfify about discontinuities */
227 if (frames_in_sequence > 0 && discontinuity_detected) {
228 DEBUG_TRACE (DEBUG::LTC, "# LTC DISCONTINUITY\n");
229 frames_in_sequence=0;
232 frames_in_sequence++;
238 LTC_Slave::process_ltc(framepos_t const now, framepos_t const sess_pos, framecnt_t const nframes)
240 bool have_frame = false;
241 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
244 while (ltc_decoder_read(decoder,&frame)) {
245 bool reinitialize_ltc_dll = false;
248 ltc_frame_to_time(&stime, &frame.ltc, 0);
249 timecode.negative = false;
250 timecode.subframes = 0;
251 /* set timecode.rate and timecode.drop: */
252 if (detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false)) {
256 if (detect_ltc_discontinuity(&frame)) {
257 ltc_discontinuity = true;
261 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
265 (frame.ltc.dfbit) ? '.' : ':',
269 frame.reverse ? " R" : " "
272 if (frames_in_sequence < 1) {
273 fprintf(stdout, " ####### FIRST LTC FRAME in SEQ #######\n");
276 if (ltc_discontinuity) {
277 fprintf(stdout, " ####### LTC DISCONTINUITY #######\n");
281 if (frames_in_sequence < 1) {
285 /* when a full LTC frame is decoded, the timecode the LTC frame
286 * is referring has just passed.
287 * So we send the _next_ timecode which
288 * is expected to start at the end of the current frame
290 int fps_i = ceil(timecode.rate);
291 if (!frame.reverse) {
292 ltc_frame_increment(&frame.ltc, fps_i , 0);
293 ltc_frame_to_time(&stime, &frame.ltc, 0);
295 ltc_frame_decrement(&frame.ltc, fps_i , 0);
296 int off = frame.off_end - frame.off_start;
297 frame.off_start += off;
298 frame.off_end += off;
301 timecode.hours = stime.hours;
302 timecode.minutes = stime.mins;
303 timecode.seconds = stime.secs;
304 timecode.frames = stime.frame;
306 /* map LTC timecode to session TC setting */
307 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
308 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
309 double(session.frame_rate()),
310 session.config.get_subframes_per_frame(),
311 session.config.get_timecode_offset_negative(), session.config.get_timecode_offset()
314 /* (frame.off_end + 1) = start of next LTC frame */
315 double poff = (frame.off_end + 1 - now);
316 ltc_transport_pos = ltc_frame - poff;
318 #if 0 // vari-speed LTC, no DLL
319 frames_per_ltc_frame = 1 + frame.off_end - frame.off_start;
321 frames_per_ltc_frame = (double(session.frame_rate()) / timecode.rate);
324 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC frame: %1 poff: %2 pos: %3\n", ltc_frame, poff, ltc_transport_pos));
326 if (ltc_discontinuity) {
327 ltc_discontinuity=false;
330 || (ltc_transport_pos - sess_pos) > FLYWHEEL_TIMEOUT)
332 engine_dll_initstate = 0;
335 reinitialize_ltc_dll = true;
338 if (last_timestamp == 0
339 || ((now - last_timestamp) > FLYWHEEL_TIMEOUT)
340 || (abs(current_delta) > FLYWHEEL_TIMEOUT) // TODO LTC-delta not engine delta
341 || (frame.reverse && transport_direction != -1)
342 || (!frame.reverse && transport_direction != 1)
344 reinitialize_ltc_dll = true;
345 engine_dll_initstate = 0;
349 if (reinitialize_ltc_dll) {
350 init_ltc_dll(ltc_transport_pos, frames_per_ltc_frame);
352 if (ltc_speed==0 || !locked()) {
354 transport_direction = -1;
355 ltc_transport_pos -= nframes * rint((2 * frames_per_ltc_frame + poff)/nframes);
357 transport_direction = 1;
358 ltc_transport_pos += nframes * rint((2 * frames_per_ltc_frame + poff)/nframes);
364 double e = (double(ltc_frame) - poff - double(sess_pos));
369 ltc_speed = (t1 - t0) / frames_per_ltc_frame;
370 current_delta = (ltc_transport_pos - sess_pos);
371 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));
375 /* the are equivalent
376 * TODO: choose the value with larger diff ->
377 * minimize roundig errors when extrapolating
380 last_timestamp = now;
381 last_ltc_frame = ltc_transport_pos;
383 last_timestamp = frame.off_end + 1;
384 last_ltc_frame = ltc_frame;
388 } /* end foreach decoded LTC frame */
394 LTC_Slave::init_ltc_dll(framepos_t const tme, double const dt)
396 omega = 2.0 * M_PI * dt / double(session.frame_rate());
397 b = 1.4142135623730950488 * omega;
403 DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init LTC DLL %1 %2 %3\n", t0, t1, e2));
407 LTC_Slave::init_engine_dll (framepos_t pos, framepos_t inc)
409 /* the bandwidth of the DLL is a trade-off,
410 * because the max-speed of the transport in ardour is
411 * limited to +-8.0, a larger bandwidth would cause oscillations
413 * But this is only really a problem if the user performs manual
414 * seeks while transport is running and slaved to LTC.
416 oe = 2.0 * M_PI * double(inc/2.0) / double(session.frame_rate());
417 be = 1.4142135623730950488 * oe;
420 ee2 = double(transport_direction * inc);
423 DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", te0, te1, ee2));
426 /* main entry point from session_process.cc
427 * called from jack_process callback context
428 * so it is OK to use jack_port_get_buffer() etc
431 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
433 //framepos_t now = session.engine().frame_time_at_cycle_start();
434 //framepos_t now = session.engine().processed_frames();
435 framepos_t now = monotonic_cnt;
436 framepos_t sess_pos = session.transport_frame(); // corresponds to now
437 framecnt_t nframes = session.engine().frames_per_cycle();
438 jack_default_audio_sample_t *in;
439 jack_latency_range_t ltc_latency;
441 monotonic_cnt += nframes;
443 boost::shared_ptr<Port> ltcport = session.engine().ltc_input_port();
444 ltcport->get_connected_latency_range(ltc_latency, false);
445 in = (jack_default_audio_sample_t*) jack_port_get_buffer (ltcport->jack_port(), nframes);
447 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC_Slave::speed_and_position - TID:%1 | latency: %2\n", ::pthread_self(), ltc_latency.max));
449 if (last_timestamp == 0) {
450 engine_dll_initstate = 0;
453 else if (engine_dll_initstate != transport_direction) {
454 engine_dll_initstate = transport_direction;
455 init_engine_dll(last_ltc_frame, session.engine().frames_per_cycle());
459 parse_ltc(nframes, in, now + ltc_latency.max );
460 if (!process_ltc(now, sess_pos, nframes) && ltc_speed != 0) {
464 /* interpolate position according to speed and time since last LTC-frame*/
465 double speed_flt = ltc_speed;
467 if (speed_flt == 0.0f) {
470 /* scale elapsed time by the current LTC speed */
471 if (last_timestamp && (now > last_timestamp)) {
472 elapsed = (now - last_timestamp) * speed_flt;
476 /* update engine DLL and calculate speed */
477 const double e = double (last_ltc_frame + elapsed - sess_pos);
481 speed_flt = (te1 - te0) / double(session.engine().frames_per_cycle());
482 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC engine DLL t0:%1 t1:%2 err:%3 spd:%4 ddt:%5\n", te0, te1, e, speed_flt, ee2 - session.engine().frames_per_cycle() ));
485 pos = last_ltc_frame + elapsed;
487 current_delta = (pos - sess_pos);
489 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
490 speed, pos, last_ltc_frame, elapsed, current_delta));
492 if (last_timestamp != 0 /* && frames_in_sequence > 8*/) {
496 if (last_timestamp == 0 || ((now - last_timestamp) > FLYWHEEL_TIMEOUT)) {
497 DEBUG_TRACE (DEBUG::LTC, "LTC no-signal - reset\n");
499 engine_dll_initstate = 0;
501 pos = session.transport_frame();
505 if (last_timestamp != 0 && ltc_speed != 0 && ((ltc_transport_pos < 0) || (labs(current_delta) > 10 * session.frame_rate()))) {
506 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift. %1\n", current_delta));
507 // XXX only re-init engine DLL ?
509 engine_dll_initstate = 0;
511 pos = session.transport_frame();
516 /* provide a 1% deadzone to lock the speed */
517 if (fabs(speed - 1.0) <= 0.01)
524 Timecode::TimecodeFormat
525 LTC_Slave::apparent_timecode_format () const
527 if (timecode.rate == 24 && !timecode.drop)
529 else if (timecode.rate == 25 && !timecode.drop)
531 else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
532 return timecode_2997;
533 else if (rint(timecode.rate * 100) == 2997 && timecode.drop)
534 return timecode_2997drop;
535 else if (timecode.rate == 30 && timecode.drop)
536 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
537 else if (timecode.rate == 30 && !timecode.drop)
540 /* XXX - unknown timecode format */
541 return session.config.get_timecode_format();
545 LTC_Slave::approximate_current_position() const
547 if (last_timestamp == 0) {
548 return " --:--:--:--";
550 return Timecode::timecode_format_time(timecode);
554 LTC_Slave::approximate_current_delta() const
557 if (last_timestamp == 0 || frames_in_sequence < 2) {
558 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
559 } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
560 snprintf(delta, sizeof(delta), "flywheel");
562 // TODO if current_delta > 1 frame -> display timecode.
563 // delta >0 if A3's transport is _behind_ LTC
564 snprintf(delta, sizeof(delta), "%s%4" PRIi64 " sm",
565 PLUSMINUS(-current_delta), abs(current_delta));
567 return std::string(delta);