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