summaryrefslogtreecommitdiff
path: root/libs/ardour/midi_clock_slave.cc
blob: 93ca9059ef8dbcd08e41f34dc1f1b9cc5f2ed9e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
    Copyright (C) 2008 Paul Davis
    Author: Hans Baier

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <cmath>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include "pbd/error.h"
#include "pbd/failed_constructor.h"
#include "pbd/pthread_utils.h"
#include "pbd/convert.h"

#include "midi++/port.h"

#include "ardour/audioengine.h"
#include "ardour/debug.h"
#include "ardour/midi_buffer.h"
#include "ardour/midi_port.h"
#include "ardour/session.h"
#include "ardour/tempo.h"
#include "ardour/transport_master.h"

#include "pbd/i18n.h"

using namespace std;
using namespace ARDOUR;
using namespace MIDI;
using namespace PBD;

#define ENGINE AudioEngine::instance()

MIDIClock_TransportMaster::MIDIClock_TransportMaster (std::string const & name, int ppqn)
	: TransportMaster (MIDIClock, name)
	, ppqn (ppqn)
	, last_timestamp (0)
	, should_be_position (0)
	, midi_clock_count (0)
	, _speed (0)
	, _running (false)
	, _bpm (0)
{
	if ((_port = create_midi_port (string_compose ("%1 in", name))) == 0) {
		throw failed_constructor();
	}
}

MIDIClock_TransportMaster::~MIDIClock_TransportMaster()
{
	port_connections.drop_connections ();
}

void
MIDIClock_TransportMaster::init ()
{
	midi_clock_count = 0;
	last_timestamp = 0;
}

void
MIDIClock_TransportMaster::set_session (Session *session)
{
	port_connections.drop_connections();
	_session = session;

	/* only connect to signals if we have a proxy, because otherwise we
	 * cannot interpet incoming data (no tempo map etc.)
	 */

	if (_session) {
		parser.timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::update_midi_clock, this, _1, _2));
		parser.start.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::start, this, _1, _2));
		parser.contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::contineu, this, _1, _2));
		parser.stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::stop, this, _1, _2));
		parser.position.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::position, this, _1, _2, 3));

		reset ();
	}
}

bool
MIDIClock_TransportMaster::speed_and_position (double& speed, samplepos_t& pos, samplepos_t now)
{
	if (!_running || !_collect) {
		return false;
	}

	if (fabs (_speed - 1.0) < 0.001) {
		speed = 1.0;
	} else {
		speed = _speed;
	}

	pos = should_be_position;
	pos += (now - last_timestamp) * _speed;

	return true;
}

void
MIDIClock_TransportMaster::pre_process (pframes_t nframes, samplepos_t now, boost::optional<samplepos_t> session_pos)
{
	/* Read and parse incoming MIDI */

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("preprocess with lt = %1 @ %2, running ? %3\n", last_timestamp, now, _running));

	_midi_port->read_and_parse_entire_midi_buffer_with_no_speed_adjustment (nframes, parser, now);

	/* no clock messages ever, or no clock messages for 1/4 second ? conclude that its stopped */

	if (!last_timestamp || (now > last_timestamp && ((now - last_timestamp) > (ENGINE->sample_rate() / 4)))) {
		_speed = 0.0;
		_bpm = 0.0;
		last_timestamp = 0;
		_running = false;
		_current_delta = 0;
		midi_clock_count = 0;

		DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock messages received for some time, stopping!\n");
		return;
	}

	if (!_running && midi_clock_count == 0 && session_pos) {
		should_be_position = *session_pos;
		DEBUG_TRACE (DEBUG::MidiClock, string_compose ("set sbp to %1\n", should_be_position));
	}

	if (session_pos) {
		const samplepos_t current_pos = should_be_position + ((now - last_timestamp) * _speed);
		_current_delta = current_pos - *session_pos;
	} else {
		_current_delta = 0;
	}

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", _speed, should_be_position, _session->transport_sample()));
}

