eventloop and abstractui debugging, lots more commenting on abstractui/eventloop...
[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                                 // PBD::stacktrace (cerr, 20);
275                         }
276                 } else {
277                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
278                         PBD::stacktrace (cerr, 20);
279                 }
280         }
281
282         if (ret > 0 && _parser) {
283                 // ardour doesn't care about this and neither should your app, probably
284                 // output_parser->raw_preparse (*output_parser, msg, ret);
285                 for (int i = 0; i < ret; i++) {
286                         _parser->scanner (msg[i]);
287                 }
288                 // ardour doesn't care about this and neither should your app, probably
289                 // output_parser->raw_postparse (*output_parser, msg, ret);
290         }       
291
292         return ret;
293 }
294
295 void
296 JackMIDIPort::flush (void* jack_port_buffer)
297 {
298         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0 } };
299         size_t written;
300
301         output_fifo.get_read_vector (&vec);
302
303         if (vec.len[0] + vec.len[1]) {
304                 // cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
305         }
306
307         if (vec.len[0]) {
308                 Evoral::Event<double>* evp = vec.buf[0];
309                 
310                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
311                         jack_midi_event_write (jack_port_buffer,
312                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
313                 }
314         }
315         
316         if (vec.len[1]) {
317                 Evoral::Event<double>* evp = vec.buf[1];
318
319                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
320                         jack_midi_event_write (jack_port_buffer,
321                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
322                 }
323         }
324         
325         if ((written = vec.len[0] + vec.len[1]) != 0) {
326                 output_fifo.increment_read_idx (written);
327         }
328 }
329
330 int
331 JackMIDIPort::read (byte *, size_t)
332 {
333         if (!receives_input()) {
334                 return 0;
335         }
336         
337         timestamp_t time;
338         Evoral::EventType type;
339         uint32_t size;
340         byte buffer[input_fifo.capacity()];
341
342         while (input_fifo.read (&time, &type, &size, buffer)) {
343                 _parser->set_timestamp (time);
344                 for (uint32_t i = 0; i < size; ++i) {
345                         _parser->scanner (buffer[i]);
346                 }
347         }
348
349         return 0;
350 }
351
352 int
353 JackMIDIPort::create_port ()
354 {
355         _jack_port = jack_port_register(_jack_client, _tagname.c_str(), JACK_DEFAULT_MIDI_TYPE, _flags, 0);
356         return _jack_port == 0 ? -1 : 0;
357 }
358
359 XMLNode& 
360 JackMIDIPort::get_state () const
361 {
362         XMLNode& root = Port::get_state ();
363         
364 #if 0
365         byte device_inquiry[6];
366
367         device_inquiry[0] = 0xf0;
368         device_inquiry[0] = 0x7e;
369         device_inquiry[0] = 0x7f;
370         device_inquiry[0] = 0x06;
371         device_inquiry[0] = 0x02;
372         device_inquiry[0] = 0xf7;
373         
374         write (device_inquiry, sizeof (device_inquiry), 0);
375 #endif
376
377         if (_jack_port) {
378                 
379                 const char** jc = jack_port_get_connections (_jack_port);
380                 string connection_string;
381                 if (jc) {
382                         for (int i = 0; jc[i]; ++i) {
383                                 if (i > 0) {
384                                         connection_string += ',';
385                                 }
386                                 connection_string += jc[i];
387                         }
388                         free (jc);
389                 }
390                 
391                 if (!connection_string.empty()) {
392                         root.add_property ("connections", connection_string);
393                 }
394         } else {
395                 if (!_connections.empty()) {
396                         root.add_property ("connections", _connections);
397                 }
398         }
399
400         return root;
401 }
402
403 void
404 JackMIDIPort::set_state (const XMLNode& node)
405 {
406         const XMLProperty* prop;
407
408         if ((prop = node.property ("tag")) == 0 || prop->value() != _tagname) {
409                 return;
410         }
411         
412         Port::set_state (node);
413
414         if ((prop = node.property ("connections")) != 0) {
415                 _connections = prop->value ();
416         }
417 }
418
419 void
420 JackMIDIPort::make_connections ()
421 {
422         if (!_connections.empty()) {
423                 vector<string> ports;
424                 split (_connections, ports, ',');
425                 for (vector<string>::iterator x = ports.begin(); x != ports.end(); ++x) {
426                         if (_jack_client) {
427                                 if (receives_input()) {
428                                         jack_connect (_jack_client, (*x).c_str(), jack_port_name (_jack_port));
429                                 } else {
430                                         jack_connect (_jack_client, jack_port_name (_jack_port), (*x).c_str());
431                                 }
432                                 /* ignore failures */
433                         }
434                 }
435         }
436
437         connect_connection.disconnect ();
438 }
439
440 void
441 JackMIDIPort::set_process_thread (pthread_t thr)
442 {
443         _process_thread = thr;
444 }
445
446 bool
447 JackMIDIPort::is_process_thread()
448 {
449         return (pthread_self() == _process_thread);
450 }
451
452 void
453 JackMIDIPort::reestablish (jack_client_t* jack)
454 {
455         _jack_client = jack;
456         int const r = create_port ();
457
458         if (r) {
459                 PBD::error << "could not reregister ports for " << name() << endmsg;
460         }
461 }
462
463 void
464 JackMIDIPort::reconnect ()
465 {
466         make_connections ();
467 }