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