Rename TYPE_DEBUG_PLAYER to TYPE_DEBUG_VIDEO_VIEW.
[dcpomatic.git] / src / lib / encode_server_finder.cc
1 /*
2     Copyright (C) 2013-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic 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 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic 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 DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "encode_server_finder.h"
22 #include "exceptions.h"
23 #include "util.h"
24 #include "config.h"
25 #include "cross.h"
26 #include "encode_server_description.h"
27 #include "dcpomatic_socket.h"
28 #include <dcp/raw_convert.h>
29 #include <libcxml/cxml.h>
30 #include <boost/lambda/lambda.hpp>
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::list;
37 using std::vector;
38 using std::cout;
39 using boost::shared_ptr;
40 using boost::scoped_array;
41 using boost::weak_ptr;
42 using boost::optional;
43 using dcp::raw_convert;
44
45 EncodeServerFinder* EncodeServerFinder::_instance = 0;
46
47 EncodeServerFinder::EncodeServerFinder ()
48         : _stop (false)
49 {
50         Config::instance()->Changed.connect (boost::bind (&EncodeServerFinder::config_changed, this, _1));
51 }
52
53 void
54 EncodeServerFinder::start ()
55 {
56         _search_thread = boost::thread (boost::bind(&EncodeServerFinder::search_thread, this));
57         _listen_thread = boost::thread (boost::bind(&EncodeServerFinder::listen_thread, this));
58 #ifdef DCPOMATIC_LINUX
59         pthread_setname_np (_search_thread.native_handle(), "encode-server-search");
60         pthread_setname_np (_listen_thread.native_handle(), "encode-server-listen");
61 #endif
62 }
63
64
65 EncodeServerFinder::~EncodeServerFinder ()
66 {
67         stop ();
68 }
69
70 void
71 EncodeServerFinder::stop ()
72 {
73         _stop = true;
74
75         _search_condition.notify_all ();
76         if (_search_thread.joinable()) {
77                 try {
78                         _search_thread.join();
79                 } catch (...) {
80
81                 }
82         }
83
84         _listen_io_service.stop ();
85         if (_listen_thread.joinable()) {
86                 try {
87                         _listen_thread.join ();
88                 } catch (...) {
89
90                 }
91         }
92
93         boost::mutex::scoped_lock lm (_servers_mutex);
94         _servers.clear ();
95 }
96
97 void
98 EncodeServerFinder::search_thread ()
99 try
100 {
101         boost::system::error_code error;
102         boost::asio::io_service io_service;
103         boost::asio::ip::udp::socket socket (io_service);
104         socket.open (boost::asio::ip::udp::v4(), error);
105         if (error) {
106                 throw NetworkError ("failed to set up broadcast socket");
107         }
108
109         socket.set_option (boost::asio::ip::udp::socket::reuse_address (true));
110         socket.set_option (boost::asio::socket_base::broadcast (true));
111
112         string const data = DCPOMATIC_HELLO;
113         int const interval = 10;
114
115         while (!_stop) {
116                 if (Config::instance()->use_any_servers ()) {
117                         /* Broadcast to look for servers */
118                         try {
119                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), HELLO_PORT);
120                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
121                         } catch (...) {
122
123                         }
124                 }
125
126                 /* Query our `definite' servers (if there are any) */
127                 vector<string> servers = Config::instance()->servers ();
128                 for (vector<string>::const_iterator i = servers.begin(); i != servers.end(); ++i) {
129                         if (server_found (*i)) {
130                                 /* Don't bother asking a server that we already know about */
131                                 continue;
132                         }
133                         try {
134                                 boost::asio::ip::udp::resolver resolver (io_service);
135                                 boost::asio::ip::udp::resolver::query query (*i, raw_convert<string> (HELLO_PORT));
136                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve (query));
137                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
138                         } catch (...) {
139
140                         }
141                 }
142
143                 /* Discard servers that we haven't seen for a while */
144                 bool removed = false;
145                 {
146                         boost::mutex::scoped_lock lm (_servers_mutex);
147
148                         list<EncodeServerDescription>::iterator i = _servers.begin();
149                         while (i != _servers.end()) {
150                                 if (i->last_seen_seconds() > 2 * interval) {
151                                         list<EncodeServerDescription>::iterator j = i;
152                                         ++j;
153                                         _servers.erase (i);
154                                         i = j;
155                                         removed = true;
156                                 } else {
157                                         ++i;
158                                 }
159                         }
160                 }
161
162                 if (removed) {
163                         emit (boost::bind (boost::ref (ServersListChanged)));
164                 }
165
166                 boost::mutex::scoped_lock lm (_search_condition_mutex);
167                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds (interval));
168         }
169 }
170 catch (...)
171 {
172         store_current ();
173 }
174
175 void
176 EncodeServerFinder::listen_thread ()
177 try {
178         using namespace boost::asio::ip;
179
180         try {
181                 _listen_acceptor.reset (
182                         new tcp::acceptor (_listen_io_service, tcp::endpoint (tcp::v4(), is_batch_converter ? BATCH_SERVER_PRESENCE_PORT : MAIN_SERVER_PRESENCE_PORT))
183                         );
184         } catch (...) {
185                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
186         }
187
188         start_accept ();
189         _listen_io_service.run ();
190 }
191 catch (...)
192 {
193         store_current ();
194 }
195
196 void
197 EncodeServerFinder::start_accept ()
198 {
199         shared_ptr<Socket> socket (new Socket ());
200         _listen_acceptor->async_accept (
201                 socket->socket(),
202                 boost::bind (&EncodeServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
203                 );
204 }
205
206 void
207 EncodeServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
208 {
209         if (ec) {
210                 start_accept ();
211                 return;
212         }
213
214         uint32_t length;
215         socket->read (reinterpret_cast<uint8_t*> (&length), sizeof (uint32_t));
216         length = ntohl (length);
217
218         scoped_array<char> buffer (new char[length]);
219         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
220
221         string s (buffer.get());
222         shared_ptr<cxml::Document> xml (new cxml::Document ("ServerAvailable"));
223         xml->read_string (s);
224
225         string const ip = socket->socket().remote_endpoint().address().to_string ();
226         optional<list<EncodeServerDescription>::iterator> found = server_found (ip);
227         if (found) {
228                 (*found)->set_seen ();
229         } else {
230                 EncodeServerDescription sd (ip, xml->number_child<int>("Threads"), xml->optional_number_child<int>("Version").get_value_or(0));
231                 {
232                         boost::mutex::scoped_lock lm (_servers_mutex);
233                         _servers.push_back (sd);
234                 }
235                 emit (boost::bind (boost::ref (ServersListChanged)));
236         }
237
238         start_accept ();
239 }
240
241 optional<list<EncodeServerDescription>::iterator>
242 EncodeServerFinder::server_found (string ip)
243 {
244         boost::mutex::scoped_lock lm (_servers_mutex);
245         list<EncodeServerDescription>::iterator i = _servers.begin();
246         while (i != _servers.end() && i->host_name() != ip) {
247                 ++i;
248         }
249
250         if (i != _servers.end()) {
251                 return i;
252         }
253
254         return optional<list<EncodeServerDescription>::iterator>();
255 }
256
257 EncodeServerFinder*
258 EncodeServerFinder::instance ()
259 {
260         if (!_instance) {
261                 _instance = new EncodeServerFinder ();
262                 _instance->start ();
263         }
264
265         return _instance;
266 }
267
268 void
269 EncodeServerFinder::drop ()
270 {
271         delete _instance;
272         _instance = 0;
273 }
274
275 list<EncodeServerDescription>
276 EncodeServerFinder::servers () const
277 {
278         boost::mutex::scoped_lock lm (_servers_mutex);
279         return _servers;
280 }
281
282 void
283 EncodeServerFinder::config_changed (Config::Property what)
284 {
285         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
286                 {
287                         boost::mutex::scoped_lock lm (_servers_mutex);
288                         _servers.clear ();
289                 }
290                 ServersListChanged ();
291                 _search_condition.notify_all ();
292         }
293 }