Fix various MIDI corruption bugs.
[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         void *buffer = jack_port_get_buffer (_jack_output_port, nframes);
64         jack_midi_clear_buffer (buffer);
65         flush (buffer);
66 }
67
68 int
69 JACK_MidiPort::write(byte * msg, size_t msglen, timestamp_t timestamp)
70 {
71         int ret = 0;
72
73         if (!is_process_thread()) {
74
75                 Glib::Mutex::Lock lm (non_process_thread_fifo_lock);
76                 RingBuffer<Event>::rw_vector vec;
77                 
78                 non_process_thread_fifo.get_write_vector (&vec);
79
80                 if (vec.len[0] + vec.len[1] < 1) {
81                         error << "no space in FIFO for non-process thread MIDI write"
82                               << endmsg;
83                         return 0;
84                 }
85
86                 if (vec.len[0]) {
87                         vec.buf[0]->set (msg, msglen, timestamp);
88                 } else {
89                         vec.buf[1]->set (msg, msglen, timestamp);
90                 }
91
92                 non_process_thread_fifo.increment_write_idx (1);
93                 
94                 ret = msglen;
95                                 
96         } else {
97
98                 assert(_jack_output_port);
99                 assert(timestamp < _nframes_this_cycle);
100
101                 if (_currently_in_cycle) {
102                         if (timestamp == 0) {
103                                 timestamp = _last_write_timestamp;
104                         } 
105
106                         if (jack_midi_event_write (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle), 
107                                                 timestamp, msg, msglen) == 0) {
108                                 ret = msglen;
109                                 _last_write_timestamp = timestamp;
110
111                         } else {
112                                 ret = 0;
113                                 cerr << "write of " << msglen << " failed, port holds "
114                                         << jack_midi_get_event_count (jack_port_get_buffer (_jack_output_port, _nframes_this_cycle))
115                                         << endl;
116                         }
117                 } else {
118                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
119                 }
120         }
121
122         if (ret > 0 && output_parser) {
123                 output_parser->raw_preparse (*output_parser, msg, ret);
124                 for (int i = 0; i < ret; i++) {
125                         output_parser->scanner (msg[i]);
126                 }
127                 output_parser->raw_postparse (*output_parser, msg, ret);
128         }       
129
130         return ret;
131 }
132
133 void
134 JACK_MidiPort::flush (void* jack_port_buffer)
135 {
136         RingBuffer<Event>::rw_vector vec;
137         size_t written;
138
139         non_process_thread_fifo.get_read_vector (&vec);
140
141         if (vec.len[0] + vec.len[1]) {
142                 cerr << "Flush " << vec.len[0] + vec.len[1] << " events from non-process FIFO\n";
143         }
144
145         if (vec.len[0]) {
146                 Event* evp = vec.buf[0];
147                 
148                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
149                         jack_midi_event_write (jack_port_buffer,
150                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
151                 }
152         }
153         
154         if (vec.len[1]) {
155                 Event* evp = vec.buf[1];
156
157                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
158                         jack_midi_event_write (jack_port_buffer,
159                                                (timestamp_t) evp->time(), evp->buffer(), evp->size());
160                 }
161         }
162         
163         if ((written = vec.len[0] + vec.len[1]) != 0) {
164                 non_process_thread_fifo.increment_read_idx (written);
165         }
166 }
167
168 int
169 JACK_MidiPort::read(byte * buf, size_t bufsize)
170 {
171         assert(_currently_in_cycle);
172         assert(_jack_input_port);
173
174         jack_midi_event_t ev;
175
176         int err = jack_midi_event_get (&ev,
177                                        jack_port_get_buffer(_jack_input_port, _nframes_this_cycle),
178                                        _last_read_index++);
179         
180         // XXX this doesn't handle ev.size > max
181
182         if (!err) {
183                 size_t limit = min (bufsize, ev.size);
184                 memcpy(buf, ev.buffer, limit);
185
186                 if (input_parser) {
187                         input_parser->raw_preparse (*input_parser, buf, limit);
188                         for (size_t i = 0; i < limit; i++) {
189                                 input_parser->scanner (buf[i]);
190                         }       
191                         input_parser->raw_postparse (*input_parser, buf, limit);
192                 }
193
194                 return limit;
195         } else {
196                 return 0;
197         }
198 }
199
200 int
201 JACK_MidiPort::create_ports(const XMLNode& node)
202 {
203         Descriptor desc (node);
204
205         assert(!_jack_input_port);
206         assert(!_jack_output_port);
207         
208         jack_nframes_t nframes = jack_get_buffer_size(_jack_client);
209
210         bool ret = true;
211
212         if (desc.mode == O_RDWR || desc.mode == O_WRONLY) {
213                 _jack_output_port = jack_port_register(_jack_client,
214                                                        string(desc.tag).append("_out").c_str(),
215                                                        JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
216                 jack_midi_clear_buffer(jack_port_get_buffer(_jack_output_port, nframes));
217                 ret = ret && (_jack_output_port != NULL);
218         }
219         
220         if (desc.mode == O_RDWR || desc.mode == O_RDONLY) {
221                 _jack_input_port = jack_port_register(_jack_client,
222                                                       string(desc.tag).append("_in").c_str(),
223                                                       JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
224                 jack_midi_clear_buffer(jack_port_get_buffer(_jack_input_port, nframes));
225                 ret = ret && (_jack_input_port != NULL);
226         }
227
228         return ret ? 0 : -1;
229 }
230
231 XMLNode& 
232 JACK_MidiPort::get_state () const
233 {
234         XMLNode& root (Port::get_state ());
235         return root;
236 }
237
238 void
239 JACK_MidiPort::set_state (const XMLNode& node)
240 {
241 }
242
243 void
244 JACK_MidiPort::set_process_thread (pthread_t thr)
245 {
246         _process_thread = thr;
247 }
248
249 bool
250 JACK_MidiPort::is_process_thread()
251 {
252         return (pthread_self() == _process_thread);
253 }