add sysex support to MIDI binding maps, and a couple more functions
[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 #define __STDC_FORMAT_MACROS 1
21 #include <stdint.h>
22
23 #include <sstream>
24 #include <algorithm>
25
26 #include "pbd/error.h"
27 #include "pbd/failed_constructor.h"
28
29 #include "midi++/port.h"
30 #include "midi++/manager.h"
31
32 #include "ardour/session.h"
33 #include "ardour/route.h"
34 #include "ardour/midi_ui.h"
35
36 #include "generic_midi_control_protocol.h"
37 #include "midicontrollable.h"
38 #include "midifunction.h"
39
40 using namespace ARDOUR;
41 using namespace PBD;
42 using namespace std;
43
44 #include "i18n.h"
45
46 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
47 #define ui_bind(x) boost::protect (boost::bind ((x)))
48
49 GenericMidiControlProtocol::GenericMidiControlProtocol (Session& s)
50         : ControlProtocol (s, _("Generic MIDI"), midi_ui_context())
51 {
52         MIDI::Manager* mm = MIDI::Manager::instance();
53
54         /* XXX it might be nice to run "control" through i18n, but thats a bit tricky because
55            the name is defined in ardour.rc which is likely not internationalized.
56         */
57         
58         _port = mm->port (X_("control"));
59
60         if (_port == 0) {
61                 error << _("no MIDI port named \"control\" exists - generic MIDI control disabled") << endmsg;
62                 throw failed_constructor();
63         }
64
65         do_feedback = false;
66         _feedback_interval = 10000; // microseconds
67         last_feedback_time = 0;
68
69         /* XXX is it right to do all these in the same thread as whatever emits the signal? */
70
71         Controllable::StartLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::start_learning, this, _1));
72         Controllable::StopLearning.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::stop_learning, this, _1));
73         Controllable::CreateBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::create_binding, this, _1, _2, _3));
74         Controllable::DeleteBinding.connect_same_thread (*this, boost::bind (&GenericMidiControlProtocol::delete_binding, this, _1));
75
76         Session::SendFeedback.connect (*this, boost::bind (&GenericMidiControlProtocol::send_feedback, this), midi_ui_context());;
77
78         std::string xmlpath = "/tmp/midi.map";
79
80         load_bindings (xmlpath);
81         reset_controllables ();
82 }
83
84 GenericMidiControlProtocol::~GenericMidiControlProtocol ()
85 {
86         Glib::Mutex::Lock lm (pending_lock);
87         Glib::Mutex::Lock lm2 (controllables_lock);
88
89         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
90                 delete *i;
91         }
92         controllables.clear ();
93
94         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
95                 delete *i;
96         }
97         pending_controllables.clear ();
98
99         for (MIDIFunctions::iterator i = functions.begin(); i != functions.end(); ++i) {
100                 delete *i;
101         }
102         functions.clear ();
103 }
104
105 int
106 GenericMidiControlProtocol::set_active (bool /*yn*/)
107 {
108         /* start/stop delivery/outbound thread */
109         return 0;
110 }
111
112 void
113 GenericMidiControlProtocol::set_feedback_interval (microseconds_t ms)
114 {
115         _feedback_interval = ms;
116 }
117
118 void 
119 GenericMidiControlProtocol::send_feedback ()
120 {
121         if (!do_feedback) {
122                 return;
123         }
124
125         microseconds_t now = get_microseconds ();
126
127         if (last_feedback_time != 0) {
128                 if ((now - last_feedback_time) < _feedback_interval) {
129                         return;
130                 }
131         }
132
133         _send_feedback ();
134         
135         last_feedback_time = now;
136 }
137
138 void 
139 GenericMidiControlProtocol::_send_feedback ()
140 {
141         const int32_t bufsize = 16 * 1024; /* XXX too big */
142         MIDI::byte buf[bufsize];
143         int32_t bsize = bufsize;
144         MIDI::byte* end = buf;
145         
146         for (MIDIControllables::iterator r = controllables.begin(); r != controllables.end(); ++r) {
147                 end = (*r)->write_feedback (end, bsize);
148         }
149         
150         if (end == buf) {
151                 return;
152         } 
153
154         _port->write (buf, (int32_t) (end - buf), 0);
155 }
156
157 bool
158 GenericMidiControlProtocol::start_learning (Controllable* c)
159 {
160         if (c == 0) {
161                 return false;
162         }
163
164         Glib::Mutex::Lock lm (pending_lock);
165         Glib::Mutex::Lock lm2 (controllables_lock);
166
167         MIDIControllables::iterator tmp;
168         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ) {
169                 tmp = i;
170                 ++tmp;
171                 if ((*i)->get_controllable() == c) {
172                         delete (*i);
173                         controllables.erase (i);
174                 }
175                 i = tmp;
176         }
177
178         MIDIPendingControllables::iterator ptmp;
179         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
180                 ptmp = i;
181                 ++ptmp;
182                 if (((*i)->first)->get_controllable() == c) {
183                         (*i)->second.disconnect();
184                         delete (*i)->first;
185                         delete *i;
186                         pending_controllables.erase (i);
187                 }
188                 i = ptmp;
189         }
190
191
192         MIDIControllable* mc = 0;
193
194         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
195                 if ((*i)->get_controllable()->id() == c->id()) {
196                         mc = *i;
197                         break;
198                 }
199         }
200
201         if (!mc) {
202                 mc = new MIDIControllable (*_port, *c);
203         }
204         
205         {
206                 Glib::Mutex::Lock lm (pending_lock);
207
208                 MIDIPendingControllable* element = new MIDIPendingControllable;
209                 element->first = mc;
210                 c->LearningFinished.connect_same_thread (element->second, boost::bind (&GenericMidiControlProtocol::learning_stopped, this, mc));
211
212                 pending_controllables.push_back (element);
213         }
214
215         mc->learn_about_external_control ();
216         return true;
217 }
218
219 void
220 GenericMidiControlProtocol::learning_stopped (MIDIControllable* mc)
221 {
222         Glib::Mutex::Lock lm (pending_lock);
223         Glib::Mutex::Lock lm2 (controllables_lock);
224         
225         MIDIPendingControllables::iterator tmp;
226
227         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ) {
228                 tmp = i;
229                 ++tmp;
230
231                 if ( (*i)->first == mc) {
232                         (*i)->second.disconnect();
233                         delete *i;
234                         pending_controllables.erase(i);
235                 }
236
237                 i = tmp;
238         }
239
240         controllables.insert (mc);
241 }
242
243 void
244 GenericMidiControlProtocol::stop_learning (Controllable* c)
245 {
246         Glib::Mutex::Lock lm (pending_lock);
247         Glib::Mutex::Lock lm2 (controllables_lock);
248         MIDIControllable* dptr = 0;
249
250         /* learning timed out, and we've been told to consider this attempt to learn to be cancelled. find the
251            relevant MIDIControllable and remove it from the pending list.
252         */
253
254         for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
255                 if (((*i)->first)->get_controllable() == c) {
256                         (*i)->first->stop_learning ();
257                         dptr = (*i)->first;
258                         (*i)->second.disconnect();
259
260                         delete *i;
261                         pending_controllables.erase (i);
262                         break;
263                 }
264         }
265         
266         delete dptr;
267 }
268
269 void
270 GenericMidiControlProtocol::delete_binding (PBD::Controllable* control)
271 {
272         if (control != 0) {
273                 Glib::Mutex::Lock lm2 (controllables_lock);
274                 
275                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ++iter) {
276                         MIDIControllable* existingBinding = (*iter);
277                         
278                         if (control == (existingBinding->get_controllable())) {
279                                 delete existingBinding;
280                                 controllables.erase (iter);
281                         }
282                         
283                 }
284         }
285 }
286
287 void
288 GenericMidiControlProtocol::create_binding (PBD::Controllable* control, int pos, int control_number)
289 {
290         if (control != NULL) {
291                 Glib::Mutex::Lock lm2 (controllables_lock);
292                 
293                 MIDI::channel_t channel = (pos & 0xf);
294                 MIDI::byte value = control_number;
295                 
296                 // Create a MIDIControllable
297                 MIDIControllable* mc = new MIDIControllable (*_port, *control);
298                 
299                 // Remove any old binding for this midi channel/type/value pair
300                 // Note:  can't use delete_binding() here because we don't know the specific controllable we want to remove, only the midi information
301                 for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ++iter) {
302                         MIDIControllable* existingBinding = (*iter);
303                         
304                         if ((existingBinding->get_control_channel() & 0xf ) == channel &&
305                             existingBinding->get_control_additional() == value &&
306                             (existingBinding->get_control_type() & 0xf0 ) == MIDI::controller) {
307                                 
308                                 delete existingBinding;
309                                 controllables.erase (iter);
310                         }
311                         
312                 }
313                 
314                 // Update the MIDI Controllable based on the the pos param
315                 // Here is where a table lookup for user mappings could go; for now we'll just wing it...
316                 mc->bind_midi(channel, MIDI::controller, value);
317                 
318                 controllables.insert (mc);
319         }
320 }
321
322 XMLNode&
323 GenericMidiControlProtocol::get_state () 
324 {
325         XMLNode* node = new XMLNode ("Protocol"); 
326         char buf[32];
327
328         node->add_property (X_("name"), _name);
329         node->add_property (X_("feedback"), do_feedback ? "1" : "0");
330         snprintf (buf, sizeof (buf), "%" PRIu64, _feedback_interval);
331         node->add_property (X_("feedback_interval"), buf);
332
333         XMLNode* children = new XMLNode (X_("controls"));
334
335         node->add_child_nocopy (*children);
336
337         Glib::Mutex::Lock lm2 (controllables_lock);
338         for (MIDIControllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
339                 children->add_child_nocopy ((*i)->get_state());
340         }
341
342         return *node;
343 }
344
345 int
346 GenericMidiControlProtocol::set_state (const XMLNode& node, int version)
347 {
348         XMLNodeList nlist;
349         XMLNodeConstIterator niter;
350         const XMLProperty* prop;
351
352         if ((prop = node.property ("feedback")) != 0) {
353                 do_feedback = (bool) atoi (prop->value().c_str());
354         } else {
355                 do_feedback = false;
356         }
357
358         if ((prop = node.property ("feedback_interval")) != 0) {
359                 if (sscanf (prop->value().c_str(), "%" PRIu64, &_feedback_interval) != 1) {
360                         _feedback_interval = 10000;
361                 }
362         } else {
363                 _feedback_interval = 10000;
364         }
365
366         boost::shared_ptr<Controllable> c;
367         
368         {
369                 Glib::Mutex::Lock lm (pending_lock);
370                 for (MIDIPendingControllables::iterator i = pending_controllables.begin(); i != pending_controllables.end(); ++i) {
371                         delete *i;
372                 }
373                 pending_controllables.clear ();
374         }
375         
376         Glib::Mutex::Lock lm2 (controllables_lock);
377         controllables.clear ();
378         nlist = node.children(); // "controls"
379         
380         if (nlist.empty()) {
381                 return 0;
382         }
383         
384         nlist = nlist.front()->children ();
385                 
386         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
387                 
388                 if ((prop = (*niter)->property ("id")) != 0) {
389                         
390                         ID id = prop->value ();
391                         c = session->controllable_by_id (id);
392                         
393                         if (c) {
394                                 MIDIControllable* mc = new MIDIControllable (*_port, *c);
395                                 if (mc->set_state (**niter, version) == 0) {
396                                         controllables.insert (mc);
397                                 }
398                                 
399                         } else {
400                                 warning << string_compose (
401                                         _("Generic MIDI control: controllable %1 not found in session (ignored)"),
402                                         id) << endmsg;
403                         }
404                 }
405         }
406         return 0;
407 }
408
409 int
410 GenericMidiControlProtocol::set_feedback (bool yn)
411 {
412         do_feedback = yn;
413         last_feedback_time = 0;
414         return 0;
415 }
416
417 bool
418 GenericMidiControlProtocol::get_feedback () const
419 {
420         return do_feedback;
421 }
422
423 int
424 GenericMidiControlProtocol::load_bindings (const string& xmlpath)
425 {
426         XMLTree state_tree;
427
428         if (!state_tree.read (xmlpath.c_str())) {
429                 error << string_compose(_("Could not understand MIDI bindings file %1"), xmlpath) << endmsg;
430                 return -1;
431         }
432
433         XMLNode* root = state_tree.root();
434
435         if (root->name() != X_("ArdourMIDIBindings")) {
436                 error << string_compose (_("MIDI Bindings file %1 is not really a MIDI bindings file"), xmlpath) << endmsg;
437                 return -1;
438         }
439
440         const XMLProperty* prop;
441
442         if ((prop = root->property ("version")) == 0) {
443                 return -1;
444         } else {
445                 int major;
446                 int minor;
447                 int micro;
448
449                 sscanf (prop->value().c_str(), "%d.%d.%d", &major, &minor, &micro);
450                 Stateful::loading_state_version = (major * 1000) + minor;
451         }
452         
453         const XMLNodeList& children (root->children());
454         XMLNodeConstIterator citer;
455         XMLNodeConstIterator gciter;
456
457         MIDIControllable* mc;
458
459         for (citer = children.begin(); citer != children.end(); ++citer) {
460                 if ((*citer)->name() == "Binding") {
461                         const XMLNode* child = *citer;
462
463                         if (child->property ("uri")) {
464                                 /* controllable */
465                                 
466                                 if ((mc = create_binding (*child)) != 0) {
467                                         Glib::Mutex::Lock lm2 (controllables_lock);
468                                         controllables.insert (mc);
469                                 }
470
471                         } else if (child->property ("function")) {
472
473                                 cerr << "try to create a function from " << child->property ("function")->value() << endl;
474
475                                 /* function */
476                                 MIDIFunction* mf;
477
478                                 if ((mf = create_function (*child)) != 0) {
479                                         functions.push_back (mf);
480                                 }
481                         }
482                 }
483         }
484
485         return 0;
486 }
487
488 MIDIControllable*
489 GenericMidiControlProtocol::create_binding (const XMLNode& node)
490 {
491         const XMLProperty* prop;
492         int detail;
493         int channel;
494         string uri;
495         MIDI::eventType ev;
496
497         if ((prop = node.property (X_("channel"))) == 0) {
498                 return 0;
499         }
500         
501         if (sscanf (prop->value().c_str(), "%d", &channel) != 1) {
502                 return 0;
503         }
504
505         if ((prop = node.property (X_("ctl"))) != 0) {
506                 ev = MIDI::controller;
507         } else if ((prop = node.property (X_("note"))) != 0) {
508                 ev = MIDI::on;
509         } else if ((prop = node.property (X_("pgm"))) != 0) {
510                 ev = MIDI::program;
511         } else {
512                 return 0;
513         }
514
515         if (sscanf (prop->value().c_str(), "%d", &detail) != 1) {
516                 return 0;
517         }
518
519         prop = node.property (X_("uri"));
520         uri = prop->value();
521
522         MIDIControllable* mc = new MIDIControllable (*_port, uri, false);
523         mc->bind_midi (channel, ev, detail);
524
525         cerr << "New MC with URI = " << uri << endl;
526
527         return mc;
528 }
529
530 void
531 GenericMidiControlProtocol::reset_controllables ()
532 {
533         Glib::Mutex::Lock lm2 (controllables_lock);
534         
535         for (MIDIControllables::iterator iter = controllables.begin(); iter != controllables.end(); ++iter) {
536                 MIDIControllable* existingBinding = (*iter);
537                 
538                 boost::shared_ptr<Controllable> c = session->controllable_by_uri (existingBinding->current_uri());
539                 existingBinding->set_controllable (c.get());
540         }
541 }
542
543 MIDIFunction*
544 GenericMidiControlProtocol::create_function (const XMLNode& node)
545 {
546         const XMLProperty* prop;
547         int intval;
548         MIDI::byte detail = 0;
549         MIDI::channel_t channel = 0;
550         string uri;
551         MIDI::eventType ev;
552         MIDI::byte* sysex = 0;
553         uint32_t sysex_size = 0;
554
555         if ((prop = node.property (X_("ctl"))) != 0) {
556                 ev = MIDI::controller;
557         } else if ((prop = node.property (X_("note"))) != 0) {
558                 ev = MIDI::on;
559         } else if ((prop = node.property (X_("pgm"))) != 0) {
560                 ev = MIDI::program;
561         } else if ((prop = node.property (X_("sysex"))) != 0) {
562
563                 ev = MIDI::sysex;
564                 int val;
565                 uint32_t cnt;
566
567                 {
568                         cnt = 0;
569                         stringstream ss (prop->value());
570                         ss << hex;
571                         
572                         while (ss >> val) {
573                                 cnt++;
574                         }
575                 }
576
577                 if (cnt == 0) {
578                         return 0;
579                 }
580
581                 sysex = new MIDI::byte[cnt];
582                 sysex_size = cnt;
583                 
584                 {
585                         stringstream ss (prop->value());
586                         ss << hex;
587                         cnt = 0;
588                         
589                         while (ss >> val) {
590                                 sysex[cnt++] = (MIDI::byte) val;
591                                 cerr << hex << (int) sysex[cnt-1] << dec << ' ' << endl;
592                         }
593                 }
594                 
595         } else {
596                 warning << "Binding ignored - unknown type" << endmsg;
597                 return 0;
598         }
599
600         if (sysex_size == 0) {
601                 if ((prop = node.property (X_("channel"))) == 0) {
602                         return 0;
603                 }
604         
605                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
606                         return 0;
607                 }
608                 channel = (MIDI::channel_t) intval;
609                 /* adjust channel to zero-based counting */
610                 if (channel > 0) {
611                         channel -= 1;
612                 }
613                 
614                 if (sscanf (prop->value().c_str(), "%d", &intval) != 1) {
615                         return 0;
616                 }
617                 
618                 detail = (MIDI::byte) intval;
619         }
620
621         prop = node.property (X_("function"));
622         
623         MIDIFunction* mf = new MIDIFunction (*_port);
624         
625         if (mf->init (*this, prop->value(), sysex, sysex_size)) {
626                 delete mf;
627                 return 0;
628         }
629
630         mf->bind_midi (channel, ev, detail);
631
632         cerr << "New MF with function = " << prop->value() << endl;
633
634         return mf;
635 }