'surfaces/generic_midi' - Specify 'MIDI::byte' instead of 'byte' so the compiler...
[ardour.git] / libs / surfaces / generic_midi / midicontrollable.cc
1 /*
2     Copyright (C) 1998-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
20 #include <stdint.h>
21 #include <cmath>
22 #include <climits>
23 #include <iostream>
24
25 #include "pbd/error.h"
26 #include "pbd/controllable_descriptor.h"
27 #include "pbd/xml++.h"
28 #include "pbd/stacktrace.h"
29
30 #include "midi++/types.h" // Added by JE - 06-01-2009. All instances of 'byte' changed to 'MIDI::byte' (for clarification)
31 #include "midi++/port.h"
32 #include "midi++/channel.h"
33
34 #include "ardour/automation_control.h"
35 #include "ardour/midi_ui.h"
36 #include "ardour/utils.h"
37
38 #include "midicontrollable.h"
39 #include "generic_midi_control_protocol.h"
40
41 using namespace std;
42 using namespace MIDI;
43 using namespace PBD;
44 using namespace ARDOUR;
45
46 MIDIControllable::MIDIControllable (GenericMidiControlProtocol* s, Port& p, bool m)
47         : _surface (s)
48         , controllable (0)
49         , _descriptor (0)
50         , _port (p)
51         , _momentary (m)
52 {
53         _learned = false; /* from URI */
54         setting = false;
55         last_value = 0; // got a better idea ?
56         last_controllable_value = 0.0f;
57         control_type = none;
58         _control_description = "MIDI Control: none";
59         control_additional = (MIDI::byte) -1;
60         feedback = true; // for now
61 }
62
63 MIDIControllable::MIDIControllable (GenericMidiControlProtocol* s, Port& p, Controllable& c, bool m)
64         : _surface (s)
65         , _descriptor (0)
66         , _port (p)
67         , _momentary (m)
68 {
69         set_controllable (&c);
70         
71         _learned = true; /* from controllable */
72         setting = false;
73         last_value = 0; // got a better idea ?
74         last_controllable_value = 0.0f;
75         control_type = none;
76         _control_description = "MIDI Control: none";
77         control_additional = (MIDI::byte) -1;
78         feedback = true; // for now
79 }
80
81 MIDIControllable::~MIDIControllable ()
82 {
83         drop_external_control ();
84 }
85
86 int
87 MIDIControllable::init (const std::string& s)
88 {
89         _current_uri = s;
90         delete _descriptor;
91         _descriptor = new ControllableDescriptor;
92         return _descriptor->set (s);
93 }
94
95 void
96 MIDIControllable::midi_forget ()
97 {
98         /* stop listening for incoming messages, but retain
99            our existing event + type information.
100         */
101
102         midi_sense_connection[0].disconnect ();
103         midi_sense_connection[1].disconnect ();
104         midi_learn_connection.disconnect ();
105 }
106
107 void
108 MIDIControllable::drop_external_control ()
109 {
110         midi_forget ();
111         control_type = none;
112         control_additional = (MIDI::byte) -1;
113 }
114
115 void
116 MIDIControllable::set_controllable (Controllable* c)
117 {
118         if (c == controllable) {
119                 return;
120         }
121         
122         controllable_death_connection.disconnect ();
123
124         controllable = c;
125
126         if (controllable) {
127                 last_controllable_value = controllable->get_value();
128         } else {
129                 last_controllable_value = 0.0f; // is there a better value?
130         }
131
132         if (controllable) {
133                 controllable->Destroyed.connect (controllable_death_connection, MISSING_INVALIDATOR,
134                                                  boost::bind (&MIDIControllable::drop_controllable, this), 
135                                                  MidiControlUI::instance());
136         }
137 }
138
139 void
140 MIDIControllable::midi_rebind (channel_t c)
141 {
142         if (c >= 0) {
143                 bind_midi (c, control_type, control_additional);
144         } else {
145                 midi_forget ();
146         }
147 }
148
149 void
150 MIDIControllable::learn_about_external_control ()
151 {
152         drop_external_control ();
153         _port.parser()->any.connect_same_thread (midi_learn_connection, boost::bind (&MIDIControllable::midi_receiver, this, _1, _2, _3));
154 }
155
156 void
157 MIDIControllable::stop_learning ()
158 {
159         midi_learn_connection.disconnect ();
160 }
161
162 int
163 MIDIControllable::control_to_midi (float val)
164 {
165         if (controllable->is_gain_like()) {
166                 return gain_to_slider_position (val) * max_value_for_type ();
167         }
168
169         float control_min = controllable->lower ();
170         float control_max = controllable->upper ();
171         const float control_range = control_max - control_min;
172
173         if (controllable->is_toggle()) {
174                 if (val >= (control_min + (control_range/2.0f))) {
175                         return max_value_for_type();
176                 } else {
177                         return 0;
178                 }
179         }
180
181         return (val - control_min) / control_range * max_value_for_type ();
182 }
183
184 float
185 MIDIControllable::midi_to_control (int val)
186 {
187         /* fiddle with MIDI value so that we get an odd number of integer steps
188            and can thus represent "middle" precisely as 0.5. this maps to
189            the range 0..+1.0
190         */
191
192         float fv = (val == 0 ? 0 : float (val - 1) / (max_value_for_type() - 1));
193
194         if (controllable->is_gain_like()) {
195                 return slider_position_to_gain (fv);
196         }
197
198         float control_min = controllable->lower ();
199         float control_max = controllable->upper ();
200         const float control_range = control_max - control_min;
201
202         return (fv * control_range) + control_min;
203 }
204
205 void
206 MIDIControllable::midi_sense_note_on (Parser &p, EventTwoBytes *tb)
207 {
208         midi_sense_note (p, tb, true);
209 }
210
211 void
212 MIDIControllable::midi_sense_note_off (Parser &p, EventTwoBytes *tb)
213 {
214         midi_sense_note (p, tb, false);
215 }
216
217 int
218 MIDIControllable::lookup_controllable()
219 {
220         if (!_descriptor) {
221                 return -1;
222         }
223
224         boost::shared_ptr<Controllable> c = _surface->lookup_controllable (*_descriptor);
225
226         if (!c) {
227                 return -1;
228         }
229
230         set_controllable (c.get ());
231
232         return 0;
233 }
234
235 void
236 MIDIControllable::drop_controllable ()
237 {
238         set_controllable (0);
239 }
240
241 void
242 MIDIControllable::midi_sense_note (Parser &, EventTwoBytes *msg, bool /*is_on*/)
243 {
244         if (!controllable) { 
245                 if (lookup_controllable()) {
246                         return;
247                 }
248         }
249
250         if (!controllable->is_toggle()) {
251                 if (control_additional == msg->note_number) {
252                         controllable->set_value (midi_to_control (msg->velocity));
253                 }
254         } else {
255                 if (control_additional == msg->note_number) {
256                         controllable->set_value (controllable->get_value() > 0.5f ? 0.0f : 1.0f);
257                 }
258         }
259
260         last_value = (MIDI::byte) (controllable->get_value() * 127.0); // to prevent feedback fights
261 }
262
263 void
264 MIDIControllable::midi_sense_controller (Parser &, EventTwoBytes *msg)
265 {
266         if (!controllable) { 
267                 if (lookup_controllable ()) {
268                         return;
269                 }
270         }
271
272         assert (controllable);
273
274         if (controllable->touching()) {
275                 return; // to prevent feedback fights when e.g. dragging a UI slider
276         }
277
278         if (control_additional == msg->controller_number) {
279
280                 if (!controllable->is_toggle()) {
281
282                         float new_value = msg->value;
283                         float max_value = max(last_controllable_value, new_value);
284                         float min_value = min(last_controllable_value, new_value);
285                         float range = max_value - min_value;
286                         float threshold = (float) _surface->threshold ();
287
288                         bool const in_sync = (
289                                 range < threshold &&
290                                 controllable->get_value() <= midi_to_control(max_value) &&
291                                 controllable->get_value() >= midi_to_control(min_value)
292                                 );
293
294                         /* If the surface is not motorised, we try to prevent jumps when
295                            the MIDI controller and controllable are out of sync.
296                            There might be a better way of doing this.
297                         */
298
299                         if (in_sync || _surface->motorised ()) {
300                                 controllable->set_value (midi_to_control (new_value));
301                         }
302
303                         last_controllable_value = new_value;
304                 } else {
305                         if (msg->value > 64.0f) {
306                                 controllable->set_value (1);
307                         } else {
308                                 controllable->set_value (0);
309                         }
310                 }
311
312                 last_value = (MIDI::byte) (control_to_midi(controllable->get_value())); // to prevent feedback fights
313         }
314 }
315
316 void
317 MIDIControllable::midi_sense_program_change (Parser &, MIDI::byte msg)
318 {
319         if (!controllable) { 
320                 if (lookup_controllable ()) {
321                         return;
322                 }
323         }
324
325         if (!controllable->is_toggle()) {
326                 controllable->set_value (midi_to_control (msg));
327         } else if (msg == control_additional) {
328                 controllable->set_value (controllable->get_value() > 0.5f ? 0.0f : 1.0f);
329         }
330
331         last_value = (MIDI::byte) (controllable->get_value() * 127.0); // to prevent feedback fights
332 }
333
334 void
335 MIDIControllable::midi_sense_pitchbend (Parser &, pitchbend_t pb)
336 {
337         if (!controllable) { 
338                 if (lookup_controllable ()) {
339                         return;
340                 }
341         }
342
343         if (!controllable->is_toggle()) {
344                 controllable->set_value (midi_to_control (pb));
345         } else {
346                 controllable->set_value (controllable->get_value() > 0.5f ? 0.0f : 1.0f);
347         }
348
349         last_value = control_to_midi (controllable->get_value ());
350 }
351
352 void
353 MIDIControllable::midi_receiver (Parser &, MIDI::byte *msg, size_t /*len*/)
354 {
355         /* we only respond to channel messages */
356
357         if ((msg[0] & 0xF0) < 0x80 || (msg[0] & 0xF0) > 0xE0) {
358                 return;
359         }
360
361         /* if the our port doesn't do input anymore, forget it ... */
362
363         if (!_port.parser()) {
364                 return;
365         }
366
367         bind_midi ((channel_t) (msg[0] & 0xf), eventType (msg[0] & 0xF0), msg[1]);
368
369         if (controllable) {
370                 controllable->LearningFinished ();
371         }
372 }
373
374 void
375 MIDIControllable::bind_midi (channel_t chn, eventType ev, MIDI::byte additional)
376 {
377         char buf[64];
378
379         drop_external_control ();
380
381         control_type = ev;
382         control_channel = chn;
383         control_additional = additional;
384
385         if (_port.parser() == 0) {
386                 return;
387         }
388
389         Parser& p = *_port.parser();
390
391         int chn_i = chn;
392         switch (ev) {
393         case MIDI::off:
394                 p.channel_note_off[chn_i].connect_same_thread (midi_sense_connection[0], boost::bind (&MIDIControllable::midi_sense_note_off, this, _1, _2));
395
396                 /* if this is a togglee, connect to noteOn as well,
397                    and we'll toggle back and forth between the two.
398                 */
399
400                 if (_momentary) {
401                         p.channel_note_on[chn_i].connect_same_thread (midi_sense_connection[1], boost::bind (&MIDIControllable::midi_sense_note_on, this, _1, _2));
402                 } 
403
404                 _control_description = "MIDI control: NoteOff";
405                 break;
406
407         case MIDI::on:
408                 p.channel_note_on[chn_i].connect_same_thread (midi_sense_connection[0], boost::bind (&MIDIControllable::midi_sense_note_on, this, _1, _2));
409                 if (_momentary) {
410                         p.channel_note_off[chn_i].connect_same_thread (midi_sense_connection[1], boost::bind (&MIDIControllable::midi_sense_note_off, this, _1, _2));
411                 }
412                 _control_description = "MIDI control: NoteOn";
413                 break;
414                 
415         case MIDI::controller:
416                 p.channel_controller[chn_i].connect_same_thread (midi_sense_connection[0], boost::bind (&MIDIControllable::midi_sense_controller, this, _1, _2));
417                 snprintf (buf, sizeof (buf), "MIDI control: Controller %d", control_additional);
418                 _control_description = buf;
419                 break;
420
421         case MIDI::program:
422                 p.channel_program_change[chn_i].connect_same_thread (midi_sense_connection[0], boost::bind (&MIDIControllable::midi_sense_program_change, this, _1, _2));
423                 _control_description = "MIDI control: ProgramChange";
424                 break;
425
426         case MIDI::pitchbend:
427                 p.channel_pitchbend[chn_i].connect_same_thread (midi_sense_connection[0], boost::bind (&MIDIControllable::midi_sense_pitchbend, this, _1, _2));
428                 _control_description = "MIDI control: Pitchbend";
429                 break;
430
431         default:
432                 break;
433         }
434 }
435
436 MIDI::byte*
437 MIDIControllable::write_feedback (MIDI::byte* buf, int32_t& bufsize, bool /*force*/)
438 {
439         if (!controllable || control_type == none || !feedback || bufsize <= 2) {
440                 return buf;
441         }
442         
443         int const gm = control_to_midi (controllable->get_value());
444
445         if (gm == last_value) {
446                 return buf;
447         }
448
449         *buf++ = (0xF0 & control_type) | (0xF & control_channel);
450         
451         switch (control_type) {
452         case MIDI::pitchbend:
453                 *buf++ = int (gm) & 127;
454                 *buf++ = (int (gm) >> 7) & 127;
455                 break;
456         default:
457                 *buf++ = control_additional; /* controller number */
458                 *buf++ = gm;
459                 break;
460         }
461
462         last_value = gm;
463         bufsize -= 3;
464
465         return buf;
466 }
467
468 int
469 MIDIControllable::set_state (const XMLNode& node, int /*version*/)
470 {
471         const XMLProperty* prop;
472         int xx;
473
474         if ((prop = node.property ("event")) != 0) {
475                 sscanf (prop->value().c_str(), "0x%x", &xx);
476                 control_type = (MIDI::eventType) xx;
477         } else {
478                 return -1;
479         }
480
481         if ((prop = node.property ("channel")) != 0) {
482                 sscanf (prop->value().c_str(), "%d", &xx);
483                 control_channel = (MIDI::channel_t) xx;
484         } else {
485                 return -1;
486         }
487
488         if ((prop = node.property ("additional")) != 0) {
489                 sscanf (prop->value().c_str(), "0x%x", &xx);
490                 control_additional = (MIDI::byte) xx;
491         } else {
492                 return -1;
493         }
494
495         if ((prop = node.property ("feedback")) != 0) {
496                 feedback = (prop->value() == "yes");
497         } else {
498                 feedback = true; // default
499         }
500
501         bind_midi (control_channel, control_type, control_additional);
502
503         return 0;
504 }
505
506 XMLNode&
507 MIDIControllable::get_state ()
508 {
509         char buf[32];
510
511         XMLNode* node = new XMLNode ("MIDIControllable");
512
513         if (_current_uri.empty()) {
514                 node->add_property ("id", controllable->id().to_s());
515         } else {
516                 node->add_property ("uri", _current_uri);
517         }
518
519         if (controllable) {
520                 snprintf (buf, sizeof(buf), "0x%x", (int) control_type);
521                 node->add_property ("event", buf);
522                 snprintf (buf, sizeof(buf), "%d", (int) control_channel);
523                 node->add_property ("channel", buf);
524                 snprintf (buf, sizeof(buf), "0x%x", (int) control_additional);
525                 node->add_property ("additional", buf);
526                 node->add_property ("feedback", (feedback ? "yes" : "no"));
527         }
528
529         return *node;
530 }
531
532 /** @return the maximum value for a control value transmitted
533  *  using a given MIDI::eventType.
534  */
535 int
536 MIDIControllable::max_value_for_type () const
537 {
538         /* XXX: this is not complete */
539         
540         if (control_type == MIDI::pitchbend) {
541                 return 16383;
542         }
543
544         return 127;
545 }