Fix 2884 and also potential crash if there are no control outs.
[ardour.git] / libs / midi++2 / jack_midiport.cc
1 /*
2   Copyright (C) 2006 Paul Davis 
3   Written by Dave Robillard
4  
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation; either version 2 of the License, or
8   (at your option) any later version.
9  
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14  
15   You should have received a copy of the GNU General Public License
16   along with this program; if not, write to the Free Software
17   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <fcntl.h>
21 #include <cerrno>
22 #include <cassert>
23
24 #include "pbd/error.h"
25
26 #include "midi++/types.h"
27 #include "midi++/jack.h"
28
29 using namespace std;
30 using namespace MIDI;
31 using namespace PBD;
32
33 pthread_t JACK_MidiPort::_process_thread;
34
35 JACK_MidiPort::JACK_MidiPort(const XMLNode& node, jack_client_t* jack_client)
36         : Port(node)
37         , _jack_client(jack_client)
38         , _jack_input_port(NULL)
39         , _jack_output_port(NULL)
40         , _last_read_index(0)
41         , non_process_thread_fifo (512)
42 {
43         int err = create_ports (node);
44
45         if (!err) {
46                 _ok = true;
47         }
48 }
49
50 JACK_MidiPort::~JACK_MidiPort()
51 {
52         // FIXME: remove port
53 }
54
55 void
56 JACK_MidiPort::cycle_start (nframes_t nframes)
57 {
58         Port::cycle_start(nframes);
59         assert(_nframes_this_cycle == nframes);
60         _last_read_index = 0;
61         _last_write_timestamp = 0;
62
63         if (_jack_output_port != 0) {
64                 // output
65                 void *buffer = jack_port_get_buffer (_jack_output_port, nframes);
66                 jack_midi_clear_buffer (buffer);
67                 flush (buffer); 
68         }
69         
70         if (_jack_input_port != 0) {
71                 // input
72                 void* jack_buffer = jack_port_get_buffer(_jack_input_port, nframes);
73                 const nframes_t event_count = jack_midi_get_event_count(jack_buffer);
74
75                 jack_midi_event_t ev;
76
77                 for (nframes_t i=0; i < event_count; ++i) {
78
79                         jack_midi_event_get (&ev, jack_buffer, i);
80
81                         if (input_parser) {
82                                 for (size_t i = 0; i < ev.size; i++) {
83                                         // the midi events here are used for MIDI clock only
84                                         input_parser->set_midi_clock_timestamp(ev.time + jack_last_frame_time(_jack_client));
85                                         input_parser->scanner (ev.buffer[i]);
86                                 }       
87                         }
88                 }       
89         }
90 }
91
92 void
93 JACK_MidiPort::cycle_end ()
94 {
95         if (_jack_output_port != 0) {
96                 flush(jack_port_get_buffer(_jack_output_port, _nframes_this_cycle));
97         }
98 }
99
100 int
101 JACK_MidiPort::write(byte * msg, size_t msglen, timestamp_t timestamp)
102 {
103         int ret = 0;
104
105         if (!is_process_thread()) {
106
107                 Glib::Mutex::Lock lm (non_process_thread_fifo_lock);
108                 RingBuffer< Evoral::Event<double> >::rw_vector vec;
109                 
110                 non_process_thread_fifo.get_write_vector (&vec);
111
112                 if (vec.len[0] + vec.len[1] < 1) {
113                         error << "no space in FIFO for non-process thread MIDI write" << endmsg;
114                         return 0;
115                 }
116
117                 if (vec.len[0]) {
118                         vec.buf[0]->set (msg, msglen, timestamp);
119                 } else {
120                         vec.buf[1]->set (msg, msglen, timestamp);
121                 }
122
123                 non_process_thread_fifo.increment_write_idx (1);
124                 
125                 ret = msglen;
126                                 
127         } else {
128
129                 assert(_jack_output_port);
130                 
131                 // XXX This had to be temporarily commented out to make export work again
132                 if (!(timestamp < _nframes_this_cycle)) {
133                         std::cerr << "assertion timestamp < _nframes_this_cycle failed!" << std::endl;
134                 }
135
136                 if (_currently_in_cycle) {
137                         if (timestamp == 0) {
138                                 timestamp = _last_write_timestamp;
139                         } 
140
141                         if (jack_midi_event_write (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle), 
142                                                 timestamp, msg, msglen) == 0) {
143                                 ret = msglen;
144                                 _last_write_timestamp = timestamp;
145
146                         } else {
147                                 ret = 0;
148                                 cerr << "write of " << msglen << " failed, port holds "
149                                         << jack_midi_get_event_count (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle))
150                                         << endl;
151                         }
152                 } else {
153                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
154                 }
155         }
156
157         if (ret > 0 && output_parser) {
158                 output_parser->raw_preparse (*output_parser, msg, ret);
159                 for (int i = 0; i < ret; i++) {
160                         output_parser->scanner (msg[i]);
161                 }
162                 output_parser->raw_postparse (*output_parser, msg, ret);
163         }       
164
165         return ret;
166 }
167
168 void
169 JACK_MidiPort::flush (void* jack_port_buffer)
170 {
171         RingBuffer< Evoral::Event<double> >::rw_vector vec;
172         size_t written;
173
174         non_process_thread_fifo.get_read_vector (&vec);
175
176         if (vec.len[0] + vec.len[1]) {
177                 // cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
178         }
179
180         if (vec.len[0]) {
181                 Evoral::Event<double>* evp = vec.buf[0];
182                 
183                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
184                         jack_midi_event_write (jack_port_buffer,
185                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
186                 }
187         }
188         
189         if (vec.len[1]) {
190                 Evoral::Event<double>* evp = vec.buf[1];
191
192                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
193                         jack_midi_event_write (jack_port_buffer,
194                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
195                 }
196         }
197         
198         if ((written = vec.len[0] + vec.len[1]) != 0) {
199                 non_process_thread_fifo.increment_read_idx (written);
200         }
201 }
202
203 int
204 JACK_MidiPort::read(byte * buf, size_t bufsize)
205 {
206         assert(_currently_in_cycle);
207         assert(_jack_input_port);
208         
209         jack_midi_event_t ev;
210
211         cerr << "JACK_MidiPort::read called" << endl;
212         
213         int err = jack_midi_event_get (&ev,
214                                        jack_port_get_buffer(_jack_input_port, _nframes_this_cycle),
215                                        _last_read_index++);
216         
217         // XXX this doesn't handle ev.size > max
218
219         if (!err) {
220                 size_t limit = min (bufsize, ev.size);
221                 memcpy(buf, ev.buffer, limit);
222
223                 if (input_parser) {
224                         input_parser->raw_preparse (*input_parser, buf, limit);
225                         for (size_t i = 0; i < limit; i++) {
226                                 input_parser->scanner (buf[i]);
227                         }       
228                         input_parser->raw_postparse (*input_parser, buf, limit);
229                 }
230
231                 return limit;
232         } else {
233                 return 0;
234         }
235 }
236
237 int
238 JACK_MidiPort::create_ports(const XMLNode& node)
239 {
240         Descriptor desc (node);
241
242         assert(!_jack_input_port);
243         assert(!_jack_output_port);
244         
245         jack_nframes_t nframes = jack_get_buffer_size(_jack_client);
246
247         bool ret = true;
248
249         if (desc.mode == O_RDWR || desc.mode == O_WRONLY) {
250                 _jack_output_port = jack_port_register(_jack_client,
251                                                        string(desc.tag).append("_out").c_str(),
252                                                        JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
253                 if (_jack_output_port) {
254                         jack_midi_clear_buffer(jack_port_get_buffer(_jack_output_port, nframes));
255                 }
256                 ret = ret && (_jack_output_port != NULL);
257         }
258         
259         if (desc.mode == O_RDWR || desc.mode == O_RDONLY) {
260                 _jack_input_port = jack_port_register(_jack_client,
261                                                       string(desc.tag).append("_in").c_str(),
262                                                       JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
263                 if (_jack_input_port) {
264                         jack_midi_clear_buffer(jack_port_get_buffer(_jack_input_port, nframes));
265                 }
266                 ret = ret && (_jack_input_port != NULL);
267         }
268
269         return ret ? 0 : -1;
270 }
271
272 XMLNode& 
273 JACK_MidiPort::get_state () const
274 {
275         XMLNode& root (Port::get_state ());
276         return root;
277 }
278
279 void
280 JACK_MidiPort::set_state (const XMLNode& /*node*/)
281 {
282 }
283
284 void
285 JACK_MidiPort::set_process_thread (pthread_t thr)
286 {
287         _process_thread = thr;
288 }
289
290 bool
291 JACK_MidiPort::is_process_thread()
292 {
293         return (pthread_self() == _process_thread);
294 }