OSC is now driven by an event loop; fix up lifetime mgmt of Glib::Source to workaroun...
[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 <iostream>
21 #include <fstream>
22 #include <cstdio>
23 #include <cstdlib>
24 #include <cerrno>
25 #include <algorithm>
26
27 #include <sys/poll.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30
31 #include <glibmm/miscutils.h>
32
33 #include <pbd/pthread_utils.h>
34 #include <pbd/file_utils.h>
35 #include <pbd/filesystem.h>
36 #include <pbd/failed_constructor.h>
37
38 #include "ardour/session.h"
39 #include "ardour/route.h"
40 #include "ardour/audio_track.h"
41 #include "ardour/midi_track.h"
42 #include "ardour/dB.h"
43 #include "ardour/filesystem_paths.h"
44
45 #include "osc.h"
46 #include "osc_controllable.h"
47 #include "i18n.h"
48
49 using namespace ARDOUR;
50 using namespace sigc;
51 using namespace std;
52 using namespace Glib;
53
54
55 #include "pbd/abstract_ui.cc" // instantiate template
56
57 #ifdef DEBUG
58 static void error_callback(int num, const char *m, const char *path)
59 {
60         fprintf(stderr, "liblo server error %d in path %s: %s\n", num, path, m);
61 }
62 #else
63 static void error_callback(int, const char *, const char *)
64 {
65
66 }
67 #endif
68
69 OSC::OSC (Session& s, uint32_t port)
70         : ControlProtocol (s, "OSC")
71         , AbstractUI<OSCUIRequest> ("osc")
72         , _port(port)
73 {
74         _shutdown = false;
75         _osc_server = 0;
76         _osc_unix_server = 0;
77         _namespace_root = "/ardour";
78         _send_route_changes = true;
79
80         /* glibmm hack */
81         local_server = 0;
82         remote_server = 0;
83
84         // "Application Hooks"
85         session_loaded (s);
86         session->Exported.connect (mem_fun (*this, &OSC::session_exported));
87 }
88
89 OSC::~OSC()
90 {
91         stop ();
92 }
93
94 void
95 OSC::do_request (OSCUIRequest* req)
96 {
97         if (req->type == CallSlot) {
98
99                 call_slot (req->the_slot);
100
101         } else if (req->type == Quit) {
102
103                 stop ();
104         }
105 }
106
107 int
108 OSC::set_active (bool yn)
109 {
110         if (yn) {
111                 return start ();
112         } else {
113                 return stop ();
114         }
115 }
116
117 bool
118 OSC::get_active () const
119 {
120         return _osc_server != 0;
121 }
122
123 int 
124 OSC::set_feedback (bool yn)
125 {
126         _send_route_changes = yn;
127         return 0;
128 }
129
130 bool
131 OSC::get_feedback () const
132 {
133         return _send_route_changes;
134 }
135
136 int
137 OSC::start ()
138 {
139         char tmpstr[255];
140
141         if (_osc_server) {
142                 /* already started */
143                 return 0;
144         }
145         
146         for (int j=0; j < 20; ++j) {
147                 snprintf(tmpstr, sizeof(tmpstr), "%d", _port);
148                 
149                 if ((_osc_server = lo_server_new (tmpstr, error_callback))) {
150                         break;
151                 }
152 #ifdef DEBUG            
153                 cerr << "can't get osc at port: " << _port << endl;
154 #endif
155                 _port++;
156                 continue;
157         }
158         
159 #ifdef ARDOUR_OSC_UNIX_SERVER
160         
161         // APPEARS sluggish for now
162         
163         // attempt to create unix socket server too
164         
165         snprintf(tmpstr, sizeof(tmpstr), "/tmp/sooperlooper_XXXXXX");
166         int fd = mkstemp(tmpstr);
167         
168         if (fd >= 0 ) {
169                 unlink (tmpstr);
170                 close (fd);
171                 
172                 _osc_unix_server = lo_server_new (tmpstr, error_callback);
173                 
174                 if (_osc_unix_server) {
175                         _osc_unix_socket_path = tmpstr;
176                 }
177         }
178 #endif
179         
180         cerr << "OSC @ " << get_server_url () << endl;
181
182         PBD::sys::path url_file;
183
184         if (find_file_in_search_path (ardour_search_path() + system_config_search_path(),
185                                       "osc_url", url_file)) {
186                 _osc_url_file = url_file.to_string();
187                 ofstream urlfile;
188                 urlfile.open(_osc_url_file.c_str(), ios::trunc);
189                 if ( urlfile )
190                 {
191                         urlfile << get_server_url () << endl;
192                         urlfile.close();
193                 }
194                 else
195                 {  
196                         cerr << "Couldn't write '" <<  _osc_url_file << "'" <<endl;
197                 }
198         }
199         
200         register_callbacks();
201         
202         // lo_server_thread_add_method(_sthread, NULL, NULL, OSC::_dummy_handler, this);
203
204         /* startup the event loop thread */
205
206         BaseUI::run ();
207
208         return 0;
209 }
210
211 void
212 OSC::thread_init ()
213 {
214         if (_osc_unix_server) {
215                 Glib::RefPtr<IOSource> src = IOSource::create (lo_server_get_socket_fd (_osc_unix_server), IO_IN|IO_HUP|IO_ERR);
216                 src->connect (bind (sigc::mem_fun (*this, &OSC::osc_input_handler), _osc_unix_server));
217                 src->attach (_main_loop->get_context());
218                 local_server = src->gobj();
219                 g_source_ref (local_server);
220         }
221
222         if (_osc_server) {
223                 Glib::RefPtr<IOSource> src  = IOSource::create (lo_server_get_socket_fd (_osc_server), IO_IN|IO_HUP|IO_ERR);
224                 src->connect (bind (sigc::mem_fun (*this, &OSC::osc_input_handler), _osc_server));
225                 src->attach (_main_loop->get_context());
226                 remote_server = src->gobj();
227                 g_source_ref (remote_server);
228         }
229 }
230
231 int
232 OSC::stop ()
233 {       
234         /* stop main loop */
235
236         if (local_server) {
237                 g_source_destroy (local_server);
238                 g_source_unref (local_server);
239                 local_server = 0;
240         }
241
242         if (remote_server) {
243                 g_source_destroy (remote_server);
244                 g_source_unref (remote_server);
245                 remote_server = 0;
246         }
247
248         BaseUI::quit ();
249
250         if (_osc_server) {
251                 int fd = lo_server_get_socket_fd(_osc_server);
252                 if (fd >=0) {
253                         close(fd);
254                 }
255                 lo_server_free (_osc_server);
256                 _osc_server = 0;
257         }
258
259         if (_osc_unix_server) {
260                 int fd = lo_server_get_socket_fd(_osc_unix_server);
261                 if (fd >=0) {
262                         close(fd);
263                 }
264                 lo_server_free (_osc_unix_server);
265                 _osc_unix_server = 0;
266         }
267         
268         if (!_osc_unix_socket_path.empty()) {
269                 unlink (_osc_unix_socket_path.c_str());
270         }
271         
272         if (!_osc_url_file.empty() ) {
273                 unlink (_osc_url_file.c_str() );
274         }
275
276         return 0;
277 }
278
279 void
280 OSC::register_callbacks()
281 {
282         lo_server srvs[2];
283         lo_server serv;
284
285         srvs[0] = _osc_server;
286         srvs[1] = _osc_unix_server;
287         
288         for (size_t i = 0; i < 2; ++i) {
289
290                 if (!srvs[i]) {
291                         continue;
292                 }
293
294                 serv = srvs[i];
295                 
296                 /* this is a special catchall handler */
297                 
298                 lo_server_add_method (serv, 0, 0, _catchall, this);
299
300 #define REGISTER_CALLBACK(serv,path,types, function) lo_server_add_method (serv, path, types, OSC::_ ## function, this)
301                 
302                 REGISTER_CALLBACK (serv, "/ardour/add_marker", "", add_marker);
303                 REGISTER_CALLBACK (serv, "/ardour/access_action", "s", access_action);
304                 REGISTER_CALLBACK (serv, "/ardour/loop_toggle", "", loop_toggle);
305                 REGISTER_CALLBACK (serv, "/ardour/goto_start", "", goto_start);
306                 REGISTER_CALLBACK (serv, "/ardour/goto_end", "", goto_end);
307                 REGISTER_CALLBACK (serv, "/ardour/rewind", "", rewind);
308                 REGISTER_CALLBACK (serv, "/ardour/ffwd", "", ffwd);
309                 REGISTER_CALLBACK (serv, "/ardour/transport_stop", "", transport_stop);
310                 REGISTER_CALLBACK (serv, "/ardour/transport_play", "", transport_play);
311                 REGISTER_CALLBACK (serv, "/ardour/set_transport_speed", "f", set_transport_speed);
312                 REGISTER_CALLBACK (serv, "/ardour/save_state", "", save_state);
313                 REGISTER_CALLBACK (serv, "/ardour/prev_marker", "", prev_marker);
314                 REGISTER_CALLBACK (serv, "/ardour/next_marker", "", next_marker);
315                 REGISTER_CALLBACK (serv, "/ardour/undo", "", undo);
316                 REGISTER_CALLBACK (serv, "/ardour/redo", "", redo);
317                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_in", "", toggle_punch_in);
318                 REGISTER_CALLBACK (serv, "/ardour/toggle_punch_out", "", toggle_punch_out);
319                 REGISTER_CALLBACK (serv, "/ardour/rec_enable_toggle", "", rec_enable_toggle);
320                 REGISTER_CALLBACK (serv, "/ardour/toggle_all_rec_enables", "", toggle_all_rec_enables);
321
322                 REGISTER_CALLBACK (serv, "/ardour/routes/mute", "ii", route_mute);
323                 REGISTER_CALLBACK (serv, "/ardour/routes/solo", "ii", route_solo);
324                 REGISTER_CALLBACK (serv, "/ardour/routes/recenable", "ii", route_recenable);
325                 REGISTER_CALLBACK (serv, "/ardour/routes/gainabs", "if", route_set_gain_abs);
326                 REGISTER_CALLBACK (serv, "/ardour/routes/gaindB", "if", route_set_gain_dB);
327
328                 
329 #if 0
330                 /* still not-really-standardized query interface */
331                 REGISTER_CALLBACK (serv, "/ardour/*/#current_value", "", current_value);
332                 REGISTER_CALLBACK (serv, "/ardour/set", "", set);
333 #endif
334
335 #if 0
336                 // un/register_update args= s:ctrl s:returl s:retpath
337                 lo_server_add_method(serv, "/register_update", "sss", OSC::global_register_update_handler, this);
338                 lo_server_add_method(serv, "/unregister_update", "sss", OSC::global_unregister_update_handler, this);
339                 lo_server_add_method(serv, "/register_auto_update", "siss", OSC::global_register_auto_update_handler, this);
340                 lo_server_add_method(serv, "/unregister_auto_update", "sss", OSC::_global_unregister_auto_update_handler, this);
341 #endif
342         }
343 }
344
345 bool
346 OSC::osc_input_handler (IOCondition ioc, lo_server srv)
347 {
348         if (ioc & ~IO_IN) {
349                 return false;
350         }
351
352         if (ioc & IO_IN) {
353                 lo_server_recv (srv);
354         }
355
356         return true;
357 }
358
359 std::string
360 OSC::get_server_url()
361 {
362         string url;
363         char * urlstr;
364
365         if (_osc_server) {
366                 urlstr = lo_server_get_url (_osc_server);
367                 url = urlstr;
368                 free (urlstr);
369         }
370         
371         return url;
372 }
373
374 std::string
375 OSC::get_unix_server_url()
376 {
377         string url;
378         char * urlstr;
379
380         if (_osc_unix_server) {
381                 urlstr = lo_server_get_url (_osc_unix_server);
382                 url = urlstr;
383                 free (urlstr);
384         }
385         
386         return url;
387 }
388
389
390 void
391 OSC::current_value_query (const char* path, size_t len, lo_arg **argv, int argc, lo_message msg)
392 {
393         char* subpath;
394         
395         subpath = (char*) malloc (len-15+1);
396         memcpy (subpath, path, len-15);
397         subpath[len-15] = '\0';
398         
399         send_current_value (subpath, argv, argc, msg);
400         
401         free (subpath);
402 }
403
404 void
405 OSC::send_current_value (const char* path, lo_arg** argv, int argc, lo_message msg)
406 {
407         if (!session) {
408                 return;
409         }
410
411         lo_message reply = lo_message_new ();
412         boost::shared_ptr<Route> r;
413         int id;
414
415         lo_message_add_string (reply, path);
416         
417         if (argc == 0) {
418                 lo_message_add_string (reply, "bad syntax");
419         } else {
420                 id = argv[0]->i;
421                 r = session->route_by_remote_id (id);
422
423                 if (!r) {
424                         lo_message_add_string (reply, "not found");
425                 } else {
426
427                         if (strcmp (path, "/routes/state") == 0) {
428                                 
429                                 if (boost::dynamic_pointer_cast<AudioTrack>(r)) {
430                                         lo_message_add_string (reply, "AT");
431                                 } else if (boost::dynamic_pointer_cast<MidiTrack>(r)) {
432                                         lo_message_add_string (reply, "MT");
433                                 } else {
434                                         lo_message_add_string (reply, "B");
435                                 }
436                                 
437                                 lo_message_add_string (reply, r->name().c_str());
438                                 lo_message_add_int32 (reply, r->n_inputs().n_audio());
439                                 lo_message_add_int32 (reply, r->n_outputs().n_audio());
440                                 lo_message_add_int32 (reply, r->muted());
441                                 lo_message_add_int32 (reply, r->soloed());
442                                 
443                         } else if (strcmp (path, "/routes/mute") == 0) {
444                                 
445                                 lo_message_add_int32 (reply, (float) r->muted());
446                                 
447                         } else if (strcmp (path, "/routes/solo") == 0) {
448                                 
449                                 lo_message_add_int32 (reply, r->soloed());
450                         }
451                 }
452         }
453
454         lo_send_message (lo_message_get_source (msg), "#reply", reply);
455         lo_message_free (reply);
456 }
457         
458 int
459 OSC::_catchall (const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) 
460 {
461         return ((OSC*)user_data)->catchall (path, types, argv, argc, data);
462 }
463
464 int
465 OSC::catchall (const char *path, const char *types, lo_arg **argv, int argc, lo_message msg) 
466 {
467         size_t len;
468         int ret = 1; /* unhandled */
469
470         cerr << "Received a message, path = " << path << " types = \"" 
471              << (types ? types : "NULL") << '"' << endl;
472
473         /* 15 for /#current_value plus 2 for /<path> */
474
475         len = strlen (path);
476
477         if (len >= 17 && !strcmp (&path[len-15], "/#current_value")) {
478                 current_value_query (path, len, argv, argc, msg);
479                 ret = 0;
480
481         } else if (strcmp (path, "/routes/listen") == 0) {
482                 
483                 cerr << "set up listener\n";
484
485                 lo_message reply = lo_message_new ();
486
487                 if (argc <= 0) {
488                         lo_message_add_string (reply, "syntax error");
489                 } else {
490                         for (int n = 0; n < argc; ++n) {
491
492                                 boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
493                                 
494                                 if (!r) {
495                                         lo_message_add_string (reply, "not found");
496                                         cerr << "no such route\n";
497                                         break;
498                                 } else {                        
499                                         cerr << "add listener\n";
500                                         listen_to_route (r, lo_message_get_source (msg));
501                                         lo_message_add_int32 (reply, argv[n]->i);
502                                 }
503                         }
504                 }
505
506                 lo_send_message (lo_message_get_source (msg), "#reply", reply);
507                 lo_message_free (reply);
508
509         } else if (strcmp (path, "/routes/ignore") == 0) {
510
511                 for (int n = 0; n < argc; ++n) {
512
513                         boost::shared_ptr<Route> r = session->route_by_remote_id (argv[n]->i);
514                         
515                         if (r) {
516                                 end_listen (r, lo_message_get_source (msg));
517                         }
518                 }
519         }
520
521         return ret;
522 }
523
524 void
525 OSC::listen_to_route (boost::shared_ptr<Route> route, lo_address addr)
526 {
527         Controllables::iterator x;
528         bool route_exists = false;
529
530         cerr << "listen to route\n";
531
532         /* avoid duplicate listens */
533         
534         for (x = controllables.begin(); x != controllables.end(); ++x) {
535                 
536                 OSCRouteControllable* rc;
537
538                 if ((rc = dynamic_cast<OSCRouteControllable*>(*x)) != 0) {
539                         
540                         if (rc->route() == route) {
541                                 route_exists = true;
542                                 
543                                 /* XXX NEED lo_address_equal() */
544                                 
545                                 if (rc->address() == addr) {
546                                         return;
547                                 }
548                         }
549                 }
550         }
551
552         cerr << "listener binding to signals\n";
553
554         OSCControllable* c;
555         string path;
556
557         path = X_("/route/solo");
558         c = new OSCRouteControllable (addr, path, route->solo_control(), route);
559         controllables.push_back (c);
560
561         path = X_("/route/mute");
562         c = new OSCRouteControllable (addr, path, route->mute_control(), route);
563         controllables.push_back (c);
564
565         path = X_("/route/gain");
566         c = new OSCRouteControllable (addr, path, route->gain_control(), route);
567         controllables.push_back (c);
568
569         cerr << "Now have " << controllables.size() << " controllables\n";
570
571         /* if there is no existing controllable related to this route, make sure we clean up
572            if it is ever deleted.
573         */
574         
575         if (!route_exists) {
576                 route->GoingAway.connect (bind (mem_fun (*this, &OSC::drop_route), boost::weak_ptr<Route> (route)));
577         }
578 }
579
580 void
581 OSC::drop_route (boost::weak_ptr<Route> wr)
582 {
583         boost::shared_ptr<Route> r = wr.lock ();
584
585         if (!r) {
586                 return;
587         }
588
589         for (Controllables::iterator x = controllables.begin(); x != controllables.end();) {
590
591                 OSCRouteControllable* rc;
592                 
593                 if ((rc = dynamic_cast<OSCRouteControllable*>(*x)) != 0) {
594                         if (rc->route() == r) {
595                                 delete *x;
596                                 x = controllables.erase (x);
597                         } else {
598                                 ++x;
599                         }
600                 } else {
601                         ++x;
602                 }
603         }
604 }
605
606 void
607 OSC::end_listen (boost::shared_ptr<Route> r, lo_address addr)
608 {
609         Controllables::iterator x;
610
611         for (x = controllables.begin(); x != controllables.end(); ++x) {
612
613                 OSCRouteControllable* rc;
614                 
615                 if ((rc = dynamic_cast<OSCRouteControllable*>(*x)) != 0) {
616
617                         /* XXX NEED lo_address_equal () */
618
619                         if (rc->route() == r && rc->address() == addr) {
620                                 controllables.erase (x);
621                                 return;
622                         }
623                 }
624         }
625 }
626
627 // "Application Hook" Handlers //
628 void
629 OSC::session_loaded( Session& s ) {
630         lo_address listener = lo_address_new( NULL, "7770" );
631         lo_send( listener, "/session/loaded", "ss", s.path().c_str(), s.name().c_str() );
632 }
633
634 void
635 OSC::session_exported( std::string path, std::string name ) {
636         lo_address listener = lo_address_new( NULL, "7770" );
637         lo_send( listener, "/session/exported", "ss", path.c_str(), name.c_str() );
638 }
639
640 // end "Application Hook" Handlers //
641
642 /* path callbacks */
643
644 int 
645 OSC::current_value (const char */*path*/, const char */*types*/, lo_arg **/*argv*/, int /*argc*/, void */*data*/, void* /*user_data*/) 
646
647 #if 0
648         const char* returl;
649
650         if (argc < 3 || types == 0 || strlen (types) < 3 || types[0] != 's' || types[1] != 's' || types[2] != s) {
651                 return 1;
652         }
653
654         const char *returl = argv[1]->s;
655         lo_address addr = find_or_cache_addr (returl);
656
657         const char *retpath = argv[2]->s;
658
659         
660         if (strcmp (argv[0]->s, "transport_frame") == 0) {
661
662                 if (session) {
663                         lo_send (addr, retpath, "i", session->transport_frame());
664                 }
665
666         } else if (strcmp (argv[0]->s, "transport_speed") == 0) {
667                 
668                 if (session) {
669                         lo_send (addr, retpath, "i", session->transport_frame());
670                 }
671                 
672         } else if (strcmp (argv[0]->s, "transport_locked") == 0) {
673                 
674                 if (session) {
675                         lo_send (addr, retpath, "i", session->transport_frame());
676                 }
677                 
678         } else if (strcmp (argv[0]->s, "punch_in") == 0) {
679                 
680                 if (session) {
681                         lo_send (addr, retpath, "i", session->transport_frame());
682                 }
683                 
684         } else if (strcmp (argv[0]->s, "punch_out") == 0) {
685
686                 if (session) {
687                         lo_send (addr, retpath, "i", session->transport_frame());
688                 }
689                 
690         } else if (strcmp (argv[0]->s, "rec_enable") == 0) {
691                         
692                 if (session) {
693                         lo_send (addr, retpath, "i", session->transport_frame());
694                 }
695
696         } else {
697
698                 /* error */
699         }
700 #endif
701         return 0;
702 }
703
704 int
705 OSC::route_mute (int rid, int yn)
706 {
707         if (!session) return -1;
708
709         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
710
711         if (r) {
712                 r->set_mute (yn, this);
713         }
714         return 0;
715 }
716
717 int
718 OSC::route_solo (int rid, int yn)
719 {
720         if (!session) return -1;
721
722         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
723
724         if (r) {
725                 r->set_solo (yn, this);
726         }
727         return 0;
728 }
729
730 int
731 OSC::route_recenable (int rid, int yn)
732 {
733         if (!session) return -1;
734
735         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
736
737         if (r) {
738                 r->set_record_enable (yn, this);
739         }
740         return 0;
741 }
742
743 int
744 OSC::route_set_gain_abs (int rid, float level)
745 {
746         if (!session) return -1;
747
748         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
749
750         if (r) {
751                 r->set_gain (level, this);
752         }
753
754         return 0;
755 }
756
757 int
758 OSC::route_set_gain_dB (int rid, float dB)
759 {
760         if (!session) return -1;
761
762         boost::shared_ptr<Route> r = session->route_by_remote_id (rid);
763
764         if (r) {
765                 r->set_gain (dB_to_coefficient (dB), this);
766         }
767         
768         return 0;
769 }
770
771 XMLNode& 
772 OSC::get_state () 
773 {
774         return *(new XMLNode ("OSC"));
775 }
776                 
777 int 
778 OSC::set_state (const XMLNode&, int /*version*/)
779 {
780         return 0;
781 }