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