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