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