add support for IP MIDI (multicast MIDI over IP UDP sockets) to ardour and use it...
[ardour.git] / libs / midi++2 / jack_midi_port.cc
1 /*
2     Copyright (C) 1998 Paul Barton-Davis
3     
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id$
19 */
20 #include <iostream>
21 #include <cstdio>
22 #include <fcntl.h>
23 #include <errno.h>
24
25 #include <jack/jack.h>
26 #include <jack/midiport.h>
27
28 #include "pbd/xml++.h"
29 #include "pbd/error.h"
30 #include "pbd/failed_constructor.h"
31 #include "pbd/convert.h"
32 #include "pbd/strsplit.h"
33 #include "pbd/stacktrace.h"
34
35 #include "midi++/types.h"
36 #include "midi++/jack_midi_port.h"
37 #include "midi++/channel.h"
38
39 using namespace MIDI;
40 using namespace std;
41 using namespace PBD;
42
43 pthread_t JackMIDIPort::_process_thread;
44 Signal0<void> JackMIDIPort::JackHalted;
45 Signal0<void> JackMIDIPort::MakeConnections;
46
47 JackMIDIPort::JackMIDIPort (string const & name, Flags flags, jack_client_t* jack_client)
48         : Port (name, flags)
49         , _currently_in_cycle (false)
50         , _nframes_this_cycle (0)
51         , _jack_client (jack_client)
52         , _jack_port (0)
53         , output_fifo (512)
54         , input_fifo (1024)
55         , xthread (true)
56 {
57         assert (jack_client);
58         init (name, flags);
59 }
60
61 JackMIDIPort::JackMIDIPort (const XMLNode& node, jack_client_t* jack_client)
62         : Port (node)
63         , _currently_in_cycle (false)
64         , _nframes_this_cycle (0)
65         , _jack_client (jack_client)
66         , _jack_port (0)
67         , output_fifo (512)
68         , input_fifo (1024)
69         , xthread (true)
70 {
71         assert (jack_client);
72
73         Descriptor desc (node);
74         init (desc.tag, desc.flags);
75         set_state (node);
76 }
77
78 void
79 JackMIDIPort::init (string const & name, Flags flags)
80 {
81         if (!create_port ()) {
82                 _ok = true;
83         }
84
85         MakeConnections.connect_same_thread (connect_connection, boost::bind (&JackMIDIPort::make_connections, this));
86         JackHalted.connect_same_thread (halt_connection, boost::bind (&JackMIDIPort::jack_halted, this));
87 }
88
89
90 JackMIDIPort::~JackMIDIPort ()
91 {
92         for (int i = 0; i < 16; i++) {
93                 delete _channel[i];
94         }
95
96         if (_jack_port) {
97                 if (_jack_client) {
98                         jack_port_unregister (_jack_client, _jack_port);
99                         _jack_port = 0;
100                 }
101         }
102 }
103
104 void
105 JackMIDIPort::parse (framecnt_t timestamp)
106 {
107         byte buf[512];
108
109         /* NOTE: parsing is done (if at all) by initiating a read from 
110            the port. Each port implementation calls on the parser
111            once it has data ready.
112         */
113         
114         _parser->set_timestamp (timestamp);
115
116         while (1) {
117                 
118                 // cerr << "+++ READ ON " << name() << endl;
119
120                 int nread = read (buf, sizeof (buf));
121
122                 // cerr << "-- READ (" << nread << " ON " << name() << endl;
123                 
124                 if (nread > 0) {
125                         if ((size_t) nread < sizeof (buf)) {
126                                 break;
127                         } else {
128                                 continue;
129                         }
130                 } else if (nread == 0) {
131                         break;
132                 } else if (errno == EAGAIN) {
133                         break;
134                 } else {
135                         fatal << "Error reading from MIDI port " << name() << endmsg;
136                         /*NOTREACHED*/
137                 }
138         }
139 }
140
141 void
142 JackMIDIPort::cycle_start (pframes_t nframes)
143 {
144         assert (_jack_port);
145         
146         _currently_in_cycle = true;
147         _nframes_this_cycle = nframes;
148
149         assert(_nframes_this_cycle == nframes);
150
151         if (sends_output()) {
152                 void *buffer = jack_port_get_buffer (_jack_port, nframes);
153                 jack_midi_clear_buffer (buffer);
154                 flush (buffer); 
155         }
156         
157         if (receives_input()) {
158                 void* jack_buffer = jack_port_get_buffer(_jack_port, nframes);
159                 const pframes_t event_count = jack_midi_get_event_count(jack_buffer);
160
161                 jack_midi_event_t ev;
162                 timestamp_t cycle_start_frame = jack_last_frame_time (_jack_client);
163
164                 for (pframes_t i = 0; i < event_count; ++i) {
165                         jack_midi_event_get (&ev, jack_buffer, i);
166                         input_fifo.write (cycle_start_frame + ev.time, (Evoral::EventType) 0, ev.size, ev.buffer);
167                 }       
168                 
169                 if (event_count) {
170                         xthread.wakeup ();
171                 }
172         }
173 }
174
175 void
176 JackMIDIPort::cycle_end ()
177 {
178         if (sends_output()) {
179                 flush (jack_port_get_buffer (_jack_port, _nframes_this_cycle));
180         }
181
182         _currently_in_cycle = false;
183         _nframes_this_cycle = 0;
184 }
185
186 void
187 JackMIDIPort::jack_halted ()
188 {
189         _jack_client = 0;
190         _jack_port = 0;
191 }
192
193 void
194 JackMIDIPort::drain (int check_interval_usecs)
195 {
196         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0} };
197
198         if (is_process_thread()) {
199                 error << "Process thread called MIDI::JackMIDIPort::drain() - this cannot work" << endmsg;
200                 return;
201         }
202
203         while (1) {
204                 output_fifo.get_write_vector (&vec);
205                 if (vec.len[0] + vec.len[1] >= output_fifo.bufsize() - 1) {
206                         break;
207                 }
208                 usleep (check_interval_usecs);
209         }
210 }
211
212 int
213 JackMIDIPort::write(byte * msg, size_t msglen, timestamp_t timestamp)
214 {
215         int ret = 0;
216
217         if (!sends_output()) {
218                 return ret;
219         }
220         
221         if (!is_process_thread()) {
222
223                 Glib::Mutex::Lock lm (output_fifo_lock);
224                 RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0} };
225                 
226                 output_fifo.get_write_vector (&vec);
227
228                 if (vec.len[0] + vec.len[1] < 1) {
229                         error << "no space in FIFO for non-process thread MIDI write" << endmsg;
230                         return 0;
231                 }
232
233                 if (vec.len[0]) {
234                         if (!vec.buf[0]->owns_buffer()) {
235                                 vec.buf[0]->set_buffer (0, 0, true);
236                         }
237                         vec.buf[0]->set (msg, msglen, timestamp);
238                 } else {
239                         if (!vec.buf[1]->owns_buffer()) {
240                                 vec.buf[1]->set_buffer (0, 0, true);
241                         }
242                         vec.buf[1]->set (msg, msglen, timestamp);
243                 }
244
245                 output_fifo.increment_write_idx (1);
246                 
247                 ret = msglen;
248
249         } else {
250
251                 // XXX This had to be temporarily commented out to make export work again
252                 if (!(timestamp < _nframes_this_cycle)) {
253                         std::cerr << "attempting to write MIDI event of " << msglen << " bytes at time "
254                                   << timestamp << " of " << _nframes_this_cycle
255                                   << " (this will not work - needs a code fix)"
256                                   << std::endl;
257                 }
258
259                 if (_currently_in_cycle) {
260                         if (timestamp == 0) {
261                                 timestamp = _last_write_timestamp;
262                         } 
263
264                         if (jack_midi_event_write (jack_port_get_buffer (_jack_port, _nframes_this_cycle), 
265                                                 timestamp, msg, msglen) == 0) {
266                                 ret = msglen;
267                                 _last_write_timestamp = timestamp;
268
269                         } else {
270                                 ret = 0;
271                                 cerr << "write of " << msglen << " failed, port holds "
272                                         << jack_midi_get_event_count (jack_port_get_buffer (_jack_port, _nframes_this_cycle))
273                                         << endl;
274                         }
275                 } else {
276                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
277                         PBD::stacktrace (cerr, 20);
278                 }
279         }
280
281         if (ret > 0 && _parser) {
282                 // ardour doesn't care about this and neither should your app, probably
283                 // output_parser->raw_preparse (*output_parser, msg, ret);
284                 for (int i = 0; i < ret; i++) {
285                         _parser->scanner (msg[i]);
286                 }
287                 // ardour doesn't care about this and neither should your app, probably
288                 // output_parser->raw_postparse (*output_parser, msg, ret);
289         }       
290
291         return ret;
292 }
293
294 void
295 JackMIDIPort::flush (void* jack_port_buffer)
296 {
297         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0 } };
298         size_t written;
299
300         output_fifo.get_read_vector (&vec);
301
302         if (vec.len[0] + vec.len[1]) {
303                 // cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
304         }
305
306         if (vec.len[0]) {
307                 Evoral::Event<double>* evp = vec.buf[0];
308                 
309                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
310                         jack_midi_event_write (jack_port_buffer,
311                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
312                 }
313         }
314         
315         if (vec.len[1]) {
316                 Evoral::Event<double>* evp = vec.buf[1];
317
318                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
319                         jack_midi_event_write (jack_port_buffer,
320                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
321                 }
322         }
323         
324         if ((written = vec.len[0] + vec.len[1]) != 0) {
325                 output_fifo.increment_read_idx (written);
326         }
327 }
328
329 int
330 JackMIDIPort::read (byte *, size_t)
331 {
332         if (!receives_input()) {
333                 return 0;
334         }
335         
336         timestamp_t time;
337         Evoral::EventType type;
338         uint32_t size;
339         byte buffer[input_fifo.capacity()];
340
341         while (input_fifo.read (&time, &type, &size, buffer)) {
342                 _parser->set_timestamp (time);
343                 for (uint32_t i = 0; i < size; ++i) {
344                         _parser->scanner (buffer[i]);
345                 }
346         }
347
348         return 0;
349 }
350
351 int
352 JackMIDIPort::create_port ()
353 {
354         _jack_port = jack_port_register(_jack_client, _tagname.c_str(), JACK_DEFAULT_MIDI_TYPE, _flags, 0);
355         return _jack_port == 0 ? -1 : 0;
356 }
357
358 XMLNode& 
359 JackMIDIPort::get_state () const
360 {
361         XMLNode& root = Port::get_state ();
362         
363 #if 0
364         byte device_inquiry[6];
365
366         device_inquiry[0] = 0xf0;
367         device_inquiry[0] = 0x7e;
368         device_inquiry[0] = 0x7f;
369         device_inquiry[0] = 0x06;
370         device_inquiry[0] = 0x02;
371         device_inquiry[0] = 0xf7;
372         
373         write (device_inquiry, sizeof (device_inquiry), 0);
374 #endif
375
376         if (_jack_port) {
377                 
378                 const char** jc = jack_port_get_connections (_jack_port);
379                 string connection_string;
380                 if (jc) {
381                         for (int i = 0; jc[i]; ++i) {
382                                 if (i > 0) {
383                                         connection_string += ',';
384                                 }
385                                 connection_string += jc[i];
386                         }
387                         free (jc);
388                 }
389                 
390                 if (!connection_string.empty()) {
391                         root.add_property ("connections", connection_string);
392                 }
393         } else {
394                 if (!_connections.empty()) {
395                         root.add_property ("connections", _connections);
396                 }
397         }
398
399         return root;
400 }
401
402 void
403 JackMIDIPort::set_state (const XMLNode& node)
404 {
405         const XMLProperty* prop;
406
407         if ((prop = node.property ("tag")) == 0 || prop->value() != _tagname) {
408                 return;
409         }
410         
411         Port::set_state (node);
412
413         if ((prop = node.property ("connections")) != 0) {
414                 _connections = prop->value ();
415         }
416 }
417
418 void
419 JackMIDIPort::make_connections ()
420 {
421         if (!_connections.empty()) {
422                 vector<string> ports;
423                 split (_connections, ports, ',');
424                 for (vector<string>::iterator x = ports.begin(); x != ports.end(); ++x) {
425                         if (_jack_client) {
426                                 if (receives_input()) {
427                                         jack_connect (_jack_client, (*x).c_str(), jack_port_name (_jack_port));
428                                 } else {
429                                         jack_connect (_jack_client, jack_port_name (_jack_port), (*x).c_str());
430                                 }
431                                 /* ignore failures */
432                         }
433                 }
434         }
435
436         connect_connection.disconnect ();
437 }
438
439 void
440 JackMIDIPort::set_process_thread (pthread_t thr)
441 {
442         _process_thread = thr;
443 }
444
445 bool
446 JackMIDIPort::is_process_thread()
447 {
448         return (pthread_self() == _process_thread);
449 }
450
451 void
452 JackMIDIPort::reestablish (jack_client_t* jack)
453 {
454         _jack_client = jack;
455         int const r = create_port ();
456
457         if (r) {
458                 PBD::error << "could not reregister ports for " << name() << endmsg;
459         }
460 }
461
462 void
463 JackMIDIPort::reconnect ()
464 {
465         make_connections ();
466 }