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