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