1 /*
2  * Copyright (C) 2008-2013 Hans Baier <hansfbaier@googlemail.com>
3  * Copyright (C) 2009-2010 Carl Hetherington <carl@carlh.net>
4  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
5  * Copyright (C) 2009-2019 Paul Davis <paul@linuxaudiosystems.com>
6  * Copyright (C) 2012-2013 Robin Gareus <robin@gareus.org>
7  * Copyright (C) 2013-2018 John Emmas <john@creativepost.co.uk>
8  * Copyright (C) 2015-2016 Nick Mainsbridge <mainsbridge@gmail.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
25 #include <cmath>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 #include "pbd/error.h"
30 #include "pbd/failed_constructor.h"
31 #include "pbd/pthread_utils.h"
32 #include "pbd/convert.h"
33 
34 #include "midi++/port.h"
35 
36 #include "ardour/audioengine.h"
37 #include "ardour/debug.h"
38 #include "ardour/midi_buffer.h"
39 #include "ardour/midi_port.h"
40 #include "ardour/session.h"
41 #include "ardour/tempo.h"
42 #include "ardour/transport_master.h"
43 #include "ardour/transport_master_manager.h"
44 
45 #include "pbd/i18n.h"
46 
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace MIDI;
50 using namespace PBD;
51 
52 #define ENGINE AudioEngine::instance()
53 
MIDIClock_TransportMaster(std::string const & name,int ppqn)54 MIDIClock_TransportMaster::MIDIClock_TransportMaster (std::string const & name, int ppqn)
55 	: TransportMaster (MIDIClock, name)
56 	, ppqn (ppqn)
57 	, midi_clock_count (0)
58 	, _running (false)
59 	, _bpm (0)
60 {
61 }
62 
~MIDIClock_TransportMaster()63 MIDIClock_TransportMaster::~MIDIClock_TransportMaster()
64 {
65 	port_connections.drop_connections ();
66 }
67 
68 void
init()69 MIDIClock_TransportMaster::init ()
70 {
71 	midi_clock_count = 0;
72 	current.reset ();
73 	resync_latency (false);
74 }
75 
76 void
connection_handler(boost::weak_ptr<ARDOUR::Port> w0,std::string n0,boost::weak_ptr<ARDOUR::Port> w1,std::string n1,bool con)77 MIDIClock_TransportMaster::connection_handler (boost::weak_ptr<ARDOUR::Port> w0, std::string n0, boost::weak_ptr<ARDOUR::Port> w1, std::string n1, bool con)
78 {
79 	TransportMaster::connection_handler(w0, n0, w1, n1, con);
80 
81 	boost::shared_ptr<Port> p = w1.lock ();
82 	if (p == _port) {
83 		resync_latency (false);
84 	}
85 }
86 
87 void
create_port()88 MIDIClock_TransportMaster::create_port ()
89 {
90 	if ((_port = create_midi_port (string_compose ("%1 in", _name))) == 0) {
91 		throw failed_constructor();
92 	}
93 }
94 
95 void
set_session(Session * s)96 MIDIClock_TransportMaster::set_session (Session* s)
97 {
98 	TransportMaster::set_session (s);
99 	TransportMasterViaMIDI::set_session (s);
100 
101 	port_connections.drop_connections();
102 
103 	/* only connect to signals if we have a proxy, because otherwise we
104 	 * cannot interpet incoming data (no tempo map etc.)
105 	 */
106 
107 	if (_session) {
108 		parser.timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::update_midi_clock, this, _1, _2));
109 		parser.start.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::start, this, _1, _2));
110 		parser.contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::contineu, this, _1, _2));
111 		parser.stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::stop, this, _1, _2));
112 		parser.position.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::position, this, _1, _2, _3, _4));
113 
114 		reset (true);
115 	}
116 }
117 
118 void
pre_process(MIDI::pframes_t nframes,samplepos_t now,boost::optional<samplepos_t> session_pos)119 MIDIClock_TransportMaster::pre_process (MIDI::pframes_t nframes, samplepos_t now, boost::optional<samplepos_t> session_pos)
120 {
121 	/* Read and parse incoming MIDI */
122 	if (!_midi_port) {
123 		_bpm = 0.0;
124 		_running = false;
125 		_current_delta = 0;
126 		midi_clock_count = 0;
127 		DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock port registered");
128 		return;
129 	}
130 
131 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("preprocess with lt = %1 @ %2, running ? %3\n", current.timestamp, now, _running));
132 
133 	_midi_port->read_and_parse_entire_midi_buffer_with_no_speed_adjustment (nframes, parser, now);
134 
135 	/* no clock messages ever, or no clock messages for 1/4 second ? conclude that its stopped */
136 
137 	if (!current.timestamp || one_ppqn_in_samples == 0 || (now > current.timestamp && ((now - current.timestamp) > (ENGINE->sample_rate() / 4)))) {
138 		_bpm = 0.0;
139 		_running = false;
140 		_current_delta = 0;
141 		midi_clock_count = 0;
142 
143 		DEBUG_TRACE (DEBUG::MidiClock, string_compose ("No MIDI Clock messages received for some time, stopping! ts = %1 @ %2 ppqn = %3\n", current.timestamp, now, one_ppqn_in_samples));
144 		return;
145 	}
146 
147 	if (session_pos) {
148 		const samplepos_t current_pos = current.position + ((now - current.timestamp) * current.speed);
149 		_current_delta = current_pos - *session_pos;
150 	} else {
151 		_current_delta = 0;
152 	}
153 
154 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", current.speed, current.position, _session->transport_sample()));
155 }
156 
157 void
calculate_one_ppqn_in_samples_at(samplepos_t time)158 MIDIClock_TransportMaster::calculate_one_ppqn_in_samples_at(samplepos_t time)
159 {
160 	const double samples_per_quarter_note = _session->tempo_map().samples_per_quarter_note_at (time, ENGINE->sample_rate());
161 
162 	one_ppqn_in_samples = samples_per_quarter_note / double (ppqn);
163 	// DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2 [spl] spqn = %3, ppqn = %4\n", time, one_ppqn_in_samples, samples_per_quarter_note, ppqn));
164 }
165 
166 ARDOUR::samplepos_t
calculate_song_position(uint16_t song_position_in_sixteenth_notes)167 MIDIClock_TransportMaster::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
168 {
169 	samplepos_t song_position_samples = 0;
170 	for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
171 		// one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
172 		calculate_one_ppqn_in_samples_at(song_position_samples);
173 		song_position_samples += one_ppqn_in_samples * (samplepos_t)(ppqn / 4);
174 	}
175 
176 	return song_position_samples;
177 }
178 
179 void
calculate_filter_coefficients(double qpm)180 MIDIClock_TransportMaster::calculate_filter_coefficients (double qpm)
181 {
182 	/* Paul says: I don't understand this computation of bandwidth
183 	*/
184 
185 	const double bandwidth = 2.0 / qpm;
186 
187 	/* Frequency of the clock messages is ENGINE->sample_rate() / * one_ppqn_in_samples, per second or in Hz */
188 	const double freq = (double) ENGINE->sample_rate() / one_ppqn_in_samples;
189 
190 	const double omega = 2.0 * M_PI * bandwidth / freq;
191 	b = 1.4142135623730950488 * omega; // sqrt (2.0) * omega
192 	c = omega * omega;
193 
194 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("DLL coefficients: bw:%1 omega:%2 b:%3 c:%4\n", bandwidth, omega, b, c));
195 }
196 
197 void
update_midi_clock(Parser &,samplepos_t timestamp)198 MIDIClock_TransportMaster::update_midi_clock (Parser& /*parser*/, samplepos_t timestamp)
199 {
200 	samplepos_t elapsed_since_start = timestamp - first_timestamp;
201 
202 	calculate_one_ppqn_in_samples_at (current.position);
203 
204 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock count %1, sbp %2\n", midi_clock_count, current.position));
205 
206 	if (midi_clock_count == 0) {
207 		/* second 0xf8 message after start/reset has arrived */
208 
209 		first_timestamp = timestamp;
210 		current.update (0, timestamp, 0);
211 
212 		DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));
213 
214 		midi_clock_count++;
215 
216 	} else if (midi_clock_count == 1) {
217 
218 		/* second 0xf8 message has arrived. we can now estimate QPM
219 		 * (quarters per minute, and fully initialize the DLL
220 		 */
221 
222 		e2 = timestamp - current.timestamp;
223 
224 		const samplecnt_t samples_per_quarter = e2 * 24;
225 		double bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
226 
227 		if (bpm < 1 || bpm > 999) {
228 			current.update (0, timestamp, 0);
229 			midi_clock_count = 1; /* start over */
230 			DEBUG_TRACE (DEBUG::MidiClock, string_compose ("BPM is out of bounds (%1)\n", timestamp, current.timestamp));
231 		} else {
232 			_bpm = bpm;
233 
234 			calculate_filter_coefficients (_bpm);
235 
236 			/* finish DLL initialization */
237 
238 			t0 = timestamp;
239 			t1 = t0 + e2; /* timestamp we predict for the next 0xf8 clock message */
240 
241 			midi_clock_count++;
242 			current.update (one_ppqn_in_samples + midi_port_latency.max, timestamp, 0);
243 		}
244 
245 	} else {
246 
247 		/* 3rd or later MIDI clock message. We can now compute actual
248 		 * speed (and tempo) with the DLL
249 		 */
250 
251 		double e = timestamp - t1; // error between actual time of arrival of clock message and our predicted time
252 		t0 = t1;
253 		t1 += b * e + e2;
254 		e2 += c * e;
255 
256 		const double samples_per_quarter = (timestamp - current.timestamp) * 24.0;
257 		const double instantaneous_bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
258 
259 		const double predicted_clock_interval_in_samples = (t1 - t0);
260 
261 		/* _speed is relative to session tempo map */
262 
263 		double speed = predicted_clock_interval_in_samples / one_ppqn_in_samples;
264 
265 		/* _bpm (really, _qpm) is absolute */
266 
267 		/* detect substantial changes in apparent tempo (defined as a
268 		 * change of more than 20% of the current tempo.
269 		 */
270 
271 		const double lpf_coeff = 0.063;
272 
273 		if (fabs (instantaneous_bpm - _bpm) > (0.20 * _bpm)) {
274 			_bpm = instantaneous_bpm;
275 		} else {
276 			_bpm += lpf_coeff * (instantaneous_bpm - _bpm);
277 		}
278 
279 		calculate_filter_coefficients (_bpm);
280 
281 		// need at least two clock events to compute speed
282 
283 		if (!_running) {
284 			DEBUG_TRACE (DEBUG::MidiClock, string_compose ("start mclock running with speed = %1\n", (t1 - t0) / one_ppqn_in_samples));
285 			_running = true;
286 		}
287 
288 		midi_clock_count++;
289 		current.update (current.position + one_ppqn_in_samples, timestamp, speed);
290 
291 		if (TransportMasterManager::instance().current().get() == this) {
292 			_session->maybe_update_tempo_from_midiclock_tempo (_bpm);
293 		}
294 	}
295 
296 	DEBUG_TRACE (DEBUG::MidiClock, string_compose (
297 	             "clock #%1 @ %2 should-be %3 transport %4 appspeed %6 "
298 	             "read-delta %7 should-be-delta %8 t1-t0 %9 t0 %10 t1 %11 sample-rate %12 engine %13 running %14\n",
299 	             midi_clock_count,                 // #
300 	             elapsed_since_start,              // @
301 	             current.position,                 // should-be
302 	             _session->transport_sample(),     // transport
303 	             (t1 - t0) / one_ppqn_in_samples,  // appspeed
304 	             timestamp - current.timestamp,    // read delta
305 	             one_ppqn_in_samples,              // should-be delta
306 	             (t1 - t0),                        // t1-t0
307 	             t0,                               // t0 (current position)
308 	             t1,                               // t1 (expected next pos)
309 	             ENGINE->sample_rate(),            // framerate
310 	             ENGINE->sample_time(),
311 	             _running
312 
313 	));
314 }
315 
316 void
start(Parser &,samplepos_t timestamp)317 MIDIClock_TransportMaster::start (Parser& /*parser*/, samplepos_t timestamp)
318 {
319 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_TransportMaster got start message at time %1 engine time %2 transport_sample %3\n", timestamp, ENGINE->sample_time(), _session->transport_sample()));
320 
321 	if (!_running) {
322 		reset(true);
323 		_running = true;
324 		current.update (_session->transport_sample(), timestamp, 0);
325 	}
326 }
327 
328 void
reset(bool with_position)329 MIDIClock_TransportMaster::reset (bool with_position)
330 {
331 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock Master reset(): calculated filter for period size %2\n", ENGINE->samples_per_cycle()));
332 
333 	if (with_position) {
334 		current.update (_session->transport_sample(), 0, 0);
335 	} else {
336 		current.reset ();
337 	}
338 
339 	_running = false;
340 	_current_delta = 0;
341 }
342 
343 void
contineu(Parser &,samplepos_t)344 MIDIClock_TransportMaster::contineu (Parser& /*parser*/, samplepos_t /*timestamp*/)
345 {
346 	DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got continue message\n");
347 
348 	_running = true;
349 }
350 
351 void
stop(Parser &,samplepos_t timestamp)352 MIDIClock_TransportMaster::stop (Parser& /*parser*/, samplepos_t timestamp)
353 {
354 	DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got stop message\n");
355 
356 	if (_running) {
357 		_running = false;
358 
359 		// we need to go back to the last MIDI beat (6 ppqn)
360 		// and lets hope the tempo didnt change in the meantime :)
361 
362 		// begin at the should be position, because
363 		// that is the position of the last MIDI Clock
364 		// message and that is probably what the master
365 		// expects where we are right now
366 		//
367 		// find out the last MIDI beat: go back #midi_clocks mod 6
368 		// and lets hope the tempo didnt change in those last 6 beats :)
369 		current.update (current.position - (midi_clock_count % 6) * one_ppqn_in_samples, 0, 0);
370 	}
371 }
372 
373 void
position(Parser &,MIDI::byte * message,size_t size,samplepos_t timestamp)374 MIDIClock_TransportMaster::position (Parser& /*parser*/, MIDI::byte* message, size_t size, samplepos_t timestamp)
375 {
376 	// we are not supposed to get position messages while we are running
377 	// so lets be robust and ignore those
378 	if (_running) {
379 		return;
380 	}
381 
382 	assert(size == 3);
383 	MIDI::byte lsb = message[1];
384 	MIDI::byte msb = message[2];
385 	assert((lsb <= 0x7f) && (msb <= 0x7f));
386 
387 	uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
388 	samplepos_t position_in_samples = calculate_song_position(position_in_sixteenth_notes);
389 
390 	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 samples: %2\n", position_in_sixteenth_notes, position_in_samples));
391 
392 	current.update (position_in_samples + midi_port_latency.max, timestamp, current.speed);
393 }
394 
395 bool
locked() const396 MIDIClock_TransportMaster::locked () const
397 {
398 	return true;
399 }
400 
401 bool
ok() const402 MIDIClock_TransportMaster::ok() const
403 {
404 	return true;
405 }
406 
407 ARDOUR::samplecnt_t
update_interval() const408 MIDIClock_TransportMaster::update_interval() const
409 {
410 	if (one_ppqn_in_samples) {
411 		return resolution ();
412 	}
413 
414 	return AudioEngine::instance()->sample_rate() / 120 / 4; /* pure guesswork */
415 }
416 
417 ARDOUR::samplecnt_t
resolution() const418 MIDIClock_TransportMaster::resolution() const
419 {
420 	// one beat
421 	return (samplecnt_t) one_ppqn_in_samples * ppqn;
422 }
423 
424 std::string
position_string() const425 MIDIClock_TransportMaster::position_string () const
426 {
427 	return std::string();
428 }
429 
430 std::string
delta_string() const431 MIDIClock_TransportMaster::delta_string() const
432 {
433 	SafeTime last;
434 	current.safe_read (last);
435 
436 	if (last.timestamp == 0 || starting()) {
437 		return X_("\u2012\u2012\u2012\u2012");
438 	} else {
439 		return format_delta_time (_current_delta);
440 	}
441 }
442 
443 void
unregister_port()444 MIDIClock_TransportMaster::unregister_port ()
445 {
446 	_midi_port.reset ();
447 	TransportMaster::unregister_port ();
448 }
449 
450