1 //  osc responder class
2 //  Copyright (C) 2008 Tim Blechmann
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; see the file COPYING.  If not, write to
16 //  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 //  Boston, MA 02111-1307, USA.
18 
19 #pragma once
20 
21 #include <thread>
22 
23 // AppleClang workaround
24 #if defined(__apple_build_version__) && __apple_build_version__ > 11000000
25 #    define BOOST_ASIO_HAS_STD_STRING_VIEW 1
26 #endif
27 
28 #include <boost/asio/io_service.hpp>
29 #include <boost/asio/ip/udp.hpp>
30 
31 #include "branch_hints.hpp"
32 
33 #include "nova-tt/semaphore.hpp"
34 #include "nova-tt/thread_priority.hpp"
35 #include "nova-tt/name_thread.hpp"
36 
37 namespace nova {
38 
39 namespace detail {
40 using namespace boost::asio;
41 using namespace boost::asio::ip;
42 
43 class network_thread {
44 public:
start_receive(void)45     void start_receive(void) {
46         thread_ = std::thread([this] {
47 #ifdef NOVA_TT_PRIORITY_RT
48             thread_set_priority_rt(thread_priority_interval_rt().first);
49 #endif
50             name_thread("Network Receive");
51 
52             sem.post();
53             io_service::work work(io_service_);
54             io_service_.run();
55         });
56         sem.wait();
57     }
58 
~network_thread(void)59     ~network_thread(void) {
60         if (!thread_.joinable())
61             return;
62         io_service_.stop();
63         thread_.join();
64     }
65 
get_io_service(void)66     io_service& get_io_service(void) { return io_service_; }
67 
send_udp(const char * data,unsigned int size,udp::endpoint const & receiver)68     void send_udp(const char* data, unsigned int size, udp::endpoint const& receiver) {
69         udp::socket socket(io_service_);
70         socket.open(udp::v4());
71         socket.send_to(boost::asio::buffer(data, size), receiver);
72     }
73 
74 protected:
75     io_service io_service_;
76 
77 private:
78     semaphore sem;
79     std::thread thread_;
80 };
81 
82 
83 } /* namespace */
84 
85 using detail::network_thread;
86 
87 } /* namespace nova */
88