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