fix my usual geometric/geographic dyslexia w.r.t jack midi port connection restoration
[ardour.git] / libs / midi++2 / jack_midiport.cc
1 /*
2   Copyright (C) 2006 Paul Davis 
3   Written by Dave Robillard
4  
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.
9  
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.
14  
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.
18 */
19
20 #include <fcntl.h>
21 #include <cerrno>
22 #include <cassert>
23 #include <cstring>
24 #include <cstdlib>
25
26 #include "pbd/error.h"
27 #include "pbd/compose.h"
28 #include "pbd/strsplit.h"
29
30 #include "midi++/types.h"
31 #include "midi++/jack.h"
32
33 using namespace std;
34 using namespace MIDI;
35 using namespace PBD;
36
37 pthread_t JACK_MidiPort::_process_thread;
38
39 Signal0<void> JACK_MidiPort::JackHalted;
40 Signal0<void> JACK_MidiPort::MakeConnections;
41
42 JACK_MidiPort::JACK_MidiPort(const XMLNode& node, jack_client_t* jack_client)
43         : Port(node)
44         , _jack_client(jack_client)
45         , _jack_input_port(NULL)
46         , _jack_output_port(NULL)
47         , _last_read_index(0)
48         , output_fifo (512)
49         , input_fifo (1024)
50 {
51         if (!create_ports (node)) {
52                 _ok = true;
53         }
54
55         MakeConnections.connect_same_thread (connect_connection, boost::bind (&JACK_MidiPort::make_connections, this));
56         JackHalted.connect_same_thread (halt_connection, boost::bind (&JACK_MidiPort::jack_halted, this));
57
58         set_state (node);
59 }
60
61 JACK_MidiPort::~JACK_MidiPort()
62 {
63         if (_jack_input_port) {
64                 if (_jack_client) {
65                         jack_port_unregister (_jack_client, _jack_input_port);
66                 }
67                 _jack_input_port = 0;
68         }
69
70         if (_jack_output_port) {
71                 if (_jack_client) {
72                         jack_port_unregister (_jack_client, _jack_input_port);
73                 }
74                 _jack_input_port = 0;
75         }
76 }
77
78 void
79 JACK_MidiPort::jack_halted ()
80 {
81         _jack_client = 0;
82         _jack_input_port = 0;
83         _jack_output_port = 0;
84 }
85
86 void
87 JACK_MidiPort::cycle_start (nframes_t nframes)
88 {
89         Port::cycle_start(nframes);
90         assert(_nframes_this_cycle == nframes);
91         _last_read_index = 0;
92         _last_write_timestamp = 0;
93
94         if (_jack_output_port != 0) {
95                 // output
96                 void *buffer = jack_port_get_buffer (_jack_output_port, nframes);
97                 jack_midi_clear_buffer (buffer);
98                 flush (buffer); 
99         }
100         
101         if (_jack_input_port != 0) {
102                 // input
103                 void* jack_buffer = jack_port_get_buffer(_jack_input_port, nframes);
104                 const nframes_t event_count = jack_midi_get_event_count(jack_buffer);
105
106                 jack_midi_event_t ev;
107                 timestamp_t cycle_start_frame = jack_last_frame_time (_jack_client);
108
109                 for (nframes_t i = 0; i < event_count; ++i) {
110                         jack_midi_event_get (&ev, jack_buffer, i);
111                         input_fifo.write (cycle_start_frame + ev.time, (Evoral::EventType) 0, ev.size, ev.buffer);
112                 }       
113                 
114                 if (event_count) {
115                         xthread.wakeup ();
116                 }
117         }
118 }
119
120 void
121 JACK_MidiPort::cycle_end ()
122 {
123         if (_jack_output_port != 0) {
124                 flush (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle));
125         }
126
127         Port::cycle_end();
128 }
129
130 int
131 JACK_MidiPort::write(byte * msg, size_t msglen, timestamp_t timestamp)
132 {
133         int ret = 0;
134
135         if (!is_process_thread()) {
136
137                 Glib::Mutex::Lock lm (output_fifo_lock);
138                 RingBuffer< Evoral::Event<double> >::rw_vector vec;
139                 
140                 output_fifo.get_write_vector (&vec);
141
142                 if (vec.len[0] + vec.len[1] < 1) {
143                         error << "no space in FIFO for non-process thread MIDI write" << endmsg;
144                         return 0;
145                 }
146
147                 if (vec.len[0]) {
148                         vec.buf[0]->set (msg, msglen, timestamp);
149                 } else {
150                         vec.buf[1]->set (msg, msglen, timestamp);
151                 }
152
153                 output_fifo.increment_write_idx (1);
154                 
155                 ret = msglen;
156
157         } else {
158
159                 assert(_jack_output_port);
160                 
161                 // XXX This had to be temporarily commented out to make export work again
162                 if (!(timestamp < _nframes_this_cycle)) {
163                         std::cerr << "assertion timestamp < _nframes_this_cycle failed!" << std::endl;
164                 }
165
166                 if (_currently_in_cycle) {
167                         if (timestamp == 0) {
168                                 timestamp = _last_write_timestamp;
169                         } 
170
171                         if (jack_midi_event_write (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle), 
172                                                 timestamp, msg, msglen) == 0) {
173                                 ret = msglen;
174                                 _last_write_timestamp = timestamp;
175
176                         } else {
177                                 ret = 0;
178                                 cerr << "write of " << msglen << " failed, port holds "
179                                         << jack_midi_get_event_count (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle))
180                                         << endl;
181                         }
182                 } else {
183                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
184                 }
185         }
186
187         if (ret > 0 && output_parser) {
188                 // ardour doesn't care about this and neither should your app, probably
189                 // output_parser->raw_preparse (*output_parser, msg, ret);
190                 for (int i = 0; i < ret; i++) {
191                         output_parser->scanner (msg[i]);
192                 }
193                 // ardour doesn't care about this and neither should your app, probably
194                 // output_parser->raw_postparse (*output_parser, msg, ret);
195         }       
196
197         return ret;
198 }
199
200 void
201 JACK_MidiPort::flush (void* jack_port_buffer)
202 {
203         RingBuffer< Evoral::Event<double> >::rw_vector vec;
204         size_t written;
205
206         output_fifo.get_read_vector (&vec);
207
208         if (vec.len[0] + vec.len[1]) {
209                 // cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
210         }
211
212         if (vec.len[0]) {
213                 Evoral::Event<double>* evp = vec.buf[0];
214                 
215                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
216                         jack_midi_event_write (jack_port_buffer,
217                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
218                 }
219         }
220         
221         if (vec.len[1]) {
222                 Evoral::Event<double>* evp = vec.buf[1];
223
224                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
225                         jack_midi_event_write (jack_port_buffer,
226                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
227                 }
228         }
229         
230         if ((written = vec.len[0] + vec.len[1]) != 0) {
231                 output_fifo.increment_read_idx (written);
232         }
233 }
234
235 int
236 JACK_MidiPort::read (byte *, size_t)
237 {
238         timestamp_t time;
239         Evoral::EventType type;
240         uint32_t size;
241         byte buffer[input_fifo.capacity()];
242
243         while (input_fifo.read (&time, &type, &size, buffer)) {
244                 if (input_parser) {
245                         input_parser->set_timestamp (time);
246                         for (uint32_t i = 0; i < size; ++i) {
247                                 input_parser->scanner (buffer[i]);
248                         }
249                 }
250         }
251
252         return 0;
253 }
254
255 int
256 JACK_MidiPort::create_ports(const XMLNode& node)
257 {
258         Descriptor desc (node);
259
260         assert(!_jack_input_port);
261         assert(!_jack_output_port);
262         
263         jack_nframes_t nframes = jack_get_buffer_size(_jack_client);
264
265         bool ret = true;
266
267         if (desc.mode == O_RDWR || desc.mode == O_WRONLY) {
268                 _jack_output_port = jack_port_register(_jack_client,
269                                                        string(desc.tag).append("_out").c_str(),
270                                                        JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
271                 if (_jack_output_port) {
272                         jack_midi_clear_buffer(jack_port_get_buffer(_jack_output_port, nframes));
273                 }
274                 ret = ret && (_jack_output_port != NULL);
275         }
276         
277         if (desc.mode == O_RDWR || desc.mode == O_RDONLY) {
278                 _jack_input_port = jack_port_register(_jack_client,
279                                                       string(desc.tag).append("_in").c_str(),
280                                                       JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
281                 if (_jack_input_port) {
282                         jack_midi_clear_buffer(jack_port_get_buffer(_jack_input_port, nframes));
283                 }
284                 ret = ret && (_jack_input_port != NULL);
285         }
286
287         return ret ? 0 : -1;
288 }
289
290 XMLNode& 
291 JACK_MidiPort::get_state () const
292 {
293         XMLNode& root (Port::get_state ());
294
295         if (_jack_output_port) {
296                 
297                 const char** jc = jack_port_get_connections (_jack_output_port);
298                 string connection_string;
299                 if (jc) {
300                         for (int i = 0; jc[i]; ++i) {
301                                 if (i > 0) {
302                                         connection_string += ',';
303                                 }
304                                 connection_string += jc[i];
305                         }
306                         free (jc);
307                 }
308                 
309                 if (!connection_string.empty()) {
310                         root.add_property ("outbound", connection_string);
311                 }
312         } else {
313                 if (!_outbound_connections.empty()) {
314                         root.add_property ("outbound", _outbound_connections);
315                 }
316         }
317
318         if (_jack_input_port) {
319
320                 const char** jc = jack_port_get_connections (_jack_input_port);
321                 string connection_string;
322                 if (jc) {
323                         for (int i = 0; jc[i]; ++i) {
324                                 if (i > 0) {
325                                         connection_string += ',';
326                                 }
327                                 connection_string += jc[i];
328                         }
329                         free (jc);
330                 }
331
332                 if (!connection_string.empty()) {
333                         root.add_property ("inbound", connection_string);
334                 }
335         } else {
336                 if (!_inbound_connections.empty()) {
337                         root.add_property ("inbound", _inbound_connections);
338                 }
339         }
340
341         return root;
342 }
343
344 void
345 JACK_MidiPort::set_state (const XMLNode& node)
346 {
347         Port::set_state (node);
348         const XMLProperty* prop;
349
350         if ((prop = node.property ("inbound")) != 0 && _jack_input_port) {
351                 _inbound_connections = prop->value ();
352         }
353
354         if ((prop = node.property ("outbound")) != 0 && _jack_output_port) {
355                 _outbound_connections = prop->value();
356         }
357 }
358
359 void
360 JACK_MidiPort::make_connections ()
361 {
362         if (!_inbound_connections.empty()) {
363                 vector<string> ports;
364                 split (_inbound_connections, ports, ',');
365                 for (vector<string>::iterator x = ports.begin(); x != ports.end(); ++x) {
366                         if (_jack_client) {
367                                 jack_connect (_jack_client, (*x).c_str(), jack_port_name (_jack_input_port));
368                                 /* ignore failures */
369                         }
370                 }
371         }
372
373         if (!_outbound_connections.empty()) {
374                 vector<string> ports;
375                 split (_outbound_connections, ports, ',');
376                 for (vector<string>::iterator x = ports.begin(); x != ports.end(); ++x) {
377                         if (_jack_client) {
378                                 jack_connect (_jack_client, jack_port_name (_jack_output_port), (*x).c_str());
379                                 /* ignore failures */
380                         }
381                 }
382         }
383         connect_connection.disconnect ();
384 }
385
386 void
387 JACK_MidiPort::set_process_thread (pthread_t thr)
388 {
389         _process_thread = thr;
390 }
391
392 bool
393 JACK_MidiPort::is_process_thread()
394 {
395         return (pthread_self() == _process_thread);
396 }