summaryrefslogtreecommitdiff
path: root/libs/ardour/midi_clock_slave.cc
blob: 273c397733a72b211ac92bfb977d1f8c161a8631 (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
/*
    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/debug.h"
#include "ardour/midi_buffer.h"
#include "ardour/midi_port.h"
#include "ardour/slave.h"
#include "ardour/tempo.h"

#include "pbd/i18n.h"

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

MIDIClock_Slave::MIDIClock_Slave (Session& s, MidiPort& p, int ppqn)
	: ppqn (ppqn)
	, bandwidth (2.0 / 60.0) // 1 BpM = 1 / 60 Hz
{
	session = (ISlaveSessionProxy *) new SlaveSessionProxy(s);
	rebind (p);
	reset ();
}

MIDIClock_Slave::MIDIClock_Slave (ISlaveSessionProxy* session_proxy, int ppqn)
	: session(session_proxy)
	, ppqn (ppqn)
	, bandwidth (2.0 / 60.0) // 1 BpM = 1 / 60 Hz
{
	reset ();
}

MIDIClock_Slave::~MIDIClock_Slave()
{
	delete session;
}

void
MIDIClock_Slave::rebind (MidiPort& port)
{
	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave: connecting to port %1\n", port.name()));

	port_connections.drop_connections ();

	port.self_parser().timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::update_midi_clock, this, _1, _2));
	port.self_parser().start.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::start, this, _1, _2));
	port.self_parser().contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::contineu, this, _1, _2));
	port.self_parser().stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::stop, this, _1, _2));
	port.self_parser().position.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::position, this, _1, _2, 3));

}

void
MIDIClock_Slave::calculate_one_ppqn_in_samples_at(samplepos_t time)
{
	const double samples_per_quarter_note = session->tempo_map().samples_per_quarter_note_at (time, session->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_Slave::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_Slave::calculate_filter_coefficients()
{
	// omega = 2 * PI * Bandwidth / MIDI clock sample frequency in Hz
	omega = 2.0 * M_PI * bandwidth * one_ppqn_in_samples / session->sample_rate();
	b = 1.4142135623730950488 * omega;
	c = omega * omega;
}

void
MIDIClock_Slave::update_midi_clock (Parser& /*parser*/, samplepos_t timestamp)
{
	// some pieces of hardware send MIDI Clock all the time
	if ( (!_starting) && (!_started) ) {
		return;
	}

	pframes_t cycle_offset = timestamp - session->sample_time_at_cycle_start();

	calculate_one_ppqn_in_samples_at(should_be_position);

	samplepos_t elapsed_since_start = timestamp - first_timestamp;
	double error = 0;

	if (_starting || last_timestamp == 0) {
		midi_clock_count = 0;

		first_timestamp = timestamp;
		elapsed_since_start = should_be_position;

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

		// calculate filter coefficients
		calculate_filter_coefficients();

		// initialize DLL
		e2 = double(one_ppqn_in_samples) / double(session->sample_rate());
		t0 = double(elapsed_since_start) / double(session->sample_rate());
		t1 = t0 + e2;

		// let ardour go after first MIDI Clock Event
		_starting = false;
	} else {
		midi_clock_count++;
		should_be_position  += one_ppqn_in_samples;
		calculate_filter_coefficients();

		// calculate loop error
		// we use session->transport_sample() instead of t1 here
		// because t1 is used to calculate the transport speed,
		// so the loop will compensate for accumulating rounding errors
		error = (double(should_be_position) - (double(session->transport_sample()) + double(cycle_offset)));
		e = error / double(session->sample_rate());
		current_delta = error;

		// update DLL
		t0 = t1;
		t1 += b * e + e2;
		e2 += c * e;
	}

	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\n",
						       midi_clock_count,                                          // #
						       elapsed_since_start,                                       // @
						       should_be_position,                                        // should-be
						       session->transport_sample(),                                // transport
						       error,                                                     // error
						       ((t1 - t0) * session->sample_rate()) / one_ppqn_in_samples, // appspeed
						       timestamp - last_timestamp,                                // read delta
						       one_ppqn_in_samples,                                        // should-be delta
						       (t1 - t0) * session->sample_rate(),                         // t1-t0
						       t0 * session->sample_rate(),                                // t0
						       t1 * session->sample_rate(),                                // t1
						       session->sample_rate(),                                      // framerate
						       session->sample_time()

	));

	last_timestamp = timestamp;
}

void
MIDIClock_Slave::start (Parser& /*parser*/, samplepos_t timestamp)
{
	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave got start message at time %1 engine time %2 transport_sample %3\n", timestamp, session->sample_time(), session->transport_sample()));

	if (!_started) {
		reset();

		_started = true;
		_starting = true;

		should_be_position = session->transport_sample();
	}
}

void
MIDIClock_Slave::reset ()
{
	DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock_Slave reset(): calculated filter bandwidth is %1 for period size %2\n", bandwidth, session->samples_per_cycle()));

	should_be_position = session->transport_sample();
	last_timestamp = 0;

	_starting = true;
	_started  = true;

	// session->request_locate(0, false);
	current_delta = 0;
}

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

	if (!_started) {
		_starting = true;
		_started  = true;
	}
}


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

	if (_started || _starting) {
		_starting = false;
		_started  = false;
		// locate to last MIDI clock position
		session->request_transport_speed(0.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
		samplepos_t stop_position = should_be_position;

		// find out the last MIDI beat: go back #midi_clocks mod 6
		// and lets hope the tempo didnt change in those last 6 beats :)
		stop_position -= (midi_clock_count % 6) * one_ppqn_in_samples;

		session->request_locate(stop_position, false);
		should_be_position = stop_position;
		last_timestamp = 0;
	}
}

void
MIDIClock_Slave::position (Parser& /*parser*/, MIDI::byte* message, size_t size)
{
	// we are note supposed to get position messages while we are running
	// so lets be robust and ignore those
	if (_started || _starting) {
		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));

	session->request_locate(position_in_samples, false);
	should_be_position  = position_in_samples;
	last_timestamp = 0;

}

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

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

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

bool
MIDIClock_Slave::stop_if_no_more_clock_events(samplepos_t& pos, samplepos_t now)
{
	/* no timecode for 1/4 second ? conclude that its stopped */
	if (last_timestamp &&
	    now > last_timestamp &&
	    now - last_timestamp > session->sample_rate() / 4) {
		DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock samples received for some time, stopping!\n");
		pos = should_be_position;
		session->request_transport_speed (0);
		session->request_locate (should_be_position, false);
		return true;
	} else {
		return false;
	}
}

bool
MIDIClock_Slave::speed_and_position (double& speed, samplepos_t& pos)
{
	if (!_started || _starting) {
		speed = 0.0;
		pos   = should_be_position;
		return true;
	}

	samplepos_t engine_now = session->sample_time();

	if (stop_if_no_more_clock_events(pos, engine_now)) {
		return false;
	}

	// calculate speed
	speed = ((t1 - t0) * session->sample_rate()) / one_ppqn_in_samples;

	// provide a 0.1% deadzone to lock the speed
	if (fabs(speed - 1.0) <= 0.001)
	        speed = 1.0;

	// calculate position
	if (engine_now > last_timestamp) {
		// we are in between MIDI clock messages
		// so we interpolate position according to speed
		samplecnt_t elapsed = engine_now - last_timestamp;
		pos = (samplepos_t) (should_be_position + double(elapsed) * speed);
	} else {
		// A new MIDI clock message has arrived this cycle
		pos = should_be_position;
	}

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

	return true;
}

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

std::string
MIDIClock_Slave::approximate_current_delta() 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);
}