implement remover_marker, jump_by_bars, and jump_by_seconds
[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/remove_marker", "", remove_marker_at_playhead);
340                 REGISTER_CALLBACK (serv, "/ardour/access_action", "s", access_action);
341                 REGISTER_CALLBACK (serv, "/ardour/loop_toggle", "", loop_toggle);
342                 REGISTER_CALLBACK (serv, "/ardour/loop_location", "ii", loop_location);
343                 REGISTER_CALLBACK (serv, "/ardour/goto_start", "", goto_start);
344                 REGISTER_CALLBACK (serv, "/ardour/goto_end", "", goto_end);
345                 REGISTER_CALLBACK (serv, "/ardour/rewind", "", rewind);
346                 REGISTER_CALLBACK (serv, "/ardour/ffwd", "", ffwd);
347                 REGISTER_CALLBACK (serv, "/ardour/transport_stop", "", transport_stop);
348                 REGISTER_CALLBACK (serv, "/ardour/transport_play", "", transport_play);
349                 REGISTER_CALLBACK (serv, "/ardour/transport_frame", "", transport_frame);
350                 REGISTER_CALLBACK (serv, "/ardour/transport_speed", "", transport_speed);
351                 REGISTER_CALLBACK (serv, "/ardour/record_enabled", "", record_enabled);
352                 REGISTER_CALLBACK (serv, "/ardour/set_transport_speed", "f", set_transport_speed);
353                 REGISTER_CALLBACK (serv, "/ardour/locate", "ii", locate);
354                 REGISTER_CALLBACK (serv, "/ardour/save_state", "", save_state);
355                 REGISTER_CALLBACK (serv, "/ardour/prev_marker", "", prev_marker);
356                 REGISTER_CALLBACK (serv, "/ardour/next_marker", "", next_marker);
357                 REGISTER_CALLBACK (serv, "/ardour/undo", "", undo);
358                 REGISTER_CALLBACK (serv, "/ardour/redo", "", redo);
359                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_in", "", toggle_punch_in);
360                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_out", "", toggle_punch_out);
361                 REGISTER_CALLBACK (serv, "/ardour/rec_enable_toggle", "", rec_enable_toggle);
362                 REGISTER_CALLBACK (serv, "/ardour/toggle_all_rec_enables", "", toggle_all_rec_enables);
363                 REGISTER_CALLBACK (serv, "/ardour/jump_bars", "f", jump_by_bars);
364                 REGISTER_CALLBACK (serv, "/ardour/jump_seconds", "f", jump_by_seconds);
365
366
367                 /*
368                  * NOTE: these messages are provided for (arguably broken) apps
369                  *   that MUST send float args ( TouchOSC and Lemur ).
370                  * Normally these ardour transport messages don't require an argument,
371                  * so we're providing redundant calls with vestigial "float" args.
372                  *
373                  * These controls are active on 1.0 only (to prevent duplicate action on
374                  * press "/button 1", and release "/button 0")
375                  * http://hexler.net/docs/touchosc-controls-reference
376                  */
377                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/loop_toggle", "f", loop_toggle);
378                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/add_marker", "f", add_marker);
379                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/remove_marker", "f", remove_marker_at_playhead);
380                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/goto_start", "f", goto_start);
381                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/goto_end", "f", goto_end);
382                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/rewind", "f", rewind);
383                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/ffwd", "f", ffwd);
384                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/transport_stop", "f", transport_stop);
385                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/transport_play", "f", transport_play);
386                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/save_state", "f", save_state);
387                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/prev_marker", "f", prev_marker);
388                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/next_marker", "f", next_marker);
389                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/undo", "f", undo);
390                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/redo", "f", redo);
391                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_punch_in", "f", toggle_punch_in);
392                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_punch_out", "f", toggle_punch_out);
393                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/rec_enable_toggle", "f", rec_enable_toggle);
394                 REGISTER_CALLBACK (serv, "/ardour/pushbutton/toggle_all_rec_enables", "f", toggle_all_rec_enables);
395
396                 //ToDo
397 //              REGISTER_CALLBACK (serv, "/ardour/pushbutton/mark_in", "f", mark_in);
398 //              REGISTER_CALLBACK (serv, "/ardour/pushbutton/mark_out", "f", mark_out);
399
400                 REGISTER_CALLBACK (serv, "/ardour/routes/mute", "ii", route_mute);
401                 REGISTER_CALLBACK (serv, "/ardour/routes/solo", "ii", route_solo);
402                 REGISTER_CALLBACK (serv, "/ardour/routes/recenable", "ii", route_recenable);
403                 REGISTER_CALLBACK (serv, "/ardour/routes/gainabs", "if", route_set_gain_abs);
404                 REGISTER_CALLBACK (serv, "/ardour/routes/gaindB", "if", route_set_gain_dB);
405                 REGISTER_CALLBACK (serv, "/ardour/routes/trimabs", "if", route_set_trim_abs);
406                 REGISTER_CALLBACK (serv, "/ardour/routes/trimdB", "if", route_set_trim_dB);
407                 REGISTER_CALLBACK (serv, "/ardour/routes/pan_stereo_position", "if", route_set_pan_stereo_position);
408                 REGISTER_CALLBACK (serv, "/ardour/routes/pan_stereo_width", "if", route_set_pan_stereo_width);
409                 REGISTER_CALLBACK (serv, "/ardour/routes/plugin/parameter", "iiif", route_plugin_parameter);
410                 REGISTER_CALLBACK (serv, "/ardour/routes/plugin/parameter/print", "iii", route_plugin_parameter_print);
411                 REGISTER_CALLBACK (serv, "/ardour/routes/send/gainabs", "iif", route_set_send_gain_abs);
412                 REGISTER_CALLBACK (serv, "/ardour/routes/send/gaindB", "iif", route_set_send_gain_dB);
413
414                 /* still not-really-standardized query interface */
415                 //REGISTER_CALLBACK (serv, "/ardour/*/#current_value", "", current_value);
416                 //REGISTER_CALLBACK (serv, "/ardour/set", "", set);
417
418                 // un/register_update args= s:ctrl s:returl s:retpath
419                 //lo_server_add_method(serv, "/register_update", "sss", OSC::global_register_update_handler, this);
420                 //lo_server_add_method(serv, "/unregister_update", "sss", OSC::global_unregister_update_handler, this);
421                 //lo_server_add_method(serv, "/register_auto_update", "siss", OSC::global_register_auto_update_handler, this);
422                 //lo_server_add_method(serv, "/unregister_auto_update", "sss", OSC::_global_unregister_auto_update_handler, this);
423
424                 /* this is a special catchall handler,
425                  * register at the end so this is only called if no
426                  * other handler matches (used for debug) */
427                 lo_server_add_method (serv, 0, 0, _catchall, this);
428         }
429 }
430
431 bool
432 OSC::osc_input_handler (IOCondition ioc, lo_server srv)
433 {
434         if (ioc & ~IO_IN) {
435                 return false;
436         }
437
438         if (ioc & IO_IN) {
439                 lo_server_recv (srv);
440         }
441
442         return true;
443 }
444
445 std::string
446 OSC::get_server_url()
447 {
448         string url;
449         char * urlstr;
450
451         if (_osc_server) {
452                 urlstr = lo_server_get_url (_osc_server);
453                 url = urlstr;
454                 free (urlstr);
455         }
456
457         return url;
458 }
459
460 std::string
461 OSC::get_unix_server_url()
462 {
463         string url;
464         char * urlstr;
465
466         if (_osc_unix_server) {
467                 urlstr = lo_server_get_url (_osc_unix_server);
468                 url = urlstr;
469                 free (urlstr);
470         }
471
472         return url;
473 }
474
475 void
476 OSC::listen_to_route (boost::shared_ptr<Route> route, lo_address addr)
477 {
478         /* avoid duplicate listens */
479
480         for (RouteObservers::iterator x = route_observers.begin(); x != route_observers.end(); ++x) {
481
482                 OSCRouteObserver* ro;
483
484                 if ((ro = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
485
486                         int res = strcmp(lo_address_get_hostname(ro->address()), lo_address_get_hostname(addr));
487
488                         if (ro->route() == route && res == 0) {
489                                 return;
490                         }
491                 }
492         }
493
494         OSCRouteObserver* o = new OSCRouteObserver (route, addr);
495         route_observers.push_back (o);
496
497         route->DropReferences.connect (*this, MISSING_INVALIDATOR, boost::bind (&OSC::drop_route, this, boost::weak_ptr<Route> (route)), this);
498 }
499
500 void
501 OSC::drop_route (boost::weak_ptr<Route> wr)
502 {
503         boost::shared_ptr<Route> r = wr.lock ();
504
505         if (!r) {
506                 return;
507         }
508
509         for (RouteObservers::iterator x = route_observers.begin(); x != route_observers.end();) {
510
511                 OSCRouteObserver* rc;
512
513                 if ((rc = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
514
515                         if (rc->route() == r) {
516                                 delete *x;
517                                 x = route_observers.erase (x);
518                         } else {
519                                 ++x;
520                         }
521                 } else {
522                         ++x;
523                 }
524         }
525 }
526
527 void
528 OSC::end_listen (boost::shared_ptr<Route> r, lo_address addr)
529 {
530         RouteObservers::iterator x;
531
532         // Remove the route observers
533         for (x = route_observers.begin(); x != route_observers.end();) {
534
535                 OSCRouteObserver* ro;
536
537                 if ((ro = dynamic_cast<OSCRouteObserver*>(*x)) != 0) {
538
539                         int res = strcmp(lo_address_get_hostname(ro->address()), lo_address_get_hostname(addr));
540
541                         if (ro->route() == r && res == 0) {
542                                 delete *x;
543                                 x = route_observers.erase (x);
544                         }
545                         else {
546                                 ++x;
547                         }
548                 }
549                 else {
550                         ++x;
551                 }
552         }
553 }
554
555 void
556 OSC::current_value_query (const char* path, size_t len, lo_arg **argv, int argc, lo_message msg)
557 {
558         char* subpath;
559
560         subpath = (char*) malloc (len-15+1);
561         memcpy (subpath, path, len-15);
562         subpath[len-15] = '\0';
563
564         send_current_value (subpath, argv, argc, msg);
565
566         free (subpath);
567 }
568
569 void
570 OSC::send_current_value (const char* path, lo_arg** argv, int argc, lo_message msg)
571 {
572         if (!session) {
573                 return;
574         }
575
576         lo_message reply = lo_message_new ();
577         boost::shared_ptr<Route> r;
578         int id;
579
580         lo_message_add_string (reply, path);
581
582         if (argc == 0) {
583                 lo_message_add_string (reply, "bad syntax");
584         } else {
585                 id = argv[0]->i;
586                 r = session->route_by_remote_id (id);
587
588                 if (!r) {
589                         lo_message_add_string (reply, "not found");
590                 } else {
591
592                         if (strcmp (path, "/routes/state") == 0) {
593
594                                 if (boost::dynamic_pointer_cast<AudioTrack>(r)) {
595                                         lo_message_add_string (reply, "AT");
596                                 } else if (boost::dynamic_pointer_cast<MidiTrack>(r)) {
597                                         lo_message_add_string (reply, "MT");
598                                 } else {
599                                         lo_message_add_string (reply, "B");
600                                 }
601
602                                 lo_message_add_string (reply, r->name().c_str());
603                                 lo_message_add_int32 (reply, r->n_inputs().n_audio());
604                                 lo_message_add_int32 (reply, r->n_outputs().n_audio());
605                                 lo_message_add_int32 (reply, r->muted());
606                                 lo_message_add_int32 (reply, r->soloed());
607
608                         } else if (strcmp (path, "/routes/mute") == 0) {
609
610                                 lo_message_add_int32 (reply, (float) r->muted());
611
612                         } else if (strcmp (path, "/routes/solo") == 0) {
613
614                                 lo_message_add_int32 (reply, r->soloed());
615                         }
616                 }
617         }
618
619         lo_send_message (lo_message_get_source (msg), "#reply", reply);
620         lo_message_free (reply);
621 }
622
623 int
624 OSC::_catchall (const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data)
625 {
626         return ((OSC*)user_data)->catchall (path, types, argv, argc, data);
627 }
628
629 int
630 OSC::catchall (const char *path, const char* types, lo_arg **argv, int argc, lo_message msg)
631 {
632         size_t len;
633         int ret = 1; /* unhandled */
634
635         //cerr << "Received a message, path = " << path << " types = \""
636         //     << (types ? types : "NULL") << '"' << endl;
637
638         /* 15 for /#current_value plus 2 for /<path> */
639
640         len = strlen (path);
641
642         if (len >= 17 && !strcmp (&path[len-15], "/#current_value")) {
643                 current_value_query (path, len, argv, argc, msg);
644                 ret = 0;
645
646         } else if (strcmp (path, "/routes/listen") == 0) {
647
648                 cerr << "set up listener\n";
649
650                 lo_message reply = lo_message_new ();
651
652                 if (argc <= 0) {
653                         lo_message_add_string (reply, "syntax error");
654                 } else {
655                         for (int n = 0; n < argc; ++n) {
656
657                                 boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
658
659                                 if (!r) {
660                                         lo_message_add_string (reply, "not found");
661                                         cerr << "no such route\n";
662                                         break;
663                                 } else {
664                                         cerr << "add listener\n";
665                                         listen_to_route (r, lo_message_get_source (msg));
666                                         lo_message_add_int32 (reply, argv[n]->i);
667                                 }
668                         }
669                 }
670
671                 lo_send_message (lo_message_get_source (msg), "#reply", reply);
672                 lo_message_free (reply);
673
674                 ret = 0;
675
676         } else if (strcmp (path, "/routes/ignore") == 0) {
677
678                 for (int n = 0; n < argc; ++n) {
679
680                         boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
681
682                         if (r) {
683                                 end_listen (r, lo_message_get_source (msg));
684                         }
685                 }
686
687                 ret = 0;
688         } else if (argc == 1 && types[0] == 'f') { // single float -- probably TouchOSC
689                 if (!strncmp (path, "/ardour/routes/gainabs/", 23) && strlen (path) > 23) {
690                         int rid = atoi (&path[23]);
691                         // use some power-scale mapping??
692                         route_set_gain_abs (rid, argv[0]->f);
693                         ret = 0;
694                 }
695                 else if (!strncmp (path, "/ardour/routes/trimabs/", 23) && strlen (path) > 23) {
696                         int rid = atoi (&path[23]);
697                         // normalize 0..1 ?
698                         route_set_trim_abs (rid, argv[0]->f);
699                         ret = 0;
700                 }
701                 else if (!strncmp (path, "/ardour/routes/mute/", 20) && strlen (path) > 20) {
702                         int rid = atoi (&path[20]);
703                         route_mute (rid, argv[0]->f == 1.0);
704                         ret = 0;
705                 }
706                 else if (!strncmp (path, "/ardour/routes/solo/", 20) && strlen (path) > 20) {
707                         int rid = atoi (&path[20]);
708                         route_solo (rid, argv[0]->f == 1.0);
709                         ret = 0;
710                 }
711                 else if (!strncmp (path, "/ardour/routes/recenable/", 25) && strlen (path) > 25) {
712                         int rid = atoi (&path[25]);
713                         route_recenable (rid, argv[0]->f == 1.0);
714                         ret = 0;
715                 }
716         }
717
718         if ((ret && _debugmode == Unhandled)) {
719                 debugmsg (_("Unhandled OSC message"), path, types, argv, argc);
720         }
721
722         return ret;
723 }
724
725 void
726 OSC::debugmsg (const char *prefix, const char *path, const char* types, lo_arg **argv, int argc)
727 {
728         std::stringstream ss;
729         for (int i = 0; i < argc; ++i) {
730                 lo_type type = (lo_type)types[i];
731                         ss << " ";
732                 switch (type) {
733                         case LO_INT32:
734                                 ss << "i:" << argv[i]->i;
735                                 break;
736                         case LO_FLOAT:
737                                 ss << "f:" << argv[i]->f;
738                                 break;
739                         case LO_DOUBLE:
740                                 ss << "d:" << argv[i]->d;
741                                 break;
742                         case LO_STRING:
743                                 ss << "s:" << &argv[i]->s;
744                                 break;
745                         case LO_INT64:
746                                 ss << "h:" << argv[i]->h;
747                                 break;
748                         case LO_CHAR:
749                                 ss << "c:" << argv[i]->s;
750                                 break;
751                         case LO_TIMETAG:
752                                 ss << "<Timetag>";
753                                 break;
754                         case LO_BLOB:
755                                 ss << "<BLOB>";
756                                 break;
757                         case LO_TRUE:
758                                 ss << "#T";
759                                 break;
760                         case LO_FALSE:
761                                 ss << "#F";
762                                 break;
763                         case LO_NIL:
764                                 ss << "NIL";
765                                 break;
766                         case LO_INFINITUM:
767                                 ss << "#inf";
768                                 break;
769                         case LO_MIDI:
770                                 ss << "<MIDI>";
771                                 break;
772                         case LO_SYMBOL:
773                                 ss << "<SYMBOL>";
774                                 break;
775                         default:
776                                 ss << "< ?? >";
777                                 break;
778                 }
779         }
780         PBD::info << prefix << ": " << path << ss.str() << endmsg;
781 }
782
783 void
784 OSC::update_clock ()
785 {
786
787 }
788
789 // "Application Hook" Handlers //
790 void
791 OSC::session_loaded (Session& s)
792 {
793         lo_address listener = lo_address_new (NULL, "7770");
794         lo_send (listener, "/session/loaded", "ss", s.path().c_str(), s.name().c_str());
795 }
796
797 void
798 OSC::session_exported (std::string path, std::string name)
799 {
800         lo_address listener = lo_address_new (NULL, "7770");
801         lo_send (listener, "/session/exported", "ss", path.c_str(), name.c_str());
802 }
803
804 // end "Application Hook" Handlers //
805
806 /* path callbacks */
807
808 int
809 OSC::current_value (const char */*path*/, const char */*types*/, lo_arg **/*argv*/, int /*argc*/, void */*data*/, void* /*user_data*/)
810 {
811 #if 0
812         const char* returl;
813
814         if (argc < 3 || types == 0 || strlen (types) < 3 || types[0] != 's' || types[1] != 's' || types[2] != s) {
815                 return 1;
816         }
817
818         const char *returl = argv[1]->s;
819         lo_address addr = find_or_cache_addr (returl);
820
821         const char *retpath = argv[2]->s;
822
823
824         if (strcmp (argv[0]->s, "transport_frame") == 0) {
825
826                 if (session) {
827                         lo_send (addr, retpath, "i", session->transport_frame());
828                 }
829
830         } else if (strcmp (argv[0]->s, "transport_speed") == 0) {
831
832                 if (session) {
833                         lo_send (addr, retpath, "i", session->transport_frame());
834                 }
835
836         } else if (strcmp (argv[0]->s, "transport_locked") == 0) {
837
838                 if (session) {
839                         lo_send (addr, retpath, "i", session->transport_frame());
840                 }
841
842         } else if (strcmp (argv[0]->s, "punch_in") == 0) {
843
844                 if (session) {
845                         lo_send (addr, retpath, "i", session->transport_frame());
846                 }
847
848         } else if (strcmp (argv[0]->s, "punch_out") == 0) {
849
850                 if (session) {
851                         lo_send (addr, retpath, "i", session->transport_frame());
852                 }
853
854         } else if (strcmp (argv[0]->s, "rec_enable") == 0) {
855
856                 if (session) {
857                         lo_send (addr, retpath, "i", session->transport_frame());
858                 }
859
860         } else {
861
862                 /* error */
863         }
864 #endif
865         return 0;
866 }
867
868 void
869 OSC::routes_list (lo_message msg)
870 {
871         if (!session) {
872                 return;
873         }
874         for (int n = 0; n < (int) session->nroutes(); ++n) {
875
876                 boost::shared_ptr<Route> r = session->route_by_remote_id (n);
877
878                 if (r) {
879
880                         lo_message reply = lo_message_new ();
881
882                         if (boost::dynamic_pointer_cast<AudioTrack>(r)) {
883                                 lo_message_add_string (reply, "AT");
884                         } else if (boost::dynamic_pointer_cast<MidiTrack>(r)) {
885                                 lo_message_add_string (reply, "MT");
886                         } else {
887                                 lo_message_add_string (reply, "B");
888                         }
889
890                         lo_message_add_string (reply, r->name().c_str());
891                         lo_message_add_int32 (reply, r->n_inputs().n_audio());
892                         lo_message_add_int32 (reply, r->n_outputs().n_audio());
893                         lo_message_add_int32 (reply, r->muted());
894                         lo_message_add_int32 (reply, r->soloed());
895                         lo_message_add_int32 (reply, r->remote_control_id());
896
897                         if (boost::dynamic_pointer_cast<AudioTrack>(r)
898                                         || boost::dynamic_pointer_cast<MidiTrack>(r)) {
899
900                                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track>(r);
901                                 lo_message_add_int32 (reply, t->record_enabled());
902                         }
903
904                         //Automatically listen to routes listed
905                         listen_to_route(r, lo_message_get_source (msg));
906
907                         lo_send_message (lo_message_get_source (msg), "#reply", reply);
908                         lo_message_free (reply);
909                 }
910         }
911
912         // Send end of listing message
913         lo_message reply = lo_message_new ();
914
915         lo_message_add_string (reply, "end_route_list");
916         lo_message_add_int64 (reply, session->frame_rate());
917         lo_message_add_int64 (reply, session->current_end_frame());
918
919         lo_send_message (lo_message_get_source (msg), "#reply", reply);
920
921         lo_message_free (reply);
922 }
923
924 void
925 OSC::transport_frame (lo_message msg)
926 {
927         if (!session) {
928                 return;
929         }
930         framepos_t pos = session->transport_frame ();
931
932         lo_message reply = lo_message_new ();
933         lo_message_add_int64 (reply, pos);
934
935         lo_send_message (lo_message_get_source (msg), "/ardour/transport_frame", reply);
936
937         lo_message_free (reply);
938 }
939
940 void
941 OSC::transport_speed (lo_message msg)
942 {
943         if (!session) {
944                 return;
945         }
946         double ts = session->transport_speed ();
947
948         lo_message reply = lo_message_new ();
949         lo_message_add_double (reply, ts);
950
951         lo_send_message (lo_message_get_source (msg), "/ardour/transport_speed", reply);
952
953         lo_message_free (reply);
954 }
955
956 void
957 OSC::record_enabled (lo_message msg)
958 {
959         if (!session) {
960                 return;
961         }
962         int re = (int)session->get_record_enabled ();
963
964         lo_message reply = lo_message_new ();
965         lo_message_add_int32 (reply, re);
966
967         lo_send_message (lo_message_get_source (msg), "/ardour/record_enabled", reply);
968
969         lo_message_free (reply);
970 }
971
972
973 int
974 OSC::route_mute (int rid, int yn)
975 {
976         if (!session) return -1;
977
978         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
979
980         if (r) {
981                 r->set_mute (yn, this);
982         }
983
984         return 0;
985 }
986
987 int
988 OSC::route_solo (int rid, int yn)
989 {
990         if (!session) return -1;
991
992         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
993
994         if (r) {
995                 boost::shared_ptr<RouteList> rl (new RouteList);
996                 rl->push_back (r);
997                 session->set_solo (rl, yn);
998         }
999
1000         return 0;
1001 }
1002
1003 int
1004 OSC::route_recenable (int rid, int yn)
1005 {
1006         if (!session) return -1;
1007
1008         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1009
1010         if (r) {
1011                 r->set_record_enabled (yn, this);
1012         }
1013
1014         return 0;
1015 }
1016
1017 int
1018 OSC::route_set_gain_abs (int rid, float level)
1019 {
1020         if (!session) return -1;
1021
1022         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1023
1024         if (r) {
1025                 r->set_gain (level, PBD::Controllable::NoGroup);
1026         }
1027
1028         return 0;
1029 }
1030
1031 int
1032 OSC::route_set_gain_dB (int rid, float dB)
1033 {
1034         return route_set_gain_abs (rid, dB_to_coefficient (dB));
1035 }
1036
1037
1038 int
1039 OSC::route_set_trim_abs (int rid, float level)
1040 {
1041         if (!session) return -1;
1042
1043         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1044
1045         if (r) {
1046                 r->set_trim (level, this);
1047         }
1048
1049         return 0;
1050 }
1051
1052 int
1053 OSC::route_set_trim_dB (int rid, float dB)
1054 {
1055         return route_set_trim_abs(rid, dB_to_coefficient (dB));
1056 }
1057
1058
1059 int
1060 OSC::route_set_pan_stereo_position (int rid, float pos)
1061 {
1062         if (!session) return -1;
1063
1064         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1065
1066         if (r) {
1067                 boost::shared_ptr<Panner> panner = r->panner();
1068                 if (panner) {
1069                         panner->set_position (pos);
1070                 }
1071         }
1072
1073         return 0;
1074
1075 }
1076
1077 int
1078 OSC::route_set_pan_stereo_width (int rid, float pos)
1079 {
1080         if (!session) return -1;
1081
1082         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1083
1084         if (r) {
1085                 boost::shared_ptr<Panner> panner = r->panner();
1086                 if (panner) {
1087                         panner->set_width (pos);
1088                 }
1089         }
1090
1091         return 0;
1092
1093 }
1094
1095 int
1096 OSC::route_set_send_gain_abs (int rid, int sid, float val)
1097 {
1098         if (!session) {
1099                 return -1;
1100         }
1101
1102         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1103
1104         if (!r) {
1105                 return -1;
1106         }
1107
1108         /* revert to zero-based counting */
1109
1110         if (sid > 0) {
1111                 --sid;
1112         }
1113
1114         boost::shared_ptr<Processor> p = r->nth_send (sid);
1115
1116         if (p) {
1117                 boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(p);
1118                 boost::shared_ptr<Amp> a = s->amp();
1119
1120                 if (a) {
1121                         a->gain_control()->set_value (val, PBD::Controllable::NoGroup);
1122                 }
1123         }
1124         return 0;
1125 }
1126
1127 int
1128 OSC::route_set_send_gain_dB (int rid, int sid, float val)
1129 {
1130         if (!session) {
1131                 return -1;
1132         }
1133
1134         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1135
1136         if (!r) {
1137                 return -1;
1138         }
1139
1140         /* revert to zero-based counting */
1141
1142         if (sid > 0) {
1143                 --sid;
1144         }
1145
1146         boost::shared_ptr<Processor> p = r->nth_send (sid);
1147
1148         if (p) {
1149                 boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(p);
1150                 boost::shared_ptr<Amp> a = s->amp();
1151
1152                 if (a) {
1153                         a->gain_control()->set_value (dB_to_coefficient (val), PBD::Controllable::NoGroup);
1154                 }
1155         }
1156         return 0;
1157 }
1158
1159 int
1160 OSC::route_plugin_parameter (int rid, int piid, int par, float val)
1161 {
1162         if (!session)
1163                 return -1;
1164
1165         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1166
1167         if (!r) {
1168                 PBD::error << "OSC: Invalid Remote Control ID '" << rid << "'" << endmsg;
1169                 return -1;
1170         }
1171
1172         boost::shared_ptr<Processor> redi=r->nth_plugin (piid);
1173
1174         if (!redi) {
1175                 PBD::error << "OSC: cannot find plugin # " << piid << " for RID '" << rid << "'" << endmsg;
1176                 return -1;
1177         }
1178
1179         boost::shared_ptr<PluginInsert> pi;
1180
1181         if (!(pi = boost::dynamic_pointer_cast<PluginInsert>(redi))) {
1182                 PBD::error << "OSC: given processor # " << piid << " on RID '" << rid << "' is not a Plugin." << endmsg;
1183                 return -1;
1184         }
1185
1186         boost::shared_ptr<ARDOUR::Plugin> pip = pi->plugin();
1187         bool ok=false;
1188
1189         uint32_t controlid = pip->nth_parameter (par,ok);
1190
1191         if (!ok) {
1192                 PBD::error << "OSC: Cannot find parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "'" << endmsg;
1193                 return -1;
1194         }
1195
1196         if (!pip->parameter_is_input(controlid)) {
1197                 PBD::error << "OSC: Parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "' is not a control input" << endmsg;
1198                 return -1;
1199         }
1200
1201         ParameterDescriptor pd;
1202         pi->plugin()->get_parameter_descriptor (controlid,pd);
1203
1204         if (val >= pd.lower && val < pd.upper) {
1205
1206                 boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
1207                 // cerr << "parameter:" << redi->describe_parameter(controlid) << " val:" << val << "\n";
1208                 c->set_value (val, PBD::Controllable::NoGroup);
1209         } else {
1210                 PBD::warning << "OSC: Parameter # " << par <<  " for plugin # " << piid << " on RID '" << rid << "' is out of range" << endmsg;
1211                 PBD::info << "OSC: Valid range min=" << pd.lower << " max=" << pd.upper << endmsg;
1212         }
1213
1214         return 0;
1215 }
1216
1217 int
1218 OSC::route_plugin_parameter_print (int rid, int piid, int par)
1219 {
1220         if (!session) {
1221                 return -1;
1222         }
1223
1224         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
1225
1226         if (!r) {
1227                 return -1;
1228         }
1229
1230         boost::shared_ptr<Processor> redi=r->nth_processor (piid);
1231
1232         if (!redi) {
1233                 return -1;
1234         }
1235
1236         boost::shared_ptr<PluginInsert> pi;
1237
1238         if (!(pi = boost::dynamic_pointer_cast<PluginInsert>(redi))) {
1239                 return -1;
1240         }
1241
1242         boost::shared_ptr<ARDOUR::Plugin> pip = pi->plugin();
1243         bool ok=false;
1244
1245         uint32_t controlid = pip->nth_parameter (par,ok);
1246
1247         if (!ok) {
1248                 return -1;
1249         }
1250
1251         ParameterDescriptor pd;
1252
1253         if (pi->plugin()->get_parameter_descriptor (controlid, pd) == 0) {
1254                 boost::shared_ptr<AutomationControl> c = pi->automation_control (Evoral::Parameter(PluginAutomation, 0, controlid));
1255
1256                 cerr << "parameter:     " << redi->describe_parameter(controlid)  << "\n";
1257                 cerr << "current value: " << c->get_value ();
1258                 cerr << "lower value:   " << pd.lower << "\n";
1259                 cerr << "upper value:   " << pd.upper << "\n";
1260         }
1261
1262         return 0;
1263 }
1264
1265 XMLNode&
1266 OSC::get_state ()
1267 {
1268         XMLNode& node (ControlProtocol::get_state());
1269         node.add_property("debugmode", (int) _debugmode); // TODO: enum2str
1270         return node;
1271 }
1272
1273 int
1274 OSC::set_state (const XMLNode& node, int version)
1275 {
1276         if (ControlProtocol::set_state (node, version)) {
1277                 return -1;
1278         }
1279         XMLProperty const * p = node.property (X_("debugmode"));
1280         if (p) {
1281                 _debugmode = OSCDebugMode (PBD::atoi(p->value ()));
1282         }
1283
1284         return 0;
1285 }