push2: first somewhat operational versions of menus
[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                 delete *i;
228         }
229         pending_controllables.clear ();
230
231         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
232                 delete *i;
233         }
234         functions.clear ();
235
236         for (MIDIActions::iterator i = actions.begin(); i != actions.end(); ++i) {
237                 delete *i;
238         }
239         actions.clear ();
240 }
241
242 void
243 GenericMidiControlProtocol::drop_bindings ()
244 {
245         DEBUG_TRACE (DEBUG::GenericMidi, "Drop bindings, leave learned\n");
246         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
247
248         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
249                 if (!(*i)->learned()) {
250                         delete *i;
251                         i = controllables.erase (i);
252                 } else {
253                         ++i;
254                 }
255         }
256
257         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
258                 delete *i;
259         }
260         functions.clear ();
261
262         _current_binding = "";
263         _bank_size = 0;
264         _current_bank = 0;
265 }
266
267 int
268 GenericMidiControlProtocol::set_active (bool /*yn*/)
269 {
270         /* nothing to do here: the MIDI UI thread in libardour handles all our
271            I/O needs.
272         */
273         return 0;
274 }
275
276 void
277 GenericMidiControlProtocol::set_feedback_interval (microseconds_t ms)
278 {
279         _feedback_interval = ms;
280 }
281
282 void
283 GenericMidiControlProtocol::send_feedback ()
284 {
285         /* This is executed in RT "process" context", so no blocking calls
286          */
287
288         if (!do_feedback) {
289                 return;
290         }
291
292         microseconds_t now = get_microseconds ();
293
294         if (last_feedback_time != 0) {
295                 if ((now - last_feedback_time) < _feedback_interval) {
296                         return;
297                 }
298         }
299
300         _send_feedback ();
301
302         last_feedback_time = now;
303 }
304
305 void
306 GenericMidiControlProtocol::_send_feedback ()
307 {
308         /* This is executed in RT "process" context", so no blocking calls
309          */
310
311         const int32_t bufsize = 16 * 1024; /* XXX too big */
312         MIDI::byte buf[bufsize];
313         int32_t bsize = bufsize;
314
315         /* XXX: due to bugs in some ALSA / JACK MIDI bridges, we have to do separate
316            writes for each controllable here; if we send more than one MIDI message
317            in a single jack_midi_event_write then some bridges will only pass the
318            first on to ALSA.
319         */
320
321         Glib::Threads::Mutex::Lock lm (controllables_lock, Glib::Threads::TRY_LOCK);
322         if (!lm.locked ()) {
323                 return;
324         }
325
326         for (MIDIControllables::iterator r = controllables.begin(); r != controllables.end(); ++r) {
327                 MIDI::byte* end = (*r)->write_feedback (buf, bsize);
328                 if (end != buf) {
329                         _output_port->write (buf, (int32_t) (end - buf), 0);
330                 }
331         }
332 }
333
334 bool
335 GenericMidiControlProtocol::start_learning (Controllable* c)
336 {
337         if (c == 0) {
338                 return false;
339         }
340
341         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
342         DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Learn binding: Controlable number: %1\n", c));
343
344         MIDIControllables::iterator tmp;
345         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
346                 tmp = i;
347                 ++tmp;
348                 if ((*i)->get_controllable() == c) {
349                         delete (*i);
350                         controllables.erase (i);
351                 }
352                 i = tmp;
353         }
354
355         {
356                 Glib::Threads::Mutex::Lock lm (pending_lock);
357
358                 MIDIPendingControllables::iterator ptmp;
359                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
360                         ptmp = i;
361                         ++ptmp;
362                         if (((*i)->mc)->get_controllable() == c) {
363                                 if ((*i)->own_mc) {
364                                         delete (*i)->mc;
365                                 }
366                                 (*i)->connection.disconnect();
367                                 delete *i;
368                                 pending_controllables.erase (i);
369                         }
370                         i = ptmp;
371                 }
372         }
373
374         MIDIControllable* mc = 0;
375         bool own_mc = false;
376
377         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
378                 if ((*i)->get_controllable() && ((*i)->get_controllable()->id() == c->id())) {
379                         mc = *i;
380                         break;
381                 }
382         }
383
384         if (!mc) {
385                 mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
386                 own_mc = true;
387         }
388
389         {
390                 Glib::Threads::Mutex::Lock lm (pending_lock);
391
392                 MIDIPendingControllable* element = new MIDIPendingControllable (mc, own_mc);
393                 c->LearningFinished.connect_same_thread (element->connection, boost::bind (&GenericMidiControlProtocol::learning_stopped, this, mc));
394
395                 pending_controllables.push_back (element);
396         }
397         mc->learn_about_external_control ();
398         return true;
399 }
400
401 void
402 GenericMidiControlProtocol::learning_stopped (MIDIControllable* mc)
403 {
404         Glib::Threads::Mutex::Lock lm (pending_lock);
405         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
406
407         MIDIPendingControllables::iterator tmp;
408
409         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
410                 tmp = i;
411                 ++tmp;
412
413                 if ( (*i)->mc == mc) {
414                         (*i)->connection.disconnect();
415                         delete *i;
416                         pending_controllables.erase(i);
417                 }
418
419                 i = tmp;
420         }
421
422         controllables.push_back (mc);
423 }
424
425 void
426 GenericMidiControlProtocol::stop_learning (Controllable* c)
427 {
428         Glib::Threads::Mutex::Lock lm (pending_lock);
429         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
430         MIDIControllable* dptr = 0;
431
432         /* learning timed out, and we've been told to consider this attempt to learn to be cancelled. find the
433            relevant MIDIControllable and remove it from the pending list.
434         */
435
436         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
437                 if (((*i)->mc)->get_controllable() == c) {
438                         (*i)->mc->stop_learning ();
439                         dptr = (*i)->mc;
440                         (*i)->connection.disconnect();
441
442                         delete *i;
443                         pending_controllables.erase (i);
444                         break;
445                 }
446         }
447
448         delete dptr;
449 }
450
451 void
452 GenericMidiControlProtocol::delete_binding (PBD::Controllable* control)
453 {
454         if (control != 0) {
455                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
456
457                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
458                         MIDIControllable* existingBinding = (*iter);
459
460                         if (control == (existingBinding->get_controllable())) {
461                                 delete existingBinding;
462                                 iter = controllables.erase (iter);
463                         } else {
464                                 ++iter;
465                         }
466
467                 }
468         }
469 }
470
471 // This next function seems unused
472 void
473 GenericMidiControlProtocol::create_binding (PBD::Controllable* control, int pos, int control_number)
474 {
475         if (control != NULL) {
476                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
477
478                 MIDI::channel_t channel = (pos & 0xf);
479                 MIDI::byte value = control_number;
480
481                 // Create a MIDIControllable
482                 MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *control, false);
483
484                 // Remove any old binding for this midi channel/type/value pair
485                 // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
486                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
487                         MIDIControllable* existingBinding = (*iter);
488
489                         if ((existingBinding->get_control_channel() & 0xf ) == channel &&
490                             existingBinding->get_control_additional() == value &&
491                             (existingBinding->get_control_type() & 0xf0 ) == MIDI::controller) {
492
493                                 delete existingBinding;
494                                 iter = controllables.erase (iter);
495                         } else {
496                                 ++iter;
497                         }
498
499                 }
500
501                 // Update the MIDI Controllable based on the the pos param
502                 // Here is where a table lookup for user mappings could go; for now we'll just wing it...
503                 mc->bind_midi(channel, MIDI::controller, value);
504                 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Create binding: Channel: %1 Controller: %2 Value: %3 \n", channel, MIDI::controller, value));
505                 controllables.push_back (mc);
506         }
507 }
508
509 void
510 GenericMidiControlProtocol::check_used_event (int pos, int control_number)
511 {
512         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
513
514         MIDI::channel_t channel = (pos & 0xf);
515         MIDI::byte value = control_number;
516
517         DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("checking for used event: Channel: %1 Controller: %2 value: %3\n", (int) channel, (pos & 0xf0), (int) value));
518
519         // Remove any old binding for this midi channel/type/value pair
520         // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
521         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
522                 MIDIControllable* existingBinding = (*iter);
523                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
524                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
525                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
526                                 delete existingBinding;
527                                 iter = controllables.erase (iter);
528                         } else {
529                                 ++iter;
530                         }
531                 } else {
532                         ++iter;
533                 }
534         }
535
536         for (MIDIFunctions::iterator iter = functions.begin(); iter != functions.end();) {
537                 MIDIFunction* existingBinding = (*iter);
538                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
539                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
540                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
541                                 delete existingBinding;
542                                 iter = functions.erase (iter);
543                         } else {
544                                 ++iter;
545                         }
546                 } else {
547                         ++iter;
548                 }
549         }
550
551         for (MIDIActions::iterator iter = actions.begin(); iter != actions.end();) {
552                 MIDIAction* existingBinding = (*iter);
553                 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
554                         if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
555                                 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
556                                 delete existingBinding;
557                                 iter = actions.erase (iter);
558                         } else {
559                                 ++iter;
560                         }
561                 } else {
562                         ++iter;
563                 }
564         }
565
566 }
567
568 XMLNode&
569 GenericMidiControlProtocol::get_state ()
570 {
571         XMLNode& node (ControlProtocol::get_state());
572         char buf[32];
573
574         snprintf (buf, sizeof (buf), "%" PRIu64, _feedback_interval);
575         node.add_property (X_("feedback_interval"), buf);
576         snprintf (buf, sizeof (buf), "%d", _threshold);
577         node.add_property (X_("threshold"), buf);
578
579         node.add_property (X_("motorized"), _motorised ? "yes" : "no");
580
581         if (!_current_binding.empty()) {
582                 node.add_property ("binding", _current_binding);
583         }
584
585         XMLNode* children = new XMLNode (X_("Controls"));
586
587         node.add_child_nocopy (*children);
588
589         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
590         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
591
592                 /* we don't care about bindings that come from a bindings map, because
593                    they will all be reset/recreated when we load the relevant bindings
594                    file.
595                 */
596
597                 if ((*i)->get_controllable() && (*i)->learned()) {
598                         children->add_child_nocopy ((*i)->get_state());
599                 }
600         }
601
602         return node;
603 }
604
605 int
606 GenericMidiControlProtocol::set_state (const XMLNode& node, int version)
607 {
608         XMLNodeList nlist;
609         XMLNodeConstIterator niter;
610         const XMLProperty* prop;
611
612         if (ControlProtocol::set_state (node, version)) {
613                 return -1;
614         }
615
616         if ((prop = node.property ("feedback_interval")) != 0) {
617                 if (sscanf (prop->value().c_str(), "%" PRIu64, &_feedback_interval) != 1) {
618                         _feedback_interval = 10000;
619                 }
620         } else {
621                 _feedback_interval = 10000;
622         }
623
624         if ((prop = node.property ("threshold")) != 0) {
625                 if (sscanf (prop->value().c_str(), "%d", &_threshold) != 1) {
626                         _threshold = 10;
627                 }
628         } else {
629                 _threshold = 10;
630         }
631
632         if ((prop = node.property ("motorized")) != 0) {
633                 _motorised = string_is_affirmative (prop->value ());
634         } else {
635                 _motorised = false;
636         }
637
638         boost::shared_ptr<Controllable> c;
639
640         {
641                 Glib::Threads::Mutex::Lock lm (pending_lock);
642                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
643                         delete *i;
644                 }
645                 pending_controllables.clear ();
646         }
647
648         // midi map has to be loaded first so learned binding can go on top
649         if ((prop = node.property ("binding")) != 0) {
650                 for (list<MapInfo>::iterator x = map_info.begin(); x != map_info.end(); ++x) {
651                         if (prop->value() == (*x).name) {
652                                 load_bindings ((*x).path);
653                                 break;
654                         }
655                 }
656         }
657
658         /* Load up specific bindings from the
659          * <Controls><MidiControllable>...</MidiControllable><Controls> section
660          */
661
662         {
663                 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
664                 nlist = node.children(); // "Controls"
665
666                 if (!nlist.empty()) {
667                         nlist = nlist.front()->children(); // "MIDIControllable" ...
668
669                         if (!nlist.empty()) {
670                                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
671
672                                         if ((prop = (*niter)->property ("id")) != 0) {
673
674                                                 ID id = prop->value ();
675                                                 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Relearned binding for session: Control ID: %1\n", id.to_s()));
676                                                 Controllable* c = Controllable::by_id (id);
677
678                                                 if (c) {
679                                                         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), *c, false);
680
681                                                         if (mc->set_state (**niter, version) == 0) {
682                                                                 controllables.push_back (mc);
683                                                         }
684
685                                                 } else {
686                                                         warning << string_compose (
687                                                                 _("Generic MIDI control: controllable %1 not found in session (ignored)"),
688                                                                 id.to_s()) << endmsg;
689                                                 }
690                                         }
691                                 }
692                         }
693                 }
694         }
695
696         return 0;
697 }
698
699 int
700 GenericMidiControlProtocol::set_feedback (bool yn)
701 {
702         do_feedback = yn;
703         last_feedback_time = 0;
704         return 0;
705 }
706
707 bool
708 GenericMidiControlProtocol::get_feedback () const
709 {
710         return do_feedback;
711 }
712
713 int
714 GenericMidiControlProtocol::load_bindings (const string& xmlpath)
715 {
716         DEBUG_TRACE (DEBUG::GenericMidi, "Load bindings: Reading midi map\n");
717         XMLTree state_tree;
718
719         if (!state_tree.read (xmlpath.c_str())) {
720                 error << string_compose(_("Could not understand MIDI bindings file %1"), xmlpath) << endmsg;
721                 return -1;
722         }
723
724         XMLNode* root = state_tree.root();
725
726         if (root->name() != X_("ArdourMIDIBindings")) {
727                 error << string_compose (_("MIDI Bindings file %1 is not really a MIDI bindings file"), xmlpath) << endmsg;
728                 return -1;
729         }
730
731         const XMLProperty* prop;
732
733         if ((prop = root->property ("version")) == 0) {
734                 return -1;
735         } else {
736                 int major;
737                 int minor;
738                 int micro;
739
740                 sscanf (prop->value().c_str(), "%d.%d.%d", &major, &minor, &micro);
741                 Stateful::loading_state_version = (major * 1000) + minor;
742         }
743
744         const XMLNodeList& children (root->children());
745         XMLNodeConstIterator citer;
746         XMLNodeConstIterator gciter;
747
748         MIDIControllable* mc;
749
750         drop_all ();
751
752         DEBUG_TRACE (DEBUG::GenericMidi, "Loading bindings\n");
753         for (citer = children.begin(); citer != children.end(); ++citer) {
754
755                 if ((*citer)->name() == "DeviceInfo") {
756                         const XMLProperty* prop;
757
758                         if ((prop = (*citer)->property ("bank-size")) != 0) {
759                                 _bank_size = atoi (prop->value());
760                                 _current_bank = 0;
761                         }
762
763                         if ((prop = (*citer)->property ("motorized")) != 0) {
764                                 _motorised = string_is_affirmative (prop->value ());
765                         } else {
766                                 _motorised = false;
767                         }
768
769                         if ((prop = (*citer)->property ("threshold")) != 0) {
770                                 _threshold = atoi (prop->value ());
771                         } else {
772                                 _threshold = 10;
773                         }
774
775                 }
776
777                 if ((*citer)->name() == "Binding") {
778                         const XMLNode* child = *citer;
779
780                         if (child->property ("uri")) {
781                                 /* controllable */
782
783                                 if ((mc = create_binding (*child)) != 0) {
784                                         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
785                                         controllables.push_back (mc);
786                                 }
787
788                         } else if (child->property ("function")) {
789
790                                 /* function */
791                                 MIDIFunction* mf;
792
793                                 if ((mf = create_function (*child)) != 0) {
794                                         functions.push_back (mf);
795                                 }
796
797                         } else if (child->property ("action")) {
798                                 MIDIAction* ma;
799
800                                 if ((ma = create_action (*child)) != 0) {
801                                         actions.push_back (ma);
802                                 }
803                         }
804                 }
805         }
806
807         if ((prop = root->property ("name")) != 0) {
808                 _current_binding = prop->value ();
809         }
810
811         reset_controllables ();
812
813         return 0;
814 }
815
816 MIDIControllable*
817 GenericMidiControlProtocol::create_binding (const XMLNode& node)
818 {
819         const XMLProperty* prop;
820         MIDI::byte detail;
821         MIDI::channel_t channel;
822         string uri;
823         MIDI::eventType ev;
824         int intval;
825         bool momentary;
826         MIDIControllable::Encoder encoder = MIDIControllable::No_enc;
827         bool rpn_value = false;
828         bool nrpn_value = false;
829         bool rpn_change = false;
830         bool nrpn_change = false;
831
832         if ((prop = node.property (X_("ctl"))) != 0) {
833                 ev = MIDI::controller;
834         } else if ((prop = node.property (X_("note"))) != 0) {
835                 ev = MIDI::on;
836         } else if ((prop = node.property (X_("pgm"))) != 0) {
837                 ev = MIDI::program;
838         } else if ((prop = node.property (X_("pb"))) != 0) {
839                 ev = MIDI::pitchbend;
840         } else if ((prop = node.property (X_("enc-l"))) != 0) {
841                 encoder = MIDIControllable::Enc_L;
842                 ev = MIDI::controller;
843         } else if ((prop = node.property (X_("enc-r"))) != 0) {
844                 encoder = MIDIControllable::Enc_R;
845                 ev = MIDI::controller;
846         } else if ((prop = node.property (X_("enc-2"))) != 0) {
847                 encoder = MIDIControllable::Enc_2;
848                 ev = MIDI::controller;
849         } else if ((prop = node.property (X_("enc-b"))) != 0) {
850                 encoder = MIDIControllable::Enc_B;
851                 ev = MIDI::controller;
852         } else if ((prop = node.property (X_("rpn"))) != 0) {
853                 rpn_value = true;
854         } else if ((prop = node.property (X_("nrpn"))) != 0) {
855                 nrpn_value = true;
856         } else if ((prop = node.property (X_("rpn-delta"))) != 0) {
857                 rpn_change = true;
858         } else if ((prop = node.property (X_("nrpn-delta"))) != 0) {
859                 nrpn_change = true;
860         } else {
861                 return 0;
862         }
863
864         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
865                 return 0;
866         }
867
868         detail = (MIDI::byte) intval;
869
870         if ((prop = node.property (X_("channel"))) == 0) {
871                 return 0;
872         }
873
874         if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
875                 return 0;
876         }
877         channel = (MIDI::channel_t) intval;
878         /* adjust channel to zero-based counting */
879         if (channel > 0) {
880                 channel -= 1;
881         }
882
883         if ((prop = node.property (X_("momentary"))) != 0) {
884                 momentary = string_is_affirmative (prop->value());
885         } else {
886                 momentary = false;
887         }
888
889         prop = node.property (X_("uri"));
890         uri = prop->value();
891
892         MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), momentary);
893
894         if (mc->init (uri)) {
895                 delete mc;
896                 return 0;
897         }
898
899         if (rpn_value) {
900                 mc->bind_rpn_value (channel, detail);
901         } else if (nrpn_value) {
902                 mc->bind_nrpn_value (channel, detail);
903         } else if (rpn_change) {
904                 mc->bind_rpn_change (channel, detail);
905         } else if (nrpn_change) {
906                 mc->bind_nrpn_change (channel, detail);
907         } else {
908                 mc->set_encoder (encoder);
909                 mc->bind_midi (channel, ev, detail);
910         }
911
912         return mc;
913 }
914
915 void
916 GenericMidiControlProtocol::reset_controllables ()
917 {
918         Glib::Threads::Mutex::Lock lm2 (controllables_lock);
919
920         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ) {
921                 MIDIControllable* existingBinding = (*iter);
922                 MIDIControllables::iterator next = iter;
923                 ++next;
924
925                 if (!existingBinding->learned()) {
926                         ControllableDescriptor& desc (existingBinding->descriptor());
927
928                         if (desc.banked()) {
929                                 desc.set_bank_offset (_current_bank * _bank_size);
930                         }
931
932                         /* its entirely possible that the session doesn't have
933                          * the specified controllable (e.g. it has too few
934                          * tracks). if we find this to be the case, we just leave
935                          * the binding around, unbound, and it will do "late
936                          * binding" (or "lazy binding") if/when any data arrives.
937                          */
938
939                         existingBinding->lookup_controllable ();
940                 }
941
942                 iter = next;
943         }
944 }
945
946 boost::shared_ptr<Controllable>
947 GenericMidiControlProtocol::lookup_controllable (const ControllableDescriptor& desc) const
948 {
949         return session->controllable_by_descriptor (desc);
950 }
951
952 MIDIFunction*
953 GenericMidiControlProtocol::create_function (const XMLNode& node)
954 {
955         const XMLProperty* prop;
956         int intval;
957         MIDI::byte detail = 0;
958         MIDI::channel_t channel = 0;
959         string uri;
960         MIDI::eventType ev;
961         MIDI::byte* data = 0;
962         uint32_t data_size = 0;
963         string argument;
964
965         if ((prop = node.property (X_("ctl"))) != 0) {
966                 ev = MIDI::controller;
967         } else if ((prop = node.property (X_("note"))) != 0) {
968                 ev = MIDI::on;
969         } else if ((prop = node.property (X_("pgm"))) != 0) {
970                 ev = MIDI::program;
971         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
972
973                 if (prop->name() == X_("sysex")) {
974                         ev = MIDI::sysex;
975                 } else {
976                         ev = MIDI::any;
977                 }
978
979                 int val;
980                 uint32_t cnt;
981
982                 {
983                         cnt = 0;
984                         stringstream ss (prop->value());
985                         ss << hex;
986
987                         while (ss >> val) {
988                                 cnt++;
989                         }
990                 }
991
992                 if (cnt == 0) {
993                         return 0;
994                 }
995
996                 data = new MIDI::byte[cnt];
997                 data_size = cnt;
998
999                 {
1000                         stringstream ss (prop->value());
1001                         ss << hex;
1002                         cnt = 0;
1003
1004                         while (ss >> val) {
1005                                 data[cnt++] = (MIDI::byte) val;
1006                         }
1007                 }
1008
1009         } else {
1010                 warning << "Binding ignored - unknown type" << endmsg;
1011                 return 0;
1012         }
1013
1014         if (data_size == 0) {
1015                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1016                         return 0;
1017                 }
1018
1019                 detail = (MIDI::byte) intval;
1020
1021                 if ((prop = node.property (X_("channel"))) == 0) {
1022                         return 0;
1023                 }
1024
1025                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1026                         return 0;
1027                 }
1028                 channel = (MIDI::channel_t) intval;
1029                 /* adjust channel to zero-based counting */
1030                 if (channel > 0) {
1031                         channel -= 1;
1032                 }
1033         }
1034
1035         if ((prop = node.property (X_("arg"))) != 0 || (prop = node.property (X_("argument"))) != 0 || (prop = node.property (X_("arguments"))) != 0) {
1036                 argument = prop->value ();
1037         }
1038
1039         prop = node.property (X_("function"));
1040
1041         MIDIFunction* mf = new MIDIFunction (*_input_port->parser());
1042
1043         if (mf->setup (*this, prop->value(), argument, data, data_size)) {
1044                 delete mf;
1045                 return 0;
1046         }
1047
1048         mf->bind_midi (channel, ev, detail);
1049
1050         return mf;
1051 }
1052
1053 MIDIAction*
1054 GenericMidiControlProtocol::create_action (const XMLNode& node)
1055 {
1056         const XMLProperty* prop;
1057         int intval;
1058         MIDI::byte detail = 0;
1059         MIDI::channel_t channel = 0;
1060         string uri;
1061         MIDI::eventType ev;
1062         MIDI::byte* data = 0;
1063         uint32_t data_size = 0;
1064
1065         if ((prop = node.property (X_("ctl"))) != 0) {
1066                 ev = MIDI::controller;
1067         } else if ((prop = node.property (X_("note"))) != 0) {
1068                 ev = MIDI::on;
1069         } else if ((prop = node.property (X_("pgm"))) != 0) {
1070                 ev = MIDI::program;
1071         } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
1072
1073                 if (prop->name() == X_("sysex")) {
1074                         ev = MIDI::sysex;
1075                 } else {
1076                         ev = MIDI::any;
1077                 }
1078
1079                 int val;
1080                 uint32_t cnt;
1081
1082                 {
1083                         cnt = 0;
1084                         stringstream ss (prop->value());
1085                         ss << hex;
1086
1087                         while (ss >> val) {
1088                                 cnt++;
1089                         }
1090                 }
1091
1092                 if (cnt == 0) {
1093                         return 0;
1094                 }
1095
1096                 data = new MIDI::byte[cnt];
1097                 data_size = cnt;
1098
1099                 {
1100                         stringstream ss (prop->value());
1101                         ss << hex;
1102                         cnt = 0;
1103
1104                         while (ss >> val) {
1105                                 data[cnt++] = (MIDI::byte) val;
1106                         }
1107                 }
1108
1109         } else {
1110                 warning << "Binding ignored - unknown type" << endmsg;
1111                 return 0;
1112         }
1113
1114         if (data_size == 0) {
1115                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1116                         return 0;
1117                 }
1118
1119                 detail = (MIDI::byte) intval;
1120
1121                 if ((prop = node.property (X_("channel"))) == 0) {
1122                         return 0;
1123                 }
1124
1125                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1126                         return 0;
1127                 }
1128                 channel = (MIDI::channel_t) intval;
1129                 /* adjust channel to zero-based counting */
1130                 if (channel > 0) {
1131                         channel -= 1;
1132                 }
1133         }
1134
1135         prop = node.property (X_("action"));
1136
1137         MIDIAction* ma = new MIDIAction (*_input_port->parser());
1138
1139         if (ma->init (*this, prop->value(), data, data_size)) {
1140                 delete ma;
1141                 return 0;
1142         }
1143
1144         ma->bind_midi (channel, ev, detail);
1145
1146         return ma;
1147 }
1148
1149 void
1150 GenericMidiControlProtocol::set_current_bank (uint32_t b)
1151 {
1152         _current_bank = b;
1153         reset_controllables ();
1154 }
1155
1156 void
1157 GenericMidiControlProtocol::next_bank ()
1158 {
1159         _current_bank++;
1160         reset_controllables ();
1161 }
1162
1163 void
1164 GenericMidiControlProtocol::prev_bank()
1165 {
1166         if (_current_bank) {
1167                 _current_bank--;
1168                 reset_controllables ();
1169         }
1170 }
1171
1172 void
1173 GenericMidiControlProtocol::set_motorised (bool m)
1174 {
1175         _motorised = m;
1176 }
1177
1178 void
1179 GenericMidiControlProtocol::set_threshold (int t)
1180 {
1181         _threshold = t;
1182 }
1183
1184 bool
1185 GenericMidiControlProtocol::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
1186 {
1187         if (!_input_port || !_output_port) {
1188                 return false;
1189         }
1190
1191         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
1192         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
1193
1194         if (ni == name1 || ni == name2) {
1195                 if (yn) {
1196                         connection_state |= InputConnected;
1197                 } else {
1198                         connection_state &= ~InputConnected;
1199                 }
1200         } else if (no == name1 || no == name2) {
1201                 if (yn) {
1202                         connection_state |= OutputConnected;
1203                 } else {
1204                         connection_state &= ~OutputConnected;
1205                 }
1206         } else {
1207                 /* not our ports */
1208                 return false;
1209         }
1210
1211         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
1212
1213                 /* XXX this is a horrible hack. Without a short sleep here,
1214                    something prevents the device wakeup messages from being
1215                    sent and/or the responses from being received.
1216                 */
1217
1218                 g_usleep (100000);
1219                 connected ();
1220
1221         } else {
1222
1223         }
1224
1225         ConnectionChange (); /* emit signal for our GUI */
1226
1227         return true; /* connection status changed */
1228 }
1229
1230 void
1231 GenericMidiControlProtocol::connected ()
1232 {
1233         cerr << "Now connected\n";
1234 }
1235
1236 boost::shared_ptr<Port>
1237 GenericMidiControlProtocol::output_port() const
1238 {
1239         return _output_port;
1240 }
1241
1242 boost::shared_ptr<Port>
1243 GenericMidiControlProtocol::input_port() const
1244 {
1245         return _input_port;
1246 }