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