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.
22 #include <sys/types.h>
25 #include "pbd/error.h"
26 #include "pbd/pthread_utils.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 ( 1 * session.frame_rate() )
44 LTC_Slave::LTC_Slave (Session& s)
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();
51 did_reset_tc_format = false;
55 sync_lock_broken = false;
57 ltc_timecode = session.config.get_timecode_format();
58 a3e_timecode = session.config.get_timecode_format();
59 printed_timecode_warning = false;
60 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
61 memset(&prev_frame, 0, sizeof(LTCFrameExt));
63 decoder = ltc_decoder_create((int) frames_per_ltc_frame, 128 /*queue size*/);
65 session.config.ParameterChanged.connect_same_thread (config_connection, boost::bind (<C_Slave::parameter_changed, this, _1));
66 parse_timecode_offset();
69 session.Xrun.connect_same_thread (port_connections, boost::bind (<C_Slave::resync_xrun, this));
70 session.engine().GraphReordered.connect_same_thread (port_connections, boost::bind (<C_Slave::resync_latency, this));
73 LTC_Slave::~LTC_Slave()
75 port_connections.drop_connections();
76 config_connection.disconnect();
78 if (did_reset_tc_format) {
79 session.config.set_timecode_format (saved_tc_format);
82 ltc_decoder_free(decoder);
86 LTC_Slave::parse_timecode_offset() {
87 Timecode::Time offset_tc;
88 Timecode::parse_timecode_format(session.config.get_slave_timecode_offset(), offset_tc);
89 offset_tc.rate = session.timecode_frames_per_second();
90 offset_tc.drop = session.timecode_drop_frames();
91 session.timecode_to_sample(offset_tc, timecode_offset, false, false);
92 timecode_negative_offset = offset_tc.negative;
96 LTC_Slave::parameter_changed (std::string const & p)
98 if (p == "slave-timecode-offset"
99 || p == "timecode-format"
101 parse_timecode_offset();
106 LTC_Slave::resolution () const
108 return (framecnt_t) (session.frame_rate() / 1000);
112 LTC_Slave::locked () const
114 return (delayedlocked < 5);
118 LTC_Slave::ok() const
124 LTC_Slave::resync_xrun()
126 DEBUG_TRACE (DEBUG::LTC, "LTC resync_xrun()\n");
127 engine_dll_initstate = 0;
128 sync_lock_broken = false;
132 LTC_Slave::resync_latency()
134 DEBUG_TRACE (DEBUG::LTC, "LTC resync_latency()\n");
135 engine_dll_initstate = 0;
136 sync_lock_broken = false;
138 if (!session.deletion_in_progress() && session.ltc_output_io()) { /* check if Port exits */
139 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
140 ltcport->get_connected_latency_range (ltc_slave_latency, false);
147 DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
150 transport_direction = 0;
152 engine_dll_initstate = 0;
153 sync_lock_broken = false;
157 LTC_Slave::parse_ltc(const ARDOUR::pframes_t nframes, const Sample* const in, const ARDOUR::framecnt_t posinfo)
160 unsigned char sound[8192];
161 if (nframes > 8192) {
162 /* TODO warn once or wrap, loop conversion below
163 * does jack/A3 support > 8192 spp anyway?
168 for (i = 0; i < nframes; i++) {
169 const int snd=(int)rint((127.0*in[i])+128.0);
170 sound[i] = (unsigned char) (snd&0xff);
172 ltc_decoder_write(decoder, sound, nframes, posinfo);
177 LTC_Slave::equal_ltc_frame_time(LTCFrame *a, LTCFrame *b) {
178 if ( a->frame_units != b->frame_units
179 || a->frame_tens != b->frame_tens
180 || a->dfbit != b->dfbit
181 || a->secs_units != b->secs_units
182 || a->secs_tens != b->secs_tens
183 || a->mins_units != b->mins_units
184 || a->mins_tens != b->mins_tens
185 || a->hours_units != b->hours_units
186 || a->hours_tens != b->hours_tens
194 LTC_Slave::detect_discontinuity(LTCFrameExt *frame, int fps, bool fuzzy) {
195 bool discontinuity_detected = false;
198 ( frame->reverse && prev_frame.ltc.frame_units == 0)
199 ||(!frame->reverse && frame->ltc.frame_units == 0)
201 memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
205 if (frame->reverse) {
206 ltc_frame_decrement(&prev_frame.ltc, fps, LTC_TV_525_60, 0);
208 ltc_frame_increment(&prev_frame.ltc, fps, LTC_TV_525_60, 0);
210 if (!equal_ltc_frame_time(&prev_frame.ltc, &frame->ltc)) {
211 discontinuity_detected = true;
214 memcpy(&prev_frame, frame, sizeof(LTCFrameExt));
215 return discontinuity_detected;
219 LTC_Slave::detect_ltc_fps(int frameno, bool df)
221 bool fps_changed = false;
222 double detected_fps = 0;
223 if (frameno > ltc_detect_fps_max)
225 ltc_detect_fps_max = frameno;
227 ltc_detect_fps_cnt++;
229 if (ltc_detect_fps_cnt > 40) {
230 if (ltc_detect_fps_cnt > ltc_detect_fps_max) {
231 detected_fps = ltc_detect_fps_max + 1;
233 /* LTC df -> indicates fractional framerate */
234 if (Config->get_timecode_source_2997()) {
235 detected_fps = detected_fps * 999.0 / 1000.0;
237 detected_fps = detected_fps * 1000.0 / 1001.0;
241 if (timecode.rate != detected_fps || timecode.drop != df) {
242 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
244 detected_fps = 0; /* no cange */
247 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
251 if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
252 timecode.rate = detected_fps;
254 frames_per_ltc_frame = double(session.frame_rate()) / timecode.rate;
255 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-frames per LTC: %3\n",
256 detected_fps, df?"df":"ndf", frames_per_ltc_frame));
260 /* poll and check session TC */
261 TimecodeFormat tc_format = apparent_timecode_format();
262 TimecodeFormat cur_timecode = session.config.get_timecode_format();
264 if (Config->get_timecode_sync_frame_rate()) {
265 /* enforce time-code */
266 if (!did_reset_tc_format) {
267 saved_tc_format = cur_timecode;
268 did_reset_tc_format = true;
270 if (cur_timecode != tc_format) {
271 if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
272 warning << string_compose(_("Session framerate adjusted from %1 to LTC's %2."),
273 Timecode::timecode_format_name(cur_timecode),
274 Timecode::timecode_format_name(tc_format))
277 session.config.set_timecode_format (tc_format);
280 /* only warn about TC mismatch */
281 if (ltc_timecode != tc_format) printed_timecode_warning = false;
282 if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
284 if (cur_timecode != tc_format && ! printed_timecode_warning) {
285 if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
286 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
287 Timecode::timecode_format_name(tc_format),
288 Timecode::timecode_format_name(cur_timecode))
291 printed_timecode_warning = true;
294 ltc_timecode = tc_format;
295 a3e_timecode = cur_timecode;
301 LTC_Slave::process_ltc(framepos_t const /*now*/)
304 enum LTC_TV_STANDARD tv_standard = LTC_TV_625_50;
305 while (ltc_decoder_read(decoder, &frame)) {
308 ltc_frame_to_time(&stime, &frame.ltc, 0);
309 timecode.negative = false;
310 timecode.subframes = 0;
312 /* set timecode.rate and timecode.drop: */
313 bool ltc_is_static = equal_ltc_frame_time(&prev_frame.ltc, &frame.ltc);
315 if (detect_discontinuity(&frame, ceil(timecode.rate), !fps_detected)) {
316 if (fps_detected) { ltc_detect_fps_cnt = ltc_detect_fps_max = 0; }
320 if (!ltc_is_static && detect_ltc_fps(stime.frame, (frame.ltc.dfbit)? true : false)) {
326 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
330 (frame.ltc.dfbit) ? '.' : ':',
334 frame.reverse ? " R" : " "
338 /* when a full LTC frame is decoded, the timecode the LTC frame
339 * is referring has just passed.
340 * So we send the _next_ timecode which
341 * is expected to start at the end of the current frame
343 int fps_i = ceil(timecode.rate);
348 tv_standard = LTC_TV_525_60;
350 tv_standard = LTC_TV_1125_60;
354 tv_standard = LTC_TV_625_50;
357 tv_standard = LTC_TV_FILM_24; /* == LTC_TV_1125_60 == no offset, 24,30fps BGF */
361 if (!frame.reverse) {
362 ltc_frame_increment(&frame.ltc, fps_i, tv_standard, 0);
363 ltc_frame_to_time(&stime, &frame.ltc, 0);
364 transport_direction = 1;
365 frame.off_start -= ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
366 frame.off_end -= ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
368 ltc_frame_decrement(&frame.ltc, fps_i, tv_standard, 0);
369 int off = frame.off_end - frame.off_start;
370 frame.off_start += off - ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
371 frame.off_end += off - ltc_frame_alignment(session.frames_per_timecode_frame(), tv_standard);
372 transport_direction = -1;
375 timecode.hours = stime.hours;
376 timecode.minutes = stime.mins;
377 timecode.seconds = stime.secs;
378 timecode.frames = stime.frame;
380 /* map LTC timecode to session TC setting */
381 framepos_t ltc_frame; ///< audio-frame corresponding to LTC frame
382 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
383 double(session.frame_rate()),
384 session.config.get_subframes_per_frame(),
385 timecode_negative_offset, timecode_offset
388 ltc_frame += ltc_slave_latency.max + session.worst_playback_latency();
390 framepos_t cur_timestamp = frame.off_end + 1;
391 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));
392 if (frame.off_end + 1 <= last_timestamp || last_timestamp == 0) {
393 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: UNCHANGED: %1\n", ltc_speed));
395 ltc_speed = double(ltc_frame - last_ltc_frame) / double(cur_timestamp - last_timestamp);
396 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: %1\n", ltc_speed));
399 if (fabs(ltc_speed) > 10.0) {
403 last_timestamp = frame.off_end + 1;
404 last_ltc_frame = ltc_frame;
405 } /* end foreach decoded LTC frame */
409 LTC_Slave::init_engine_dll (framepos_t pos, int32_t inc)
411 double omega = 2.0 * M_PI * double(inc) / double(session.frame_rate());
412 b = 1.4142135623730950488 * omega;
415 e2 = double(ltc_speed * inc);
418 DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", t0, t1, e2));
421 /* main entry point from session_process.cc
422 * called from process callback context
423 * so it is OK to use get_buffer()
426 LTC_Slave::speed_and_position (double& speed, framepos_t& pos)
428 bool engine_init_called = false;
429 framepos_t now = session.engine().sample_time_at_cycle_start();
430 framepos_t sess_pos = session.transport_frame(); // corresponds to now
431 framecnt_t nframes = session.engine().samples_per_cycle();
435 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
437 in = (Sample*) AudioEngine::instance()->port_engine().get_buffer (ltcport->port_handle(), nframes);
439 frameoffset_t skip = now - (monotonic_cnt + nframes);
441 DEBUG_TRACE (DEBUG::LTC, string_compose ("speed_and_position - TID:%1 | latency: %2 | skip %3\n", pthread_name(), ltc_slave_latency.max, skip));
443 if (last_timestamp == 0) {
444 engine_dll_initstate = 0;
445 if (delayedlocked < 10) ++delayedlocked;
447 else if (engine_dll_initstate != transport_direction && ltc_speed != 0) {
448 engine_dll_initstate = transport_direction;
449 init_engine_dll(last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp)),
450 session.engine().samples_per_cycle());
451 engine_init_called = true;
455 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
456 /* when the jack-graph changes and if ardour performs
457 * locates, the audioengine is stopped (skipping frames) while
458 * jack [time] moves along.
461 DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames. Feeding silence to LTC parser.\n", skip));
462 if (skip >= 8192) skip = 8192;
463 unsigned char sound[8192];
464 memset(sound, 0, sizeof(char) * skip);
465 ltc_decoder_write(decoder, sound, nframes, now);
466 } else if (skip != 0) {
467 /* this should never happen. it may if monotonic_cnt, now overflow on 64bit */
468 DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 frames\n", skip));
472 parse_ltc(nframes, in, now);
476 if (last_timestamp == 0) {
477 DEBUG_TRACE (DEBUG::LTC, "last timestamp == 0\n");
479 pos = session.transport_frame();
481 } else if (ltc_speed != 0) {
482 if (delayedlocked > 1) delayedlocked--;
483 else if (current_delta == 0) delayedlocked = 0;
486 if (abs(now - last_timestamp) > FLYWHEEL_TIMEOUT) {
487 DEBUG_TRACE (DEBUG::LTC, "flywheel timeout\n");
490 pos = session.transport_frame();
494 /* it take 2 cycles from naught to rolling.
495 * during these to initial cycles the speed == 0
498 * DEBUG::Slave: slave stopped, move to NNN
499 * DEBUG::Transport: Request forced locate to NNN
500 * DEBUG::Slave: slave state 0 @ NNN speed 0 cur delta VERY-LARGE-DELTA avg delta 1800
501 * DEBUG::Slave: silent motion
502 * DEBUG::Transport: realtime stop @ NNN
503 * DEBUG::Transport: Butler transport work, todo = PostTransportStop,PostTransportLocate,PostTransportClearSubstate
505 * [engine skips frames to locate, jack time keeps rolling on]
509 * DEBUG::LTC: [re-]init Engine DLL
510 * DEBUG::Slave: slave stopped, move to NNN+
513 * we need to seek two cycles ahead: 2 * nframes
515 if (engine_dll_initstate == 0) {
516 DEBUG_TRACE (DEBUG::LTC, "engine DLL not initialized. ltc_speed\n");
518 pos = last_ltc_frame + rint(ltc_speed * double(2 * nframes + now - last_timestamp));
522 /* interpolate position according to speed and time since last LTC-frame*/
523 double speed_flt = ltc_speed;
524 double elapsed = (now - last_timestamp) * speed_flt;
526 if (!engine_init_called) {
527 const double e = elapsed + double (last_ltc_frame - sess_pos);
531 speed_flt = (t1 - t0) / double(session.engine().samples_per_cycle());
532 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() ));
534 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC adjusting elapsed (no DLL) from %1 by %2\n", elapsed, (2 * nframes * ltc_speed)));
536 elapsed += 2.0 * nframes * ltc_speed; /* see note above */
539 pos = last_ltc_frame + rint(elapsed);
541 current_delta = (pos - sess_pos);
543 if (((pos < 0) || (labs(current_delta) > 2 * session.frame_rate()))) {
544 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift: %1\n", current_delta));
547 pos = session.transport_frame();
551 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
552 speed, pos, last_ltc_frame, elapsed, current_delta));
554 /* provide a .1% deadzone to lock the speed */
555 if (fabs(speed - 1.0) <= 0.001) {
559 if (speed != 0 && delayedlocked == 0 && fabsf(speed) != 1.0) {
560 sync_lock_broken = true;
561 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed not locked %1 %2\n", speed, ltc_speed));
567 Timecode::TimecodeFormat
568 LTC_Slave::apparent_timecode_format () const
570 if (timecode.rate == 24 && !timecode.drop)
572 else if (timecode.rate == 25 && !timecode.drop)
574 else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
575 return (Config->get_timecode_source_2997() ? timecode_2997000 : timecode_2997);
576 else if (rint(timecode.rate * 100) == 2997 && timecode.drop)
577 return (Config->get_timecode_source_2997() ? timecode_2997000drop : timecode_2997drop);
578 else if (timecode.rate == 30 && timecode.drop)
579 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 frames w/DF *means* 29.97 df
580 else if (timecode.rate == 30 && !timecode.drop)
583 /* XXX - unknown timecode format */
584 return session.config.get_timecode_format();
588 LTC_Slave::approximate_current_position() const
590 if (last_timestamp == 0) {
591 return " --:--:--:--";
593 return Timecode::timecode_format_time(timecode);
597 LTC_Slave::approximate_current_delta() const
600 if (last_timestamp == 0 || engine_dll_initstate == 0) {
601 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
602 } else if ((monotonic_cnt - last_timestamp) > 2 * frames_per_ltc_frame) {
603 snprintf(delta, sizeof(delta), "%s", _("flywheel"));
605 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"%s\" face=\"monospace\" >%s%s%lld</span>sm",
606 sync_lock_broken ? "red" : "green",
607 LEADINGZERO(llabs(current_delta)), PLUSMINUS(-current_delta), llabs(current_delta));
609 return std::string(delta);