void
MIDIClock_TransportMaster::calculate_one_ppqn_in_samples_at(samplepos_t time)
{
	const double samples_per_quarter_note = _session->tempo_map().samples_per_quarter_note_at (time, ENGINE->sample_rate());

	one_ppqn_in_samples = samples_per_quarter_note / double (ppqn);
	// DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_samples));
}

ARDOUR::samplepos_t
MIDIClock_TransportMaster::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
{
	samplepos_t song_position_samples = 0;
	for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
		// one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
		calculate_one_ppqn_in_samples_at(song_position_samples);
		song_position_samples += one_ppqn_in_samples * (samplepos_t)(ppqn / 4);
	}

	return song_position_samples;
}

void
MIDIClock_TransportMaster::calculate_filter_coefficients (double qpm)
{
	/* Paul says: I don't understand this computation of bandwidth
	*/

	const double bandwidth = 2.0 / qpm;

	/* Frequency of the clock messages is ENGINE->sample_rate() / * one_ppqn_in_samples, per second or in Hz */
	const double freq = (double) ENGINE->sample_rate() / one_ppqn_in_samples;

	const double omega = 2.0 * M_PI * bandwidth / freq;
	b = 1.4142135623730950488 * omega; // sqrt (2.0) * omega
	c = omega * omega;

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("DLL coefficients: bw:%1 omega:%2 b:%3 c:%4\n", bandwidth, omega, b, c));
}

void
MIDIClock_TransportMaster::update_midi_clock (Parser& /*parser*/, samplepos_t timestamp)
{
	samplepos_t elapsed_since_start = timestamp - first_timestamp;
	double e = 0;

	calculate_one_ppqn_in_samples_at (should_be_position);

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock count %1, sbp %2\n", midi_clock_count, should_be_position));

	if (midi_clock_count == 0) {
		/* second 0xf8 message after start/reset has arrived */

		first_timestamp = timestamp;
		last_timestamp = timestamp;

		DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));

		midi_clock_count++;

		should_be_position += one_ppqn_in_samples;

	} else if (midi_clock_count == 1) {

		/* second 0xf8 message has arrived. we can now estimate QPM
		 * (quarters per minute, and fully initialize the DLL
		 */

		e  = timestamp - last_timestamp;

		const samplecnt_t samples_per_quarter = e * 24;
		_bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;

		calculate_filter_coefficients (_bpm);

		/* finish DLL initialization */

		t0 = timestamp;
		e2 = e;
		t1 = t0 + e2; /* timestamp we predict for the next 0xf8 clock message */

		midi_clock_count++;
		should_be_position += one_ppqn_in_samples;

	} else {

		/* 3rd or later MIDI clock message. We can now compute actual
		 * speed (and tempo) with the DLL
		 */

		e = timestamp - t1; // error between actual time of arrival of clock message and our predicted time
		t0 = t1;
		t1 += b * e + e2;
		e2 += c * e;

		const double samples_per_quarter = (timestamp - last_timestamp) * 24.0;
		const double instantaneous_bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
		const double lpf_coeff = 0.05;

		const double predicted_clock_interval_in_samples = (t1 - t0);

		/* _speed is relative to session tempo map */

		_speed = predicted_clock_interval_in_samples / one_ppqn_in_samples;

		/* _bpm (really, _qpm) is absolute */

		/* detect substantial changes in apparent tempo (defined as a
		 * change of more than 20% of the current tempo.
		 */

		if (fabs (instantaneous_bpm - _bpm) > (0.20 * _bpm)) {
			_bpm = instantaneous_bpm;
		} else {
			_bpm += lpf_coeff * (instantaneous_bpm - _bpm);
		}

		calculate_filter_coefficients (_bpm);

		// need at least two clock events to compute speed

		if (!_running) {
			DEBUG_TRACE (DEBUG::MidiClock, string_compose ("start mclock running with speed = %1\n", (t1 - t0) / one_ppqn_in_samples));
			_running = true;
		}

		midi_clock_count++;
		should_be_position += one_ppqn_in_samples;
	}

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 should-be %3 transport %4 error %5 appspeed %6 "
						       "read-delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 engine %13 running %14\n",
						       midi_clock_count,                                          // #
						       elapsed_since_start,                                       // @
						       should_be_position,                                        // should-be
						       _session->transport_sample(),                                // transport
	                                               e,                                                     // error
						       (t1 - t0) / one_ppqn_in_samples, // appspeed
						       timestamp - last_timestamp,                                // read delta
						       one_ppqn_in_samples,                                        // should-be delta
	                                               (t1 - t0),                         // t1-t0
	                                               t0,                                // t0
						       t1,                                // t1
						       ENGINE->sample_rate(),                                      // framerate
	                                               ENGINE->sample_time(),
	                                               _running

	));

	last_timestamp = timestamp;
}

