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