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