Collect plugin runtime profile statistics.
[ardour.git] / libs / ardour / midi_port.cc
1 /*
2     Copyright (C) 2006 Paul 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
19 #include <cassert>
20 #include <iostream>
21
22 #include "pbd/compose.h"
23 #include "pbd/debug.h"
24
25 #include "ardour/audioengine.h"
26 #include "ardour/data_type.h"
27 #include "ardour/debug.h"
28 #include "ardour/midi_buffer.h"
29 #include "ardour/midi_port.h"
30 #include "ardour/session.h"
31
32 using namespace std;
33 using namespace ARDOUR;
34 using namespace PBD;
35
36 #define port_engine AudioEngine::instance()->port_engine()
37
38 MidiPort::MidiPort (const std::string& name, PortFlags flags)
39         : Port (name, DataType::MIDI, flags)
40         , _has_been_mixed_down (false)
41         , _resolve_required (false)
42         , _input_active (true)
43         , _always_parse (false)
44         , _trace_on (false)
45 {
46         _buffer = new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI));
47 }
48
49 MidiPort::~MidiPort()
50 {
51         if (_shadow_port) {
52                 AudioEngine::instance()->unregister_port (_shadow_port);
53                 _shadow_port.reset ();
54         }
55
56         delete _buffer;
57 }
58
59 void
60 MidiPort::cycle_start (pframes_t nframes)
61 {
62         samplepos_t now = AudioEngine::instance()->sample_time_at_cycle_start();
63
64         Port::cycle_start (nframes);
65
66         _buffer->clear ();
67
68         if (sends_output () && _port_handle) {
69                 port_engine.midi_clear (port_engine.get_buffer (_port_handle, nframes));
70         }
71
72         if (_always_parse || (receives_input() && _trace_on)) {
73                 MidiBuffer& mb (get_midi_buffer (nframes));
74
75                 /* dump incoming MIDI to parser */
76
77                 for (MidiBuffer::iterator b = mb.begin(); b != mb.end(); ++b) {
78                         uint8_t* buf = (*b).buffer();
79
80                         _self_parser.set_timestamp (now + (*b).time());
81
82                         uint32_t limit = (*b).size();
83
84                         for (size_t n = 0; n < limit; ++n) {
85                                 _self_parser.scanner (buf[n]);
86                         }
87                 }
88         }
89
90         if (inbound_midi_filter) {
91                 MidiBuffer& mb (get_midi_buffer (nframes));
92                 inbound_midi_filter (mb, mb);
93         }
94
95         if (_shadow_port) {
96                 MidiBuffer& mb (get_midi_buffer (nframes));
97                 if (shadow_midi_filter (mb, _shadow_port->get_midi_buffer (nframes))) {
98                         _shadow_port->flush_buffers (nframes);
99                 }
100         }
101
102 }
103
104 Buffer&
105 MidiPort::get_buffer (pframes_t nframes)
106 {
107         return get_midi_buffer (nframes);
108 }
109
110 MidiBuffer &
111 MidiPort::get_midi_buffer (pframes_t nframes)
112 {
113         if (_has_been_mixed_down) {
114                 return *_buffer;
115         }
116
117         if (receives_input ()) {
118
119                 if (_input_active) {
120
121                         void* buffer = port_engine.get_buffer (_port_handle, nframes);
122                         const pframes_t event_count = port_engine.get_midi_event_count (buffer);
123
124                         /* suck all relevant MIDI events from the MIDI port buffer
125                            into our MidiBuffer
126                         */
127
128                         for (pframes_t i = 0; i < event_count; ++i) {
129
130                                 pframes_t timestamp;
131                                 size_t size;
132                                 uint8_t const* buf;
133
134                                 port_engine.midi_event_get (timestamp, size, &buf, buffer, i);
135
136                                 if (buf[0] == 0xfe) {
137                                         /* throw away active sensing */
138                                         continue;
139                                 }
140
141                                 timestamp = floor (timestamp * _speed_ratio);
142
143                                 /* check that the event is in the acceptable time range */
144                                 if ((timestamp <  (_global_port_buffer_offset)) ||
145                                     (timestamp >= (_global_port_buffer_offset + nframes))) {
146                                         // XXX this is normal after a split cycles:
147                                         // The engine buffer contains the data for the complete cycle, but
148                                         // only the part after _global_port_buffer_offset is needed.
149 #ifndef NDEBUG
150                                         cerr << "Dropping incoming MIDI at time " << timestamp << "; offset="
151                                                 << _global_port_buffer_offset << " limit="
152                                                 << (_global_port_buffer_offset + nframes)
153                                                 << " = (" << _global_port_buffer_offset
154                                                 << " + " << nframes
155                                                 << ")\n";
156 #endif
157                                         continue;
158                                 }
159
160                                 /* adjust timestamp to match current cycle */
161                                 timestamp -= _global_port_buffer_offset;
162                                 assert (timestamp < nframes);
163
164                                 if ((buf[0] & 0xF0) == 0x90 && buf[2] == 0) {
165                                         /* normalize note on with velocity 0 to proper note off */
166                                         uint8_t ev[3];
167                                         ev[0] = 0x80 | (buf[0] & 0x0F);  /* note off */
168                                         ev[1] = buf[1];
169                                         ev[2] = 0x40;  /* default velocity */
170                                         _buffer->push_back (timestamp, size, ev);
171                                 } else {
172                                         _buffer->push_back (timestamp, size, buf);
173                                 }
174                         }
175
176                 } else {
177                         _buffer->silence (nframes);
178                 }
179
180         } else {
181                 _buffer->silence (nframes);
182         }
183
184         if (nframes) {
185                 _has_been_mixed_down = true;
186         }
187
188         return *_buffer;
189 }
190
191 void
192 MidiPort::cycle_end (pframes_t /*nframes*/)
193 {
194         _has_been_mixed_down = false;
195 }
196
197 void
198 MidiPort::cycle_split ()
199 {
200         _has_been_mixed_down = false;
201 }
202
203 void
204 MidiPort::resolve_notes (void* port_buffer, MidiBuffer::TimeType when)
205 {
206         for (uint8_t channel = 0; channel <= 0xF; channel++) {
207
208                 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), MIDI_CTL_SUSTAIN, 0 };
209                 pframes_t tme = floor (when / _speed_ratio);
210
211                 /* we need to send all notes off AND turn the
212                  * sustain/damper pedal off to handle synths
213                  * that prioritize sustain over AllNotesOff
214                  */
215
216                 if (port_engine.midi_event_put (port_buffer, tme, ev, 3) != 0) {
217                         cerr << "failed to deliver sustain-zero on channel " << (int)channel << " on port " << name() << endl;
218                 }
219
220                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
221
222                 if (port_engine.midi_event_put (port_buffer, tme, ev, 3) != 0) {
223                         cerr << "failed to deliver ALL NOTES OFF on channel " << (int)channel << " on port " << name() << endl;
224                 }
225         }
226 }
227
228 void
229 MidiPort::flush_buffers (pframes_t nframes)
230 {
231         if (sends_output ()) {
232
233                 void* port_buffer = 0;
234
235                 if (_resolve_required) {
236                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
237                         /* resolve all notes at the start of the buffer */
238                         resolve_notes (port_buffer, _global_port_buffer_offset);
239                         _resolve_required = false;
240                 }
241
242                 if (_buffer->empty()) {
243                         return;
244                 }
245
246                 if (!port_buffer) {
247                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
248                 }
249
250
251                 for (MidiBuffer::iterator i = _buffer->begin(); i != _buffer->end(); ++i) {
252
253                         const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
254
255
256                         if (sends_output() && _trace_on) {
257                                 uint8_t const * const buf = ev.buffer();
258                                 const samplepos_t now = AudioEngine::instance()->sample_time_at_cycle_start();
259
260                                 _self_parser.set_timestamp (now + ev.time());
261
262                                 uint32_t limit = ev.size();
263
264                                 for (size_t n = 0; n < limit; ++n) {
265                                         _self_parser.scanner (buf[n]);
266                                 }
267                         }
268
269
270                         // event times are in samples, relative to cycle start
271
272 #ifndef NDEBUG
273                         if (DEBUG_ENABLED (DEBUG::MidiIO)) {
274                                 const Session* s = AudioEngine::instance()->session();
275                                 const samplepos_t now = (s ? s->transport_sample() : 0);
276                                 DEBUG_STR_DECL(a);
277                                 DEBUG_STR_APPEND(a, string_compose ("MidiPort %7 %1 pop event    @ %2 (global %4, within %5 gpbo %6 sz %3 ", _buffer, ev.time(), ev.size(),
278                                                                     now + ev.time(), nframes, _global_port_buffer_offset, name()));
279                                 for (size_t i=0; i < ev.size(); ++i) {
280                                         DEBUG_STR_APPEND(a,hex);
281                                         DEBUG_STR_APPEND(a,"0x");
282                                         DEBUG_STR_APPEND(a,(int)(ev.buffer()[i]));
283                                         DEBUG_STR_APPEND(a,' ');
284                                 }
285                                 DEBUG_STR_APPEND(a,'\n');
286                                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
287                         }
288 #endif
289
290                         assert (ev.time() < (nframes + _global_port_buffer_offset));
291
292                         if (ev.time() >= _global_port_buffer_offset) {
293                                 pframes_t tme = floor (ev.time() / _speed_ratio);
294                                 if (port_engine.midi_event_put (port_buffer, tme, ev.buffer(), ev.size()) != 0) {
295                                         cerr << "write failed, dropped event, time "
296                                              << ev.time()
297                                                          << " > " << _global_port_buffer_offset << endl;
298                                 }
299                         } else {
300                                 cerr << "drop flushed event on the floor, time " << ev.time()
301                                      << " too early for " << _global_port_buffer_offset;
302                                 for (size_t xx = 0; xx < ev.size(); ++xx) {
303                                         cerr << ' ' << hex << (int) ev.buffer()[xx];
304                                 }
305                                 cerr << dec << endl;
306                         }
307                 }
308
309                 /* done.. the data has moved to the port buffer, mark it so
310                  */
311
312                 _buffer->clear ();
313         }
314 }
315
316 void
317 MidiPort::require_resolve ()
318 {
319         _resolve_required = true;
320 }
321
322 void
323 MidiPort::transport_stopped ()
324 {
325         _resolve_required = true;
326 }
327
328 void
329 MidiPort::realtime_locate ()
330 {
331         _resolve_required = true;
332 }
333
334 void
335 MidiPort::reset ()
336 {
337         Port::reset ();
338         delete _buffer;
339         cerr << name() << " new MIDI buffer of size " << AudioEngine::instance()->raw_buffer_size (DataType::MIDI) << endl;
340         _buffer = new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI));
341 }
342
343 void
344 MidiPort::set_input_active (bool yn)
345 {
346         _input_active = yn;
347 }
348
349 void
350 MidiPort::set_always_parse (bool yn)
351 {
352         _always_parse = yn;
353 }
354
355 void
356 MidiPort::set_trace_on (bool yn)
357 {
358         _trace_on = yn;
359 }
360
361 int
362 MidiPort::add_shadow_port (string const & name, MidiFilter mf)
363 {
364         if (!ARDOUR::Port::receives_input()) {
365                 return -1;
366         }
367
368         if (_shadow_port) {
369                 return -2;
370         }
371
372         shadow_midi_filter = mf;
373
374         if (!(_shadow_port = boost::dynamic_pointer_cast<MidiPort> (AudioEngine::instance()->register_output_port (DataType::MIDI, name, false, PortFlags (Shadow|IsTerminal))))) {
375                 return -3;
376         }
377
378         /* forward on our port latency to the shadow port.
379
380            XXX: need to capture latency changes and forward them too.
381         */
382
383         LatencyRange latency = private_latency_range (false);
384         _shadow_port->set_private_latency_range (latency, false);
385
386         return 0;
387 }