slight DEBUG_TRACE enhancement for MidiPort::flush_buffers() output
[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         delete _buffer;
52 }
53
54 void
55 MidiPort::cycle_start (pframes_t nframes)
56 {
57         framepos_t now = AudioEngine::instance()->sample_time_at_cycle_start();
58
59         Port::cycle_start (nframes);
60
61         _buffer->clear ();
62
63         if (sends_output ()) {
64                 port_engine.midi_clear (port_engine.get_buffer (_port_handle, nframes));
65         }
66
67         if (_always_parse || (receives_input() && _trace_on)) {
68                 MidiBuffer& mb (get_midi_buffer (nframes));
69
70                 /* dump incoming MIDI to parser */
71
72                 for (MidiBuffer::iterator b = mb.begin(); b != mb.end(); ++b) {
73                         uint8_t* buf = (*b).buffer();
74
75                         _self_parser.set_timestamp (now + (*b).time());
76
77                         uint32_t limit = (*b).size();
78
79                         for (size_t n = 0; n < limit; ++n) {
80                                 _self_parser.scanner (buf[n]);
81                         }
82                 }
83         }
84 }
85
86 Buffer&
87 MidiPort::get_buffer (pframes_t nframes)
88 {
89         return get_midi_buffer (nframes);
90 }
91
92 MidiBuffer &
93 MidiPort::get_midi_buffer (pframes_t nframes)
94 {
95         if (_has_been_mixed_down) {
96                 return *_buffer;
97         }
98
99         if (receives_input ()) {
100
101                 if (_input_active) {
102
103                         void* buffer = port_engine.get_buffer (_port_handle, nframes);
104                         const pframes_t event_count = port_engine.get_midi_event_count (buffer);
105
106                         /* suck all relevant MIDI events from the MIDI port buffer
107                            into our MidiBuffer
108                         */
109
110                         for (pframes_t i = 0; i < event_count; ++i) {
111
112                                 pframes_t timestamp;
113                                 size_t size;
114                                 uint8_t* buf;
115
116                                 port_engine.midi_event_get (timestamp, size, &buf, buffer, i);
117
118                                 if (buf[0] == 0xfe) {
119                                         /* throw away active sensing */
120                                         continue;
121                                 } else if ((buf[0] & 0xF0) == 0x90 && buf[2] == 0) {
122                                         /* normalize note on with velocity 0 to proper note off */
123                                         buf[0] = 0x80 | (buf[0] & 0x0F);  /* note off */
124                                         buf[2] = 0x40;  /* default velocity */
125                                 }
126
127                                 /* check that the event is in the acceptable time range */
128
129                                 if ((timestamp >= (_global_port_buffer_offset + _port_buffer_offset)) &&
130                                     (timestamp < (_global_port_buffer_offset + _port_buffer_offset + nframes))) {
131                                         _buffer->push_back (timestamp, size, buf);
132                                 } else {
133                                         cerr << "Dropping incoming MIDI at time " << timestamp << "; offset="
134                                              << _global_port_buffer_offset << " limit="
135                                              << (_global_port_buffer_offset + _port_buffer_offset + nframes) << "\n";
136                                 }
137                         }
138
139                 } else {
140                         _buffer->silence (nframes);
141                 }
142
143         } else {
144                 _buffer->silence (nframes);
145         }
146
147         if (nframes) {
148                 _has_been_mixed_down = true;
149         }
150
151         return *_buffer;
152 }
153
154 void
155 MidiPort::cycle_end (pframes_t /*nframes*/)
156 {
157         _has_been_mixed_down = false;
158 }
159
160 void
161 MidiPort::cycle_split ()
162 {
163         _has_been_mixed_down = false;
164 }
165
166 void
167 MidiPort::resolve_notes (void* port_buffer, MidiBuffer::TimeType when)
168 {
169         for (uint8_t channel = 0; channel <= 0xF; channel++) {
170
171                 uint8_t ev[3] = { ((uint8_t) (MIDI_CMD_CONTROL | channel)), MIDI_CTL_SUSTAIN, 0 };
172
173                 /* we need to send all notes off AND turn the
174                  * sustain/damper pedal off to handle synths
175                  * that prioritize sustain over AllNotesOff
176                  */
177
178                 if (port_engine.midi_event_put (port_buffer, when, ev, 3) != 0) {
179                         cerr << "failed to deliver sustain-zero on channel " << (int)channel << " on port " << name() << endl;
180                 }
181
182                 ev[1] = MIDI_CTL_ALL_NOTES_OFF;
183
184                 if (port_engine.midi_event_put (port_buffer, when, ev, 3) != 0) {
185                         cerr << "failed to deliver ALL NOTES OFF on channel " << (int)channel << " on port " << name() << endl;
186                 }
187         }
188 }
189
190 void
191 MidiPort::flush_buffers (pframes_t nframes)
192 {
193         if (sends_output ()) {
194
195                 void* port_buffer = 0;
196
197                 if (_resolve_required) {
198                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
199                         /* resolve all notes at the start of the buffer */
200                         resolve_notes (port_buffer, _global_port_buffer_offset);
201                         _resolve_required = false;
202                 }
203
204                 if (_buffer->empty()) {
205                         return;
206                 }
207
208                 if (!port_buffer) {
209                         port_buffer = port_engine.get_buffer (_port_handle, nframes);
210                 }
211
212
213                 for (MidiBuffer::iterator i = _buffer->begin(); i != _buffer->end(); ++i) {
214
215                         const Evoral::MIDIEvent<MidiBuffer::TimeType> ev (*i, false);
216
217
218                         if (sends_output() && _trace_on) {
219                                 uint8_t const * const buf = ev.buffer();
220                                 const framepos_t now = AudioEngine::instance()->sample_time_at_cycle_start();
221
222                                 _self_parser.set_timestamp (now + ev.time());
223
224                                 uint32_t limit = ev.size();
225
226                                 for (size_t n = 0; n < limit; ++n) {
227                                         _self_parser.scanner (buf[n]);
228                                 }
229                         }
230
231
232                         // event times are in frames, relative to cycle start
233
234 #ifndef NDEBUG
235                         if (DEBUG_ENABLED (DEBUG::MidiIO)) {
236                                 const Session* s = AudioEngine::instance()->session();
237                                 const framepos_t now = (s ? s->transport_frame() : 0);
238                                 DEBUG_STR_DECL(a);
239                                 DEBUG_STR_APPEND(a, string_compose ("MidiPort %8 %1 pop event    @ %2 (global %4, within %5 gpbo %6 pbo %7 sz %3 ", _buffer, ev.time(), ev.size(),
240                                                                     now + ev.time(), nframes, _global_port_buffer_offset, _port_buffer_offset, name()));
241                                 for (size_t i=0; i < ev.size(); ++i) {
242                                         DEBUG_STR_APPEND(a,hex);
243                                         DEBUG_STR_APPEND(a,"0x");
244                                         DEBUG_STR_APPEND(a,(int)(ev.buffer()[i]));
245                                         DEBUG_STR_APPEND(a,' ');
246                                 }
247                                 DEBUG_STR_APPEND(a,'\n');
248                                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
249                         }
250 #endif
251
252                         assert (ev.time() < (nframes + _global_port_buffer_offset + _port_buffer_offset));
253
254                         if (ev.time() >= _global_port_buffer_offset + _port_buffer_offset) {
255                                 if (port_engine.midi_event_put (port_buffer, (pframes_t) ev.time(), ev.buffer(), ev.size()) != 0) {
256                                         cerr << "write failed, drop flushed note off on the floor, time "
257                                              << ev.time() << " > " << _global_port_buffer_offset + _port_buffer_offset << endl;
258                                 }
259                         } else {
260                                 cerr << "drop flushed event on the floor, time " << ev.time()
261                                      << " too early for " << _global_port_buffer_offset
262                                      << " + " << _port_buffer_offset;
263                                 for (size_t xx = 0; xx < ev.size(); ++xx) {
264                                         cerr << ' ' << hex << (int) ev.buffer()[xx];
265                                 }
266                                 cerr << dec << endl;
267                         }
268                 }
269
270                 /* done.. the data has moved to the port buffer, mark it so
271                  */
272
273                 _buffer->clear ();
274         }
275 }
276
277 void
278 MidiPort::require_resolve ()
279 {
280         _resolve_required = true;
281 }
282
283 void
284 MidiPort::transport_stopped ()
285 {
286         _resolve_required = true;
287 }
288
289 void
290 MidiPort::realtime_locate ()
291 {
292         _resolve_required = true;
293 }
294
295 void
296 MidiPort::reset ()
297 {
298         Port::reset ();
299         delete _buffer;
300         cerr << name() << " new MIDI buffer of size " << AudioEngine::instance()->raw_buffer_size (DataType::MIDI) << endl;
301         _buffer = new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI));
302 }
303
304 void
305 MidiPort::set_input_active (bool yn)
306 {
307         _input_active = yn;
308 }
309
310 void
311 MidiPort::set_always_parse (bool yn)
312 {
313         _always_parse = yn;
314 }
315
316 void
317 MidiPort::set_trace_on (bool yn)
318 {
319         _trace_on = yn;
320 }