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