1 /*
2 * Copyright (C) 2006-2010 David Robillard <d@drobilla.net>
3 * Copyright (C) 2006-2018 Paul Davis <paul@linuxaudiosystems.com>
4 * Copyright (C) 2008-2012 Carl Hetherington <carl@carlh.net>
5 * Copyright (C) 2012-2017 Tim Mayberry <mojofunk@gmail.com>
6 * Copyright (C) 2015-2019 Robin Gareus <robin@gareus.org>
7 * Copyright (C) 2015 Len Ovens <len@ovenwerks.net>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 #include <stdint.h>
25
26 #include <sstream>
27 #include <algorithm>
28
29 #ifdef COMPILER_MSVC
30 #include <io.h> // Microsoft's nearest equivalent to <unistd.h>
31 #include <ardourext/misc.h>
32 #else
33 #include <regex.h>
34 #endif
35
36 #include <glibmm/fileutils.h>
37 #include <glibmm/miscutils.h>
38
39 #include "pbd/compose.h"
40 #include "pbd/convert.h"
41 #include "pbd/error.h"
42 #include "pbd/failed_constructor.h"
43 #include "pbd/file_utils.h"
44 #include "pbd/strsplit.h"
45 #include "pbd/types_convert.h"
46 #include "pbd/xml++.h"
47
48 #include "midi++/port.h"
49
50 #include "ardour/async_midi_port.h"
51 #include "ardour/audioengine.h"
52 #include "ardour/auditioner.h"
53 #include "ardour/filesystem_paths.h"
54 #include "ardour/session.h"
55 #include "ardour/midi_ui.h"
56 #include "ardour/plugin_insert.h"
57 #include "ardour/rc_configuration.h"
58 #include "ardour/midiport_manager.h"
59 #include "ardour/debug.h"
60
61 #include "generic_midi_control_protocol.h"
62 #include "midicontrollable.h"
63 #include "midifunction.h"
64 #include "midiaction.h"
65
66 #include "pbd/abstract_ui.cc" // instantiate template
67
68 #include "pbd/i18n.h"
69
70 using namespace ARDOUR;
71 using namespace PBD;
72 using namespace Glib;
73 using namespace std;
74
GenericMidiControlProtocol(Session & s)75 GenericMidiControlProtocol::GenericMidiControlProtocol (Session& s)
76 : ControlProtocol (s, _("Generic MIDI"))
77 , AbstractUI<GenericMIDIRequest> (name())
78 , connection_state (ConnectionState (0))
79 , _motorised (false)
80 , _threshold (10)
81 , gui (0)
82 {
83 boost::shared_ptr<ARDOUR::Port> inp;
84 boost::shared_ptr<ARDOUR::Port> outp;
85
86 inp = AudioEngine::instance()->register_input_port (DataType::MIDI, _("MIDI Control In"), true);
87 outp = AudioEngine::instance()->register_output_port (DataType::MIDI, _("MIDI Control Out"), true);
88
89 if (inp == 0 || outp == 0) {
90 throw failed_constructor();
91 }
92
93 _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(inp);
94 _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(outp);
95
96 _input_bundle.reset (new ARDOUR::Bundle (_("Generic MIDI Control In"), true));
97 _output_bundle.reset (new ARDOUR::Bundle (_("Generic MIDI Control Out"), false));
98
99 _input_bundle->add_channel (
100 "",
101 ARDOUR::DataType::MIDI,
102 session->engine().make_port_name_non_relative (inp->name())
103 );
104
105 _output_bundle->add_channel (
106 "",
107 ARDOUR::DataType::MIDI,
108 session->engine().make_port_name_non_relative (outp->name())
109 );
110
111 session->BundleAddedOrRemoved ();
112
113 do_feedback = false;
114 _feedback_interval = 10000; // microseconds
115 last_feedback_time = 0;
116
117 _current_bank = 0;
118 _bank_size = 0;
119
120 /* these signals are emitted by our event loop thread
121 * and we may as well handle them right there in the same the same
122 * thread
123 */
124
125 Controllable::StartLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::start_learning, this, _1));
126 Controllable::StopLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::stop_learning, this, _1));
127
128 /* this signal is emitted by the process() callback, and if
129 * send_feedback() is going to do anything, it should do it in the
130 * context of the process() callback itself.
131 */
132
133 Session::SendFeedback.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::send_feedback, this));
134
135 /* this one is cross-thread */
136
137 PresentationInfo::Change.connect (*this, MISSING_INVALIDATOR, boost::bind (&GenericMidiControlProtocol::reset_controllables, this), this);
138
139 /* Catch port connections and disconnections (cross-thread) */
140 ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (_port_connection, MISSING_INVALIDATOR,
141 boost::bind (&GenericMidiControlProtocol::connection_handler, this, _1, _2, _3, _4, _5),
142 this);
143
144 reload_maps ();
145 }
146
~GenericMidiControlProtocol()147 GenericMidiControlProtocol::~GenericMidiControlProtocol ()
148 {
149 if (_input_port) {
150 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("unregistering input port %1\n", boost::shared_ptr<ARDOUR::Port>(_input_port)->name()));
151 Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock());
152 AudioEngine::instance()->unregister_port (_input_port);
153 _input_port.reset ();
154 }
155
156 if (_output_port) {
157 _output_port->drain (10000, 250000); /* check every 10 msecs, wait up to 1/4 second for the port to drain */
158 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("unregistering output port %1\n", boost::shared_ptr<ARDOUR::Port>(_output_port)->name()));
159 Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock());
160 AudioEngine::instance()->unregister_port (_output_port);
161 _output_port.reset ();
162 }
163
164 drop_all ();
165 tear_down_gui ();
166 }
167
168 list<boost::shared_ptr<ARDOUR::Bundle> >
bundles()169 GenericMidiControlProtocol::bundles ()
170 {
171 list<boost::shared_ptr<ARDOUR::Bundle> > b;
172
173 if (_input_bundle) {
174 b.push_back (_input_bundle);
175 b.push_back (_output_bundle);
176 }
177
178 return b;
179 }
180
181
182 static const char * const midimap_env_variable_name = "ARDOUR_MIDIMAPS_PATH";
183 static const char* const midi_map_dir_name = "midi_maps";
184 static const char* const midi_map_suffix = ".map";
185
186 Searchpath
system_midi_map_search_path()187 system_midi_map_search_path ()
188 {
189 bool midimap_path_defined = false;
190 std::string spath_env (Glib::getenv (midimap_env_variable_name, midimap_path_defined));
191
192 if (midimap_path_defined) {
193 return spath_env;
194 }
195
196 Searchpath spath (ardour_data_search_path());
197 spath.add_subdirectory_to_paths(midi_map_dir_name);
198 return spath;
199 }
200
201 static std::string
user_midi_map_directory()202 user_midi_map_directory ()
203 {
204 return Glib::build_filename (user_config_directory(), midi_map_dir_name);
205 }
206
207 static bool
midi_map_filter(const string & str,void *)208 midi_map_filter (const string &str, void* /*arg*/)
209 {
210 return (str.length() > strlen(midi_map_suffix) &&
211 str.find (midi_map_suffix) == (str.length() - strlen (midi_map_suffix)));
212 }
213
214 void
reload_maps()215 GenericMidiControlProtocol::reload_maps ()
216 {
217 vector<string> midi_maps;
218 Searchpath spath (system_midi_map_search_path());
219 spath += user_midi_map_directory ();
220
221 find_files_matching_filter (midi_maps, spath, midi_map_filter, 0, false, true);
222
223 if (midi_maps.empty()) {
224 cerr << "No MIDI maps found using " << spath.to_string() << endl;
225 return;
226 }
227
228 for (vector<string>::iterator i = midi_maps.begin(); i != midi_maps.end(); ++i) {
229 string fullpath = *i;
230
231 XMLTree tree;
232
233 if (!tree.read (fullpath.c_str())) {
234 continue;
235 }
236
237 MapInfo mi;
238
239 std::string str;
240 if (!tree.root()->get_property ("name", str)) {
241 continue;
242 }
243
244 mi.name = str;
245 mi.path = fullpath;
246
247 map_info.push_back (mi);
248 }
249 }
250
251 void
drop_all()252 GenericMidiControlProtocol::drop_all ()
253 {
254 DEBUG_TRACE (DEBUG::GenericMidi, "Drop all bindings\n");
255 Glib::Threads::Mutex::Lock lm (pending_lock);
256 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
257
258 for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
259 delete *i;
260 }
261 controllables.clear ();
262
263 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
264 (*i)->connection.disconnect();
265 if ((*i)->own_mc) {
266 delete (*i)->mc;
267 }
268 delete *i;
269 }
270 pending_controllables.clear ();
271
272 for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
273 delete *i;
274 }
275 functions.clear ();
276
277 for (MIDIActions::iterator i = actions.begin(); i != actions.end(); ++i) {
278 delete *i;
279 }
280 actions.clear ();
281 }
282
283 void
drop_bindings()284 GenericMidiControlProtocol::drop_bindings ()
285 {
286 DEBUG_TRACE (DEBUG::GenericMidi, "Drop bindings, leave learned\n");
287 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
288
289 for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
290 if (!(*i)->learned()) {
291 delete *i;
292 i = controllables.erase (i);
293 } else {
294 ++i;
295 }
296 }
297
298 for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
299 delete *i;
300 }
301 functions.clear ();
302
303 _current_binding = "";
304 _bank_size = 0;
305 _current_bank = 0;
306 }
307
308 void
do_request(GenericMIDIRequest * req)309 GenericMidiControlProtocol::do_request (GenericMIDIRequest* req)
310 {
311 if (req->type == CallSlot) {
312
313 call_slot (MISSING_INVALIDATOR, req->the_slot);
314
315 } else if (req->type == Quit) {
316
317 stop ();
318 }
319 }
320
321 int
stop()322 GenericMidiControlProtocol::stop ()
323 {
324 BaseUI::quit ();
325
326 return 0;
327 }
328
329 void
thread_init()330 GenericMidiControlProtocol::thread_init ()
331 {
332 pthread_set_name (event_loop_name().c_str());
333
334 PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
335 ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
336
337 set_thread_priority ();
338 }
339
340 int
set_active(bool yn)341 GenericMidiControlProtocol::set_active (bool yn)
342 {
343 DEBUG_TRACE (DEBUG::GenericMidi, string_compose("GenericMIDI::set_active init with yn: '%1'\n", yn));
344
345 if (yn == active()) {
346 return 0;
347 }
348
349 if (yn) {
350 BaseUI::run ();
351 } else {
352 BaseUI::quit ();
353 }
354
355 ControlProtocol::set_active (yn);
356
357 DEBUG_TRACE (DEBUG::GenericMidi, string_compose("GenericMIDI::set_active done with yn: '%1'\n", yn));
358
359 return 0;
360 }
361
362 void
set_feedback_interval(microseconds_t ms)363 GenericMidiControlProtocol::set_feedback_interval (microseconds_t ms)
364 {
365 _feedback_interval = ms;
366 }
367
368 void
send_feedback()369 GenericMidiControlProtocol::send_feedback ()
370 {
371 /* This is executed in RT "process" context", so no blocking calls
372 */
373
374 if (!do_feedback) {
375 return;
376 }
377
378 microseconds_t now = get_microseconds ();
379
380 if (last_feedback_time != 0) {
381 if ((now - last_feedback_time) < _feedback_interval) {
382 return;
383 }
384 }
385
386 _send_feedback ();
387
388 last_feedback_time = now;
389 }
390
391 void
_send_feedback()392 GenericMidiControlProtocol::_send_feedback ()
393 {
394 /* This is executed in RT "process" context", so no blocking calls
395 */
396
397 const int32_t bufsize = 16 * 1024; /* XXX too big */
398 MIDI::byte buf[bufsize];
399 int32_t bsize = bufsize;
400
401 /* XXX: due to bugs in some ALSA / JACK MIDI bridges, we have to do separate
402 writes for each controllable here; if we send more than one MIDI message
403 in a single jack_midi_event_write then some bridges will only pass the
404 first on to ALSA.
405 */
406
407 Glib::Threads::Mutex::Lock lm (controllables_lock, Glib::Threads::TRY_LOCK);
408 if (!lm.locked ()) {
409 return;
410 }
411
412 for (MIDIControllables::iterator r = controllables.begin(); r != controllables.end(); ++r) {
413 MIDI::byte* end = (*r)->write_feedback (buf, bsize);
414 if (end != buf) {
415 _output_port->write (buf, (int32_t) (end - buf), 0);
416 }
417 }
418 }
419
420 bool
start_learning(boost::weak_ptr<Controllable> wc)421 GenericMidiControlProtocol::start_learning (boost::weak_ptr <Controllable> wc)
422 {
423 boost::shared_ptr<Controllable> c = wc.lock ();
424 if (!c) {
425 return false;
426 }
427
428 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
429 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Learn binding: Controlable number: %1\n", c));
430
431 /* drop any existing mappings for the same controllable for which
432 * learning has just started.
433 */
434
435 MIDIControllables::iterator tmp;
436 for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
437 tmp = i;
438 ++tmp;
439 if ((*i)->get_controllable() == c) {
440 delete (*i);
441 controllables.erase (i);
442 }
443 i = tmp;
444 }
445
446 /* check pending controllables (those for which a learn is underway) to
447 * see if it is for the same one for which learning has just started.
448 */
449
450 {
451 Glib::Threads::Mutex::Lock lm (pending_lock);
452
453 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
454 if (((*i)->mc)->get_controllable() == c) {
455 (*i)->connection.disconnect();
456 if ((*i)->own_mc) {
457 delete (*i)->mc;
458 }
459 delete *i;
460 i = pending_controllables.erase (i);
461 } else {
462 ++i;
463 }
464 }
465 }
466
467 MIDIControllable* mc = 0;
468 bool own_mc = false;
469
470 for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
471 if ((*i)->get_controllable() && ((*i)->get_controllable()->id() == c->id())) {
472 mc = *i;
473 break;
474 }
475 }
476
477 if (!mc) {
478 mc = new MIDIControllable (this, *_input_port->parser(), c, false);
479 own_mc = true;
480 }
481
482 /* stuff the new controllable into pending */
483
484 {
485 Glib::Threads::Mutex::Lock lm (pending_lock);
486
487 MIDIPendingControllable* element = new MIDIPendingControllable (mc, own_mc);
488 c->LearningFinished.connect_same_thread (element->connection, boost::bind (&GenericMidiControlProtocol::learning_stopped, this, mc));
489
490 pending_controllables.push_back (element);
491 }
492 mc->learn_about_external_control ();
493 return true;
494 }
495
496 void
learning_stopped(MIDIControllable * mc)497 GenericMidiControlProtocol::learning_stopped (MIDIControllable* mc)
498 {
499 Glib::Threads::Mutex::Lock lm (pending_lock);
500 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
501
502 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
503 if ( (*i)->mc == mc) {
504 (*i)->connection.disconnect();
505 delete *i;
506 i = pending_controllables.erase(i);
507 } else {
508 ++i;
509 }
510 }
511
512 /* add the controllable for which learning stopped to our list of
513 * controllables
514 */
515
516 controllables.push_back (mc);
517 }
518
519 void
stop_learning(boost::weak_ptr<PBD::Controllable> wc)520 GenericMidiControlProtocol::stop_learning (boost::weak_ptr<PBD::Controllable> wc)
521 {
522 boost::shared_ptr<Controllable> c = wc.lock ();
523 if (!c) {
524 return;
525 }
526
527 Glib::Threads::Mutex::Lock lm (pending_lock);
528 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
529 MIDIControllable* dptr = 0;
530
531 /* learning timed out, and we've been told to consider this attempt to learn to be cancelled. find the
532 relevant MIDIControllable and remove it from the pending list.
533 */
534
535 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
536 if (((*i)->mc)->get_controllable() == c) {
537 (*i)->mc->stop_learning ();
538 dptr = (*i)->mc;
539 (*i)->connection.disconnect();
540
541 delete *i;
542 pending_controllables.erase (i);
543 break;
544 }
545 }
546
547 delete dptr;
548 }
549
550 void
check_used_event(int pos,int control_number)551 GenericMidiControlProtocol::check_used_event (int pos, int control_number)
552 {
553 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
554
555 MIDI::channel_t channel = (pos & 0xf);
556 MIDI::byte value = control_number;
557
558 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("checking for used event: Channel: %1 Controller: %2 value: %3\n", (int) channel, (pos & 0xf0), (int) value));
559
560 // Remove any old binding for this midi channel/type/value pair
561 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end();) {
562 MIDIControllable* existingBinding = (*iter);
563 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
564 if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
565 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
566 delete existingBinding;
567 iter = controllables.erase (iter);
568 } else {
569 ++iter;
570 }
571 } else {
572 ++iter;
573 }
574 }
575
576 for (MIDIFunctions::iterator iter = functions.begin(); iter != functions.end();) {
577 MIDIFunction* existingBinding = (*iter);
578 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
579 if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
580 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
581 delete existingBinding;
582 iter = functions.erase (iter);
583 } else {
584 ++iter;
585 }
586 } else {
587 ++iter;
588 }
589 }
590
591 for (MIDIActions::iterator iter = actions.begin(); iter != actions.end();) {
592 MIDIAction* existingBinding = (*iter);
593 if ( (existingBinding->get_control_type() & 0xf0 ) == (pos & 0xf0) && (existingBinding->get_control_channel() & 0xf ) == channel ) {
594 if ( ((int) existingBinding->get_control_additional() == (int) value) || ((pos & 0xf0) == MIDI::pitchbend)) {
595 DEBUG_TRACE (DEBUG::GenericMidi, "checking: found match, delete old binding.\n");
596 delete existingBinding;
597 iter = actions.erase (iter);
598 } else {
599 ++iter;
600 }
601 } else {
602 ++iter;
603 }
604 }
605
606 }
607
608 XMLNode&
get_state()609 GenericMidiControlProtocol::get_state ()
610 {
611 XMLNode& node (ControlProtocol::get_state());
612
613
614 XMLNode* child;
615
616 child = new XMLNode (X_("Input"));
617 child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_input_port)->get_state());
618 node.add_child_nocopy (*child);
619
620 child = new XMLNode (X_("Output"));
621 child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_output_port)->get_state());
622 node.add_child_nocopy (*child);
623
624 node.set_property (X_("feedback-interval"), _feedback_interval);
625 node.set_property (X_("threshold"), _threshold);
626 node.set_property (X_("motorized"), _motorised);
627
628 if (!_current_binding.empty()) {
629 node.set_property ("binding", _current_binding);
630 }
631
632 XMLNode* children = new XMLNode (X_("Controls"));
633
634 node.add_child_nocopy (*children);
635
636 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
637 for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
638
639 /* we don't care about bindings that come from a bindings map, because
640 they will all be reset/recreated when we load the relevant bindings
641 file.
642 */
643
644 if ((*i)->get_controllable() && (*i)->learned()) {
645 children->add_child_nocopy ((*i)->get_state());
646 }
647 }
648
649 return node;
650 }
651
652 int
set_state(const XMLNode & node,int version)653 GenericMidiControlProtocol::set_state (const XMLNode& node, int version)
654 {
655 XMLNodeList nlist;
656 XMLNodeConstIterator niter;
657 XMLNode const* child;
658
659 if (ControlProtocol::set_state (node, version)) {
660 return -1;
661 }
662
663 if ((child = node.child (X_("Input"))) != 0) {
664 XMLNode* portnode = child->child (Port::state_node_name.c_str());
665 if (portnode) {
666 portnode->remove_property ("name");
667 boost::shared_ptr<ARDOUR::Port>(_input_port)->set_state (*portnode, version);
668 }
669 }
670
671 if ((child = node.child (X_("Output"))) != 0) {
672 XMLNode* portnode = child->child (Port::state_node_name.c_str());
673 if (portnode) {
674 portnode->remove_property ("name");
675 boost::shared_ptr<ARDOUR::Port>(_output_port)->set_state (*portnode, version);
676 }
677 }
678
679 if (!node.get_property ("feedback-interval", _feedback_interval)) {
680 _feedback_interval = 10000;
681 }
682
683 if (!node.get_property ("threshold", _threshold)) {
684 _threshold = 10;
685 }
686
687 if (!node.get_property ("motorized", _motorised)) {
688 _motorised = false;
689 }
690
691 boost::shared_ptr<Controllable> c;
692
693 {
694 Glib::Threads::Mutex::Lock lm (pending_lock);
695 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
696 (*i)->connection.disconnect();
697 if ((*i)->own_mc) {
698 delete (*i)->mc;
699 }
700 delete *i;
701 }
702 pending_controllables.clear ();
703 }
704
705 std::string str;
706 // midi map has to be loaded first so learned binding can go on top
707 if (node.get_property ("binding", str)) {
708 for (list<MapInfo>::iterator x = map_info.begin(); x != map_info.end(); ++x) {
709 if (str == (*x).name) {
710 load_bindings ((*x).path);
711 break;
712 }
713 }
714 }
715
716 /* Load up specific bindings from the
717 * <Controls><MidiControllable>...</MidiControllable><Controls> section
718 */
719
720 bool load_dynamic_bindings = false;
721 node.get_property ("session-state", load_dynamic_bindings);
722
723 if (load_dynamic_bindings) {
724 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
725 XMLNode* controls_node = node.child (X_("Controls"));
726
727 if (controls_node) {
728
729 nlist = controls_node->children();
730
731 if (!nlist.empty()) {
732
733 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
734
735 PBD::ID id;
736
737 if ((*niter)->get_property ("id", id)) {
738
739 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("Relearned binding for session: Control ID: %1\n", id.to_s()));
740 boost::shared_ptr<PBD::Controllable> c = Controllable::by_id (id);
741
742 if (c) {
743 MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), c, false);
744
745 if (mc->set_state (**niter, version) == 0) {
746 controllables.push_back (mc);
747 } else {
748 warning << string_compose ("Generic MIDI control: Failed to set state for Control ID: %1\n", id.to_s());
749 delete mc;
750 }
751
752 } else {
753 warning << string_compose (
754 _("Generic MIDI control: controllable %1 not found in session (ignored)"),
755 id.to_s()) << endmsg;
756 }
757 }
758 }
759 }
760 }
761 }
762
763 return 0;
764 }
765
766 int
set_feedback(bool yn)767 GenericMidiControlProtocol::set_feedback (bool yn)
768 {
769 do_feedback = yn;
770 last_feedback_time = 0;
771 return 0;
772 }
773
774 bool
get_feedback() const775 GenericMidiControlProtocol::get_feedback () const
776 {
777 return do_feedback;
778 }
779
780 int
load_bindings(const string & xmlpath)781 GenericMidiControlProtocol::load_bindings (const string& xmlpath)
782 {
783 DEBUG_TRACE (DEBUG::GenericMidi, "Load bindings: Reading midi map\n");
784 XMLTree state_tree;
785
786 if (!state_tree.read (xmlpath.c_str())) {
787 error << string_compose(_("Could not understand MIDI bindings file %1"), xmlpath) << endmsg;
788 return -1;
789 }
790
791 XMLNode* root = state_tree.root();
792
793 if (root->name() != X_("ArdourMIDIBindings")) {
794 error << string_compose (_("MIDI Bindings file %1 is not really a MIDI bindings file"), xmlpath) << endmsg;
795 return -1;
796 }
797
798 const XMLProperty* prop;
799
800 if ((prop = root->property ("version")) == 0) {
801 return -1;
802 }
803
804 const XMLNodeList& children (root->children());
805 XMLNodeConstIterator citer;
806
807 MIDIControllable* mc;
808
809 drop_all ();
810
811 DEBUG_TRACE (DEBUG::GenericMidi, "Loading bindings\n");
812 for (citer = children.begin(); citer != children.end(); ++citer) {
813
814 if ((*citer)->name() == "DeviceInfo") {
815
816 if ((*citer)->get_property ("bank-size", _bank_size)) {
817 _current_bank = 0;
818 }
819
820 if (!(*citer)->get_property ("motorized", _motorised)) {
821 _motorised = false;
822 }
823
824 if (!(*citer)->get_property ("threshold", _threshold)) {
825 _threshold = 10;
826 }
827 }
828
829 if ((*citer)->name() == "Binding") {
830 const XMLNode* child = *citer;
831
832 if (child->property ("uri")) {
833 /* controllable */
834
835 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
836 if ((mc = create_binding (*child)) != 0) {
837 controllables.push_back (mc);
838 }
839
840 } else if (child->property ("function")) {
841
842 /* function */
843 MIDIFunction* mf;
844
845 if ((mf = create_function (*child)) != 0) {
846 functions.push_back (mf);
847 }
848
849 } else if (child->property ("action")) {
850 MIDIAction* ma;
851
852 if ((ma = create_action (*child)) != 0) {
853 actions.push_back (ma);
854 }
855 }
856 }
857 }
858
859 if ((prop = root->property ("name")) != 0) {
860 _current_binding = prop->value ();
861 }
862
863 reset_controllables ();
864
865 return 0;
866 }
867
868 MIDIControllable*
create_binding(const XMLNode & node)869 GenericMidiControlProtocol::create_binding (const XMLNode& node)
870 {
871 const XMLProperty* prop;
872 MIDI::byte detail;
873 MIDI::channel_t channel;
874 string uri;
875 MIDI::eventType ev;
876 int intval;
877 bool momentary;
878 MIDIControllable::CtlType ctltype;
879 MIDIControllable::Encoder encoder = MIDIControllable::No_enc;
880 bool rpn_value = false;
881 bool nrpn_value = false;
882 bool rpn_change = false;
883 bool nrpn_change = false;
884
885 if ((prop = node.property (X_("ctl"))) != 0) {
886 ctltype = MIDIControllable::Ctl_Momentary;
887 ev = MIDI::controller;
888 } else if ((prop = node.property (X_("ctl-toggle"))) !=0) {
889 ctltype = MIDIControllable::Ctl_Toggle;
890 ev = MIDI::controller;
891 } else if ((prop = node.property (X_("ctl-dial"))) !=0) {
892 ctltype = MIDIControllable::Ctl_Dial;
893 ev = MIDI::controller;
894 } else if ((prop = node.property (X_("note"))) != 0) {
895 ev = MIDI::on;
896 } else if ((prop = node.property (X_("pgm"))) != 0) {
897 ev = MIDI::program;
898 } else if ((prop = node.property (X_("pb"))) != 0) {
899 ev = MIDI::pitchbend;
900 } else if ((prop = node.property (X_("enc-l"))) != 0) {
901 encoder = MIDIControllable::Enc_L;
902 ev = MIDI::controller;
903 } else if ((prop = node.property (X_("enc-r"))) != 0) {
904 encoder = MIDIControllable::Enc_R;
905 ev = MIDI::controller;
906 } else if ((prop = node.property (X_("enc-2"))) != 0) {
907 encoder = MIDIControllable::Enc_2;
908 ev = MIDI::controller;
909 } else if ((prop = node.property (X_("enc-b"))) != 0) {
910 encoder = MIDIControllable::Enc_B;
911 ev = MIDI::controller;
912 } else if ((prop = node.property (X_("rpn"))) != 0) {
913 rpn_value = true;
914 } else if ((prop = node.property (X_("nrpn"))) != 0) {
915 nrpn_value = true;
916 } else if ((prop = node.property (X_("rpn-delta"))) != 0) {
917 rpn_change = true;
918 } else if ((prop = node.property (X_("nrpn-delta"))) != 0) {
919 nrpn_change = true;
920 } else {
921 return 0;
922 }
923
924 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
925 return 0;
926 }
927
928 detail = (MIDI::byte) intval;
929
930 if ((prop = node.property (X_("channel"))) == 0) {
931 return 0;
932 }
933
934 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
935 return 0;
936 }
937 channel = (MIDI::channel_t) intval;
938 /* adjust channel to zero-based counting */
939 if (channel > 0) {
940 channel -= 1;
941 }
942
943 if ((prop = node.property (X_("momentary"))) != 0) {
944 momentary = string_to<bool> (prop->value());
945 } else {
946 momentary = false;
947 }
948
949 prop = node.property (X_("uri"));
950 uri = prop->value();
951
952 MIDIControllable* mc = new MIDIControllable (this, *_input_port->parser(), momentary);
953
954 if (mc->init (uri)) {
955 delete mc;
956 return 0;
957 }
958
959 if (rpn_value) {
960 mc->bind_rpn_value (channel, detail);
961 } else if (nrpn_value) {
962 mc->bind_nrpn_value (channel, detail);
963 } else if (rpn_change) {
964 mc->bind_rpn_change (channel, detail);
965 } else if (nrpn_change) {
966 mc->bind_nrpn_change (channel, detail);
967 } else {
968 mc->set_ctltype (ctltype);
969 mc->set_encoder (encoder);
970 mc->bind_midi (channel, ev, detail);
971 }
972
973 return mc;
974 }
975
976 void
reset_controllables()977 GenericMidiControlProtocol::reset_controllables ()
978 {
979 Glib::Threads::Mutex::Lock lm2 (controllables_lock);
980
981 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ) {
982 MIDIControllable* existingBinding = (*iter);
983 MIDIControllables::iterator next = iter;
984 ++next;
985
986 if (!existingBinding->learned()) {
987
988 /* its entirely possible that the session doesn't have
989 * the specified controllable (e.g. it has too few
990 * tracks). if we find this to be the case, we just leave
991 * the binding around, unbound, and it will do "late
992 * binding" (or "lazy binding") if/when any data arrives.
993 */
994
995 existingBinding->lookup_controllable ();
996 }
997
998 iter = next;
999 }
1000 }
1001
1002 boost::shared_ptr<Controllable>
lookup_controllable(const string & str) const1003 GenericMidiControlProtocol::lookup_controllable (const string & str) const
1004 {
1005 boost::shared_ptr<Controllable> c;
1006
1007 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("lookup controllable from \"%1\"\n", str));
1008
1009 if (!session) {
1010 DEBUG_TRACE (DEBUG::GenericMidi, "no session\n");
1011 return c;
1012 }
1013
1014 /* step 1: split string apart */
1015
1016 string::size_type first_space = str.find_first_of (" ");
1017
1018 if (first_space == string::npos) {
1019 return c;
1020 }
1021
1022 string front = str.substr (0, first_space);
1023 vector<string> path;
1024 split (front, path, '/');
1025
1026 if (path.size() < 2) {
1027 return c;
1028 }
1029
1030 string back = str.substr (first_space);
1031 vector<string> rest;
1032 split (back, rest, ' ');
1033
1034 if (rest.empty()) {
1035 return c;
1036 }
1037
1038 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("parsed into path of %1, rest of %1\n", path.size(), rest.size()));
1039
1040 /* Step 2: analyse parts of the string to figure out what type of
1041 * Stripable we're looking for
1042 */
1043
1044 enum Type {
1045 Selection,
1046 PresentationOrder,
1047 Named,
1048 };
1049 Type type = Named;
1050 int id = 1;
1051 string name;
1052
1053 static regex_t compiled_pattern;
1054 static bool compiled = false;
1055
1056 if (!compiled) {
1057 const char * const pattern = "^[BS]?[0-9]+";
1058 /* this pattern compilation is not going to fail */
1059 regcomp (&compiled_pattern, pattern, REG_EXTENDED|REG_NOSUB);
1060 /* leak compiled pattern */
1061 compiled = true;
1062 }
1063
1064 /* Step 3: identify what "rest" looks like - name, or simple nueric, or
1065 * banked/selection specifier
1066 */
1067
1068 bool matched = (regexec (&compiled_pattern, rest[0].c_str(), 0, 0, 0) == 0);
1069
1070 if (matched) {
1071 bool banked = false;
1072
1073 if (rest[0][0] == 'B') {
1074 banked = true;
1075 /* already matched digits, so we know atoi() will succeed */
1076 id = atoi (rest[0].substr (1));
1077 type = PresentationOrder;
1078 } else if (rest[0][0] == 'S') {
1079 /* already matched digits, so we know atoi() will succeed */
1080 id = atoi (rest[0].substr (1));
1081 type = Selection;
1082 } else if (isdigit (rest[0][0])) {
1083 /* already matched digits, so we know atoi() will succeed */
1084 id = atoi (rest[0]);
1085 type = PresentationOrder;
1086 } else {
1087 return c;
1088 }
1089
1090 id -= 1; /* order is zero-based, but maps use 1-based */
1091
1092 if (banked) {
1093 id += _current_bank * _bank_size;
1094 }
1095
1096 } else {
1097
1098 type = Named;
1099 name = rest[0];
1100 }
1101
1102 /* step 4: find the reference Stripable */
1103
1104 boost::shared_ptr<Stripable> s;
1105
1106 if (path[0] == X_("route") || path[0] == X_("rid")) {
1107
1108 std::string name;
1109
1110 switch (type) {
1111 case PresentationOrder:
1112 s = session->get_remote_nth_stripable (id, PresentationInfo::Route);
1113 break;
1114 case Named:
1115 /* name */
1116 name = rest[0];
1117
1118 if (name == "Master" || name == X_("master")) {
1119 s = session->master_out();
1120 } else if (name == X_("control") || name == X_("listen") || name == X_("monitor") || name == "Monitor") {
1121 s = session->monitor_out();
1122 } else if (name == X_("auditioner")) {
1123 s = session->the_auditioner();
1124 } else {
1125 s = session->route_by_name (name);
1126 }
1127 break;
1128
1129 case Selection:
1130 s = session->route_by_selected_count (id);
1131 break;
1132 }
1133
1134 } else if (path[0] == X_("vca")) {
1135
1136 s = session->get_remote_nth_stripable (id, PresentationInfo::VCA);
1137
1138 } else if (path[0] == X_("bus")) {
1139
1140 switch (type) {
1141 case Named:
1142 s = session->route_by_name (name);
1143 break;
1144 default:
1145 s = session->get_remote_nth_stripable (id, PresentationInfo::Bus);
1146 }
1147
1148 } else if (path[0] == X_("track")) {
1149
1150 switch (type) {
1151 case Named:
1152 s = session->route_by_name (name);
1153 break;
1154 default:
1155 s = session->get_remote_nth_stripable (id, PresentationInfo::Track);
1156 }
1157 }
1158
1159 if (!s) {
1160 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("no stripable found for \"%1\"\n", str));
1161 return c;
1162 }
1163
1164 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("found stripable %1\n", s->name()));
1165
1166 /* step 5: find the referenced controllable for that stripable.
1167 *
1168 * Some controls exist only for Route, so we need that too
1169 */
1170
1171 boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (s);
1172
1173 if (path[1] == X_("gain")) {
1174 c = s->gain_control();
1175 } else if (path[1] == X_("trim")) {
1176 c = s->trim_control ();
1177 } else if (path[1] == X_("solo")) {
1178 c = s->solo_control();
1179 } else if (path[1] == X_("mute")) {
1180 c = s->mute_control();
1181 } else if (path[1] == X_("recenable")) {
1182 c = s->rec_enable_control ();
1183 } else if (path[1] == X_("panwidth")) {
1184 c = s->pan_width_control ();
1185 } else if (path[1] == X_("pandirection") || path[1] == X_("balance")) {
1186 c = s->pan_azimuth_control ();
1187 } else if (path[1] == X_("plugin")) {
1188
1189 /* /route/plugin/parameter */
1190
1191 if (path.size() == 3 && rest.size() == 3) {
1192 if (path[2] == X_("parameter")) {
1193
1194 int plugin = atoi (rest[1]);
1195 int parameter_index = atoi (rest[2]);
1196
1197 /* revert to zero based counting */
1198 if (plugin > 0) {
1199 --plugin;
1200 }
1201 if (parameter_index > 0) {
1202 --parameter_index;
1203 }
1204
1205 if (r) {
1206 boost::shared_ptr<Processor> proc = r->nth_plugin (plugin);
1207
1208 if (proc) {
1209 boost::shared_ptr<PluginInsert> p = boost::dynamic_pointer_cast<PluginInsert> (proc);
1210 if (p) {
1211 uint32_t param;
1212 bool ok;
1213 param = p->plugin()->nth_parameter (parameter_index, ok);
1214 if (ok) {
1215 c = boost::dynamic_pointer_cast<Controllable> (proc->control (Evoral::Parameter (PluginAutomation, 0, param)));
1216 }
1217 }
1218 }
1219 }
1220 }
1221 }
1222
1223 } else if (path[1] == X_("send")) {
1224
1225 if (path.size() == 3 && rest.size() == 2) {
1226 if (path[2] == X_("gain")) {
1227 uint32_t send = atoi (rest[1]);
1228 if (send > 0) {
1229 --send;
1230 }
1231 c = s->send_level_controllable (send);
1232 } else if (path[2] == X_("direction")) {
1233 /* XXX not implemented yet */
1234
1235 } else if (path[2] == X_("enable")) {
1236 /* XXX not implemented yet */
1237 }
1238 }
1239
1240 } else if (path[1] == X_("eq")) {
1241
1242 /* /route/eq/enable */
1243 /* /route/eq/gain/<band> */
1244 /* /route/eq/freq/<band> */
1245 /* /route/eq/q/<band> */
1246 /* /route/eq/shape/<band> */
1247
1248 if (path.size() == 3) {
1249
1250 if (path[2] == X_("enable")) {
1251 c = s->eq_enable_controllable ();
1252 }
1253
1254 } else if (path.size() == 4) {
1255
1256 int band = atoi (path[3]); /* band number */
1257
1258 if (path[2] == X_("gain")) {
1259 c = s->eq_gain_controllable (band);
1260 } else if (path[2] == X_("freq")) {
1261 c = s->eq_freq_controllable (band);
1262 } else if (path[2] == X_("q")) {
1263 c = s->eq_q_controllable (band);
1264 } else if (path[2] == X_("shape")) {
1265 c = s->eq_shape_controllable (band);
1266 }
1267 }
1268
1269 } else if (path[1] == X_("filter")) {
1270
1271 /* /route/filter/hi/freq */
1272
1273 if (path.size() == 4) {
1274
1275 int filter;
1276
1277 if (path[2] == X_("hi")) {
1278 filter = 1; /* high pass filter */
1279 } else {
1280 filter = 0; /* low pass filter */
1281 }
1282
1283 if (path[3] == X_("enable")) {
1284 c = s->filter_enable_controllable (filter);
1285 } else if (path[3] == X_("freq")) {
1286 c = s->filter_freq_controllable (filter);
1287 } else if (path[3] == X_("slope")) {
1288 c = s->filter_slope_controllable (filter);
1289 }
1290
1291 }
1292
1293 } else if (path[1] == X_("compressor")) {
1294
1295 if (path.size() == 3) {
1296 if (path[2] == X_("enable")) {
1297 c = s->comp_enable_controllable ();
1298 } else if (path[2] == X_("threshold")) {
1299 c = s->comp_threshold_controllable ();
1300 } else if (path[2] == X_("mode")) {
1301 c = s->comp_mode_controllable ();
1302 } else if (path[2] == X_("speed")) {
1303 c = s->comp_speed_controllable ();
1304 } else if (path[2] == X_("makeup")) {
1305 c = s->comp_makeup_controllable ();
1306 }
1307 }
1308 }
1309
1310 if (c) {
1311 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("found controllable \"%1\"\n", c->name()));
1312 } else {
1313 DEBUG_TRACE (DEBUG::GenericMidi, "no controllable found\n");
1314 }
1315
1316 return c;
1317 }
1318
1319 MIDIFunction*
create_function(const XMLNode & node)1320 GenericMidiControlProtocol::create_function (const XMLNode& node)
1321 {
1322 const XMLProperty* prop;
1323 int intval;
1324 MIDI::byte detail = 0;
1325 MIDI::channel_t channel = 0;
1326 string uri;
1327 MIDI::eventType ev;
1328 MIDI::byte* data = 0;
1329 uint32_t data_size = 0;
1330 string argument;
1331
1332 if ((prop = node.property (X_("ctl"))) != 0) {
1333 ev = MIDI::controller;
1334 } else if ((prop = node.property (X_("note"))) != 0) {
1335 ev = MIDI::on;
1336 } else if ((prop = node.property (X_("pgm"))) != 0) {
1337 ev = MIDI::program;
1338 } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
1339
1340 if (prop->name() == X_("sysex")) {
1341 ev = MIDI::sysex;
1342 } else {
1343 ev = MIDI::any;
1344 }
1345
1346 int val;
1347 uint32_t cnt;
1348
1349 {
1350 cnt = 0;
1351 stringstream ss (prop->value());
1352 ss << hex;
1353
1354 while (ss >> val) {
1355 cnt++;
1356 }
1357 }
1358
1359 if (cnt == 0) {
1360 return 0;
1361 }
1362
1363 data = new MIDI::byte[cnt];
1364 data_size = cnt;
1365
1366 {
1367 stringstream ss (prop->value());
1368 ss << hex;
1369 cnt = 0;
1370
1371 while (ss >> val) {
1372 data[cnt++] = (MIDI::byte) val;
1373 }
1374 }
1375
1376 } else {
1377 warning << "Binding ignored - unknown type" << endmsg;
1378 return 0;
1379 }
1380
1381 if (data_size == 0) {
1382 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1383 return 0;
1384 }
1385
1386 detail = (MIDI::byte) intval;
1387
1388 if ((prop = node.property (X_("channel"))) == 0) {
1389 return 0;
1390 }
1391
1392 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1393 return 0;
1394 }
1395 channel = (MIDI::channel_t) intval;
1396 /* adjust channel to zero-based counting */
1397 if (channel > 0) {
1398 channel -= 1;
1399 }
1400 }
1401
1402 if ((prop = node.property (X_("arg"))) != 0 || (prop = node.property (X_("argument"))) != 0 || (prop = node.property (X_("arguments"))) != 0) {
1403 argument = prop->value ();
1404 }
1405
1406 prop = node.property (X_("function"));
1407
1408 MIDIFunction* mf = new MIDIFunction (*_input_port->parser());
1409
1410 if (mf->setup (*this, prop->value(), argument, data, data_size)) {
1411 delete mf;
1412 return 0;
1413 }
1414
1415 mf->bind_midi (channel, ev, detail);
1416
1417 return mf;
1418 }
1419
1420 MIDIAction*
create_action(const XMLNode & node)1421 GenericMidiControlProtocol::create_action (const XMLNode& node)
1422 {
1423 const XMLProperty* prop;
1424 int intval;
1425 MIDI::byte detail = 0;
1426 MIDI::channel_t channel = 0;
1427 string uri;
1428 MIDI::eventType ev;
1429 MIDI::byte* data = 0;
1430 uint32_t data_size = 0;
1431
1432 if ((prop = node.property (X_("ctl"))) != 0) {
1433 ev = MIDI::controller;
1434 } else if ((prop = node.property (X_("note"))) != 0) {
1435 ev = MIDI::on;
1436 } else if ((prop = node.property (X_("pgm"))) != 0) {
1437 ev = MIDI::program;
1438 } else if ((prop = node.property (X_("sysex"))) != 0 || (prop = node.property (X_("msg"))) != 0) {
1439
1440 if (prop->name() == X_("sysex")) {
1441 ev = MIDI::sysex;
1442 } else {
1443 ev = MIDI::any;
1444 }
1445
1446 int val;
1447 uint32_t cnt;
1448
1449 {
1450 cnt = 0;
1451 stringstream ss (prop->value());
1452 ss << hex;
1453
1454 while (ss >> val) {
1455 cnt++;
1456 }
1457 }
1458
1459 if (cnt == 0) {
1460 return 0;
1461 }
1462
1463 data = new MIDI::byte[cnt];
1464 data_size = cnt;
1465
1466 {
1467 stringstream ss (prop->value());
1468 ss << hex;
1469 cnt = 0;
1470
1471 while (ss >> val) {
1472 data[cnt++] = (MIDI::byte) val;
1473 }
1474 }
1475
1476 } else {
1477 warning << "Binding ignored - unknown type" << endmsg;
1478 return 0;
1479 }
1480
1481 if (data_size == 0) {
1482 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1483 return 0;
1484 }
1485
1486 detail = (MIDI::byte) intval;
1487
1488 if ((prop = node.property (X_("channel"))) == 0) {
1489 return 0;
1490 }
1491
1492 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
1493 return 0;
1494 }
1495 channel = (MIDI::channel_t) intval;
1496 /* adjust channel to zero-based counting */
1497 if (channel > 0) {
1498 channel -= 1;
1499 }
1500 }
1501
1502 prop = node.property (X_("action"));
1503
1504 MIDIAction* ma = new MIDIAction (*_input_port->parser());
1505
1506 if (ma->init (*this, prop->value(), data, data_size)) {
1507 delete ma;
1508 return 0;
1509 }
1510
1511 ma->bind_midi (channel, ev, detail);
1512
1513 return ma;
1514 }
1515
1516 void
set_current_bank(uint32_t b)1517 GenericMidiControlProtocol::set_current_bank (uint32_t b)
1518 {
1519 _current_bank = b;
1520 reset_controllables ();
1521 }
1522
1523 void
next_bank()1524 GenericMidiControlProtocol::next_bank ()
1525 {
1526 _current_bank++;
1527 reset_controllables ();
1528 }
1529
1530 void
prev_bank()1531 GenericMidiControlProtocol::prev_bank()
1532 {
1533 if (_current_bank) {
1534 _current_bank--;
1535 reset_controllables ();
1536 }
1537 }
1538
1539 void
set_motorised(bool m)1540 GenericMidiControlProtocol::set_motorised (bool m)
1541 {
1542 _motorised = m;
1543 }
1544
1545 void
set_threshold(int t)1546 GenericMidiControlProtocol::set_threshold (int t)
1547 {
1548 _threshold = t;
1549 }
1550
1551 bool
connection_handler(boost::weak_ptr<ARDOUR::Port>,std::string name1,boost::weak_ptr<ARDOUR::Port>,std::string name2,bool yn)1552 GenericMidiControlProtocol::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
1553 {
1554 bool input_was_connected = (connection_state & InputConnected);
1555
1556 if (!_input_port || !_output_port) {
1557 return false;
1558 }
1559
1560 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("connection change: %1 and %2 connected ? %3\n", name1, name2, yn));
1561
1562 string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
1563 string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
1564
1565 if (ni == name1 || ni == name2) {
1566 if (yn) {
1567 connection_state |= InputConnected;
1568 } else {
1569 connection_state &= ~InputConnected;
1570 }
1571 } else if (no == name1 || no == name2) {
1572 if (yn) {
1573 connection_state |= OutputConnected;
1574 } else {
1575 connection_state &= ~OutputConnected;
1576 }
1577 } else {
1578 /* not our ports */
1579 return false;
1580 }
1581
1582 if (connection_state & InputConnected) {
1583 if (!input_was_connected) {
1584 start_midi_handling ();
1585 }
1586 } else {
1587 if (input_was_connected) {
1588 stop_midi_handling ();
1589 }
1590 }
1591
1592 ConnectionChange (); /* emit signal for our GUI */
1593
1594 return true; /* connection status changed */
1595 }
1596
1597 boost::shared_ptr<Port>
output_port() const1598 GenericMidiControlProtocol::output_port() const
1599 {
1600 return _output_port;
1601 }
1602
1603 boost::shared_ptr<Port>
input_port() const1604 GenericMidiControlProtocol::input_port() const
1605 {
1606 return _input_port;
1607 }
1608
1609 void
maybe_start_touch(boost::shared_ptr<Controllable> controllable)1610 GenericMidiControlProtocol::maybe_start_touch (boost::shared_ptr<Controllable> controllable)
1611 {
1612 boost::shared_ptr<AutomationControl> actl = boost::dynamic_pointer_cast<AutomationControl> (controllable);
1613 if (actl) {
1614 actl->start_touch (session->audible_sample ());
1615 }
1616 }
1617
1618
1619 void
start_midi_handling()1620 GenericMidiControlProtocol::start_midi_handling ()
1621 {
1622 /* This connection means that whenever data is ready from the input
1623 * port, the relevant thread will invoke our ::midi_input_handler()
1624 * method, which will read the data, and invoke the parser.
1625 */
1626
1627 _input_port->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &GenericMidiControlProtocol::midi_input_handler), boost::weak_ptr<AsyncMIDIPort> (_input_port)));
1628 _input_port->xthread().attach (main_loop()->get_context());
1629 }
1630
1631 void
stop_midi_handling()1632 GenericMidiControlProtocol::stop_midi_handling ()
1633 {
1634 midi_connections.drop_connections ();
1635
1636 /* Note: the input handler is still active at this point, but we're no
1637 * longer connected to any of the parser signals
1638 */
1639 }
1640
1641 bool
midi_input_handler(Glib::IOCondition ioc,boost::weak_ptr<ARDOUR::AsyncMIDIPort> wport)1642 GenericMidiControlProtocol::midi_input_handler (Glib::IOCondition ioc, boost::weak_ptr<ARDOUR::AsyncMIDIPort> wport)
1643 {
1644 boost::shared_ptr<AsyncMIDIPort> port (wport.lock());
1645
1646 if (!port) {
1647 return false;
1648 }
1649
1650 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("something happend on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
1651
1652 if (ioc & ~IO_IN) {
1653 return false;
1654 }
1655
1656 if (ioc & IO_IN) {
1657
1658 port->clear ();
1659 DEBUG_TRACE (DEBUG::GenericMidi, string_compose ("data available on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
1660 samplepos_t now = session->engine().sample_time();
1661 port->parse (now);
1662 }
1663
1664 return true;
1665 }
1666