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