alter Async MIDI port implementation to use crossthreadchannel on all platforms
[ardour.git] / libs / ardour / async_midi_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
21 #include <iostream>
22 #include <vector>
23
24 #include <glibmm/timer.h>
25
26 #include "pbd/error.h"
27 #include "pbd/stacktrace.h"
28
29 #include "midi++/types.h"
30
31 #include "ardour/async_midi_port.h"
32 #include "ardour/audioengine.h"
33 #include "ardour/midi_buffer.h"
34
35 using namespace MIDI;
36 using namespace ARDOUR;
37 using namespace std;
38 using namespace PBD;
39
40 namespace Evoral {
41         template class EventRingBuffer<MIDI::timestamp_t>;
42 }
43
44 pthread_t AsyncMIDIPort::_process_thread;
45
46 #define port_engine AudioEngine::instance()->port_engine()
47
48 AsyncMIDIPort::AsyncMIDIPort (string const & name, PortFlags flags)
49         : MidiPort (name, flags)
50         , MIDI::Port (name, MIDI::Port::Flags (0))
51         , _currently_in_cycle (false)
52         , _last_write_timestamp (0)
53         , have_timer (false)
54         , output_fifo (512)
55         , input_fifo (1024)
56         , _xthread (true)
57 {
58 }
59
60 AsyncMIDIPort::~AsyncMIDIPort ()
61 {
62 }
63
64 void
65 AsyncMIDIPort::set_timer (boost::function<MIDI::framecnt_t (void)>& f)
66 {
67         timer = f;
68         have_timer = true;
69 }
70
71 void
72 AsyncMIDIPort::flush_output_fifo (MIDI::pframes_t nframes)
73 {
74         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0 } };
75         size_t written;
76
77         output_fifo.get_read_vector (&vec);
78
79         MidiBuffer& mb (get_midi_buffer (nframes));
80                         
81         if (vec.len[0]) {
82                 Evoral::Event<double>* evp = vec.buf[0];
83                 
84                 for (size_t n = 0; n < vec.len[0]; ++n, ++evp) {
85                         mb.push_back (evp->time(), evp->size(), evp->buffer());
86                 }
87         }
88         
89         if (vec.len[1]) {
90                 Evoral::Event<double>* evp = vec.buf[1];
91
92                 for (size_t n = 0; n < vec.len[1]; ++n, ++evp) {
93                         mb.push_back (evp->time(), evp->size(), evp->buffer());
94                 }
95         }
96         
97         if ((written = vec.len[0] + vec.len[1]) != 0) {
98                 output_fifo.increment_read_idx (written);
99         }
100 }
101
102 void
103 AsyncMIDIPort::cycle_start (MIDI::pframes_t nframes)
104 {
105         _currently_in_cycle = true;
106         MidiPort::cycle_start (nframes);
107
108         /* dump anything waiting in the output FIFO at the start of the port
109          * buffer
110          */
111
112         if (ARDOUR::Port::sends_output()) {
113                 flush_output_fifo (nframes);
114         } 
115         
116         /* copy incoming data from the port buffer into the input FIFO
117            and if necessary wakeup the reader
118         */
119
120         if (ARDOUR::Port::receives_input()) {
121                 MidiBuffer& mb (get_midi_buffer (nframes));
122                 framecnt_t when;
123                 
124                 if (have_timer) {
125                         when = timer ();
126                 } else {
127                         when = AudioEngine::instance()->sample_time_at_cycle_start();
128                 }
129
130                 for (MidiBuffer::iterator b = mb.begin(); b != mb.end(); ++b) {
131                         if (!have_timer) {
132                                 when += (*b).time();
133                         }
134                         input_fifo.write (when, (Evoral::EventType) 0, (*b).size(), (*b).buffer());
135                 }
136
137                 if (!mb.empty()) {
138                         _xthread.wakeup ();
139                 }
140         }
141 }
142
143 void
144 AsyncMIDIPort::cycle_end (MIDI::pframes_t nframes)
145 {
146         if (ARDOUR::Port::sends_output()) {
147                 /* move any additional data from output FIFO into the port
148                    buffer.
149                 */
150                 flush_output_fifo (nframes);
151         }
152
153         MidiPort::cycle_end (nframes);
154
155         _currently_in_cycle = false;
156 }
157
158 /** wait for the output FIFO to be emptied by successive process() callbacks.
159  *
160  * Cannot be called from a processing thread.
161  */
162 void
163 AsyncMIDIPort::drain (int check_interval_usecs)
164 {
165         RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0} };
166
167         if (!AudioEngine::instance()->running() || AudioEngine::instance()->session() == 0) {
168                 /* no more process calls - it will never drain */
169                 return;
170         }
171
172
173         if (is_process_thread()) {
174                 error << "Process thread called MIDI::AsyncMIDIPort::drain() - this cannot work" << endmsg;
175                 return;
176         }
177
178         while (1) {
179                 output_fifo.get_write_vector (&vec);
180                 if (vec.len[0] + vec.len[1] >= output_fifo.bufsize() - 1) {
181                         break;
182                 }
183                 Glib::usleep (check_interval_usecs);
184         }
185 }
186
187 int
188 AsyncMIDIPort::write (const MIDI::byte * msg, size_t msglen, MIDI::timestamp_t timestamp)
189 {
190         int ret = 0;
191
192         if (!ARDOUR::Port::sends_output()) {
193                 return ret;
194         }
195
196         if (!is_process_thread()) {
197
198                 /* this is the best estimate of "when" this MIDI data is being
199                  * delivered
200                  */
201                 
202                 _parser->set_timestamp (AudioEngine::instance()->sample_time() + timestamp);
203                 for (size_t n = 0; n < msglen; ++n) {
204                         _parser->scanner (msg[n]);
205                 }
206
207                 Glib::Threads::Mutex::Lock lm (output_fifo_lock);
208                 RingBuffer< Evoral::Event<double> >::rw_vector vec = { { 0, 0 }, { 0, 0} };
209                 
210                 output_fifo.get_write_vector (&vec);
211
212                 if (vec.len[0] + vec.len[1] < 1) {
213                         error << "no space in FIFO for non-process thread MIDI write" << endmsg;
214                         return 0;
215                 }
216
217                 if (vec.len[0]) {
218                         if (!vec.buf[0]->owns_buffer()) {
219                                 vec.buf[0]->set_buffer (0, 0, true);
220                         }
221                         vec.buf[0]->set (msg, msglen, timestamp);
222                 } else {
223                         if (!vec.buf[1]->owns_buffer()) {
224                                 vec.buf[1]->set_buffer (0, 0, true);
225                         }
226                         vec.buf[1]->set (msg, msglen, timestamp);
227                 }
228
229                 output_fifo.increment_write_idx (1);
230                 
231                 ret = msglen;
232
233         } else {
234
235                 _parser->set_timestamp (AudioEngine::instance()->sample_time_at_cycle_start() + timestamp);
236                 for (size_t n = 0; n < msglen; ++n) {
237                         _parser->scanner (msg[n]);
238                 }
239
240                 if (timestamp >= _cycle_nframes) {
241                         std::cerr << "attempting to write MIDI event of " << msglen << " MIDI::bytes at time "
242                                   << timestamp << " of " << _cycle_nframes
243                                   << " (this will not work - needs a code fix)"
244                                   << std::endl;
245                 }
246
247                 /* This is the process thread, which makes checking
248                  * _currently_in_cycle atomic and safe, since it is only
249                  * set from cycle_start() and cycle_end(), also called
250                  * only from the process thread.
251                  */
252
253                 if (_currently_in_cycle) {
254
255                         MidiBuffer& mb (get_midi_buffer (_cycle_nframes));
256                         
257                         if (timestamp == 0) {
258                                 timestamp = _last_write_timestamp;
259                         } 
260                         
261                         if (mb.push_back (timestamp, msglen, msg)) {
262                                 ret = msglen;
263                                 _last_write_timestamp = timestamp;
264
265                         } else {
266                                 cerr << "AsyncMIDIPort (" << ARDOUR::Port::name() << "): write of " << msglen << " @ " << timestamp << " failed\n" << endl;
267                                 PBD::stacktrace (cerr, 20);
268                                 ret = 0;
269                         }
270                 } else {
271                         cerr << "write to JACK midi port failed: not currently in a process cycle." << endl;
272                         PBD::stacktrace (cerr, 20);
273                 }
274         }
275
276         return ret;
277 }
278
279
280 int
281 AsyncMIDIPort::read (MIDI::byte *, size_t)
282 {
283         if (!ARDOUR::Port::receives_input()) {
284                 return 0;
285         }
286         
287         timestamp_t time;
288         Evoral::EventType type;
289         uint32_t size;
290         vector<MIDI::byte> buffer(input_fifo.capacity());
291
292         while (input_fifo.read (&time, &type, &size, &buffer[0])) {
293                 _parser->set_timestamp (time);
294                 for (uint32_t i = 0; i < size; ++i) {
295                         _parser->scanner (buffer[i]);
296                 }
297         }
298
299         return 0;
300 }
301
302 void
303 AsyncMIDIPort::parse (MIDI::framecnt_t)
304 {
305         MIDI::byte buf[1];
306
307         /* see ::read() to realize why buf is not used */
308         read (buf, sizeof (buf));
309 }
310
311 void
312 AsyncMIDIPort::set_process_thread (pthread_t thr)
313 {
314         _process_thread = thr;
315 }
316
317 bool
318 AsyncMIDIPort::is_process_thread()
319 {
320         return pthread_equal (pthread_self(), _process_thread);
321 }
322