move ownership of an RT MIDI buffer from DiskIO to MidiPlaylist
[ardour.git] / libs / ardour / midi_port.cc
1 /*
2  * Copyright (C) 2006-2016 David Robillard <d@drobilla.net>
3  * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
4  * Copyright (C) 2007-2018 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2008 Hans Baier <hansfbaier@googlemail.com>
6  * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <cassert>
24 #include <iostream>
25
26 #include "pbd/compose.h"
27 #include "pbd/debug.h"
28
29 #include "ardour/audioengine.h"
30 #include "ardour/data_type.h"
31 #include "ardour/debug.h"
32 #include "ardour/midi_buffer.h"
33 #include "ardour/midi_port.h"
34 #include "ardour/session.h"
35
36 using namespace std;
37 using namespace ARDOUR;
38 using namespace PBD;
39
40 #define port_engine AudioEngine::instance()->port_engine()
41
42 MidiPort::MidiPort (const std::string& name, PortFlags flags)
43         : Port (name, DataType::MIDI, flags)
44         , _resolve_required (false)
45         , _input_active (true)
46         , _trace_parser (0)
47         , _data_fetched_for_cycle (false)
48 {
49         _buffer = new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI));
50 }
51
52 MidiPort::~MidiPort()
53 {
54         if (_shadow_port) {
55                 AudioEngine::instance()->unregister_port (_shadow_port);
56                 _shadow_port.reset ();
57         }
58
59         delete _buffer;
60 }
61
62 void
63 MidiPort::parse_input (pframes_t nframes, MIDI::Parser& parser)
64 {
65 }
66
67 void
68 MidiPort::cycle_start (pframes_t nframes)
69 {
70         Port::cycle_start (nframes);
71
72         _buffer->clear ();
73
74         if (sends_output () && _port_handle) {
75                 port_engine.midi_clear (port_engine.get_buffer (_port_handle, nframes));
76         }
77
78         if (receives_input() && _trace_parser) {
79                 read_and_parse_entire_midi_buffer_with_no_speed_adjustment (nframes, *_trace_parser, AudioEngine::instance()->sample_time_at_cycle_start());
80         }
81
82         if (_inbound_midi_filter) {
83                 MidiBuffer& mb (get_midi_buffer (nframes));
84                 _inbound_midi_filter (mb, mb);
85         }
86
87         if (_shadow_port) {
88                 MidiBuffer& mb (get_midi_buffer (nframes));
89                 if (_shadow_midi_filter (mb, _shadow_port->get_midi_buffer (nframes))) {
90                         _shadow_port->flush_buffers (nframes);
91                 }
92         }
93
94 }
95
96 MidiBuffer &
97 MidiPort::get_midi_buffer (pframes_t nframes)
98 {
99         if (_data_fetched_for_cycle) {
100                 return *_buffer;
101         }
102
103         if (receives_input () && _input_active) {
104
105                 void* buffer = port_engine.get_buffer (_port_handle, nframes);
106                 const pframes_t event_count = port_engine.get_midi_event_count (buffer);
107
108                 /* suck all MIDI events for this cycle of nframes from
109                    the MIDI port buffer into our MidiBuffer.
110                 */
111
112                 for (pframes_t i = 0; i < event_count; ++i) {
113
114                         pframes_t timestamp;
115                         size_t size;
116                         uint8_t const* buf;
117
118                         port_engine.midi_event_get (timestamp, size, &buf, buffer, i);
119
120                         if (buf[0] == 0xfe) {
121                                 /* throw away active sensing */
122                                 continue;
123                         }
124
125                         timestamp = floor (timestamp * _speed_ratio);
126
127                         /* check that the event is in the acceptable time range */
128                         if ((timestamp <  (_global_port_buffer_offset)) ||
129                             (timestamp >= (_global_port_buffer_offset + nframes))) {
130                                 // XXX this is normal after a split cycles:
131                                 // The engine buffer contains the data for the complete cycle, but
132                                 // only the part after _global_port_buffer_offset is needed.
133 #ifndef NDEBUG
134                                 cerr << "Dropping incoming MIDI at time " << timestamp << "; offset="
135                                      << _global_port_buffer_offset << " limit="
136                                      << (_global_port_buffer_offset + nframes)
137                                      << " = (" << _global_port_buffer_offset
138                                      << " + " << nframes
139                                      << ")\n";
140 #endif
141                                 continue;
142                         }
143
144                         if ((buf[0] & 0xF0) == 0x90 && buf[2] == 0) {
145                                 /* normalize note on with velocity 0 to proper note off */
146                                 uint8_t ev[3];
147                                 ev[0] = 0x80 | (buf[0] & 0x0F);  /* note off */
148                                 ev[1] = buf[1];
149                                 ev[2] = 0x40;  /* default velocity */
150                                 _buffer->push_back (timestamp, size, ev);
151                         } else {
152                                 _buffer->push_back (timestamp, size, buf);
153                         }
154                 }
155
156         } else {
157                 _buffer->silence (nframes);
158         }
159
160         if (nframes) {
161                 _data_fetched_for_cycle = true;
162         }
163
164         return *_buffer;
165 }
166
167 void
168 MidiPort::read_and_parse_entire_midi_buffer_with_no_speed_adjustment (pframes_t nframes, MIDI::Parser& parser, samplepos_t now)
169 {
170         void* buffer = port_engine.get_buffer (_port_handle, nframes);
171         const pframes_t event_count = port_engine.get_midi_event_count (buffer);
172
173         for (pframes_t i = 0; i < event_count; ++i) {
174
175                 pframes_t timestamp;
176                 size_t size;
177                 uint8_t const* buf;
178
179                 port_engine.midi_event_get (timestamp, size, &buf, buffer, i);
180
181                 if (buf[0] == 0xfe) {
182                         /* throw away active sensing */
183                         continue;
184                 }
185
186                 parser.set_timestamp (now + timestamp);
187
188                 /* During this parsing stage, signals will be emitted from the
189                  * Parser, which will update anything connected to it.
190                  *
191                  * As of July 2018, this is only used by TransportMasters which
192                  * read MIDI before the process() cycle really gets started.
193                  */
194
195                 if ((buf[0] & 0xF0) == 0x90 && buf[2] == 0) {
196                         /* normalize note on with velocity 0 to proper note off */
197                         parser.scanner (0x80 | (buf[0] & 0x0F));  /* note off */
198                         parser.scanner (buf[1]);
199                         parser.scanner (0x40);  /* default (off) velocity */
200                 } else {
201                         for (size_t n = 0; n < size; ++n) {
202                                 parser.scanner (buf[n]);
203                         }
204                 }
205         }
206 }
207
208 void
209 MidiPort::cycle_end (pframes_t /*nframes*/)
210 {
211         _data_fetched_for_cycle = false;
212 }
213
214 void
215 MidiPort::cycle_split ()
216 {
217         _data_fetched_for_cycle = false;
218 }
219
220 void
221 MidiPort::resolve_notes (void* port_buffer, MidiBuffer::TimeType when)
222 {
223         for (uint8_t channel = 0; channel <= 0xF; channel++) {
224
225                 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), MIDI_CTL_SUSTAIN, 0 };
226                 pframes_t tme = floor (when / _speed_ratio);
227
228                 /* we need to send all notes off AND turn the
229                  * sustain/damper pedal off to handle synths
230                  * that prioritize sustain over AllNotesOff
231                  */
232
233                 if (port_engine.midi_event_put (port_buffer, tme, ev, 3) != 0) {
234                         cerr << "failed to deliver sustain-zero on channel " << (int)channel << " on port " << name() << endl;
235                 }
236
237                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
238
239                 if (port_engine.midi_event_put (port_buffer, tme, ev, 3) != 0) {
240                         cerr << "failed to deliver ALL NOTES OFF on channel " << (int)channel << " on port " << name() << endl;
241                 }
242         }
243 }
244
245 void
246 MidiPort::flush_buffers (pframes_t nframes)
247 {
248         if (sends_output ()) {
249
250                 void* port_buffer = 0;
251
252                 if (_resolve_required) {
253                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
254                         /* resolve all notes at the start of the buffer */
255                         resolve_notes (port_buffer, _global_port_buffer_offset);
256                         _resolve_required = false;
257                 }
258
259                 if (_buffer->empty()) {
260                         return;
261                 }
262
263                 if (!port_buffer) {
264                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
265                 }
266
267
268                 for (MidiBuffer::iterator i = _buffer->begin(); i != _buffer->end(); ++i) {
269
270                         const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
271
272
273                         if (sends_output() && _trace_parser) {
274                                 uint8_t const * const buf = ev.buffer();
275                                 const samplepos_t now = AudioEngine::instance()->sample_time_at_cycle_start();
276
277                                 _trace_parser->set_timestamp (now + ev.time());
278
279                                 uint32_t limit = ev.size();
280
281                                 for (size_t n = 0; n < limit; ++n) {
282                                         _trace_parser->scanner (buf[n]);
283                                 }
284                         }
285
286
287                         // event times are in samples, relative to cycle start
288
289 #ifndef NDEBUG
290                         if (DEBUG_ENABLED (DEBUG::MidiIO)) {
291                                 const Session* s = AudioEngine::instance()->session();
292                                 const samplepos_t now = (s ? s->transport_sample() : 0);
293                                 DEBUG_STR_DECL(a);
294                                 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(),
295                                                                     now + ev.time(), nframes, _global_port_buffer_offset, name()));
296                                 for (size_t i=0; i < ev.size(); ++i) {
297                                         DEBUG_STR_APPEND(a,hex);
298                                         DEBUG_STR_APPEND(a,"0x");
299                                         DEBUG_STR_APPEND(a,(int)(ev.buffer()[i]));
300                                         DEBUG_STR_APPEND(a,' ');
301                                 }
302                                 DEBUG_STR_APPEND(a,'\n');
303                                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
304                         }
305 #endif
306
307                         assert (ev.time() < (nframes + _global_port_buffer_offset));
308
309                         if (ev.time() >= _global_port_buffer_offset) {
310                                 pframes_t tme = floor (ev.time() / _speed_ratio);
311                                 if (port_engine.midi_event_put (port_buffer, tme, ev.buffer(), ev.size()) != 0) {
312                                         cerr << "write failed, dropped event, time "
313                                              << ev.time()
314                                                          << " > " << _global_port_buffer_offset << endl;
315                                 }
316                         } else {
317                                 cerr << "drop flushed event on the floor, time " << ev.time()
318                                      << " too early for " << _global_port_buffer_offset;
319                                 for (size_t xx = 0; xx < ev.size(); ++xx) {
320                                         cerr << ' ' << hex << (int) ev.buffer()[xx];
321                                 }
322                                 cerr << dec << endl;
323                         }
324                 }
325
326                 /* done.. the data has moved to the port buffer, mark it so
327                  */
328
329                 _buffer->clear ();
330         }
331 }
332
333 void
334 MidiPort::require_resolve ()
335 {
336         _resolve_required = true;
337 }
338
339 void
340 MidiPort::transport_stopped ()
341 {
342         _resolve_required = true;
343 }
344
345 void
346 MidiPort::realtime_locate ()
347 {
348         _resolve_required = true;
349 }
350
351 void
352 MidiPort::reset ()
353 {
354         Port::reset ();
355         delete _buffer;
356         cerr << name() << " new MIDI buffer of size " << AudioEngine::instance()->raw_buffer_size (DataType::MIDI) << endl;
357         _buffer = new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI));
358 }
359
360 void
361 MidiPort::set_input_active (bool yn)
362 {
363         _input_active = yn;
364 }
365
366 void
367 MidiPort::set_trace (MIDI::Parser * p)
368 {
369         _trace_parser = p;
370 }
371
372 int
373 MidiPort::add_shadow_port (string const & name, MidiFilter mf)
374 {
375         if (!ARDOUR::Port::receives_input()) {
376                 return -1;
377         }
378
379         if (_shadow_port) {
380                 return -2;
381         }
382
383         _shadow_midi_filter = mf;
384
385         if (!(_shadow_port = boost::dynamic_pointer_cast<MidiPort> (AudioEngine::instance()->register_output_port (DataType::MIDI, name, false, PortFlags (Shadow|IsTerminal))))) {
386                 return -3;
387         }
388
389         /* forward on our port latency to the shadow port.
390
391            XXX: need to capture latency changes and forward them too.
392         */
393
394         LatencyRange latency = private_latency_range (false);
395         _shadow_port->set_private_latency_range (latency, false);
396
397         return 0;
398 }