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