702d361965d6f0d385d1857daf1b63cf2e7edf57
[ardour.git] / libs / surfaces / generic_midi / generic_midi_control_protocol.cc
1 /*
2     Copyright (C) 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
22 #include <sstream>
23 #include <algorithm>
24
25 #include <glibmm/fileutils.h>
26 #include <glibmm/miscutils.h>
27
28 #include "pbd/controllable_descriptor.h"
29 #include "pbd/error.h"
30 #include "pbd/failed_constructor.h"
31 #include "pbd/file_utils.h"
32 #include "pbd/xml++.h"
33
34 #include "midi++/port.h"
35
36 #include "ardour/audioengine.h"
37 #include "ardour/filesystem_paths.h"
38 #include "ardour/session.h"
39 #include "ardour/route.h"
40 #include "ardour/midi_ui.h"
41 #include "ardour/rc_configuration.h"
42 #include "ardour/midiport_manager.h"
43
44 #include "generic_midi_control_protocol.h"
45 #include "midicontrollable.h"
46 #include "midifunction.h"
47 #include "midiaction.h"
48
49 using namespace ARDOUR;
50 using namespace PBD;
51 using namespace std;
52
53 #include "i18n.h"
54
55 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
56
57 GenericMidiControlProtocol::GenericMidiControlProtocol (Session& s)
58         : ControlProtocol (s, _("Generic MIDI"))
59         , _motorised (false)
60         , _threshold (10)
61         , gui (0)
62 {
63         _input_port = s.midi_input_port ();
64         _output_port = s.midi_output_port ();
65
66         do_feedback = false;
67         _feedback_interval = 10000; // microseconds
68         last_feedback_time = 0;
69
70         _current_bank = 0;
71         _bank_size = 0;
72
73         /* these signals are emitted by the MidiControlUI's event loop thread
74          * and we may as well handle them right there in the same the same
75          * thread
76          */
77
78         Controllable::StartLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::start_learning, this, _1));
79         Controllable::StopLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::stop_learning, this, _1));
80         Controllable::CreateBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::create_binding, this, _1, _2, _3));
81         Controllable::DeleteBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::delete_binding, this, _1));
82
83         /* this signal is emitted by the process() callback, and if
84          * send_feedback() is going to do anything, it should do it in the
85          * context of the process() callback itself.
86          */
87
88         Session::SendFeedback.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::send_feedback, this));
89         //Session::SendFeedback.connect (*this, MISSING_INVALIDATOR, boost::bind (&GenericMidiControlProtocol::send_feedback, this), midi_ui_context());;
90
91         /* this one is cross-thread */
92
93         Route::RemoteControlIDChange.connect (*this, MISSING_INVALIDATOR, boost::bind (&GenericMidiControlProtocol::reset_controllables, this), midi_ui_context());
94
95         reload_maps ();
96 }
97
98 GenericMidiControlProtocol::~GenericMidiControlProtocol ()
99 {
100         drop_all ();
101         tear_down_gui ();
102 }
103
104 static const char * const midimap_env_variable_name = "ARDOUR_MIDIMAPS_PATH";
105 static const char* const midi_map_dir_name = "midi_maps";
106 static const char* const midi_map_suffix = ".map";
107
108 Searchpath
109 system_midi_map_search_path ()
110 {
111         bool midimap_path_defined = false;
112         std::string spath_env (Glib::getenv (midimap_env_variable_name, midimap_path_defined));
113
114         if (midimap_path_defined) {
115                 return spath_env;
116         }
117
118         Searchpath spath (ardour_data_search_path());
119         spath.add_subdirectory_to_paths(midi_map_dir_name);
120         return spath;
121 }
122
123 static std::string
124 user_midi_map_directory ()
125 {
126         return Glib::build_filename (user_config_directory(), midi_map_dir_name);
127 }
128
129 static bool
130 midi_map_filter (const string &str, void* /*arg*/)
131 {
132         return (str.length() > strlen(midi_map_suffix) &&
133                 str.find (midi_map_suffix) == (str.length() - strlen (midi_map_suffix)));
134 }
135
136 void
137 GenericMidiControlProtocol::reload_maps ()
138 {
139         vector<string> midi_maps;
140         Searchpath spath (system_midi_map_search_path());
141         spath += user_midi_map_directory ();
142
143         find_files_matching_filter (midi_maps, spath, midi_map_filter, 0, false, true);
144
145         if (midi_maps.empty()) {
146                 cerr << "No MIDI maps found using " << spath.to_string() << endl;
147                 return;
148         }
149
150         for (vector<string>::iterator i = midi_maps.begin(); i != midi_maps.end(); ++i) {
151                 string fullpath = *i;
152
153                 XMLTree tree;
154
155                 if (!tree.read (fullpath.c_str())) {
156                         continue;
157                 }
158
159                 MapInfo mi;
160
161                 XMLProperty* prop = tree.root()->property ("name");
162
163                 if (!prop) {
164                         continue;
165                 }
166
167                 mi.name = prop->value ();
168                 mi.path = fullpath;
169                 
170                 map_info.push_back (mi);
171         }
172 }
173         
174 void
175 GenericMidiControlProtocol::drop_all ()
176 {
177         Glib::Threads::Mutex::Lock lm (pending_lock);
178         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
179
180         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
181                 delete *i;
182         }
183         controllables.clear ();
184
185         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
186                 delete *i;
187         }
188         pending_controllables.clear ();
189
190         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
191                 delete *i;
192         }
193         functions.clear ();
194
195         for (MIDIActions::iterator i = actions.begin(); i != actions.end(); ++i) {
196                 delete *i;
197         }
198         actions.clear ();
199 }
200
201 void
202 GenericMidiControlProtocol::drop_bindings ()
203 {
204         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
205
206         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
207                 if (!(*i)->learned()) {
208                         delete *i;
209                         i = controllables.erase (i);
210                 } else {
211                         ++i;
212                 }
213         }
214
215         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
216                 delete *i;
217         }
218         functions.clear ();
219
220         _current_binding = "";
221         _bank_size = 0;
222         _current_bank = 0;
223 }
224
225 int
226 GenericMidiControlProtocol::set_active (bool /*yn*/)
227 {
228         /* start/stop delivery/outbound thread */
229         return 0;
230 }
231
232 void
233 GenericMidiControlProtocol::set_feedback_interval (microseconds_t ms)
234 {
235         _feedback_interval = ms;
236 }
237
238 void 
239 GenericMidiControlProtocol::send_feedback ()
240 {
241         /* This is executed in RT "process" context", so no blocking calls
242          */
243
244         if (!do_feedback) {
245                 return;
246         }
247
248         microseconds_t now = get_microseconds ();
249
250         if (last_feedback_time != 0) {
251                 if ((now - last_feedback_time) < _feedback_interval) {
252                         return;
253                 }
254         }
255
256         _send_feedback ();
257         
258         last_feedback_time = now;
259 }
260
261 void 
262 GenericMidiControlProtocol::_send_feedback ()
263 {
264         /* This is executed in RT "process" context", so no blocking calls
265          */
266
267         const int32_t bufsize = 16 * 1024; /* XXX too big */
268         MIDI::byte buf[bufsize];
269         int32_t bsize = bufsize;
270
271         /* XXX: due to bugs in some ALSA / JACK MIDI bridges, we have to do separate
272            writes for each controllable here; if we send more than one MIDI message
273            in a single jack_midi_event_write then some bridges will only pass the
274            first on to ALSA.
275         */
276
277         Glib::Threads::Mutex::Lock lm (controllables_lock, Glib::Threads::TRY_LOCK);
278         if (!lm.locked ()) {
279                 return;
280         }
281         
282         for (MIDIControllables::iterator r = controllables.begin(); r != controllables.end(); ++r) {
283                 MIDI::byte* end = (*r)->write_feedback (buf, bsize);
284                 if (end != buf) {
285                         _output_port->write (buf, (int32_t) (end - buf), 0);
286                 }
287         }
288 }
289
290 bool
291 GenericMidiControlProtocol::start_learning (Controllable* c)
292 {
293         if (c == 0) {
294                 return false;
295         }
296
297         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
298
299         MIDIControllables::iterator tmp;
300         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
301                 tmp = i;
302                 ++tmp;
303                 if ((*i)->get_controllable() == c) {
304                         delete (*i);
305                         controllables.erase (i);
306                 }
307                 i = tmp;
308         }
309
310         {
311                 Glib::Threads::Mutex::Lock lm (pending_lock);
312                 
313                 MIDIPendingControllables::iterator ptmp;
314                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
315                         ptmp = i;
316                         ++ptmp;
317                         if (((*i)->first)->get_controllable() == c) {
318                                 (*i)->second.disconnect();
319                                 delete (*i)->first;
320                                 delete *i;
321                                 pending_controllables.erase (i);
322                         }
323                         i = ptmp;
324                 }
325         }
326
327         MIDIControllable* mc = 0;
328
329         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
330                 if ((*i)->get_controllable() && ((*i)->get_controllable()->id() == c->id())) {
331                         mc = *i;
332                         break;
333                 }
334         }
335
336         if (!mc) {
337                 mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
338         }
339         
340         {
341                 Glib::Threads::Mutex::Lock lm (pending_lock);
342
343                 MIDIPendingControllable* element = new MIDIPendingControllable;
344                 element->first = mc;
345                 c->LearningFinished.connect_same_thread (element->second, boost::bind (&GenericMidiControlProtocol::learning_stopped, this, mc));
346
347                 pending_controllables.push_back (element);
348         }
349
350         mc->learn_about_external_control ();
351         return true;
352 }
353
354 void
355 GenericMidiControlProtocol::learning_stopped (MIDIControllable* mc)
356 {
357         Glib::Threads::Mutex::Lock lm (pending_lock);
358         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
359         
360         MIDIPendingControllables::iterator tmp;
361
362         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
363                 tmp = i;
364                 ++tmp;
365
366                 if ( (*i)->first == mc) {
367                         (*i)->second.disconnect();
368                         delete *i;
369                         pending_controllables.erase(i);
370                 }
371
372                 i = tmp;
373         }
374
375         controllables.push_back (mc);
376 }
377
378 void
379 GenericMidiControlProtocol::stop_learning (Controllable* c)
380 {
381         Glib::Threads::Mutex::Lock lm (pending_lock);
382         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
383         MIDIControllable* dptr = 0;
384
385         /* learning timed out, and we've been told to consider this attempt to learn to be cancelled. find the
386            relevant MIDIControllable and remove it from the pending list.
387         */
388
389         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
390                 if (((*i)->first)->get_controllable() == c) {
391                         (*i)->first->stop_learning ();
392                         dptr = (*i)->first;
393                         (*i)->second.disconnect();
394
395                         delete *i;
396                         pending_controllables.erase (i);
397                         break;
398                 }
399         }
400         
401         delete dptr;
402 }
403
404 void
405 GenericMidiControlProtocol::delete_binding (PBD::Controllable* control)
406 {
407         if (control != 0) {
408                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
409                 
410                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
411                         MIDIControllable* existingBinding = (*iter);
412                         
413                         if (control == (existingBinding->get_controllable())) {
414                                 delete existingBinding;
415                                 iter = controllables.erase (iter);
416                         } else {
417                                 ++iter;
418                         }
419                         
420                 }
421         }
422 }
423
424 void
425 GenericMidiControlProtocol::create_binding (PBD::Controllable* control, int pos, int control_number)
426 {
427         if (control != NULL) {
428                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
429                 
430                 MIDI::channel_t channel = (pos & 0xf);
431                 MIDI::byte value = control_number;
432                 
433                 // Create a MIDIControllable
434                 MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *control, false);
435
436                 // Remove any old binding for this midi channel/type/value pair
437                 // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
438                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
439                         MIDIControllable* existingBinding = (*iter);
440                         
441                         if ((existingBinding->get_control_channel() & 0xf ) == channel &&
442                             existingBinding->get_control_additional() == value &&
443                             (existingBinding->get_control_type() & 0xf0 ) == MIDI::controller) {
444                                 
445                                 delete existingBinding;
446                                 iter = controllables.erase (iter);
447                         } else {
448                                 ++iter;
449                         }
450                         
451                 }
452                 
453                 // Update the MIDI Controllable based on the the pos param
454                 // Here is where a table lookup for user mappings could go; for now we'll just wing it...
455                 mc->bind_midi(channel, MIDI::controller, value);
456
457                 controllables.push_back (mc);
458         }
459 }
460
461 XMLNode&
462 GenericMidiControlProtocol::get_state () 
463 {
464         XMLNode& node (ControlProtocol::get_state());
465         char buf[32];
466
467         node.add_property (X_("feedback"), do_feedback ? "1" : "0");
468         snprintf (buf, sizeof (buf), "%" PRIu64, _feedback_interval);
469         node.add_property (X_("feedback_interval"), buf);
470         snprintf (buf, sizeof (buf), "%d", _threshold);
471         node.add_property (X_("threshold"), buf);
472
473         if (!_current_binding.empty()) {
474                 node.add_property ("binding", _current_binding);
475         }
476
477         XMLNode* children = new XMLNode (X_("Controls"));
478
479         node.add_child_nocopy (*children);
480
481         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
482         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
483
484                 /* we don't care about bindings that come from a bindings map, because
485                    they will all be reset/recreated when we load the relevant bindings
486                    file.
487                 */
488
489                 if ((*i)->get_controllable() && (*i)->learned()) {
490                         children->add_child_nocopy ((*i)->get_state());
491                 }
492         }
493
494         return node;
495 }
496
497 int
498 GenericMidiControlProtocol::set_state (const XMLNode& node, int version)
499 {
500         XMLNodeList nlist;
501         XMLNodeConstIterator niter;
502         const XMLProperty* prop;
503
504         if ((prop = node.property ("feedback")) != 0) {
505                 do_feedback = (bool) atoi (prop->value().c_str());
506         } else {
507                 do_feedback = false;
508         }
509
510         if ((prop = node.property ("feedback_interval")) != 0) {
511                 if (sscanf (prop->value().c_str(), "%" PRIu64, &_feedback_interval) != 1) {
512                         _feedback_interval = 10000;
513                 }
514         } else {
515                 _feedback_interval = 10000;
516         }
517
518         if ((prop = node.property ("threshold")) != 0) {
519                 if (sscanf (prop->value().c_str(), "%d", &_threshold) != 1) {
520                         _threshold = 10;
521                 }
522         } else {
523                 _threshold = 10;
524         }
525
526         boost::shared_ptr<Controllable> c;
527         
528         {
529                 Glib::Threads::Mutex::Lock lm (pending_lock);
530                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
531                         delete *i;
532                 }
533                 pending_controllables.clear ();
534         }
535
536         /* Load up specific bindings from the
537          * <Controls><MidiControllable>...</MidiControllable><Controls> section
538          */
539
540         {
541                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
542                 controllables.clear ();
543                 nlist = node.children(); // "Controls"
544
545                 if (!nlist.empty()) {
546                         nlist = nlist.front()->children(); // "MIDIControllable" ...
547
548                         if (!nlist.empty()) {
549                                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
550                                         
551                                         if ((prop = (*niter)->property ("id")) != 0) {
552                                                 
553                                                 ID id = prop->value ();
554                                                 Controllable* c = Controllable::by_id (id);
555                                                 
556                                                 if (c) {
557                                                         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
558                                                         
559                                                         if (mc->set_state (**niter, version) == 0) {
560                                                                 controllables.push_back (mc);
561                                                         }
562                                                         
563                                                 } else {
564                                                         warning << string_compose (
565                                                                 _("Generic MIDI control: controllable %1 not found in session (ignored)"),
566                                                                 id) << endmsg;
567                                                 }
568                                         }
569                                 }
570                         }
571                 }
572         }
573
574         if ((prop = node.property ("binding")) != 0) {
575                 for (list<MapInfo>::iterator x = map_info.begin(); x != map_info.end(); ++x) {
576                         if (prop->value() == (*x).name) {
577                                 load_bindings ((*x).path);
578                                 break;
579                         }
580                 }
581         }
582
583         return 0;
584 }
585
586 int
587 GenericMidiControlProtocol::set_feedback (bool yn)
588 {
589         do_feedback = yn;
590         last_feedback_time = 0;
591         return 0;
592 }
593
594 bool
595 GenericMidiControlProtocol::get_feedback () const
596 {
597         return do_feedback;
598 }
599
600 int
601 GenericMidiControlProtocol::load_bindings (const string& xmlpath)
602 {
603         XMLTree state_tree;
604
605         if (!state_tree.read (xmlpath.c_str())) {
606                 error << string_compose(_("Could not understand MIDI bindings file %1"), xmlpath) << endmsg;
607                 return -1;
608         }
609
610         XMLNode* root = state_tree.root();
611
612         if (root->name() != X_("ArdourMIDIBindings")) {
613                 error << string_compose (_("MIDI Bindings file %1 is not really a MIDI bindings file"), xmlpath) << endmsg;
614                 return -1;
615         }
616
617         const XMLProperty* prop;
618
619         if ((prop = root->property ("version")) == 0) {
620                 return -1;
621         } else {
622                 int major;
623                 int minor;
624                 int micro;
625
626                 sscanf (prop->value().c_str(), "%d.%d.%d", &major, &minor, &micro);
627                 Stateful::loading_state_version = (major * 1000) + minor;
628         }
629         
630         const XMLNodeList& children (root->children());
631         XMLNodeConstIterator citer;
632         XMLNodeConstIterator gciter;
633
634         MIDIControllable* mc;
635
636         drop_all ();
637
638         for (citer = children.begin(); citer != children.end(); ++citer) {
639                 
640                 if ((*citer)->name() == "DeviceInfo") {
641                         const XMLProperty* prop;
642
643                         if ((prop = (*citer)->property ("bank-size")) != 0) {
644                                 _bank_size = atoi (prop->value());
645                                 _current_bank = 0;
646                         }
647
648                         if ((prop = (*citer)->property ("motorised")) != 0 || ((prop = (*citer)->property ("motorized")) != 0)) {
649                                 _motorised = string_is_affirmative (prop->value ());
650                         } else {
651                                 _motorised = false;
652                         }
653
654                         if ((prop = (*citer)->property ("threshold")) != 0) {
655                                 _threshold = atoi (prop->value ());
656                         } else {
657                                 _threshold = 10;
658                         }
659
660                 }
661
662                 if ((*citer)->name() == "Binding") {
663                         const XMLNode* child = *citer;
664
665                         if (child->property ("uri")) {
666                                 /* controllable */
667                                 
668                                 if ((mc = create_binding (*child)) != 0) {
669                                         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
670                                         controllables.push_back (mc);
671                                 }
672
673                         } else if (child->property ("function")) {
674
675                                 /* function */
676                                 MIDIFunction* mf;
677
678                                 if ((mf = create_function (*child)) != 0) {
679                                         functions.push_back (mf);
680                                 }
681
682                         } else if (child->property ("action")) {
683                                 MIDIAction* ma;
684
685                                 if ((ma = create_action (*child)) != 0) {
686                                         actions.push_back (ma);
687                                 }
688                         }
689                 }
690         }
691         
692         if ((prop = root->property ("name")) != 0) {
693                 _current_binding = prop->value ();
694         }
695
696         reset_controllables ();
697
698         return 0;
699 }
700
701 MIDIControllable*
702 GenericMidiControlProtocol::create_binding (const XMLNode& node)
703 {
704         const XMLProperty* prop;
705         MIDI::byte detail;
706         MIDI::channel_t channel;
707         string uri;
708         MIDI::eventType ev;
709         int intval;
710         bool momentary;
711
712         if ((prop = node.property (X_("ctl"))) != 0) {
713                 ev = MIDI::controller;
714         } else if ((prop = node.property (X_("note"))) != 0) {
715                 ev = MIDI::on;
716         } else if ((prop = node.property (X_("pgm"))) != 0) {
717                 ev = MIDI::program;
718         } else if ((prop = node.property (X_("pb"))) != 0) {
719                 ev = MIDI::pitchbend;
720         } else {
721                 return 0;
722         }
723         
724         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
725                 return 0;
726         }
727         
728         detail = (MIDI::byte) intval;
729
730         if ((prop = node.property (X_("channel"))) == 0) {
731                 return 0;
732         }
733         
734         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
735                 return 0;
736         }
737         channel = (MIDI::channel_t) intval;
738         /* adjust channel to zero-based counting */
739         if (channel > 0) {
740                 channel -= 1;
741         }
742
743         if ((prop = node.property (X_("momentary"))) != 0) {
744                 momentary = string_is_affirmative (prop->value());
745         } else {
746                 momentary = false;
747         }
748         
749         prop = node.property (X_("uri"));
750         uri = prop->value();
751
752         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), momentary);
753
754         if (mc->init (uri)) {
755                 delete mc;
756                 return 0;
757         }
758
759         mc->bind_midi (channel, ev, detail);
760
761         return mc;
762 }
763
764 void
765 GenericMidiControlProtocol::reset_controllables ()
766 {
767         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
768
769         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ) {
770                 MIDIControllable* existingBinding = (*iter);
771                 MIDIControllables::iterator next = iter;
772                 ++next;
773
774                 if (!existingBinding->learned()) {
775                         ControllableDescriptor& desc (existingBinding->descriptor());
776
777                         if (desc.banked()) {
778                                 desc.set_bank_offset (_current_bank * _bank_size);
779                         }
780
781                         /* its entirely possible that the session doesn't have
782                          * the specified controllable (e.g. it has too few
783                          * tracks). if we find this to be the case, we just leave
784                          * the binding around, unbound, and it will do "late
785                          * binding" (or "lazy binding") if/when any data arrives.
786                          */
787
788                         existingBinding->lookup_controllable ();
789                 }
790
791                 iter = next;
792         }
793 }
794
795 boost::shared_ptr<Controllable>
796 GenericMidiControlProtocol::lookup_controllable (const ControllableDescriptor& desc) const
797 {
798         return session->controllable_by_descriptor (desc);
799 }
800
801 MIDIFunction*
802 GenericMidiControlProtocol::create_function (const XMLNode& node)
803 {
804         const XMLProperty* prop;
805         int intval;
806         MIDI::byte detail = 0;
807         MIDI::channel_t channel = 0;
808         string uri;
809         MIDI::eventType ev;
810         MIDI::byte* data = 0;
811         uint32_t data_size = 0;
812         string argument;
813
814         if ((prop = node.property (X_("ctl"))) != 0) {
815                 ev = MIDI::controller;
816         } else if ((prop = node.property (X_("note"))) != 0) {
817                 ev = MIDI::on;
818         } else if ((prop = node.property (X_("pgm"))) != 0) {
819                 ev = MIDI::program;
820         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
821
822                 if (prop->name() == X_("sysex")) {
823                         ev = MIDI::sysex;
824                 } else {
825                         ev = MIDI::any;
826                 }
827
828                 int val;
829                 uint32_t cnt;
830
831                 {
832                         cnt = 0;
833                         stringstream ss (prop->value());
834                         ss << hex;
835                         
836                         while (ss >> val) {
837                                 cnt++;
838                         }
839                 }
840
841                 if (cnt == 0) {
842                         return 0;
843                 }
844
845                 data = new MIDI::byte[cnt];
846                 data_size = cnt;
847                 
848                 {
849                         stringstream ss (prop->value());
850                         ss << hex;
851                         cnt = 0;
852                         
853                         while (ss >> val) {
854                                 data[cnt++] = (MIDI::byte) val;
855                         }
856                 }
857
858         } else {
859                 warning << "Binding ignored - unknown type" << endmsg;
860                 return 0;
861         }
862
863         if (data_size == 0) {
864                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
865                         return 0;
866                 }
867                 
868                 detail = (MIDI::byte) intval;
869
870                 if ((prop = node.property (X_("channel"))) == 0) {
871                         return 0;
872                 }
873         
874                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
875                         return 0;
876                 }
877                 channel = (MIDI::channel_t) intval;
878                 /* adjust channel to zero-based counting */
879                 if (channel > 0) {
880                         channel -= 1;
881                 }
882         }
883
884         if ((prop = node.property (X_("arg"))) != 0 || (prop = node.property (X_("argument"))) != 0 || (prop = node.property (X_("arguments"))) != 0) {
885                 argument = prop->value ();
886         }
887
888         prop = node.property (X_("function"));
889         
890         MIDIFunction* mf = new MIDIFunction (*_input_port->parser());
891         
892         if (mf->setup (*this, prop->value(), argument, data, data_size)) {
893                 delete mf;
894                 return 0;
895         }
896
897         mf->bind_midi (channel, ev, detail);
898
899         return mf;
900 }
901
902 MIDIAction*
903 GenericMidiControlProtocol::create_action (const XMLNode& node)
904 {
905         const XMLProperty* prop;
906         int intval;
907         MIDI::byte detail = 0;
908         MIDI::channel_t channel = 0;
909         string uri;
910         MIDI::eventType ev;
911         MIDI::byte* data = 0;
912         uint32_t data_size = 0;
913
914         if ((prop = node.property (X_("ctl"))) != 0) {
915                 ev = MIDI::controller;
916         } else if ((prop = node.property (X_("note"))) != 0) {
917                 ev = MIDI::on;
918         } else if ((prop = node.property (X_("pgm"))) != 0) {
919                 ev = MIDI::program;
920         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
921
922                 if (prop->name() == X_("sysex")) {
923                         ev = MIDI::sysex;
924                 } else {
925                         ev = MIDI::any;
926                 }
927
928                 int val;
929                 uint32_t cnt;
930
931                 {
932                         cnt = 0;
933                         stringstream ss (prop->value());
934                         ss << hex;
935                         
936                         while (ss >> val) {
937                                 cnt++;
938                         }
939                 }
940
941                 if (cnt == 0) {
942                         return 0;
943                 }
944
945                 data = new MIDI::byte[cnt];
946                 data_size = cnt;
947                 
948                 {
949                         stringstream ss (prop->value());
950                         ss << hex;
951                         cnt = 0;
952                         
953                         while (ss >> val) {
954                                 data[cnt++] = (MIDI::byte) val;
955                         }
956                 }
957
958         } else {
959                 warning << "Binding ignored - unknown type" << endmsg;
960                 return 0;
961         }
962
963         if (data_size == 0) {
964                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
965                         return 0;
966                 }
967                 
968                 detail = (MIDI::byte) intval;
969
970                 if ((prop = node.property (X_("channel"))) == 0) {
971                         return 0;
972                 }
973         
974                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
975                         return 0;
976                 }
977                 channel = (MIDI::channel_t) intval;
978                 /* adjust channel to zero-based counting */
979                 if (channel > 0) {
980                         channel -= 1;
981                 }
982         }
983
984         prop = node.property (X_("action"));
985         
986         MIDIAction* ma = new MIDIAction (*_input_port->parser());
987         
988         if (ma->init (*this, prop->value(), data, data_size)) {
989                 delete ma;
990                 return 0;
991         }
992
993         ma->bind_midi (channel, ev, detail);
994
995         return ma;
996 }
997
998 void
999 GenericMidiControlProtocol::set_current_bank (uint32_t b)
1000 {
1001         _current_bank = b;
1002         reset_controllables ();
1003 }
1004
1005 void
1006 GenericMidiControlProtocol::next_bank ()
1007 {
1008         _current_bank++;
1009         reset_controllables ();
1010 }
1011
1012 void
1013 GenericMidiControlProtocol::prev_bank()
1014 {
1015         if (_current_bank) {
1016                 _current_bank--;
1017                 reset_controllables ();
1018         }
1019 }
1020
1021 void
1022 GenericMidiControlProtocol::set_motorised (bool m)
1023 {
1024         _motorised = m;
1025 }
1026
1027 void
1028 GenericMidiControlProtocol::set_threshold (int t)
1029 {
1030         _threshold = t;
1031 }