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