working version of new gain control design
[ardour.git] / libs / surfaces / osc / osc.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  */
19
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cerrno>
23 #include <algorithm>
24
25 #include <unistd.h>
26 #include <fcntl.h>
27
28 #include "pbd/gstdio_compat.h"
29 #include <glibmm/miscutils.h>
30
31 #include <pbd/convert.h>
32 #include <pbd/pthread_utils.h>
33 #include <pbd/file_utils.h>
34 #include <pbd/failed_constructor.h>
35
36 #include "ardour/amp.h"
37 #include "ardour/session.h"
38 #include "ardour/route.h"
39 #include "ardour/audio_track.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/dB.h"
42 #include "ardour/filesystem_paths.h"
43 #include "ardour/panner.h"
44 #include "ardour/plugin.h"
45 #include "ardour/plugin_insert.h"
46 #include "ardour/send.h"
47
48 #include "osc.h"
49 #include "osc_controllable.h"
50 #include "osc_route_observer.h"
51 #include "i18n.h"
52
53 using namespace ARDOUR;
54 using namespace std;
55 using namespace Glib;
56 using namespace ArdourSurface;
57
58 #include "pbd/abstract_ui.cc" // instantiate template
59
60 OSC* OSC::_instance = 0;
61
62 #ifdef DEBUG
63 static void error_callback(int num, const char *m, const char *path)
64 {
65         fprintf(stderr, "liblo server error %d in path %s: %s\n", num, path, m);
66 }
67 #else
68 static void error_callback(int, const char *, const char *)
69 {
70
71 }
72 #endif
73
74 OSC::OSC (Session& s, uint32_t port)
75         : ControlProtocol (s, X_("Open Sound Control (OSC)"))
76         , AbstractUI<OSCUIRequest> (name())
77         , local_server (0)
78         , remote_server (0)
79         , _port(port)
80         , _ok (true)
81         , _shutdown (false)
82         , _osc_server (0)
83         , _osc_unix_server (0)
84         , _namespace_root ("/ardour")
85         , _send_route_changes (true)
86         , _debugmode (Off)
87         , gui (0)
88 {
89         _instance = this;
90
91         session_loaded (s);
92         session->Exported.connect (*this, MISSING_INVALIDATOR, boost::bind (&OSC::session_exported, this, _1, _2), this);
93 }
94
95 OSC::~OSC()
96 {
97         stop ();
98         _instance = 0;
99 }
100
101 void*
102 OSC::request_factory (uint32_t num_requests)
103 {
104         /* AbstractUI<T>::request_buffer_factory() is a template method only
105            instantiated in this source module. To provide something visible for
106            use in the interface/descriptor, we have this static method that is
107            template-free.
108         */
109         return request_buffer_factory (num_requests);
110 }
111
112 void
113 OSC::do_request (OSCUIRequest* req)
114 {
115         if (req->type == CallSlot) {
116
117                 call_slot (MISSING_INVALIDATOR, req->the_slot);
118
119         } else if (req->type == Quit) {
120
121                 stop ();
122         }
123 }
124
125 int
126 OSC::set_active (bool yn)
127 {
128         if (yn != active()) {
129
130                 if (yn) {
131                         if (start ()) {
132                                 return -1;
133                         }
134                 } else {
135                         if (stop ()) {
136                                 return -1;
137                         }
138                 }
139
140         }
141
142         return ControlProtocol::set_active (yn);
143 }
144
145 bool
146 OSC::get_active () const
147 {
148         return _osc_server != 0;
149 }
150
151 int
152 OSC::set_feedback (bool yn)
153 {
154         _send_route_changes = yn;
155         return 0;
156 }
157
158 bool
159 OSC::get_feedback () const
160 {
161         return _send_route_changes;
162 }
163
164 int
165 OSC::start ()
166 {
167         char tmpstr[255];
168
169         if (_osc_server) {
170                 /* already started */
171                 return 0;
172         }
173
174         for (int j=0; j < 20; ++j) {
175                 snprintf(tmpstr, sizeof(tmpstr), "%d", _port);
176
177                 //if ((_osc_server = lo_server_new_with_proto (tmpstr, LO_TCP, error_callback))) {
178                 //      break;
179                 //}
180
181                 if ((_osc_server = lo_server_new (tmpstr, error_callback))) {
182                         break;
183                 }
184
185 #ifdef DEBUG
186                 cerr << "can't get osc at port: " << _port << endl;
187 #endif
188                 _port++;
189                 continue;
190         }
191
192         if (!_osc_server) {
193                 return 1;
194         }
195
196 #ifdef ARDOUR_OSC_UNIX_SERVER
197
198         // APPEARS sluggish for now
199
200         // attempt to create unix socket server too
201
202         snprintf(tmpstr, sizeof(tmpstr), "/tmp/sooperlooper_XXXXXX");
203         int fd = mkstemp(tmpstr);
204
205         if (fd >= 0 ) {
206                 ::g_unlink (tmpstr);
207                 close (fd);
208
209                 _osc_unix_server = lo_server_new (tmpstr, error_callback);
210
211                 if (_osc_unix_server) {
212                         _osc_unix_socket_path = tmpstr;
213                 }
214         }
215 #endif
216
217         PBD::info << "OSC @ " << get_server_url () << endmsg;
218
219         std::string url_file;
220
221         if (find_file (ardour_config_search_path(), "osc_url", url_file)) {
222                 _osc_url_file = url_file;
223                 if (g_file_set_contents (_osc_url_file.c_str(), get_server_url().c_str(), -1, NULL)) {
224                         cerr << "Couldn't write '" <<  _osc_url_file << "'" <<endl;
225                 }
226         }
227
228         register_callbacks();
229
230         // lo_server_thread_add_method(_sthread, NULL, NULL, OSC::_dummy_handler, this);
231
232         /* startup the event loop thread */
233
234         BaseUI::run ();
235
236         return 0;
237 }
238
239 void
240 OSC::thread_init ()
241 {
242         pthread_set_name (event_loop_name().c_str());
243
244         if (_osc_unix_server) {
245                 Glib::RefPtr<IOSource> src = IOSource::create (lo_server_get_socket_fd (_osc_unix_server), IO_IN|IO_HUP|IO_ERR);
246                 src->connect (sigc::bind (sigc::mem_fun (*this, &OSC::osc_input_handler), _osc_unix_server));
247                 src->attach (_main_loop->get_context());
248                 local_server = src->gobj();
249                 g_source_ref (local_server);
250         }
251
252         if (_osc_server) {
253                 Glib::RefPtr<IOSource> src  = IOSource::create (lo_server_get_socket_fd (_osc_server), IO_IN|IO_HUP|IO_ERR);
254                 src->connect (sigc::bind (sigc::mem_fun (*this, &OSC::osc_input_handler), _osc_server));
255                 src->attach (_main_loop->get_context());
256                 remote_server = src->gobj();
257                 g_source_ref (remote_server);
258         }
259
260         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
261         SessionEvent::create_per_thread_pool (event_loop_name(), 128);
262 }
263
264 int
265 OSC::stop ()
266 {
267         /* stop main loop */
268
269         if (local_server) {
270                 g_source_destroy (local_server);
271                 g_source_unref (local_server);
272                 local_server = 0;
273         }
274
275         if (remote_server) {
276                 g_source_destroy (remote_server);
277                 g_source_unref (remote_server);
278                 remote_server = 0;
279         }
280
281         BaseUI::quit ();
282
283         if (_osc_server) {
284                 lo_server_free (_osc_server);
285                 _osc_server = 0;
286         }
287
288         if (_osc_unix_server) {
289                 lo_server_free (_osc_unix_server);
290                 _osc_unix_server = 0;
291         }
292
293         if (!_osc_unix_socket_path.empty()) {
294                 ::g_unlink (_osc_unix_socket_path.c_str());
295         }
296
297         if (!_osc_url_file.empty() ) {
298                 ::g_unlink (_osc_url_file.c_str() );
299         }
300
301         // Delete any active route observers
302         for (RouteObservers::iterator x = route_observers.begin(); x != route_observers.end();) {
303
304                 OSCRouteObserver* rc;
305
306                 if ((rc = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
307                         delete *x;
308                         x = route_observers.erase (x);
309                 } else {
310                         ++x;
311                 }
312         }
313
314         return 0;
315 }
316
317 void
318 OSC::register_callbacks()
319 {
320         lo_server srvs[2];
321         lo_server serv;
322
323         srvs[0] = _osc_server;
324         srvs[1] = _osc_unix_server;
325
326         for (size_t i = 0; i < 2; ++i) {
327
328                 if (!srvs[i]) {
329                         continue;
330                 }
331
332                 serv = srvs[i];
333
334
335 #define REGISTER_CALLBACK(serv,path,types, function) lo_server_add_method (serv, path, types, OSC::_ ## function, this)
336
337                 REGISTER_CALLBACK (serv, "/routes/list", "", routes_list);
338                 REGISTER_CALLBACK (serv, "/ardour/add_marker", "", add_marker);
339                 REGISTER_CALLBACK (serv, "/ardour/access_action", "s", access_action);
340                 REGISTER_CALLBACK (serv, "/ardour/loop_toggle", "", loop_toggle);
341                 REGISTER_CALLBACK (serv, "/ardour/loop_location", "ii", loop_location);
342                 REGISTER_CALLBACK (serv, "/ardour/goto_start", "", goto_start);
343                 REGISTER_CALLBACK (serv, "/ardour/goto_end", "", goto_end);
344                 REGISTER_CALLBACK (serv, "/ardour/rewind", "", rewind);
345                 REGISTER_CALLBACK (serv, "/ardour/ffwd", "", ffwd);
346                 REGISTER_CALLBACK (serv, "/ardour/transport_stop", "", transport_stop);
347                 REGISTER_CALLBACK (serv, "/ardour/transport_play", "", transport_play);
348                 REGISTER_CALLBACK (serv, "/ardour/transport_frame", "", transport_frame);
349                 REGISTER_CALLBACK (serv, "/ardour/transport_speed", "", transport_speed);
350                 REGISTER_CALLBACK (serv, "/ardour/record_enabled", "", record_enabled);
351                 REGISTER_CALLBACK (serv, "/ardour/set_transport_speed", "f", set_transport_speed);
352                 REGISTER_CALLBACK (serv, "/ardour/locate", "ii", locate);
353                 REGISTER_CALLBACK (serv, "/ardour/save_state", "", save_state);
354                 REGISTER_CALLBACK (serv, "/ardour/prev_marker", "", prev_marker);
355                 REGISTER_CALLBACK (serv, "/ardour/next_marker", "", next_marker);
356                 REGISTER_CALLBACK (serv, "/ardour/undo", "", undo);
357                 REGISTER_CALLBACK (serv, "/ardour/redo", "", redo);
358                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_in", "", toggle_punch_in);
359                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_out", "", toggle_punch_out);
360                 REGISTER_CALLBACK (serv, "/ardour/rec_enable_toggle", "", rec_enable_toggle);
361                 REGISTER_CALLBACK (serv, "/ardour/toggle_all_rec_enables", "", toggle_all_rec_enables);
362
363                 /*
364                  * NOTE: these messages are provided for (arguably broken) apps
365                  *   that MUST send float args ( TouchOSC and Lemur ).
366                  * Normally these ardour transport messages don't require an argument,
367                  * so we're providing redundant calls with vestigial "float" args.
368                  *
369                  * These controls are active on 1.0 only (to prevent duplicate action on
370                  * press "/button 1", and release "/button 0")
371                  * http://hexler.net/docs/touchosc-controls-reference
372                  */
373                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/loop_toggle", "f", loop_toggle);
374                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/add_marker", "f", add_marker);
375                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/goto_start", "f", goto_start);
376                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/goto_end", "f", goto_end);
377                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/rewind", "f", rewind);
378                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/ffwd", "f", ffwd);
379                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/transport_stop", "f", transport_stop);
380                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/transport_play", "f", transport_play);
381                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/save_state", "f", save_state);
382                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/prev_marker", "f", prev_marker);
383                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/next_marker", "f", next_marker);
384                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/undo", "f", undo);
385                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/redo", "f", redo);
386                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_punch_in", "f", toggle_punch_in);
387                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_punch_out", "f", toggle_punch_out);
388                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/rec_enable_toggle", "f", rec_enable_toggle);
389                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_all_rec_enables", "f", toggle_all_rec_enables);
390
391                 REGISTER_CALLBACK (serv, "/ardour/routes/mute", "ii", route_mute);
392                 REGISTER_CALLBACK (serv, "/ardour/routes/solo", "ii", route_solo);
393                 REGISTER_CALLBACK (serv, "/ardour/routes/recenable", "ii", route_recenable);
394                 REGISTER_CALLBACK (serv, "/ardour/routes/gainabs", "if", route_set_gain_abs);
395                 REGISTER_CALLBACK (serv, "/ardour/routes/gaindB", "if", route_set_gain_dB);
396                 REGISTER_CALLBACK (serv, "/ardour/routes/trimabs", "if", route_set_trim_abs);
397                 REGISTER_CALLBACK (serv, "/ardour/routes/trimdB", "if", route_set_trim_dB);
398                 REGISTER_CALLBACK (serv, "/ardour/routes/pan_stereo_position", "if", route_set_pan_stereo_position);
399                 REGISTER_CALLBACK (serv, "/ardour/routes/pan_stereo_width", "if", route_set_pan_stereo_width);
400                 REGISTER_CALLBACK (serv, "/ardour/routes/plugin/parameter", "iiif", route_plugin_parameter);
401                 REGISTER_CALLBACK (serv, "/ardour/routes/plugin/parameter/print", "iii", route_plugin_parameter_print);
402                 REGISTER_CALLBACK (serv, "/ardour/routes/send/gainabs", "iif", route_set_send_gain_abs);
403                 REGISTER_CALLBACK (serv, "/ardour/routes/send/gaindB", "iif", route_set_send_gain_dB);
404
405                 /* still not-really-standardized query interface */
406                 //REGISTER_CALLBACK (serv, "/ardour/*/#current_value", "", current_value);
407                 //REGISTER_CALLBACK (serv, "/ardour/set", "", set);
408
409                 // un/register_update args= s:ctrl s:returl s:retpath
410                 //lo_server_add_method(serv, "/register_update", "sss", OSC::global_register_update_handler, this);
411                 //lo_server_add_method(serv, "/unregister_update", "sss", OSC::global_unregister_update_handler, this);
412                 //lo_server_add_method(serv, "/register_auto_update", "siss", OSC::global_register_auto_update_handler, this);
413                 //lo_server_add_method(serv, "/unregister_auto_update", "sss", OSC::_global_unregister_auto_update_handler, this);
414
415                 /* this is a special catchall handler,
416                  * register at the end so this is only called if no
417                  * other handler matches (used for debug) */
418                 lo_server_add_method (serv, 0, 0, _catchall, this);
419         }
420 }
421
422 bool
423 OSC::osc_input_handler (IOCondition ioc, lo_server srv)
424 {
425         if (ioc & ~IO_IN) {
426                 return false;
427         }
428
429         if (ioc & IO_IN) {
430                 lo_server_recv (srv);
431         }
432
433         return true;
434 }
435
436 std::string
437 OSC::get_server_url()
438 {
439         string url;
440         char * urlstr;
441
442         if (_osc_server) {
443                 urlstr = lo_server_get_url (_osc_server);
444                 url = urlstr;
445                 free (urlstr);
446         }
447
448         return url;
449 }
450
451 std::string
452 OSC::get_unix_server_url()
453 {
454         string url;
455         char * urlstr;
456
457         if (_osc_unix_server) {
458                 urlstr = lo_server_get_url (_osc_unix_server);
459                 url = urlstr;
460                 free (urlstr);
461         }
462
463         return url;
464 }
465
466 void
467 OSC::listen_to_route (boost::shared_ptr<Route> route, lo_address addr)
468 {
469         /* avoid duplicate listens */
470
471         for (RouteObservers::iterator x = route_observers.begin(); x != route_observers.end(); ++x) {
472
473                 OSCRouteObserver* ro;
474
475                 if ((ro = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
476
477                         int res = strcmp(lo_address_get_hostname(ro->address()), lo_address_get_hostname(addr));
478
479                         if (ro->route() == route && res == 0) {
480                                 return;
481                         }
482                 }
483         }
484
485         OSCRouteObserver* o = new OSCRouteObserver (route, addr);
486         route_observers.push_back (o);
487
488         route->DropReferences.connect (*this, MISSING_INVALIDATOR, boost::bind (&OSC::drop_route, this, boost::weak_ptr<Route> (route)), this);
489 }
490
491 void
492 OSC::drop_route (boost::weak_ptr<Route> wr)
493 {
494         boost::shared_ptr<Route> r = wr.lock ();
495
496         if (!r) {
497                 return;
498         }
499
500         for (RouteObservers::iterator x = route_observers.begin(); x != route_observers.end();) {
501
502                 OSCRouteObserver* rc;
503
504                 if ((rc = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
505
506                         if (rc->route() == r) {
507                                 delete *x;
508                                 x = route_observers.erase (x);
509                         } else {
510                                 ++x;
511                         }
512                 } else {
513                         ++x;
514                 }
515         }
516 }
517
518 void
519 OSC::end_listen (boost::shared_ptr<Route> r, lo_address addr)
520 {
521         RouteObservers::iterator x;
522
523         // Remove the route observers
524         for (x = route_observers.begin(); x != route_observers.end();) {
525
526                 OSCRouteObserver* ro;
527
528                 if ((ro = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
529
530                         int res = strcmp(lo_address_get_hostname(ro->address()), lo_address_get_hostname(addr));
531
532                         if (ro->route() == r && res == 0) {
533                                 delete *x;
534                                 x = route_observers.erase (x);
535                         }
536                         else {
537                                 ++x;
538                         }
539                 }
540                 else {
541                         ++x;
542                 }
543         }
544 }
545
546 void
547 OSC::current_value_query (const char* path, size_t len, lo_arg **argv, int argc, lo_message msg)
548 {
549         char* subpath;
550
551         subpath = (char*) malloc (len-15+1);
552         memcpy (subpath, path, len-15);
553         subpath[len-15] = '\0';
554
555         send_current_value (subpath, argv, argc, msg);
556
557         free (subpath);
558 }
559
560 void
561 OSC::send_current_value (const char* path, lo_arg** argv, int argc, lo_message msg)
562 {
563         if (!session) {
564                 return;
565         }
566
567         lo_message reply = lo_message_new ();
568         boost::shared_ptr<Route> r;
569         int id;
570
571         lo_message_add_string (reply, path);
572
573         if (argc == 0) {
574                 lo_message_add_string (reply, "bad syntax");
575         } else {
576                 id = argv[0]->i;
577                 r = session->route_by_remote_id (id);
578
579                 if (!r) {
580                         lo_message_add_string (reply, "not found");
581                 } else {
582
583                         if (strcmp (path, "/routes/state") == 0) {
584
585                                 if (boost::dynamic_pointer_cast<AudioTrack>(r)) {
586                                         lo_message_add_string (reply, "AT");
587                                 } else if (boost::dynamic_pointer_cast<MidiTrack>(r)) {
588                                         lo_message_add_string (reply, "MT");
589                                 } else {
590                                         lo_message_add_string (reply, "B");
591                                 }
592
593                                 lo_message_add_string (reply, r->name().c_str());
594                                 lo_message_add_int32 (reply, r->n_inputs().n_audio());
595                                 lo_message_add_int32 (reply, r->n_outputs().n_audio());
596                                 lo_message_add_int32 (reply, r->muted());
597                                 lo_message_add_int32 (reply, r->soloed());
598
599                         } else if (strcmp (path, "/routes/mute") == 0) {
600
601                                 lo_message_add_int32 (reply, (float) r->muted());
602
603                         } else if (strcmp (path, "/routes/solo") == 0) {
604
605                                 lo_message_add_int32 (reply, r->soloed());
606                         }
607                 }
608         }
609
610         lo_send_message (lo_message_get_source (msg), "#reply", reply);
611         lo_message_free (reply);
612 }
613
614 int
615 OSC::_catchall (const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data)
616 {
617         return ((OSC*)user_data)->catchall (path, types, argv, argc, data);
618 }
619
620 int
621 OSC::catchall (const char *path, const char* types, lo_arg **argv, int argc, lo_message msg)
622 {
623         size_t len;
624         int ret = 1; /* unhandled */
625
626         //cerr << "Received a message, path = " << path << " types = \""
627         //     << (types ? types : "NULL") << '"' << endl;
628
629         /* 15 for /#current_value plus 2 for /<path> */
630
631         len = strlen (path);
632
633         if (len >= 17 && !strcmp (&path[len-15], "/#current_value")) {
634                 current_value_query (path, len, argv, argc, msg);
635                 ret = 0;
636
637         } else if (strcmp (path, "/routes/listen") == 0) {
638
639                 cerr << "set up listener\n";
640
641                 lo_message reply = lo_message_new ();
642
643                 if (argc <= 0) {
644                         lo_message_add_string (reply, "syntax error");
645                 } else {
646                         for (int n = 0; n < argc; ++n) {
647
648                                 boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
649
650                                 if (!r) {
651                                         lo_message_add_string (reply, "not found");
652                                         cerr << "no such route\n";
653                                         break;
654                                 } else {
655                                         cerr << "add listener\n";
656                                         listen_to_route (r, lo_message_get_source (msg));
657                                         lo_message_add_int32 (reply, argv[n]->i);
658                                 }
659                         }
660                 }
661
662                 lo_send_message (lo_message_get_source (msg), "#reply", reply);
663                 lo_message_free (reply);
664
665                 ret = 0;
666
667         } else if (strcmp (path, "/routes/ignore") == 0) {
668
669                 for (int n = 0; n < argc; ++n) {
670
671                         boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
672
673                         if (r) {
674                                 end_listen (r, lo_message_get_source (msg));
675                         }
676                 }
677
678                 ret = 0;
679         } else if (argc == 1 && types[0] == 'f') { // single float -- probably TouchOSC
680                 if (!strncmp (path, "/ardour/routes/gainabs/", 23) && strlen (path) > 23) {
681                         int rid = atoi (&path[23]);
682                         // use some power-scale mapping??
683                         route_set_gain_abs (rid, argv[0]->f);
684                         ret = 0;
685                 }
686                 else if (!strncmp (path, "/ardour/routes/trimabs/", 23) && strlen (path) > 23) {
687                         int rid = atoi (&path[23]);
688                         // normalize 0..1 ?
689                         route_set_trim_abs (rid, argv[0]->f);
690                         ret = 0;
691                 }
692                 else if (!strncmp (path, "/ardour/routes/mute/", 20) && strlen (path) > 20) {
693                         int rid = atoi (&path[20]);
694                         route_mute (rid, argv[0]->f == 1.0);
695                         ret = 0;
696                 }
697                 else if (!strncmp (path, "/ardour/routes/solo/", 20) && strlen (path) > 20) {
698                         int rid = atoi (&path[20]);
699                         route_solo (rid, argv[0]->f == 1.0);
700                         ret = 0;
701                 }
702                 else if (!strncmp (path, "/ardour/routes/recenable/", 25) && strlen (path) > 25) {
703                         int rid = atoi (&path[25]);
704                         route_recenable (rid, argv[0]->f == 1.0);
705                         ret = 0;
706                 }
707         }
708
709         if ((ret && _debugmode == Unhandled)) {
710                 debugmsg (_("Unhandled OSC message"), path, types, argv, argc);
711         }
712
713         return ret;
714 }
715
716 void
717 OSC::debugmsg (const char *prefix, const char *path, const char* types, lo_arg **argv, int argc)
718 {
719         std::stringstream ss;
720         for (int i = 0; i < argc; ++i) {
721                 lo_type type = (lo_type)types[i];
722                         ss << " ";
723                 switch (type) {
724                         case LO_INT32:
725                                 ss << "i:" << argv[i]->i;
726                                 break;
727                         case LO_FLOAT:
728                                 ss << "f:" << argv[i]->f;
729                                 break;
730                         case LO_DOUBLE:
731                                 ss << "d:" << argv[i]->d;
732                                 break;
733                         case LO_STRING:
734                                 ss << "s:" << &argv[i]->s;
735                                 break;
736                         case LO_INT64:
737                                 ss << "h:" << argv[i]->h;
738                                 break;
739                         case LO_CHAR:
740                                 ss << "c:" << argv[i]->s;
741                                 break;
742                         case LO_TIMETAG:
743                                 ss << "<Timetag>";
744                                 break;
745                         case LO_BLOB:
746                                 ss << "<BLOB>";
747                                 break;
748                         case LO_TRUE:
749                                 ss << "#T";
750                                 break;
751                         case LO_FALSE:
752                                 ss << "#F";
753                                 break;
754                         case LO_NIL:
755                                 ss << "NIL";
756                                 break;
757                         case LO_INFINITUM:
758                                 ss << "#inf";
759                                 break;
760                         case LO_MIDI:
761                                 ss << "<MIDI>";
762                                 break;
763                         case LO_SYMBOL:
764                                 ss << "<SYMBOL>";
765                                 break;
766                         default:
767                                 ss << "< ?? >";
768                                 break;
769                 }
770         }
771         PBD::info << prefix << ": " << path << ss.str() << endmsg;
772 }
773
774 void
775 OSC::update_clock ()
776 {
777
778 }
779
780 // "Application Hook" Handlers //
781 void
782 OSC::session_loaded (Session& s)
783 {
784         lo_address listener = lo_address_new (NULL, "7770");
785         lo_send (listener, "/session/loaded", "ss", s.path().c_str(), s.name().c_str());
786 }
787
788 void
789 OSC::session_exported (std::string path, std::string name)
790 {
791         lo_address listener = lo_address_new (NULL, "7770");
792         lo_send (listener, "/session/exported", "ss", path.c_str(), name.c_str());
793 }
794
795 // end "Application Hook" Handlers //
796
797 /* path callbacks */
798
799 int
800 OSC::current_value (const char */*path*/, const char */*types*/, lo_arg **/*argv*/, int /*argc*/, void */*data*/, void* /*user_data*/)
801 {
802 #if 0
803         const char* returl;
804
805         if (argc < 3 || types == 0 || strlen (types) < 3 || types[0] != 's' || types[1] != 's' || types[2] != s) {
806                 return 1;
807         }
808
809         const char *returl = argv[1]->s;
810         lo_address addr = find_or_cache_addr (returl);
811
812         const char *retpath = argv[2]->s;
813
814
815         if (strcmp (argv[0]->s, "transport_frame") == 0) {
816
817                 if (session) {
818                         lo_send (addr, retpath, "i", session->transport_frame());
819                 }
820
821         } else if (strcmp (argv[0]->s, "transport_speed") == 0) {
822
823                 if (session) {
824                         lo_send (addr, retpath, "i", session->transport_frame());
825                 }
826
827         } else if (strcmp (argv[0]->s, "transport_locked") == 0) {
828
829                 if (session) {
830                         lo_send (addr, retpath, "i", session->transport_frame());
831                 }
832
833         } else if (strcmp (argv[0]->s, "punch_in") == 0) {
834
835                 if (session) {
836                         lo_send (addr, retpath, "i", session->transport_frame());
837                 }
838
839         } else if (strcmp (argv[0]->s, "punch_out") == 0) {
840
841                 if (session) {
842                         lo_send (addr, retpath, "i", session->transport_frame());
843                 }
844
845         } else if (strcmp (argv[0]->s, "rec_enable") == 0) {
846
847                 if (session) {
848                         lo_send (addr, retpath, "i", session->transport_frame());
849                 }
850
851         } else {
852
853                 /* error */
854         }
855 #endif
856         return 0;
857 }
858
859 void
860 OSC::routes_list (lo_message msg)
861 {
862         if (!session) {
863                 return;
864         }
865         for (int n = 0; n < (int) session->nroutes(); ++n) {
866
867                 boost::shared_ptr<Route> r = session->route_by_remote_id (n);
868
869                 if (r) {
870
871                         lo_message reply = lo_message_new ();
872
873                         if (boost::dynamic_pointer_cast<AudioTrack>(r)) {
874                                 lo_message_add_string (reply, "AT");
875                         } else if (boost::dynamic_pointer_cast<MidiTrack>(r)) {
876                                 lo_message_add_string (reply, "MT");
877                         } else {
878                                 lo_message_add_string (reply, "B");
879                         }
880
881                         lo_message_add_string (reply, r->name().c_str());
882                         lo_message_add_int32 (reply, r->n_inputs().n_audio());
883                         lo_message_add_int32 (reply, r->n_outputs().n_audio());
884                         lo_message_add_int32 (reply, r->muted());
885                         lo_message_add_int32 (reply, r->soloed());
886                         lo_message_add_int32 (reply, r->remote_control_id());
887
888                         if (boost::dynamic_pointer_cast<AudioTrack>(r)
889                                         || boost::dynamic_pointer_cast<MidiTrack>(r)) {
890
891                                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track>(r);
892                                 lo_message_add_int32 (reply, t->record_enabled());
893                         }
894
895                         //Automatically listen to routes listed
896                         listen_to_route(r, lo_message_get_source (msg));
897
898                         lo_send_message (lo_message_get_source (msg), "#reply", reply);
899                         lo_message_free (reply);
900                 }
901         }
902
903         // Send end of listing message
904         lo_message reply = lo_message_new ();
905
906         lo_message_add_string (reply, "end_route_list");
907         lo_message_add_int64 (reply, session->frame_rate());
908         lo_message_add_int64 (reply, session->current_end_frame());
909
910         lo_send_message (lo_message_get_source (msg), "#reply", reply);
911
912         lo_message_free (reply);
913 }
914
915 void
916 OSC::transport_frame (lo_message msg)
917 {
918         if (!session) {
919                 return;
920         }
921         framepos_t pos = session->transport_frame ();
922
923         lo_message reply = lo_message_new ();
924         lo_message_add_int64 (reply, pos);
925
926         lo_send_message (lo_message_get_source (msg), "/ardour/transport_frame", reply);
927
928         lo_message_free (reply);
929 }
930
931 void
932 OSC::transport_speed (lo_message msg)
933 {
934         if (!session) {
935                 return;
936         }
937         double ts = session->transport_speed ();
938
939         lo_message reply = lo_message_new ();
940         lo_message_add_double (reply, ts);
941
942         lo_send_message (lo_message_get_source (msg), "/ardour/transport_speed", reply);
943
944         lo_message_free (reply);
945 }
946
947 void
948 OSC::record_enabled (lo_message msg)
949 {
950         if (!session) {
951                 return;
952         }
953         int re = (int)session->get_record_enabled ();
954
955         lo_message reply = lo_message_new ();
956         lo_message_add_int32 (reply, re);
957
958         lo_send_message (lo_message_get_source (msg), "/ardour/record_enabled", reply);
959
960         lo_message_free (reply);
961 }
962
963
964 int
965 OSC::route_mute (int rid, int yn)
966 {
967         if (!session) return -1;
968
969         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
970
971         if (r) {
972                 r->set_mute (yn, this);
973         }
974
975         return 0;
976 }
977
978 int
979 OSC::route_solo (int rid, int yn)
980 {
981         if (!session) return -1;
982
983         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
984
985         if (r) {
986                 boost::shared_ptr<RouteList> rl (new RouteList);
987                 rl->push_back (r);
988                 session->set_solo (rl, yn);
989         }
990
991         return 0;
992 }
993
994 int
995 OSC::route_recenable (int rid, int yn)
996 {
997         if (!session) return -1;
998
999         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1000
1001         if (r) {
1002                 r->set_record_enabled (yn, this);
1003         }
1004
1005         return 0;
1006 }
1007
1008 int
1009 OSC::route_set_gain_abs (int rid, float level)
1010 {
1011         if (!session) return -1;
1012
1013         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1014
1015         if (r) {
1016                 r->set_gain (level, this);
1017         }
1018
1019         return 0;
1020 }
1021
1022 int
1023 OSC::route_set_gain_dB (int rid, float dB)
1024 {
1025         return route_set_gain_abs (rid, dB_to_coefficient (dB));
1026 }
1027
1028
1029 int
1030 OSC::route_set_trim_abs (int rid, float level)
1031 {
1032         if (!session) return -1;
1033
1034         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1035
1036         if (r) {
1037                 r->set_trim (level, this);
1038         }
1039
1040         return 0;
1041 }
1042
1043 int
1044 OSC::route_set_trim_dB (int rid, float dB)
1045 {
1046         return route_set_trim_abs(rid, dB_to_coefficient (dB));
1047 }
1048
1049
1050 int
1051 OSC::route_set_pan_stereo_position (int rid, float pos)
1052 {
1053         if (!session) return -1;
1054
1055         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1056
1057         if (r) {
1058                 boost::shared_ptr<Panner> panner = r->panner();
1059                 if (panner) {
1060                         panner->set_position (pos);
1061                 }
1062         }
1063
1064         return 0;
1065
1066 }
1067
1068 int
1069 OSC::route_set_pan_stereo_width (int rid, float pos)
1070 {
1071         if (!session) return -1;
1072
1073         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1074
1075         if (r) {
1076                 boost::shared_ptr<Panner> panner = r->panner();
1077                 if (panner) {
1078                         panner->set_width (pos);
1079                 }
1080         }
1081
1082         return 0;
1083
1084 }
1085
1086 int
1087 OSC::route_set_send_gain_abs (int rid, int sid, float val)
1088 {
1089         if (!session) {
1090                 return -1;
1091         }
1092
1093         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1094
1095         if (!r) {
1096                 return -1;
1097         }
1098
1099         /* revert to zero-based counting */
1100
1101         if (sid > 0) {
1102                 --sid;
1103         }
1104
1105         boost::shared_ptr<Processor> p = r->nth_send (sid);
1106
1107         if (p) {
1108                 boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(p);
1109                 boost::shared_ptr<Amp> a = s->amp();
1110
1111                 if (a) {
1112                         a->gain_control()->set_value (val, PBD::Controllable::NoGroup);
1113                 }
1114         }
1115         return 0;
1116 }
1117
1118 int
1119 OSC::route_set_send_gain_dB (int rid, int sid, float val)
1120 {
1121         if (!session) {
1122                 return -1;
1123         }
1124
1125         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1126
1127         if (!r) {
1128                 return -1;
1129         }
1130
1131         /* revert to zero-based counting */
1132
1133         if (sid > 0) {
1134                 --sid;
1135         }
1136
1137         boost::shared_ptr<Processor> p = r->nth_send (sid);
1138
1139         if (p) {
1140                 boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(p);
1141                 boost::shared_ptr<Amp> a = s->amp();
1142
1143                 if (a) {
1144                         a->gain_control()->set_value (dB_to_coefficient (val), PBD::Controllable::NoGroup);
1145                 }
1146         }
1147         return 0;
1148 }
1149
1150 int
1151 OSC::route_plugin_parameter (int rid, int piid, int par, float val)
1152 {
1153         if (!session)
1154                 return -1;
1155
1156         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1157
1158         if (!r) {
1159                 PBD::error << "OSC: Invalid Remote Control ID '" << rid << "'" << endmsg;
1160                 return -1;
1161         }
1162
1163         boost::shared_ptr<Processor> redi=r->nth_plugin (piid);
1164
1165         if (!redi) {
1166                 PBD::error << "OSC: cannot find plugin # " << piid << " for RID '" << rid << "'" << endmsg;
1167                 return -1;
1168         }
1169
1170         boost::shared_ptr<PluginInsert> pi;
1171
1172         if (!(pi = boost::dynamic_pointer_cast<PluginInsert>(redi))) {
1173                 PBD::error << "OSC: given processor # " << piid << " on RID '" << rid << "' is not a Plugin." << endmsg;
1174                 return -1;
1175         }
1176
1177         boost::shared_ptr<ARDOUR::Plugin> pip = pi->plugin();
1178         bool ok=false;
1179
1180         uint32_t controlid = pip->nth_parameter (par,ok);
1181
1182         if (!ok) {
1183                 PBD::error << "OSC: Cannot find parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "'" << endmsg;
1184                 return -1;
1185         }
1186
1187         if (!pip->parameter_is_input(controlid)) {
1188                 PBD::error << "OSC: Parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "' is not a control input" << endmsg;
1189                 return -1;
1190         }
1191
1192         ParameterDescriptor pd;
1193         pi->plugin()->get_parameter_descriptor (controlid,pd);
1194
1195         if (val >= pd.lower && val < pd.upper) {
1196
1197                 boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
1198                 // cerr << "parameter:" << redi->describe_parameter(controlid) << " val:" << val << "\n";
1199                 c->set_value (val, PBD::Controllable::NoGroup);
1200         } else {
1201                 PBD::warning << "OSC: Parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "' is out of range" << endmsg;
1202                 PBD::info << "OSC: Valid range min=" << pd.lower << " max=" << pd.upper << endmsg;
1203         }
1204
1205         return 0;
1206 }
1207
1208 int
1209 OSC::route_plugin_parameter_print (int rid, int piid, int par)
1210 {
1211         if (!session) {
1212                 return -1;
1213         }
1214
1215         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1216
1217         if (!r) {
1218                 return -1;
1219         }
1220
1221         boost::shared_ptr<Processor> redi=r->nth_processor (piid);
1222
1223         if (!redi) {
1224                 return -1;
1225         }
1226
1227         boost::shared_ptr<PluginInsert> pi;
1228
1229         if (!(pi = boost::dynamic_pointer_cast<PluginInsert>(redi))) {
1230                 return -1;
1231         }
1232
1233         boost::shared_ptr<ARDOUR::Plugin> pip = pi->plugin();
1234         bool ok=false;
1235
1236         uint32_t controlid = pip->nth_parameter (par,ok);
1237
1238         if (!ok) {
1239                 return -1;
1240         }
1241
1242         ParameterDescriptor pd;
1243
1244         if (pi->plugin()->get_parameter_descriptor (controlid, pd) == 0) {
1245                 boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
1246
1247                 cerr << "parameter:     " << redi->describe_parameter(controlid)  << "\n";
1248                 cerr << "current value: " << c->get_value ();
1249                 cerr << "lower value:   " << pd.lower << "\n";
1250                 cerr << "upper value:   " << pd.upper << "\n";
1251         }
1252
1253         return 0;
1254 }
1255
1256 XMLNode&
1257 OSC::get_state ()
1258 {
1259         XMLNode& node (ControlProtocol::get_state());
1260         node.add_property("debugmode", (int) _debugmode); // TODO: enum2str
1261         return node;
1262 }
1263
1264 int
1265 OSC::set_state (const XMLNode& node, int version)
1266 {
1267         if (ControlProtocol::set_state (node, version)) {
1268                 return -1;
1269         }
1270         XMLProperty const * p = node.property (X_("debugmode"));
1271         if (p) {
1272                 _debugmode = OSCDebugMode (PBD::atoi(p->value ()));
1273         }
1274
1275         return 0;
1276 }