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/profile.h"
30 #include "ardour/slave.h"
31 #include "ardour/session.h"
32 #include "ardour/audioengine.h"
33 #include "ardour/audio_port.h"
38 using namespace ARDOUR;
41 using namespace Timecode;
43 #define FLYWHEEL_TIMEOUT ( 1 * session.sample_rate() )
45 LTC_Slave::LTC_Slave (Session& s)
48 samples_per_ltc_frame = session.samples_per_timecode_frame();
49 timecode.rate = session.timecode_frames_per_second();
50 timecode.drop = session.timecode_drop_frames();
52 did_reset_tc_format = false;
56 sync_lock_broken = false;
58 ltc_timecode = session.config.get_timecode_format();
59 a3e_timecode = session.config.get_timecode_format();
60 printed_timecode_warning = false;
61 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
62 memset(&prev_sample, 0, sizeof(LTCFrameExt));
64 decoder = ltc_decoder_create((int) samples_per_ltc_frame, 128 /*queue size*/);
66 session.config.ParameterChanged.connect_same_thread (config_connection, boost::bind (<C_Slave::parameter_changed, this, _1));
67 parse_timecode_offset();
70 session.Xrun.connect_same_thread (port_connections, boost::bind (<C_Slave::resync_xrun, this));
71 session.engine().GraphReordered.connect_same_thread (port_connections, boost::bind (<C_Slave::resync_latency, this));
74 LTC_Slave::~LTC_Slave()
76 port_connections.drop_connections();
77 config_connection.disconnect();
79 if (did_reset_tc_format) {
80 session.config.set_timecode_format (saved_tc_format);
83 ltc_decoder_free(decoder);
87 LTC_Slave::parse_timecode_offset() {
88 Timecode::Time offset_tc;
89 Timecode::parse_timecode_format(session.config.get_slave_timecode_offset(), offset_tc);
90 offset_tc.rate = session.timecode_frames_per_second();
91 offset_tc.drop = session.timecode_drop_frames();
92 session.timecode_to_sample(offset_tc, timecode_offset, false, false);
93 timecode_negative_offset = offset_tc.negative;
97 LTC_Slave::parameter_changed (std::string const & p)
99 if (p == "slave-timecode-offset"
100 || p == "timecode-format"
102 parse_timecode_offset();
107 LTC_Slave::resolution () const
109 return (samplecnt_t) (session.sample_rate() / 1000);
113 LTC_Slave::locked () const
115 return (delayedlocked < 5);
119 LTC_Slave::ok() const
125 LTC_Slave::resync_xrun()
127 DEBUG_TRACE (DEBUG::LTC, "LTC resync_xrun()\n");
128 engine_dll_initstate = 0;
129 sync_lock_broken = false;
133 LTC_Slave::resync_latency()
135 DEBUG_TRACE (DEBUG::LTC, "LTC resync_latency()\n");
136 engine_dll_initstate = 0;
137 sync_lock_broken = false;
139 if (!session.deletion_in_progress() && session.ltc_output_io()) { /* check if Port exits */
140 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
141 ltcport->get_connected_latency_range (ltc_slave_latency, false);
146 LTC_Slave::reset (bool with_ts)
148 DEBUG_TRACE (DEBUG::LTC, "LTC reset()\n");
153 transport_direction = 0;
155 engine_dll_initstate = 0;
156 sync_lock_broken = false;
158 ActiveChanged (false); /* EMIT SIGNAL */
162 LTC_Slave::parse_ltc(const ARDOUR::pframes_t nframes, const Sample* const in, const ARDOUR::samplecnt_t posinfo)
165 unsigned char sound[8192];
166 if (nframes > 8192) {
167 /* TODO warn once or wrap, loop conversion below
168 * does jack/A3 support > 8192 spp anyway?
173 for (i = 0; i < nframes; i++) {
174 const int snd=(int)rint((127.0*in[i])+128.0);
175 sound[i] = (unsigned char) (snd&0xff);
177 ltc_decoder_write(decoder, sound, nframes, posinfo);
182 LTC_Slave::equal_ltc_sample_time(LTCFrame *a, LTCFrame *b) {
183 if ( a->frame_units != b->frame_units
184 || a->frame_tens != b->frame_tens
185 || a->dfbit != b->dfbit
186 || a->secs_units != b->secs_units
187 || a->secs_tens != b->secs_tens
188 || a->mins_units != b->mins_units
189 || a->mins_tens != b->mins_tens
190 || a->hours_units != b->hours_units
191 || a->hours_tens != b->hours_tens
199 LTC_Slave::detect_discontinuity(LTCFrameExt *sample, int fps, bool fuzzy) {
200 bool discontinuity_detected = false;
203 ( sample->reverse && prev_sample.ltc.frame_units == 0)
204 ||(!sample->reverse && sample->ltc.frame_units == 0)
206 memcpy(&prev_sample, sample, sizeof(LTCFrameExt));
210 if (sample->reverse) {
211 ltc_frame_decrement(&prev_sample.ltc, fps, LTC_TV_525_60, 0);
213 ltc_frame_increment(&prev_sample.ltc, fps, LTC_TV_525_60, 0);
215 if (!equal_ltc_sample_time(&prev_sample.ltc, &sample->ltc)) {
216 discontinuity_detected = true;
219 memcpy(&prev_sample, sample, sizeof(LTCFrameExt));
220 return discontinuity_detected;
224 LTC_Slave::detect_ltc_fps(int frameno, bool df)
226 bool fps_changed = false;
227 double detected_fps = 0;
228 if (frameno > ltc_detect_fps_max)
230 ltc_detect_fps_max = frameno;
232 ltc_detect_fps_cnt++;
234 if (ltc_detect_fps_cnt > 40) {
235 if (ltc_detect_fps_cnt > ltc_detect_fps_max) {
236 detected_fps = ltc_detect_fps_max + 1;
238 /* LTC df -> indicates fractional framerate */
239 if (Config->get_timecode_source_2997()) {
240 detected_fps = detected_fps * 999.0 / 1000.0;
242 detected_fps = detected_fps * 1000.0 / 1001.0;
246 if (timecode.rate != detected_fps || timecode.drop != df) {
247 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC detected FPS: %1%2\n", detected_fps, df?"df":"ndf"));
249 detected_fps = 0; /* no cange */
252 ltc_detect_fps_cnt = ltc_detect_fps_max = 0;
256 if (detected_fps != 0 && (detected_fps != timecode.rate || df != timecode.drop)) {
257 timecode.rate = detected_fps;
259 samples_per_ltc_frame = double(session.sample_rate()) / timecode.rate;
260 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC reset to FPS: %1%2 ; audio-samples per LTC: %3\n",
261 detected_fps, df?"df":"ndf", samples_per_ltc_frame));
265 /* poll and check session TC */
266 TimecodeFormat tc_format = apparent_timecode_format();
267 TimecodeFormat cur_timecode = session.config.get_timecode_format();
269 if (Config->get_timecode_sync_frame_rate()) {
270 /* enforce time-code */
271 if (!did_reset_tc_format) {
272 saved_tc_format = cur_timecode;
273 did_reset_tc_format = true;
275 if (cur_timecode != tc_format) {
276 if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
277 warning << string_compose(_("Session framerate adjusted from %1 to LTC's %2."),
278 Timecode::timecode_format_name(cur_timecode),
279 Timecode::timecode_format_name(tc_format))
282 session.config.set_timecode_format (tc_format);
285 /* only warn about TC mismatch */
286 if (ltc_timecode != tc_format) printed_timecode_warning = false;
287 if (a3e_timecode != cur_timecode) printed_timecode_warning = false;
289 if (cur_timecode != tc_format && ! printed_timecode_warning) {
290 if (ceil(Timecode::timecode_to_frames_per_second(cur_timecode)) != ceil(Timecode::timecode_to_frames_per_second(tc_format))) {
291 warning << string_compose(_("Session and LTC framerate mismatch: LTC:%1 Session:%2."),
292 Timecode::timecode_format_name(tc_format),
293 Timecode::timecode_format_name(cur_timecode))
296 printed_timecode_warning = true;
299 ltc_timecode = tc_format;
300 a3e_timecode = cur_timecode;
306 LTC_Slave::process_ltc(samplepos_t const /*now*/)
309 enum LTC_TV_STANDARD tv_standard = LTC_TV_625_50;
310 while (ltc_decoder_read(decoder, &sample)) {
313 ltc_frame_to_time(&stime, &sample.ltc, 0);
314 timecode.negative = false;
315 timecode.subframes = 0;
317 /* set timecode.rate and timecode.drop: */
318 bool ltc_is_static = equal_ltc_sample_time(&prev_sample.ltc, &sample.ltc);
320 if (detect_discontinuity(&sample, ceil(timecode.rate), !fps_detected)) {
321 if (fps_detected) { ltc_detect_fps_cnt = ltc_detect_fps_max = 0; }
325 if (!ltc_is_static && detect_ltc_fps(stime.frame, (sample.ltc.dfbit)? true : false)) {
331 fprintf(stdout, "LTC %02d:%02d:%02d%c%02d | %8lld %8lld%s\n",
335 (sample.ltc.dfbit) ? '.' : ':',
339 sample.reverse ? " R" : " "
343 /* when a full LTC sample is decoded, the timecode the LTC sample
344 * is referring has just passed.
345 * So we send the _next_ timecode which
346 * is expected to start at the end of the current sample
348 int fps_i = ceil(timecode.rate);
353 tv_standard = LTC_TV_525_60;
355 tv_standard = LTC_TV_1125_60;
359 tv_standard = LTC_TV_625_50;
362 tv_standard = LTC_TV_FILM_24; /* == LTC_TV_1125_60 == no offset, 24,30fps BGF */
366 if (!sample.reverse) {
367 ltc_frame_increment(&sample.ltc, fps_i, tv_standard, 0);
368 ltc_frame_to_time(&stime, &sample.ltc, 0);
369 transport_direction = 1;
370 sample.off_start -= ltc_frame_alignment(session.samples_per_timecode_frame(), tv_standard);
371 sample.off_end -= ltc_frame_alignment(session.samples_per_timecode_frame(), tv_standard);
373 ltc_frame_decrement(&sample.ltc, fps_i, tv_standard, 0);
374 int off = sample.off_end - sample.off_start;
375 sample.off_start += off - ltc_frame_alignment(session.samples_per_timecode_frame(), tv_standard);
376 sample.off_end += off - ltc_frame_alignment(session.samples_per_timecode_frame(), tv_standard);
377 transport_direction = -1;
380 timecode.hours = stime.hours;
381 timecode.minutes = stime.mins;
382 timecode.seconds = stime.secs;
383 timecode.frames = stime.frame;
385 /* map LTC timecode to session TC setting */
386 samplepos_t ltc_frame; ///< audio-sample corresponding to LTC sample
387 Timecode::timecode_to_sample (timecode, ltc_frame, true, false,
388 double(session.sample_rate()),
389 session.config.get_subframes_per_frame(),
390 timecode_negative_offset, timecode_offset
393 ltc_frame += ltc_slave_latency.max + session.worst_playback_latency();
395 samplepos_t cur_timestamp = sample.off_end + 1;
396 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC F: %1 LF: %2 N: %3 L: %4\n", ltc_frame, last_ltc_sample, cur_timestamp, last_timestamp));
397 if (sample.off_end + 1 <= last_timestamp || last_timestamp == 0) {
398 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: UNCHANGED: %1\n", ltc_speed));
400 ltc_speed = double(ltc_frame - last_ltc_sample) / double(cur_timestamp - last_timestamp);
401 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed: %1\n", ltc_speed));
404 if (fabs(ltc_speed) > 10.0) {
408 last_timestamp = sample.off_end + 1;
409 last_ltc_sample = ltc_frame;
410 } /* end foreach decoded LTC sample */
414 LTC_Slave::init_engine_dll (samplepos_t pos, int32_t inc)
416 double omega = 2.0 * M_PI * double(inc) / double(session.sample_rate());
417 b = 1.4142135623730950488 * omega;
420 e2 = double(ltc_speed * inc);
423 DEBUG_TRACE (DEBUG::LTC, string_compose ("[re-]init Engine DLL %1 %2 %3\n", t0, t1, e2));
426 /* main entry point from session_process.cc
427 * called from process callback context
428 * so it is OK to use get_buffer()
431 LTC_Slave::speed_and_position (double& speed, samplepos_t& pos)
433 bool engine_init_called = false;
434 samplepos_t now = session.engine().sample_time_at_cycle_start();
435 samplepos_t sess_pos = session.transport_sample(); // corresponds to now
436 samplecnt_t nframes = session.engine().samples_per_cycle();
440 boost::shared_ptr<Port> ltcport = session.ltc_input_port();
442 in = (Sample*) AudioEngine::instance()->port_engine().get_buffer (ltcport->port_handle(), nframes);
444 sampleoffset_t skip = now - (monotonic_cnt + nframes);
446 DEBUG_TRACE (DEBUG::LTC, string_compose ("speed_and_position - TID:%1 | latency: %2 | skip %3\n", pthread_name(), ltc_slave_latency.max, skip));
448 if (last_timestamp == 0) {
449 engine_dll_initstate = 0;
450 if (delayedlocked < 10) ++delayedlocked;
451 } else if (engine_dll_initstate != transport_direction && ltc_speed != 0) {
453 ActiveChanged (true); /* EMIT SIGNAL */
455 engine_dll_initstate = transport_direction;
456 init_engine_dll(last_ltc_sample + rint(ltc_speed * double(2 * nframes + now - last_timestamp)),
457 session.engine().samples_per_cycle());
458 engine_init_called = true;
462 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC Process eng-tme: %1 eng-pos: %2\n", now, sess_pos));
463 /* when the jack-graph changes and if ardour performs
464 * locates, the audioengine is stopped (skipping samples) while
465 * jack [time] moves along.
468 DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 samples. Feeding silence to LTC parser.\n", skip));
469 if (skip >= 8192) skip = 8192;
470 unsigned char sound[8192];
471 memset(sound, 0x80, sizeof(char) * skip);
472 ltc_decoder_write(decoder, sound, nframes, now);
473 } else if (skip != 0) {
474 /* this should never happen. it may if monotonic_cnt, now overflow on 64bit */
475 DEBUG_TRACE (DEBUG::LTC, string_compose("engine skipped %1 samples\n", skip));
479 parse_ltc(nframes, in, now);
483 if (last_timestamp == 0) {
484 DEBUG_TRACE (DEBUG::LTC, "last timestamp == 0\n");
486 pos = session.transport_sample();
488 } else if (ltc_speed != 0) {
489 if (delayedlocked > 1) delayedlocked--;
490 else if (current_delta == 0) delayedlocked = 0;
493 if (abs(now - last_timestamp) > FLYWHEEL_TIMEOUT) {
494 DEBUG_TRACE (DEBUG::LTC, "flywheel timeout\n");
497 pos = session.transport_sample();
498 ActiveChanged (false); /* EMIT SIGNAL */
502 /* it take 2 cycles from naught to rolling.
503 * during these to initial cycles the speed == 0
506 * DEBUG::Slave: slave stopped, move to NNN
507 * DEBUG::Transport: Request forced locate to NNN
508 * DEBUG::Slave: slave state 0 @ NNN speed 0 cur delta VERY-LARGE-DELTA avg delta 1800
509 * DEBUG::Slave: silent motion
510 * DEBUG::Transport: realtime stop @ NNN
511 * DEBUG::Transport: Butler transport work, todo = PostTransportStop,PostTransportLocate,PostTransportClearSubstate
513 * [engine skips samples to locate, jack time keeps rolling on]
517 * DEBUG::LTC: [re-]init Engine DLL
518 * DEBUG::Slave: slave stopped, move to NNN+
521 * we need to seek two cycles ahead: 2 * nframes
523 if (engine_dll_initstate == 0) {
524 DEBUG_TRACE (DEBUG::LTC, "engine DLL not initialized. ltc_speed\n");
526 pos = last_ltc_sample + rint(ltc_speed * double(2 * nframes + now - last_timestamp));
530 /* interpolate position according to speed and time since last LTC-sample*/
531 double speed_flt = ltc_speed;
532 double elapsed = (now - last_timestamp) * speed_flt;
534 if (!engine_init_called) {
535 const double e = elapsed + double (last_ltc_sample - sess_pos);
539 speed_flt = (t1 - t0) / double(session.engine().samples_per_cycle());
540 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() ));
542 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC adjusting elapsed (no DLL) from %1 by %2\n", elapsed, (2 * nframes * ltc_speed)));
544 elapsed += 2.0 * nframes * ltc_speed; /* see note above */
547 pos = last_ltc_sample + rint(elapsed);
549 current_delta = (pos - sess_pos);
551 if (((pos < 0) || (labs(current_delta) > 2 * session.sample_rate()))) {
552 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC large drift: %1\n", current_delta));
558 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTCsync spd: %1 pos: %2 | last-pos: %3 elapsed: %4 delta: %5\n",
559 speed, pos, last_ltc_sample, elapsed, current_delta));
561 /* provide a .1% deadzone to lock the speed */
562 if (fabs(speed - 1.0) <= 0.001) {
566 if (speed != 0 && delayedlocked == 0 && fabs(speed) != 1.0) {
567 sync_lock_broken = true;
568 DEBUG_TRACE (DEBUG::LTC, string_compose ("LTC speed not locked %1 %2\n", speed, ltc_speed));
574 Timecode::TimecodeFormat
575 LTC_Slave::apparent_timecode_format () const
577 if (timecode.rate == 24 && !timecode.drop)
579 else if (timecode.rate == 25 && !timecode.drop)
581 else if (rint(timecode.rate * 100) == 2997 && !timecode.drop)
582 return (Config->get_timecode_source_2997() ? timecode_2997000 : timecode_2997);
583 else if (rint(timecode.rate * 100) == 2997 && timecode.drop)
584 return (Config->get_timecode_source_2997() ? timecode_2997000drop : timecode_2997drop);
585 else if (timecode.rate == 30 && timecode.drop)
586 return timecode_2997drop; // timecode_30drop; // LTC counting to 30 samples w/DF *means* 29.97 df
587 else if (timecode.rate == 30 && !timecode.drop)
590 /* XXX - unknown timecode format */
591 return session.config.get_timecode_format();
595 LTC_Slave::approximate_current_position() const
597 if (last_timestamp == 0) {
598 return " --:--:--:--";
600 return Timecode::timecode_format_time(timecode);
604 LTC_Slave::approximate_current_delta() const
607 if (last_timestamp == 0 || engine_dll_initstate == 0) {
608 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
609 } else if ((monotonic_cnt - last_timestamp) > 2 * samples_per_ltc_frame) {
610 snprintf(delta, sizeof(delta), "%s", _("flywheel"));
612 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"%s\" face=\"monospace\" >%s%s%lld</span>sm",
613 sync_lock_broken ? "red" : "green",
614 LEADINGZERO(::llabs(current_delta)), PLUSMINUS(-current_delta), ::llabs(current_delta));
616 return std::string(delta);