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