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