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