summaryrefslogtreecommitdiff
path: root/libs/backends/alsa/alsa_midi.cc
blob: 8bf7f4aecedbba182d2fd029f2f175aa0a78bca3 (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
/*
 * Copyright (C) 2014 Robin Gareus <robin@gareus.org>
 *
 * 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 <unistd.h>

#include <glibmm.h>

#include "alsa_midi.h"

#include "pbd/error.h"
#include "pbd/pthread_utils.h"
#include "pbd/i18n.h"

using namespace ARDOUR;

#ifndef NDEBUG
#define _DEBUGPRINT(STR) fprintf(stderr, STR);
#else
#define _DEBUGPRINT(STR) ;
#endif

AlsaMidiIO::AlsaMidiIO ()
	: _state (-1)
	, _running (false)
	, _pfds (0)
	, _sample_length_us (1e6 / 48000.0)
	, _period_length_us (1.024e6 / 48000.0)
	, _samples_per_period (1024)
	, _rb (0)
{
	pthread_mutex_init (&_notify_mutex, 0);
	pthread_cond_init (&_notify_ready, 0);

	// MIDI (hw port) 31.25 kbaud
	// worst case here is  8192 SPP and 8KSPS for which we'd need
	// 4000 bytes sans MidiEventHeader.
	// since we're not always in sync, let's use 4096.
	_rb = new PBD::RingBuffer<uint8_t>(4096 + 4096 * sizeof(MidiEventHeader));
}

AlsaMidiIO::~AlsaMidiIO ()
{
	delete _rb;
	pthread_mutex_destroy (&_notify_mutex);
	pthread_cond_destroy (&_notify_ready);
	free (_pfds);
}

static void * pthread_process (void *arg)
{
	AlsaMidiIO *d = static_cast<AlsaMidiIO *>(arg);
	d->main_process_thread ();
	pthread_exit (0);
	return 0;
}

int
AlsaMidiIO::start ()
{
	if (pbd_realtime_pthread_create (PBD_SCHED_FIFO, -21, 100000,
				&_main_thread, pthread_process, this))
	{
		if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
			PBD::error << _("AlsaMidiIO: Failed to create process thread.") << endmsg;
			return -1;
		} else {
			PBD::warning << _("AlsaMidiIO: Cannot acquire realtime permissions.") << endmsg;
		}
	}
	int timeout = 5000;
	while (!_running && --timeout > 0) { Glib::usleep (1000); }
	if (timeout == 0 || !_running) {
		return -1;
	}
	return 0;
}

int
AlsaMidiIO::stop ()
{
	void *status;
	if (!_running) {
		return 0;
	}

	_running = false;

	pthread_mutex_lock (&_notify_mutex);
	pthread_cond_signal (&_notify_ready);
	pthread_mutex_unlock (&_notify_mutex);

	if (pthread_join (_main_thread, &status)) {
		PBD::error << _("AlsaMidiIO: Failed to terminate.") << endmsg;
		return -1;
	}
	return 0;
}

void
AlsaMidiIO::setup_timing (const size_t samples_per_period, const float samplerate)
{
	_period_length_us = (double) samples_per_period * 1e6 / samplerate;
	_sample_length_us = 1e6 / samplerate;
	_samples_per_period = samples_per_period;
}

void
AlsaMidiIO::sync_time (const uint64_t tme)
{
	// TODO consider a PLL, if this turns out to be the bottleneck for jitter
	// also think about using
	// snd_pcm_status_get_tstamp() and snd_rawmidi_status_get_tstamp()
	// instead of monotonic clock.
#ifdef DEBUG_TIMING
	double tdiff = (_clock_monotonic + _period_length_us - tme) / 1000.0;
	if (abs(tdiff) >= .05) {
		printf("AlsaMidiIO MJ: %.1f ms\n", tdiff);
	}
#endif
	_clock_monotonic = tme;
}

///////////////////////////////////////////////////////////////////////////////

AlsaMidiOut::AlsaMidiOut ()
	: AlsaMidiIO ()
{
}

int
AlsaMidiOut::send_event (const pframes_t time, const uint8_t *data, const size_t size)
{
	const uint32_t  buf_size = sizeof (MidiEventHeader) + size;
	if (_rb->write_space() < buf_size) {
		_DEBUGPRINT("AlsaMidiOut: ring buffer overflow\n");
		return -1;
	}
	struct MidiEventHeader h (_clock_monotonic + time * _sample_length_us, size);
	_rb->write ((uint8_t*) &h, sizeof(MidiEventHeader));
	_rb->write (data, size);

	if (pthread_mutex_trylock (&_notify_mutex) == 0) {
		pthread_cond_signal (&_notify_ready);
		pthread_mutex_unlock (&_notify_mutex);
	}
	return 0;
}

///////////////////////////////////////////////////////////////////////////////

AlsaMidiIn::AlsaMidiIn ()
	: AlsaMidiIO ()
{
}

size_t
AlsaMidiIn::recv_event (pframes_t &time, uint8_t *data, size_t &size)
{
	const uint32_t read_space = _rb->read_space();
	struct MidiEventHeader h(0,0);

	if (read_space <= sizeof(MidiEventHeader)) {
		return 0;
	}

	PBD::RingBuffer<uint8_t>::rw_vector vector;
	_rb->get_read_vector(&vector);
	if (vector.len[0] >= sizeof(MidiEventHeader)) {
		memcpy((uint8_t*)&h, vector.buf[0], sizeof(MidiEventHeader));
	} else {
		if (vector.len[0] > 0) {
			memcpy ((uint8_t*)&h, vector.buf[0], vector.len[0]);
		}
		assert(vector.buf[1]);
		memcpy (((uint8_t*)&h) + vector.len[0], vector.buf[1], sizeof(MidiEventHeader) - vector.len[0]);
	}

	if (h.time >= _clock_monotonic + _period_length_us ) {
#ifdef DEBUG_TIMING
		printf("AlsaMidiIn DEBUG: POSTPONE EVENT TO NEXT CYCLE: %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
#endif
		return 0;
	}
	_rb->increment_read_idx (sizeof(MidiEventHeader));

	assert (h.size > 0);
	if (h.size > size) {
		_DEBUGPRINT("AlsaMidiIn::recv_event MIDI event too large!\n");
		_rb->increment_read_idx (h.size);
		return 0;
	}
	if (_rb->read (&data[0], h.size) != h.size) {
		_DEBUGPRINT("AlsaMidiIn::recv_event Garbled MIDI EVENT DATA!!\n");
		return 0;
	}
	if (h.time < _clock_monotonic) {
#ifdef DEBUG_TIMING
		printf("AlsaMidiIn DEBUG: MIDI TIME < 0 %.1f spl\n", ((_clock_monotonic - h.time) / -_sample_length_us));
#endif
		time = 0;
	} else if (h.time >= _clock_monotonic + _period_length_us ) {
#ifdef DEBUG_TIMING
		printf("AlsaMidiIn DEBUG: MIDI TIME > PERIOD %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
#endif
		time = _samples_per_period - 1;
	} else {
		time = floor ((h.time - _clock_monotonic) / _sample_length_us);
	}
	assert(time < _samples_per_period);
	size = h.size;
	return h.size;
}

int
AlsaMidiIn::queue_event (const uint64_t time, const uint8_t *data, const size_t size) {
	const uint32_t  buf_size = sizeof(MidiEventHeader) + size;

	if (size == 0) {
		return -1;
	}
	if (_rb->write_space() < buf_size) {
		_DEBUGPRINT("AlsaMidiIn: ring buffer overflow\n");
		return -1;
	}
	struct MidiEventHeader h (time, size);
	_rb->write ((uint8_t*) &h, sizeof(MidiEventHeader));
	_rb->write (data, size);
	return 0;
}