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