void
MIDIClock_TransportMaster::start (Parser& /*parser*/, samplepos_t timestamp)
{
	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()));

	if (!_running) {
		reset();
		_running = true;
		should_be_position = _session->transport_sample();
	}
}

void
MIDIClock_TransportMaster::reset ()
{
	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock Master reset(): calculated filter for period size %2\n", ENGINE->samples_per_cycle()));

	should_be_position = _session->transport_sample();
	_speed = 0;
	last_timestamp = 0;

	_running = false;
	_current_delta = 0;
}

void
MIDIClock_TransportMaster::contineu (Parser& /*parser*/, samplepos_t /*timestamp*/)
{
	DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got continue message\n");

	_running = true;
}

void
MIDIClock_TransportMaster::stop (Parser& /*parser*/, samplepos_t /*timestamp*/)
{
	DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got stop message\n");

	if (_running) {
		_running = false;
		_speed = 0;
		last_timestamp = 0;

		// we need to go back to the last MIDI beat (6 ppqn)
		// and lets hope the tempo didnt change in the meantime :)

		// begin at the should be position, because
		// that is the position of the last MIDI Clock
		// message and that is probably what the master
		// expects where we are right now
		//
		// find out the last MIDI beat: go back #midi_clocks mod 6
		// and lets hope the tempo didnt change in those last 6 beats :)
		should_be_position -= (midi_clock_count % 6) * one_ppqn_in_samples;
	}
}

void
MIDIClock_TransportMaster::position (Parser& /*parser*/, MIDI::byte* message, size_t size)
{
	// we are not supposed to get position messages while we are running
	// so lets be robust and ignore those
	if (_running) {
		return;
	}

	assert(size == 3);
	MIDI::byte lsb = message[1];
	MIDI::byte msb = message[2];
	assert((lsb <= 0x7f) && (msb <= 0x7f));

	uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
	samplepos_t position_in_samples = calculate_song_position(position_in_sixteenth_notes);

	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 samples: %2\n", position_in_sixteenth_notes, position_in_samples));

	should_be_position = position_in_samples;
	last_timestamp = 0;

}

bool
MIDIClock_TransportMaster::locked () const
{
	return true;
}

bool
MIDIClock_TransportMaster::ok() const
{
	return true;
}

bool
MIDIClock_TransportMaster::starting() const
{
	return false;
}

ARDOUR::samplecnt_t
MIDIClock_TransportMaster::resolution() const
{
	// one beat
	return (samplecnt_t) one_ppqn_in_samples * ppqn;
}

std::string
MIDIClock_TransportMaster::position_string () const
{
	return std::string();
}

std::string
MIDIClock_TransportMaster::delta_string() const
{
	char delta[80];
	if (last_timestamp == 0 || starting()) {
		snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
	} else {
		snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
				LEADINGZERO(abs(_current_delta)), PLUSMINUS(-_current_delta), abs(_current_delta));
	}
	return std::string(delta);
}