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