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