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