Re-claim double-clicks on pixfaders to re-fix #3470.
[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         , xthread (true)
54         , output_fifo (512)
55         , input_fifo (1024)
56         , _flags (flags)
57 {
58         assert (jack_client);
59         init (name, flags);
60 }
61
62 Port::Port (const XMLNode& node, jack_client_t* jack_client)
63         : _currently_in_cycle (false)
64         , _nframes_this_cycle (0)
65         , _jack_client (jack_client)
66         , _jack_port (0)
67         , _last_read_index (0)
68         , xthread (true)
69         , output_fifo (512)
70         , input_fifo (1024)
71 {
72         assert (jack_client);
73         
74         Descriptor desc (node);
75
76         init (desc.tag, desc.flags);
77
78         set_state (node);
79 }
80
81 void
82 Port::init (string const & name, Flags flags)
83 {
84         _ok = false;  /* derived class must set to true if constructor
85                          succeeds.
86                       */
87
88         _parser = 0;
89
90         _tagname = name;
91         _flags = flags;
92
93         _parser = new Parser (*this);
94
95         for (int i = 0; i < 16; i++) {
96                 _channel[i] = new Channel (i, *this);
97                 _channel[i]->connect_signals ();
98         }
99
100         if (!create_port ()) {
101                 _ok = true;
102         }
103
104         MakeConnections.connect_same_thread (connect_connection, boost::bind (&Port::make_connections, this));
105         JackHalted.connect_same_thread (halt_connection, boost::bind (&Port::jack_halted, this));
106 }
107
108
109 Port::~Port ()
110 {
111         for (int i = 0; i < 16; i++) {
112                 delete _channel[i];
113         }
114
115         if (_jack_port) {
116                 if (_jack_client && _jack_port) {
117                         jack_port_unregister (_jack_client, _jack_port);
118                 }
119                 _jack_port = 0;
120         }
121 }
122
123 void
124 Port::parse (framecnt_t timestamp)
125 {
126         byte buf[512];
127
128         /* NOTE: parsing is done (if at all) by initiating a read from 
129            the port. Each port implementation calls on the parser
130            once it has data ready.
131         */
132         
133         _parser->set_timestamp (timestamp);
134
135         while (1) {
136                 
137                 // cerr << "+++ READ ON " << name() << endl;
138
139                 int nread = read (buf, sizeof (buf));
140
141                 // cerr << "-- READ (" << nread << " ON " << name() << endl;
142                 
143                 if (nread > 0) {
144                         if ((size_t) nread < sizeof (buf)) {
145                                 break;
146                         } else {
147                                 continue;
148                         }
149                 } else if (nread == 0) {
150                         break;
151                 } else if (errno == EAGAIN) {
152                         break;
153                 } else {
154                         fatal << "Error reading from MIDI port " << name() << endmsg;
155                         /*NOTREACHED*/
156                 }
157         }
158 }
159
160 /** Send a clock tick message.
161  * \return true on success.
162  */
163 bool
164 Port::clock (timestamp_t timestamp)
165 {
166         static byte clockmsg = 0xf8;
167         
168         if (sends_output()) {
169                 return midimsg (&clockmsg, 1, timestamp);
170         }
171         
172         return false;
173 }
174
175 void
176 Port::cycle_start (pframes_t nframes)
177 {
178         assert (_jack_port);
179         
180         _currently_in_cycle = true;
181         _nframes_this_cycle = nframes;
182
183         assert(_nframes_this_cycle == nframes);
184         _last_read_index = 0;
185         _last_write_timestamp = 0;
186
187         if (sends_output()) {
188                 void *buffer = jack_port_get_buffer (_jack_port, nframes);
189                 jack_midi_clear_buffer (buffer);
190                 flush (buffer); 
191         }
192         
193         if (receives_input()) {
194                 void* jack_buffer = jack_port_get_buffer(_jack_port, nframes);
195                 const pframes_t event_count = jack_midi_get_event_count(jack_buffer);
196
197                 jack_midi_event_t ev;
198                 timestamp_t cycle_start_frame = jack_last_frame_time (_jack_client);
199
200                 for (pframes_t i = 0; i < event_count; ++i) {
201                         jack_midi_event_get (&ev, jack_buffer, i);
202                         input_fifo.write (cycle_start_frame + ev.time, (Evoral::EventType) 0, ev.size, ev.buffer);
203                 }       
204                 
205                 if (event_count) {
206                         xthread.wakeup ();
207                 }
208         }
209 }
210
211 void
212 Port::cycle_end ()
213 {
214         if (sends_output()) {
215                 flush (jack_port_get_buffer (_jack_port, _nframes_this_cycle));
216         }
217
218         _currently_in_cycle = false;
219         _nframes_this_cycle = 0;
220 }
221
222 std::ostream & MIDI::operator << ( std::ostream & os, const MIDI::Port & port )
223 {
224         using namespace std;
225         os << "MIDI::Port { ";
226         os << "name: " << port.name();
227         os << "; ";
228         os << "ok: " << port.ok();
229         os << "; ";
230         os << " }";
231         return os;
232 }
233
234 Port::Descriptor::Descriptor (const XMLNode& node)
235 {
236         const XMLProperty *prop;
237         bool have_tag = false;
238         bool have_mode = false;
239
240         if ((prop = node.property ("tag")) != 0) {
241                 tag = prop->value();
242                 have_tag = true;
243         }
244
245         if ((prop = node.property ("mode")) != 0) {
246
247                 if (strings_equal_ignore_case (prop->value(), "output") || strings_equal_ignore_case (prop->value(), "out")) {
248                         flags = IsOutput;
249                 } else if (strings_equal_ignore_case (prop->value(), "input") || strings_equal_ignore_case (prop->value(), "in")) {
250                         flags = IsInput;
251                 }
252
253                 have_mode = true;
254         }
255
256         if (!have_tag || !have_mode) {
257                 throw failed_constructor();
258         }
259 }
260
261 void
262 Port::jack_halted ()
263 {
264         _jack_client = 0;
265         _jack_port = 0;
266 }
267
268 int
269 Port::write(byte * msg, size_t msglen, timestamp_t timestamp)
270 {
271         int ret = 0;
272
273         if (!sends_output()) {
274                 return ret;
275         }
276         
277         if (!is_process_thread()) {
278
279                 Glib::Mutex::Lock lm (output_fifo_lock);
280                 RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0} };
281                 
282                 output_fifo.get_write_vector (&vec);
283
284                 if (vec.len[0] + vec.len[1] < 1) {
285                         error << "no space in FIFO for non-process thread MIDI write" << endmsg;
286                         return 0;
287                 }
288
289                 if (vec.len[0]) {
290                         if (!vec.buf[0]->owns_buffer()) {
291                                 vec.buf[0]->set_buffer (0, 0, true);
292                         }
293                         vec.buf[0]->set (msg, msglen, timestamp);
294                 } else {
295                         if (!vec.buf[1]->owns_buffer()) {
296                                 vec.buf[1]->set_buffer (0, 0, true);
297                         }
298                         vec.buf[1]->set (msg, msglen, timestamp);
299                 }
300
301                 output_fifo.increment_write_idx (1);
302                 
303                 ret = msglen;
304
305         } else {
306
307                 // XXX This had to be temporarily commented out to make export work again
308                 if (!(timestamp < _nframes_this_cycle)) {
309                         std::cerr << "assertion timestamp < _nframes_this_cycle failed!" << std::endl;
310                 }
311
312                 if (_currently_in_cycle) {
313                         if (timestamp == 0) {
314                                 timestamp = _last_write_timestamp;
315                         } 
316
317                         if (jack_midi_event_write (jack_port_get_buffer (_jack_port, _nframes_this_cycle), 
318                                                 timestamp, msg, msglen) == 0) {
319                                 ret = msglen;
320                                 _last_write_timestamp = timestamp;
321
322                         } else {
323                                 ret = 0;
324                                 cerr << "write of " << msglen << " failed, port holds "
325                                         << jack_midi_get_event_count (jack_port_get_buffer (_jack_port, _nframes_this_cycle))
326                                         << endl;
327                         }
328                 } else {
329                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
330                 }
331         }
332
333         if (ret > 0 && _parser) {
334                 // ardour doesn't care about this and neither should your app, probably
335                 // output_parser->raw_preparse (*output_parser, msg, ret);
336                 for (int i = 0; i < ret; i++) {
337                         _parser->scanner (msg[i]);
338                 }
339                 // ardour doesn't care about this and neither should your app, probably
340                 // output_parser->raw_postparse (*output_parser, msg, ret);
341         }       
342
343         return ret;
344 }
345
346 void
347 Port::flush (void* jack_port_buffer)
348 {
349         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0 } };
350         size_t written;
351
352         output_fifo.get_read_vector (&vec);
353
354         if (vec.len[0] + vec.len[1]) {
355                 // cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
356         }
357
358         if (vec.len[0]) {
359                 Evoral::Event<double>* evp = vec.buf[0];
360                 
361                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
362                         jack_midi_event_write (jack_port_buffer,
363                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
364                 }
365         }
366         
367         if (vec.len[1]) {
368                 Evoral::Event<double>* evp = vec.buf[1];
369
370                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
371                         jack_midi_event_write (jack_port_buffer,
372                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
373                 }
374         }
375         
376         if ((written = vec.len[0] + vec.len[1]) != 0) {
377                 output_fifo.increment_read_idx (written);
378         }
379 }
380
381 int
382 Port::read (byte *, size_t)
383 {
384         if (!receives_input()) {
385                 return 0;
386         }
387         
388         timestamp_t time;
389         Evoral::EventType type;
390         uint32_t size;
391         byte buffer[input_fifo.capacity()];
392
393         while (input_fifo.read (&time, &type, &size, buffer)) {
394                 _parser->set_timestamp (time);
395                 for (uint32_t i = 0; i < size; ++i) {
396                         _parser->scanner (buffer[i]);
397                 }
398         }
399
400         return 0;
401 }
402
403 int
404 Port::create_port ()
405 {
406         _jack_port = jack_port_register(_jack_client, _tagname.c_str(), JACK_DEFAULT_MIDI_TYPE, _flags, 0);
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 }