]> git.sesse.net Git - casparcg/blob - protocol/osc/client.cpp
Refactored to use range based for instead of BOOST_FOREACH
[casparcg] / protocol / osc / client.cpp
1 /*
2 * Copyright 2013 Sveriges Television AB http://casparcg.com/
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 * Author: Helge Norberg, helge.norberg@svt.se
21 */
22
23 #include "../stdafx.h"
24
25 #include "client.h"
26
27 #include "oscpack/OscOutboundPacketStream.h"
28 #include "oscpack/OscHostEndianness.h"
29
30 #include <common/utf.h>
31 #include <common/except.h>
32 #include <common/endian.h>
33
34 #include <core/monitor/monitor.h>
35
36 #include <functional>
37 #include <vector>
38 #include <unordered_map>
39
40 #include <boost/asio.hpp>
41 #include <boost/bind.hpp>
42 #include <boost/thread.hpp>
43
44 #include <tbb/spin_mutex.h>
45 #include <tbb/cache_aligned_allocator.h>
46
47 using namespace boost::asio::ip;
48
49 namespace caspar { namespace protocol { namespace osc {
50
51 template<typename T>
52 struct no_init_proxy
53 {
54     T value;
55
56     no_init_proxy() 
57         {
58                 static_assert(sizeof(no_init_proxy) == sizeof(T), "invalid size");
59         static_assert(__alignof(no_init_proxy) == __alignof(T), "invalid alignment");
60     }
61 };
62
63 typedef std::vector<no_init_proxy<char>, tbb::cache_aligned_allocator<no_init_proxy<char>>> byte_vector;
64
65 template<typename T>
66 struct param_visitor : public boost::static_visitor<void>
67 {
68         T& o;
69
70         param_visitor(T& o)
71                 : o(o)
72         {
73         }               
74                 
75         void operator()(const bool value)                                       {o << value;}
76         void operator()(const int32_t value)                            {o << static_cast<int64_t>(value);}
77         void operator()(const uint32_t value)                           {o << static_cast<int64_t>(value);}
78         void operator()(const int64_t value)                            {o << static_cast<int64_t>(value);}
79         void operator()(const uint64_t value)                           {o << static_cast<int64_t>(value);}
80         void operator()(const float value)                                      {o << value;}
81         void operator()(const double value)                                     {o << static_cast<float>(value);}
82         void operator()(const std::string& value)                       {o << value.c_str();}
83         void operator()(const std::wstring& value)                      {o << u8(value).c_str();}
84         void operator()(const std::vector<int8_t>& value)       {o << ::osc::Blob(value.data(), static_cast<unsigned long>(value.size()));}
85 };
86
87 void write_osc_event(byte_vector& destination, const core::monitor::message& e)
88 {               
89         destination.resize(4096);
90
91         ::osc::OutboundPacketStream o(reinterpret_cast<char*>(destination.data()), static_cast<unsigned long>(destination.size()));
92         o << ::osc::BeginMessage(e.path().c_str());
93                                 
94         param_visitor<decltype(o)> param_visitor(o);
95         for (const auto& data : e.data())
96                 boost::apply_visitor(param_visitor, data);
97                                 
98         o << ::osc::EndMessage;
99                 
100         destination.resize(o.Size());
101 }
102
103 byte_vector write_osc_bundle_start()
104 {
105         byte_vector destination;
106         destination.resize(16);
107
108         ::osc::OutboundPacketStream o(reinterpret_cast<char*>(destination.data()), static_cast<unsigned long>(destination.size()));
109         o << ::osc::BeginBundle();
110
111         destination.resize(o.Size());
112
113         return destination;
114 }
115
116 void write_osc_bundle_element_start(byte_vector& destination, const byte_vector& message)
117 {               
118         destination.resize(4);
119
120         int32_t* bundle_element_size = reinterpret_cast<int32_t*>(destination.data());
121
122 #ifdef OSC_HOST_LITTLE_ENDIAN
123         *bundle_element_size = swap_byte_order(static_cast<int32_t>(message.size()));
124 #else
125         *bundle_element_size = static_cast<int32_t>(bundle.size());
126 #endif
127 }
128
129 struct client::impl : public spl::enable_shared_from_this<client::impl>, core::monitor::sink
130 {
131         udp::socket socket_;
132         tbb::spin_mutex                                                                 endpoints_mutex_;
133         std::map<udp::endpoint, int>                                    reference_counts_by_endpoint_;
134
135         std::unordered_map<std::string, byte_vector>    updates_;
136         boost::mutex                                                                    updates_mutex_;                                                         
137         boost::condition_variable                                               updates_cond_;
138
139         tbb::atomic<bool>                                                               is_running_;
140
141         boost::thread                                                                   thread_;
142         
143 public:
144         impl(boost::asio::io_service& service)
145                 : socket_(service, udp::v4())
146                 , thread_(boost::bind(&impl::run, this))
147         {
148         }
149
150         ~impl()
151         {
152                 is_running_ = false;
153
154                 updates_cond_.notify_one();
155
156                 thread_.join();
157         }
158
159         std::shared_ptr<void> get_subscription_token(
160                         const boost::asio::ip::udp::endpoint& endpoint)
161         {
162                 tbb::spin_mutex::scoped_lock lock(endpoints_mutex_);
163
164                 ++reference_counts_by_endpoint_[endpoint];
165
166                 std::weak_ptr<impl> weak_self = shared_from_this();
167
168                 return std::shared_ptr<void>(nullptr, [weak_self, endpoint] (void*)
169                 {
170                         auto strong = weak_self.lock();
171
172                         if (!strong)
173                                 return;
174
175                         auto& self = *strong;
176
177                         tbb::spin_mutex::scoped_lock lock(self.endpoints_mutex_);
178
179                         int reference_count_after =
180                                 --self.reference_counts_by_endpoint_[endpoint];
181
182                         if (reference_count_after == 0)
183                                 self.reference_counts_by_endpoint_.erase(endpoint);
184                 });
185         }
186 private:
187         void propagate(const core::monitor::message& msg)
188         {
189                 boost::lock_guard<boost::mutex> lock(updates_mutex_);
190
191                 try 
192                 {
193                         write_osc_event(updates_[msg.path()], msg);
194                 }
195                 catch(...)
196                 {
197                         CASPAR_LOG_CURRENT_EXCEPTION();
198                         updates_.erase(msg.path());
199                 }
200
201                 updates_cond_.notify_one();
202         }
203
204         template<typename T>
205         void do_send(
206                         const T& buffers, const std::vector<udp::endpoint>& destinations)
207         {
208                 boost::system::error_code ec;
209
210                 for (const auto& endpoint : destinations)
211                         socket_.send_to(buffers, endpoint, 0, ec);
212         }
213
214         void run()
215         {
216                 // http://stackoverflow.com/questions/14993000/the-most-reliable-and-efficient-udp-packet-size
217                 const int SAFE_DATAGRAM_SIZE = 508;
218
219                 try
220                 {
221                         is_running_ = true;
222
223                         std::unordered_map<std::string, byte_vector> updates;
224                         std::vector<udp::endpoint> destinations;
225                         const byte_vector bundle_header = write_osc_bundle_start();
226                         std::vector<byte_vector> element_headers;
227
228                         while (is_running_)
229                         {               
230                                 updates.clear();
231                                 destinations.clear();
232
233                                 {                       
234                                         boost::unique_lock<boost::mutex> cond_lock(updates_mutex_);
235
236                                         if (updates_.empty())
237                                                 updates_cond_.wait(cond_lock);
238
239                                         std::swap(updates, updates_);
240                                 }
241
242                                 {
243                                         tbb::spin_mutex::scoped_lock lock(endpoints_mutex_);
244
245                                         for (const auto& endpoint : reference_counts_by_endpoint_)
246                                                 destinations.push_back(endpoint.first);
247                                 }
248
249                                 if (destinations.empty())
250                                         continue;
251
252                                 std::vector<boost::asio::const_buffers_1> buffers;
253                                 element_headers.resize(
254                                                 std::max(element_headers.size(), updates.size()));
255
256                                 int i = 0;
257                                 auto datagram_size = bundle_header.size();
258                                 buffers.push_back(boost::asio::buffer(bundle_header));
259
260                                 for (const auto& slot : updates)
261                                 {
262                                         write_osc_bundle_element_start(element_headers[i], slot.second);
263                                         const auto& headers = element_headers;
264
265                                         auto size_of_element = headers[i].size() + slot.second.size();
266         
267                                         if (datagram_size + size_of_element >= SAFE_DATAGRAM_SIZE)
268                                         {
269                                                 do_send(buffers, destinations);
270                                                 buffers.clear();
271                                                 buffers.push_back(boost::asio::buffer(bundle_header));
272                                                 datagram_size = bundle_header.size();
273                                         }
274
275                                         buffers.push_back(boost::asio::buffer(headers[i]));
276                                         buffers.push_back(boost::asio::buffer(slot.second));
277
278                                         datagram_size += size_of_element;
279                                         ++i;
280                                 }
281                         
282                                 if (!buffers.empty())
283                                         do_send(buffers, destinations);
284                         }
285                 }
286                 catch (...)
287                 {
288                         CASPAR_LOG_CURRENT_EXCEPTION();
289                 }
290         }
291 };
292
293 client::client(boost::asio::io_service& service) 
294         : impl_(new impl(service))
295 {
296 }
297
298 client::client(client&& other)
299         : impl_(std::move(other.impl_))
300 {
301 }
302
303 client& client::operator=(client&& other)
304 {
305         impl_ = std::move(other.impl_);
306         return *this;
307 }
308
309 client::~client()
310 {
311 }
312
313 std::shared_ptr<void> client::get_subscription_token(
314                         const boost::asio::ip::udp::endpoint& endpoint)
315 {
316         return impl_->get_subscription_token(endpoint);
317 }
318
319 spl::shared_ptr<core::monitor::sink> client::sink()
320 {
321         return impl_;
322 }
323
324 }}}