Possible fix to problems when the Server is destroyed.
[dcpomatic.git] / src / lib / server.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/server.cc
21  *  @brief Class to describe a server to which we can send
22  *  encoding work, and a class to implement such a server.
23  */
24
25 #include "server.h"
26 #include "util.h"
27 #include "dcpomatic_socket.h"
28 #include "image.h"
29 #include "dcp_video.h"
30 #include "config.h"
31 #include "cross.h"
32 #include "player_video.h"
33 #include "data.h"
34 #include "safe_stringstream.h"
35 #include "raw_convert.h"
36 #include "compose.hpp"
37 #include "log.h"
38 #include <libcxml/cxml.h>
39 #include <libxml++/libxml++.h>
40 #include <boost/algorithm/string.hpp>
41 #include <boost/scoped_array.hpp>
42 #include <string>
43 #include <vector>
44 #include <iostream>
45
46 #include "i18n.h"
47
48 #define LOG_GENERAL(...)    _log->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
49 #define LOG_GENERAL_NC(...) _log->log (__VA_ARGS__, Log::TYPE_GENERAL);
50 #define LOG_ERROR(...)      _log->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
51 #define LOG_ERROR_NC(...)   _log->log (__VA_ARGS__, Log::TYPE_ERROR);
52
53 using std::string;
54 using std::vector;
55 using std::list;
56 using std::cout;
57 using std::cerr;
58 using std::fixed;
59 using boost::shared_ptr;
60 using boost::thread;
61 using boost::bind;
62 using boost::scoped_array;
63 using boost::optional;
64 using dcp::Size;
65
66 Server::Server (shared_ptr<Log> log, bool verbose)
67         : _terminate (false)
68         , _log (log)
69         , _verbose (verbose)
70         , _acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), Config::instance()->server_port_base()))
71 {
72
73 }
74
75 Server::~Server ()
76 {
77         {
78                 boost::mutex::scoped_lock lm (_worker_mutex);
79                 _terminate = true;
80                 _empty_condition.notify_all ();
81                 _full_condition.notify_all ();
82         }
83
84         for (vector<boost::thread*>::iterator i = _worker_threads.begin(); i != _worker_threads.end(); ++i) {
85                 (*i)->join ();
86                 delete *i;
87         }
88
89         _io_service.stop ();
90
91         _broadcast.io_service.stop ();
92         _broadcast.thread->join ();
93 }
94
95 /** @param after_read Filled in with gettimeofday() after reading the input from the network.
96  *  @param after_encode Filled in with gettimeofday() after encoding the image.
97  */
98 int
99 Server::process (shared_ptr<Socket> socket, struct timeval& after_read, struct timeval& after_encode)
100 {
101         uint32_t length = socket->read_uint32 ();
102         scoped_array<char> buffer (new char[length]);
103         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
104
105         string s (buffer.get());
106         shared_ptr<cxml::Document> xml (new cxml::Document ("EncodingRequest"));
107         xml->read_string (s);
108         /* This is a double-check; the server shouldn't even be on the candidate list
109            if it is the wrong version, but it doesn't hurt to make sure here.
110         */
111         if (xml->number_child<int> ("Version") != SERVER_LINK_VERSION) {
112                 cerr << "Mismatched server/client versions\n";
113                 LOG_ERROR_NC ("Mismatched server/client versions");
114                 return -1;
115         }
116
117         shared_ptr<PlayerVideo> pvf (new PlayerVideo (xml, socket));
118
119         DCPVideo dcp_video_frame (pvf, xml, _log);
120
121         gettimeofday (&after_read, 0);
122
123         Data encoded = dcp_video_frame.encode_locally (boost::bind (&Log::dcp_log, _log.get(), _1, _2));
124
125         gettimeofday (&after_encode, 0);
126
127         try {
128                 socket->write (encoded.size ());
129                 socket->write (encoded.data ().get (), encoded.size ());
130         } catch (std::exception& e) {
131                 cerr << "Send failed; frame " << dcp_video_frame.index() << "\n";
132                 LOG_ERROR ("Send failed; frame %1", dcp_video_frame.index());
133                 throw;
134         }
135
136         return dcp_video_frame.index ();
137 }
138
139 void
140 Server::worker_thread ()
141 {
142         while (true) {
143                 boost::mutex::scoped_lock lock (_worker_mutex);
144                 while (_queue.empty () && !_terminate) {
145                         _empty_condition.wait (lock);
146                 }
147
148                 if (_terminate) {
149                         return;
150                 }
151
152                 shared_ptr<Socket> socket = _queue.front ();
153                 _queue.pop_front ();
154
155                 lock.unlock ();
156
157                 int frame = -1;
158                 string ip;
159
160                 struct timeval start;
161                 struct timeval after_read;
162                 struct timeval after_encode;
163                 struct timeval end;
164
165                 gettimeofday (&start, 0);
166
167                 try {
168                         frame = process (socket, after_read, after_encode);
169                         ip = socket->socket().remote_endpoint().address().to_string();
170                 } catch (std::exception& e) {
171                         cerr << "Error: " << e.what() << "\n";
172                         LOG_ERROR ("Error: %1", e.what());
173                 }
174
175                 gettimeofday (&end, 0);
176
177                 socket.reset ();
178
179                 lock.lock ();
180
181                 if (frame >= 0) {
182                         struct timeval end;
183                         gettimeofday (&end, 0);
184
185                         SafeStringStream message;
186                         message.precision (2);
187                         message << fixed
188                                 << "Encoded frame " << frame << " from " << ip << ": "
189                                 << "receive " << (seconds(after_read) - seconds(start)) << "s "
190                                 << "encode " << (seconds(after_encode) - seconds(after_read)) << "s "
191                                 << "send " << (seconds(end) - seconds(after_encode)) << "s.";
192
193                         if (_verbose) {
194                                 cout << message.str() << "\n";
195                         }
196
197                         LOG_GENERAL_NC (message.str ());
198                 }
199
200                 _full_condition.notify_all ();
201         }
202 }
203
204 void
205 Server::run (int num_threads)
206 {
207         LOG_GENERAL ("Server starting with %1 threads", num_threads);
208         if (_verbose) {
209                 cout << "DCP-o-matic server starting with " << num_threads << " threads.\n";
210         }
211
212         for (int i = 0; i < num_threads; ++i) {
213                 _worker_threads.push_back (new thread (bind (&Server::worker_thread, this)));
214         }
215
216         _broadcast.thread = new thread (bind (&Server::broadcast_thread, this));
217
218         start_accept ();
219         _io_service.run ();
220 }
221
222 void
223 Server::broadcast_thread ()
224 try
225 {
226         boost::asio::ip::address address = boost::asio::ip::address_v4::any ();
227         boost::asio::ip::udp::endpoint listen_endpoint (address, Config::instance()->server_port_base() + 1);
228
229         _broadcast.socket = new boost::asio::ip::udp::socket (_broadcast.io_service);
230         _broadcast.socket->open (listen_endpoint.protocol ());
231         _broadcast.socket->bind (listen_endpoint);
232
233         _broadcast.socket->async_receive_from (
234                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
235                 _broadcast.send_endpoint,
236                 boost::bind (&Server::broadcast_received, this)
237                 );
238
239         _broadcast.io_service.run ();
240 }
241 catch (...)
242 {
243         store_current ();
244 }
245
246 void
247 Server::broadcast_received ()
248 {
249         _broadcast.buffer[sizeof(_broadcast.buffer) - 1] = '\0';
250
251         if (strcmp (_broadcast.buffer, DCPOMATIC_HELLO) == 0) {
252                 /* Reply to the client saying what we can do */
253                 xmlpp::Document doc;
254                 xmlpp::Element* root = doc.create_root_node ("ServerAvailable");
255                 root->add_child("Threads")->add_child_text (raw_convert<string> (_worker_threads.size ()));
256                 root->add_child("Version")->add_child_text (raw_convert<string> (SERVER_LINK_VERSION));
257                 string xml = doc.write_to_string ("UTF-8");
258
259                 if (_verbose) {
260                         cout << "Offering services to master " << _broadcast.send_endpoint.address().to_string () << "\n";
261                 }
262                 shared_ptr<Socket> socket (new Socket);
263                 try {
264                         socket->connect (boost::asio::ip::tcp::endpoint (_broadcast.send_endpoint.address(), Config::instance()->server_port_base() + 1));
265                         socket->write (xml.length() + 1);
266                         socket->write ((uint8_t *) xml.c_str(), xml.length() + 1);
267                 } catch (...) {
268
269                 }
270         }
271
272         _broadcast.socket->async_receive_from (
273                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
274                 _broadcast.send_endpoint, boost::bind (&Server::broadcast_received, this)
275                 );
276 }
277
278 void
279 Server::start_accept ()
280 {
281         if (_terminate) {
282                 return;
283         }
284
285         shared_ptr<Socket> socket (new Socket);
286         _acceptor.async_accept (socket->socket (), boost::bind (&Server::handle_accept, this, socket, boost::asio::placeholders::error));
287 }
288
289 void
290 Server::handle_accept (shared_ptr<Socket> socket, boost::system::error_code const & error)
291 {
292         if (error) {
293                 return;
294         }
295
296         boost::mutex::scoped_lock lock (_worker_mutex);
297
298         /* Wait until the queue has gone down a bit */
299         while (_queue.size() >= _worker_threads.size() * 2 && !_terminate) {
300                 _full_condition.wait (lock);
301         }
302
303         _queue.push_back (socket);
304         _empty_condition.notify_all ();
305
306         start_accept ();
307 }