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