Clean up after generic MIDI surface -- #7311
[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/error.h"
29 #include "pbd/failed_constructor.h"
30 #include "pbd/file_utils.h"
31 #include "pbd/xml++.h"
32 #include "pbd/compose.h"
33
34 #include "midi++/port.h"
35
36 #include "ardour/async_midi_port.h"
37 #include "ardour/audioengine.h"
38 #include "ardour/audioengine.h"
39 #include "ardour/controllable_descriptor.h"
40 #include "ardour/filesystem_paths.h"
41 #include "ardour/session.h"
42 #include "ardour/midi_ui.h"
43 #include "ardour/rc_configuration.h"
44 #include "ardour/midiport_manager.h"
45 #include "ardour/debug.h"
46
47 #include "generic_midi_control_protocol.h"
48 #include "midicontrollable.h"
49 #include "midifunction.h"
50 #include "midiaction.h"
51
52 using namespace ARDOUR;
53 using namespace PBD;
54 using namespace std;
55
56 #include "pbd/i18n.h"
57
58 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
59
60 GenericMidiControlProtocol::GenericMidiControlProtocol (Session& s)
61         : ControlProtocol (s, _("Generic MIDI"))
62         , connection_state (ConnectionState (0))
63         , _motorised (false)
64         , _threshold (10)
65         , gui (0)
66 {
67         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort> (s.midi_input_port ());
68         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort> (s.midi_output_port ());
69
70         _input_bundle.reset (new ARDOUR::Bundle (_("Generic MIDI Control In"), true));
71         _output_bundle.reset (new ARDOUR::Bundle (_("Generic MIDI Control Out"), false));
72
73         _input_bundle->add_channel (
74                 boost::static_pointer_cast<MidiPort>(_input_port)->name(),
75                 ARDOUR::DataType::MIDI,
76                 session->engine().make_port_name_non_relative (boost::static_pointer_cast<MidiPort>(_input_port)->name())
77                 );
78
79         _output_bundle->add_channel (
80                 boost::static_pointer_cast<MidiPort>(_output_port)->name(),
81                 ARDOUR::DataType::MIDI,
82                 session->engine().make_port_name_non_relative (boost::static_pointer_cast<MidiPort>(_output_port)->name())
83                 );
84
85         session->BundleAddedOrRemoved ();
86
87         do_feedback = false;
88         _feedback_interval = 10000; // microseconds
89         last_feedback_time = 0;
90
91         _current_bank = 0;
92         _bank_size = 0;
93
94         /* these signals are emitted by the MidiControlUI's event loop thread
95          * and we may as well handle them right there in the same the same
96          * thread
97          */
98
99         Controllable::StartLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::start_learning, this, _1));
100         Controllable::StopLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::stop_learning, this, _1));
101         Controllable::CreateBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::create_binding, this, _1, _2, _3));
102         Controllable::DeleteBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::delete_binding, this, _1));
103
104         /* this signal is emitted by the process() callback, and if
105          * send_feedback() is going to do anything, it should do it in the
106          * context of the process() callback itself.
107          */
108
109         Session::SendFeedback.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::send_feedback, this));
110         //Session::SendFeedback.connect (*this, MISSING_INVALIDATOR, boost::bind (&GenericMidiControlProtocol::send_feedback, this), midi_ui_context());;
111
112         /* this one is cross-thread */
113
114         PresentationInfo::Change.connect (*this, MISSING_INVALIDATOR, boost::bind (&GenericMidiControlProtocol::reset_controllables, this), midi_ui_context());
115
116         /* Catch port connections and disconnections (cross-thread) */
117         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR,
118                                                                               boost::bind (&GenericMidiControlProtocol::connection_handler, this, _1, _2, _3, _4, _5),
119                                                                               midi_ui_context());
120
121         reload_maps ();
122 }
123
124 GenericMidiControlProtocol::~GenericMidiControlProtocol ()
125 {
126         drop_all ();
127         tear_down_gui ();
128 }
129
130 list<boost::shared_ptr<ARDOUR::Bundle> >
131 GenericMidiControlProtocol::bundles ()
132 {
133         list<boost::shared_ptr<ARDOUR::Bundle> > b;
134
135         if (_input_bundle) {
136                 b.push_back (_input_bundle);
137                 b.push_back (_output_bundle);
138         }
139
140         return b;
141 }
142
143
144 static const char * const midimap_env_variable_name = "ARDOUR_MIDIMAPS_PATH";
145 static const char* const midi_map_dir_name = "midi_maps";
146 static const char* const midi_map_suffix = ".map";
147
148 Searchpath
149 system_midi_map_search_path ()
150 {
151         bool midimap_path_defined = false;
152         std::string spath_env (Glib::getenv (midimap_env_variable_name, midimap_path_defined));
153
154         if (midimap_path_defined) {
155                 return spath_env;
156         }
157
158         Searchpath spath (ardour_data_search_path());
159         spath.add_subdirectory_to_paths(midi_map_dir_name);
160         return spath;
161 }
162
163 static std::string
164 user_midi_map_directory ()
165 {
166         return Glib::build_filename (user_config_directory(), midi_map_dir_name);
167 }
168
169 static bool
170 midi_map_filter (const string &str, void* /*arg*/)
171 {
172         return (str.length() > strlen(midi_map_suffix) &&
173                 str.find (midi_map_suffix) == (str.length() - strlen (midi_map_suffix)));
174 }
175
176 void
177 GenericMidiControlProtocol::reload_maps ()
178 {
179         vector<string> midi_maps;
180         Searchpath spath (system_midi_map_search_path());
181         spath += user_midi_map_directory ();
182
183         find_files_matching_filter (midi_maps, spath, midi_map_filter, 0, false, true);
184
185         if (midi_maps.empty()) {
186                 cerr << "No MIDI maps found using " << spath.to_string() << endl;
187                 return;
188         }
189
190         for (vector<string>::iterator i = midi_maps.begin(); i != midi_maps.end(); ++i) {
191                 string fullpath = *i;
192
193                 XMLTree tree;
194
195                 if (!tree.read (fullpath.c_str())) {
196                         continue;
197                 }
198
199                 MapInfo mi;
200
201                 XMLProperty const * prop = tree.root()->property ("name");
202
203                 if (!prop) {
204                         continue;
205                 }
206
207                 mi.name = prop->value ();
208                 mi.path = fullpath;
209
210                 map_info.push_back (mi);
211         }
212 }
213
214 void
215 GenericMidiControlProtocol::drop_all ()
216 {
217         DEBUG_TRACE (DEBUG::GenericMidi, "Drop all bindings\n");
218         Glib::Threads::Mutex::Lock lm (pending_lock);
219         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
220
221         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
222                 delete *i;
223         }
224         controllables.clear ();
225
226         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
227                 (*i)->connection.disconnect();
228                 if ((*i)->own_mc) {
229                         delete (*i)->mc;
230                 }
231                 delete *i;
232         }
233         pending_controllables.clear ();
234
235         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
236                 delete *i;
237         }
238         functions.clear ();
239
240         for (MIDIActions::iterator i = actions.begin(); i != actions.end(); ++i) {
241                 delete *i;
242         }
243         actions.clear ();
244 }
245
246 void
247 GenericMidiControlProtocol::drop_bindings ()
248 {
249         DEBUG_TRACE (DEBUG::GenericMidi, "Drop bindings, leave learned\n");
250         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
251
252         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
253                 if (!(*i)->learned()) {
254                         delete *i;
255                         i = controllables.erase (i);
256                 } else {
257                         ++i;
258                 }
259         }
260
261         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
262                 delete *i;
263         }
264         functions.clear ();
265
266         _current_binding = "";
267         _bank_size = 0;
268         _current_bank = 0;
269 }
270
271 int
272 GenericMidiControlProtocol::set_active (bool /*yn*/)
273 {
274         /* nothing to do here: the MIDI UI thread in libardour handles all our
275            I/O needs.
276         */
277         return 0;
278 }
279
280 void
281 GenericMidiControlProtocol::set_feedback_interval (microseconds_t ms)
282 {
283         _feedback_interval = ms;
284 }
285
286 void
287 GenericMidiControlProtocol::send_feedback ()
288 {
289         /* This is executed in RT "process" context", so no blocking calls
290          */
291
292         if (!do_feedback) {
293                 return;
294         }
295
296         microseconds_t now = get_microseconds ();
297
298         if (last_feedback_time != 0) {
299                 if ((now - last_feedback_time) < _feedback_interval) {
300                         return;
301                 }
302         }
303
304         _send_feedback ();
305
306         last_feedback_time = now;
307 }
308
309 void
310 GenericMidiControlProtocol::_send_feedback ()
311 {
312         /* This is executed in RT "process" context", so no blocking calls
313          */
314
315         const int32_t bufsize = 16 * 1024; /* XXX too big */
316         MIDI::byte buf[bufsize];
317         int32_t bsize = bufsize;
318
319         /* XXX: due to bugs in some ALSA / JACK MIDI bridges, we have to do separate
320            writes for each controllable here; if we send more than one MIDI message
321            in a single jack_midi_event_write then some bridges will only pass the
322            first on to ALSA.
323         */
324
325         Glib::Threads::Mutex::Lock lm (controllables_lock, Glib::Threads::TRY_LOCK);
326         if (!lm.locked ()) {
327                 return;
328         }
329
330         for (MIDIControllables::iterator r = controllables.begin(); r != controllables.end(); ++r) {
331                 MIDI::byte* end = (*r)->write_feedback (buf, bsize);
332                 if (end != buf) {
333                         _output_port->write (buf, (int32_t) (end - buf), 0);
334                 }
335         }
336 }
337
338 bool
339 GenericMidiControlProtocol::start_learning (Controllable* c)
340 {
341         if (c == 0) {
342                 return false;
343         }
344
345         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
346         DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Learn binding: Controlable number: %1\n", c));
347
348         /* drop any existing mappings for the same controllable for which
349          * learning has just started.
350          */
351
352         MIDIControllables::iterator tmp;
353         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
354                 tmp = i;
355                 ++tmp;
356                 if ((*i)->get_controllable() == c) {
357                         delete (*i);
358                         controllables.erase (i);
359                 }
360                 i = tmp;
361         }
362
363         /* check pending controllables (those for which a learn is underway) to
364          * see if it is for the same one for which learning has just started.
365          */
366
367         {
368                 Glib::Threads::Mutex::Lock lm (pending_lock);
369
370                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
371                         if (((*i)->mc)->get_controllable() == c) {
372                                 (*i)->connection.disconnect();
373                                 if ((*i)->own_mc) {
374                                         delete (*i)->mc;
375                                 }
376                                 delete *i;
377                                 i = pending_controllables.erase (i);
378                         } else {
379                                 ++i;
380                         }
381                 }
382         }
383
384         MIDIControllable* mc = 0;
385         bool own_mc = false;
386
387         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
388                 if ((*i)->get_controllable() && ((*i)->get_controllable()->id() == c->id())) {
389                         mc = *i;
390                         break;
391                 }
392         }
393
394         if (!mc) {
395                 mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
396                 own_mc = true;
397         }
398
399         /* stuff the new controllable into pending */
400
401         {
402                 Glib::Threads::Mutex::Lock lm (pending_lock);
403
404                 MIDIPendingControllable* element = new MIDIPendingControllable (mc, own_mc);
405                 c->LearningFinished.connect_same_thread (element->connection, boost::bind (&GenericMidiControlProtocol::learning_stopped, this, mc));
406
407                 pending_controllables.push_back (element);
408         }
409         mc->learn_about_external_control ();
410         return true;
411 }
412
413 void
414 GenericMidiControlProtocol::learning_stopped (MIDIControllable* mc)
415 {
416         Glib::Threads::Mutex::Lock lm (pending_lock);
417         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
418
419         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
420                 if ( (*i)->mc == mc) {
421                         (*i)->connection.disconnect();
422                         delete *i;
423                         i = pending_controllables.erase(i);
424                 } else {
425                         ++i;
426                 }
427         }
428
429         /* add the controllable for which learning stopped to our list of
430          * controllables
431          */
432
433         controllables.push_back (mc);
434 }
435
436 void
437 GenericMidiControlProtocol::stop_learning (Controllable* c)
438 {
439         Glib::Threads::Mutex::Lock lm (pending_lock);
440         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
441         MIDIControllable* dptr = 0;
442
443         /* learning timed out, and we've been told to consider this attempt to learn to be cancelled. find the
444            relevant MIDIControllable and remove it from the pending list.
445         */
446
447         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
448                 if (((*i)->mc)->get_controllable() == c) {
449                         (*i)->mc->stop_learning ();
450                         dptr = (*i)->mc;
451                         (*i)->connection.disconnect();
452
453                         delete *i;
454                         pending_controllables.erase (i);
455                         break;
456                 }
457         }
458
459         delete dptr;
460 }
461
462 void
463 GenericMidiControlProtocol::delete_binding (PBD::Controllable* control)
464 {
465         if (control != 0) {
466                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
467
468                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
469                         MIDIControllable* existingBinding = (*iter);
470
471                         if (control == (existingBinding->get_controllable())) {
472                                 delete existingBinding;
473                                 iter = controllables.erase (iter);
474                         } else {
475                                 ++iter;
476                         }
477
478                 }
479         }
480 }
481
482 // This next function seems unused
483 void
484 GenericMidiControlProtocol::create_binding (PBD::Controllable* control, int pos, int control_number)
485 {
486         if (control != NULL) {
487                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
488
489                 MIDI::channel_t channel = (pos & 0xf);
490                 MIDI::byte value = control_number;
491
492                 // Create a MIDIControllable
493                 MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *control, false);
494
495                 // Remove any old binding for this midi channel/type/value pair
496                 // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
497                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
498                         MIDIControllable* existingBinding = (*iter);
499
500                         if ((existingBinding->get_control_channel() & 0xf ) == channel &&
501                             existingBinding->get_control_additional() == value &&
502                             (existingBinding->get_control_type() & 0xf0 ) == MIDI::controller) {
503
504                                 delete existingBinding;
505                                 iter = controllables.erase (iter);
506                         } else {
507                                 ++iter;
508                         }
509
510                 }
511
512                 // Update the MIDI Controllable based on the the pos param
513                 // Here is where a table lookup for user mappings could go; for now we'll just wing it...
514                 mc->bind_midi(channel, MIDI::controller, value);
515                 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Create binding: Channel: %1 Controller: %2 Value: %3 \n", channel, MIDI::controller, value));
516                 controllables.push_back (mc);
517         }
518 }
519
520 void
521 GenericMidiControlProtocol::check_used_event (int pos, int control_number)
522 {
523         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
524
525         MIDI::channel_t channel = (pos & 0xf);
526         MIDI::byte value = control_number;
527
528         DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("checking for used event: Channel: %1 Controller: %2 value: %3\n", (int) channel, (pos & 0xf0), (int) value));
529
530         // Remove any old binding for this midi channel/type/value pair
531         // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
532         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
533                 MIDIControllable* existingBinding = (*iter);
534                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
535                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
536                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
537                                 delete existingBinding;
538                                 iter = controllables.erase (iter);
539                         } else {
540                                 ++iter;
541                         }
542                 } else {
543                         ++iter;
544                 }
545         }
546
547         for (MIDIFunctions::iterator iter = functions.begin(); iter != functions.end();) {
548                 MIDIFunction* existingBinding = (*iter);
549                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
550                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
551                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
552                                 delete existingBinding;
553                                 iter = functions.erase (iter);
554                         } else {
555                                 ++iter;
556                         }
557                 } else {
558                         ++iter;
559                 }
560         }
561
562         for (MIDIActions::iterator iter = actions.begin(); iter != actions.end();) {
563                 MIDIAction* existingBinding = (*iter);
564                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
565                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
566                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
567                                 delete existingBinding;
568                                 iter = actions.erase (iter);
569                         } else {
570                                 ++iter;
571                         }
572                 } else {
573                         ++iter;
574                 }
575         }
576
577 }
578
579 XMLNode&
580 GenericMidiControlProtocol::get_state ()
581 {
582         XMLNode& node (ControlProtocol::get_state());
583         char buf[32];
584
585         snprintf (buf, sizeof (buf), "%" PRIu64, _feedback_interval);
586         node.add_property (X_("feedback_interval"), buf);
587         snprintf (buf, sizeof (buf), "%d", _threshold);
588         node.add_property (X_("threshold"), buf);
589
590         node.add_property (X_("motorized"), _motorised ? "yes" : "no");
591
592         if (!_current_binding.empty()) {
593                 node.add_property ("binding", _current_binding);
594         }
595
596         XMLNode* children = new XMLNode (X_("Controls"));
597
598         node.add_child_nocopy (*children);
599
600         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
601         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
602
603                 /* we don't care about bindings that come from a bindings map, because
604                    they will all be reset/recreated when we load the relevant bindings
605                    file.
606                 */
607
608                 if ((*i)->get_controllable() && (*i)->learned()) {
609                         children->add_child_nocopy ((*i)->get_state());
610                 }
611         }
612
613         return node;
614 }
615
616 int
617 GenericMidiControlProtocol::set_state (const XMLNode& node, int version)
618 {
619         XMLNodeList nlist;
620         XMLNodeConstIterator niter;
621         const XMLProperty* prop;
622
623         if (ControlProtocol::set_state (node, version)) {
624                 return -1;
625         }
626
627         if ((prop = node.property ("feedback_interval")) != 0) {
628                 if (sscanf (prop->value().c_str(), "%" PRIu64, &_feedback_interval) != 1) {
629                         _feedback_interval = 10000;
630                 }
631         } else {
632                 _feedback_interval = 10000;
633         }
634
635         if ((prop = node.property ("threshold")) != 0) {
636                 if (sscanf (prop->value().c_str(), "%d", &_threshold) != 1) {
637                         _threshold = 10;
638                 }
639         } else {
640                 _threshold = 10;
641         }
642
643         if ((prop = node.property ("motorized")) != 0) {
644                 _motorised = string_is_affirmative (prop->value ());
645         } else {
646                 _motorised = false;
647         }
648
649         boost::shared_ptr<Controllable> c;
650
651         {
652                 Glib::Threads::Mutex::Lock lm (pending_lock);
653                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
654                         (*i)->connection.disconnect();
655                         if ((*i)->own_mc) {
656                                 delete (*i)->mc;
657                         }
658                         delete *i;
659                 }
660                 pending_controllables.clear ();
661         }
662
663         // midi map has to be loaded first so learned binding can go on top
664         if ((prop = node.property ("binding")) != 0) {
665                 for (list<MapInfo>::iterator x = map_info.begin(); x != map_info.end(); ++x) {
666                         if (prop->value() == (*x).name) {
667                                 load_bindings ((*x).path);
668                                 break;
669                         }
670                 }
671         }
672
673         /* Load up specific bindings from the
674          * <Controls><MidiControllable>...</MidiControllable><Controls> section
675          */
676
677         {
678                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
679                 nlist = node.children(); // "Controls"
680
681                 if (!nlist.empty()) {
682                         nlist = nlist.front()->children(); // "MIDIControllable" ...
683
684                         if (!nlist.empty()) {
685                                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
686
687                                         if ((prop = (*niter)->property ("id")) != 0) {
688
689                                                 ID id = prop->value ();
690                                                 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Relearned binding for session: Control ID: %1\n", id.to_s()));
691                                                 Controllable* c = Controllable::by_id (id);
692
693                                                 if (c) {
694                                                         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
695
696                                                         if (mc->set_state (**niter, version) == 0) {
697                                                                 controllables.push_back (mc);
698                                                         } else {
699                                                                 warning << string_compose ("Generic MIDI control: Failed to set state for Control ID: %1\n", id.to_s());
700                                                                 delete mc;
701                                                         }
702
703                                                 } else {
704                                                         warning << string_compose (
705                                                                 _("Generic MIDI control: controllable %1 not found in session (ignored)"),
706                                                                 id.to_s()) << endmsg;
707                                                 }
708                                         }
709                                 }
710                         }
711                 }
712         }
713
714         return 0;
715 }
716
717 int
718 GenericMidiControlProtocol::set_feedback (bool yn)
719 {
720         do_feedback = yn;
721         last_feedback_time = 0;
722         return 0;
723 }
724
725 bool
726 GenericMidiControlProtocol::get_feedback () const
727 {
728         return do_feedback;
729 }
730
731 int
732 GenericMidiControlProtocol::load_bindings (const string& xmlpath)
733 {
734         DEBUG_TRACE (DEBUG::GenericMidi, "Load bindings: Reading midi map\n");
735         XMLTree state_tree;
736
737         if (!state_tree.read (xmlpath.c_str())) {
738                 error << string_compose(_("Could not understand MIDI bindings file %1"), xmlpath) << endmsg;
739                 return -1;
740         }
741
742         XMLNode* root = state_tree.root();
743
744         if (root->name() != X_("ArdourMIDIBindings")) {
745                 error << string_compose (_("MIDI Bindings file %1 is not really a MIDI bindings file"), xmlpath) << endmsg;
746                 return -1;
747         }
748
749         const XMLProperty* prop;
750
751         if ((prop = root->property ("version")) == 0) {
752                 return -1;
753         }
754
755         const XMLNodeList& children (root->children());
756         XMLNodeConstIterator citer;
757         XMLNodeConstIterator gciter;
758
759         MIDIControllable* mc;
760
761         drop_all ();
762
763         DEBUG_TRACE (DEBUG::GenericMidi, "Loading bindings\n");
764         for (citer = children.begin(); citer != children.end(); ++citer) {
765
766                 if ((*citer)->name() == "DeviceInfo") {
767                         const XMLProperty* prop;
768
769                         if ((prop = (*citer)->property ("bank-size")) != 0) {
770                                 _bank_size = atoi (prop->value());
771                                 _current_bank = 0;
772                         }
773
774                         if ((prop = (*citer)->property ("motorized")) != 0) {
775                                 _motorised = string_is_affirmative (prop->value ());
776                         } else {
777                                 _motorised = false;
778                         }
779
780                         if ((prop = (*citer)->property ("threshold")) != 0) {
781                                 _threshold = atoi (prop->value ());
782                         } else {
783                                 _threshold = 10;
784                         }
785
786                 }
787
788                 if ((*citer)->name() == "Binding") {
789                         const XMLNode* child = *citer;
790
791                         if (child->property ("uri")) {
792                                 /* controllable */
793
794                                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
795                                 if ((mc = create_binding (*child)) != 0) {
796                                         controllables.push_back (mc);
797                                 }
798
799                         } else if (child->property ("function")) {
800
801                                 /* function */
802                                 MIDIFunction* mf;
803
804                                 if ((mf = create_function (*child)) != 0) {
805                                         functions.push_back (mf);
806                                 }
807
808                         } else if (child->property ("action")) {
809                                 MIDIAction* ma;
810
811                                 if ((ma = create_action (*child)) != 0) {
812                                         actions.push_back (ma);
813                                 }
814                         }
815                 }
816         }
817
818         if ((prop = root->property ("name")) != 0) {
819                 _current_binding = prop->value ();
820         }
821
822         reset_controllables ();
823
824         return 0;
825 }
826
827 MIDIControllable*
828 GenericMidiControlProtocol::create_binding (const XMLNode& node)
829 {
830         const XMLProperty* prop;
831         MIDI::byte detail;
832         MIDI::channel_t channel;
833         string uri;
834         MIDI::eventType ev;
835         int intval;
836         bool momentary;
837         MIDIControllable::Encoder encoder = MIDIControllable::No_enc;
838         bool rpn_value = false;
839         bool nrpn_value = false;
840         bool rpn_change = false;
841         bool nrpn_change = false;
842
843         if ((prop = node.property (X_("ctl"))) != 0) {
844                 ev = MIDI::controller;
845         } else if ((prop = node.property (X_("note"))) != 0) {
846                 ev = MIDI::on;
847         } else if ((prop = node.property (X_("pgm"))) != 0) {
848                 ev = MIDI::program;
849         } else if ((prop = node.property (X_("pb"))) != 0) {
850                 ev = MIDI::pitchbend;
851         } else if ((prop = node.property (X_("enc-l"))) != 0) {
852                 encoder = MIDIControllable::Enc_L;
853                 ev = MIDI::controller;
854         } else if ((prop = node.property (X_("enc-r"))) != 0) {
855                 encoder = MIDIControllable::Enc_R;
856                 ev = MIDI::controller;
857         } else if ((prop = node.property (X_("enc-2"))) != 0) {
858                 encoder = MIDIControllable::Enc_2;
859                 ev = MIDI::controller;
860         } else if ((prop = node.property (X_("enc-b"))) != 0) {
861                 encoder = MIDIControllable::Enc_B;
862                 ev = MIDI::controller;
863         } else if ((prop = node.property (X_("rpn"))) != 0) {
864                 rpn_value = true;
865         } else if ((prop = node.property (X_("nrpn"))) != 0) {
866                 nrpn_value = true;
867         } else if ((prop = node.property (X_("rpn-delta"))) != 0) {
868                 rpn_change = true;
869         } else if ((prop = node.property (X_("nrpn-delta"))) != 0) {
870                 nrpn_change = true;
871         } else {
872                 return 0;
873         }
874
875         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
876                 return 0;
877         }
878
879         detail = (MIDI::byte) intval;
880
881         if ((prop = node.property (X_("channel"))) == 0) {
882                 return 0;
883         }
884
885         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
886                 return 0;
887         }
888         channel = (MIDI::channel_t) intval;
889         /* adjust channel to zero-based counting */
890         if (channel > 0) {
891                 channel -= 1;
892         }
893
894         if ((prop = node.property (X_("momentary"))) != 0) {
895                 momentary = string_is_affirmative (prop->value());
896         } else {
897                 momentary = false;
898         }
899
900         prop = node.property (X_("uri"));
901         uri = prop->value();
902
903         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), momentary);
904
905         if (mc->init (uri)) {
906                 delete mc;
907                 return 0;
908         }
909
910         if (rpn_value) {
911                 mc->bind_rpn_value (channel, detail);
912         } else if (nrpn_value) {
913                 mc->bind_nrpn_value (channel, detail);
914         } else if (rpn_change) {
915                 mc->bind_rpn_change (channel, detail);
916         } else if (nrpn_change) {
917                 mc->bind_nrpn_change (channel, detail);
918         } else {
919                 mc->set_encoder (encoder);
920                 mc->bind_midi (channel, ev, detail);
921         }
922
923         return mc;
924 }
925
926 void
927 GenericMidiControlProtocol::reset_controllables ()
928 {
929         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
930
931         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ) {
932                 MIDIControllable* existingBinding = (*iter);
933                 MIDIControllables::iterator next = iter;
934                 ++next;
935
936                 if (!existingBinding->learned()) {
937                         ControllableDescriptor& desc (existingBinding->descriptor());
938
939                         if (desc.banked()) {
940                                 desc.set_bank_offset (_current_bank * _bank_size);
941                         }
942
943                         /* its entirely possible that the session doesn't have
944                          * the specified controllable (e.g. it has too few
945                          * tracks). if we find this to be the case, we just leave
946                          * the binding around, unbound, and it will do "late
947                          * binding" (or "lazy binding") if/when any data arrives.
948                          */
949
950                         existingBinding->lookup_controllable ();
951                 }
952
953                 iter = next;
954         }
955 }
956
957 boost::shared_ptr<Controllable>
958 GenericMidiControlProtocol::lookup_controllable (const ControllableDescriptor& desc) const
959 {
960         return session->controllable_by_descriptor (desc);
961 }
962
963 MIDIFunction*
964 GenericMidiControlProtocol::create_function (const XMLNode& node)
965 {
966         const XMLProperty* prop;
967         int intval;
968         MIDI::byte detail = 0;
969         MIDI::channel_t channel = 0;
970         string uri;
971         MIDI::eventType ev;
972         MIDI::byte* data = 0;
973         uint32_t data_size = 0;
974         string argument;
975
976         if ((prop = node.property (X_("ctl"))) != 0) {
977                 ev = MIDI::controller;
978         } else if ((prop = node.property (X_("note"))) != 0) {
979                 ev = MIDI::on;
980         } else if ((prop = node.property (X_("pgm"))) != 0) {
981                 ev = MIDI::program;
982         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
983
984                 if (prop->name() == X_("sysex")) {
985                         ev = MIDI::sysex;
986                 } else {
987                         ev = MIDI::any;
988                 }
989
990                 int val;
991                 uint32_t cnt;
992
993                 {
994                         cnt = 0;
995                         stringstream ss (prop->value());
996                         ss << hex;
997
998                         while (ss >> val) {
999                                 cnt++;
1000                         }
1001                 }
1002
1003                 if (cnt == 0) {
1004                         return 0;
1005                 }
1006
1007                 data = new MIDI::byte[cnt];
1008                 data_size = cnt;
1009
1010                 {
1011                         stringstream ss (prop->value());
1012                         ss << hex;
1013                         cnt = 0;
1014
1015                         while (ss >> val) {
1016                                 data[cnt++] = (MIDI::byte) val;
1017                         }
1018                 }
1019
1020         } else {
1021                 warning << "Binding ignored - unknown type" << endmsg;
1022                 return 0;
1023         }
1024
1025         if (data_size == 0) {
1026                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1027                         return 0;
1028                 }
1029
1030                 detail = (MIDI::byte) intval;
1031
1032                 if ((prop = node.property (X_("channel"))) == 0) {
1033                         return 0;
1034                 }
1035
1036                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1037                         return 0;
1038                 }
1039                 channel = (MIDI::channel_t) intval;
1040                 /* adjust channel to zero-based counting */
1041                 if (channel > 0) {
1042                         channel -= 1;
1043                 }
1044         }
1045
1046         if ((prop = node.property (X_("arg"))) != 0 || (prop = node.property (X_("argument"))) != 0 || (prop = node.property (X_("arguments"))) != 0) {
1047                 argument = prop->value ();
1048         }
1049
1050         prop = node.property (X_("function"));
1051
1052         MIDIFunction* mf = new MIDIFunction (*_input_port->parser());
1053
1054         if (mf->setup (*this, prop->value(), argument, data, data_size)) {
1055                 delete mf;
1056                 return 0;
1057         }
1058
1059         mf->bind_midi (channel, ev, detail);
1060
1061         return mf;
1062 }
1063
1064 MIDIAction*
1065 GenericMidiControlProtocol::create_action (const XMLNode& node)
1066 {
1067         const XMLProperty* prop;
1068         int intval;
1069         MIDI::byte detail = 0;
1070         MIDI::channel_t channel = 0;
1071         string uri;
1072         MIDI::eventType ev;
1073         MIDI::byte* data = 0;
1074         uint32_t data_size = 0;
1075
1076         if ((prop = node.property (X_("ctl"))) != 0) {
1077                 ev = MIDI::controller;
1078         } else if ((prop = node.property (X_("note"))) != 0) {
1079                 ev = MIDI::on;
1080         } else if ((prop = node.property (X_("pgm"))) != 0) {
1081                 ev = MIDI::program;
1082         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
1083
1084                 if (prop->name() == X_("sysex")) {
1085                         ev = MIDI::sysex;
1086                 } else {
1087                         ev = MIDI::any;
1088                 }
1089
1090                 int val;
1091                 uint32_t cnt;
1092
1093                 {
1094                         cnt = 0;
1095                         stringstream ss (prop->value());
1096                         ss << hex;
1097
1098                         while (ss >> val) {
1099                                 cnt++;
1100                         }
1101                 }
1102
1103                 if (cnt == 0) {
1104                         return 0;
1105                 }
1106
1107                 data = new MIDI::byte[cnt];
1108                 data_size = cnt;
1109
1110                 {
1111                         stringstream ss (prop->value());
1112                         ss << hex;
1113                         cnt = 0;
1114
1115                         while (ss >> val) {
1116                                 data[cnt++] = (MIDI::byte) val;
1117                         }
1118                 }
1119
1120         } else {
1121                 warning << "Binding ignored - unknown type" << endmsg;
1122                 return 0;
1123         }
1124
1125         if (data_size == 0) {
1126                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1127                         return 0;
1128                 }
1129
1130                 detail = (MIDI::byte) intval;
1131
1132                 if ((prop = node.property (X_("channel"))) == 0) {
1133                         return 0;
1134                 }
1135
1136                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1137                         return 0;
1138                 }
1139                 channel = (MIDI::channel_t) intval;
1140                 /* adjust channel to zero-based counting */
1141                 if (channel > 0) {
1142                         channel -= 1;
1143                 }
1144         }
1145
1146         prop = node.property (X_("action"));
1147
1148         MIDIAction* ma = new MIDIAction (*_input_port->parser());
1149
1150         if (ma->init (*this, prop->value(), data, data_size)) {
1151                 delete ma;
1152                 return 0;
1153         }
1154
1155         ma->bind_midi (channel, ev, detail);
1156
1157         return ma;
1158 }
1159
1160 void
1161 GenericMidiControlProtocol::set_current_bank (uint32_t b)
1162 {
1163         _current_bank = b;
1164         reset_controllables ();
1165 }
1166
1167 void
1168 GenericMidiControlProtocol::next_bank ()
1169 {
1170         _current_bank++;
1171         reset_controllables ();
1172 }
1173
1174 void
1175 GenericMidiControlProtocol::prev_bank()
1176 {
1177         if (_current_bank) {
1178                 _current_bank--;
1179                 reset_controllables ();
1180         }
1181 }
1182
1183 void
1184 GenericMidiControlProtocol::set_motorised (bool m)
1185 {
1186         _motorised = m;
1187 }
1188
1189 void
1190 GenericMidiControlProtocol::set_threshold (int t)
1191 {
1192         _threshold = t;
1193 }
1194
1195 bool
1196 GenericMidiControlProtocol::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
1197 {
1198         if (!_input_port || !_output_port) {
1199                 return false;
1200         }
1201
1202         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
1203         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
1204
1205         if (ni == name1 || ni == name2) {
1206                 if (yn) {
1207                         connection_state |= InputConnected;
1208                 } else {
1209                         connection_state &= ~InputConnected;
1210                 }
1211         } else if (no == name1 || no == name2) {
1212                 if (yn) {
1213                         connection_state |= OutputConnected;
1214                 } else {
1215                         connection_state &= ~OutputConnected;
1216                 }
1217         } else {
1218                 /* not our ports */
1219                 return false;
1220         }
1221
1222         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
1223
1224                 /* XXX this is a horrible hack. Without a short sleep here,
1225                    something prevents the device wakeup messages from being
1226                    sent and/or the responses from being received.
1227                 */
1228
1229                 g_usleep (100000);
1230                 connected ();
1231
1232         } else {
1233
1234         }
1235
1236         ConnectionChange (); /* emit signal for our GUI */
1237
1238         return true; /* connection status changed */
1239 }
1240
1241 void
1242 GenericMidiControlProtocol::connected ()
1243 {
1244         cerr << "Now connected\n";
1245 }
1246
1247 boost::shared_ptr<Port>
1248 GenericMidiControlProtocol::output_port() const
1249 {
1250         return _output_port;
1251 }
1252
1253 boost::shared_ptr<Port>
1254 GenericMidiControlProtocol::input_port() const
1255 {
1256         return _input_port;
1257 }
1258
1259 void
1260 GenericMidiControlProtocol::maybe_start_touch (Controllable* controllable)
1261 {
1262         AutomationControl *actl = dynamic_cast<AutomationControl*> (controllable);
1263         if (actl) {
1264                 if (actl->automation_state() == Touch && !actl->touching()) {
1265                         actl->start_touch (session->audible_frame ());
1266                 }
1267         }
1268 }
1269