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