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