Use SafeStringStream instead of std::stringstream to try to fix random crashes on...
[dcpomatic.git] / src / lib / server.cc
1 /*
2     Copyright (C) 2012-2014 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 <string>
26 #include <vector>
27 #include <iostream>
28 #include <boost/algorithm/string.hpp>
29 #include <boost/scoped_array.hpp>
30 #include <libcxml/cxml.h>
31 #include <libdcp/raw_convert.h>
32 #include "server.h"
33 #include "util.h"
34 #include "scaler.h"
35 #include "image.h"
36 #include "dcp_video_frame.h"
37 #include "config.h"
38 #include "cross.h"
39 #include "player_video_frame.h"
40 #include "safe_stringstream.h"
41
42 #include "i18n.h"
43
44 #define LOG_GENERAL(...)    _log->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
45 #define LOG_GENERAL_NC(...) _log->log (__VA_ARGS__, Log::TYPE_GENERAL);
46 #define LOG_ERROR(...)      _log->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
47 #define LOG_ERROR_NC(...)   _log->log (__VA_ARGS__, Log::TYPE_ERROR);
48
49 using std::string;
50 using std::multimap;
51 using std::vector;
52 using std::list;
53 using std::cout;
54 using std::cerr;
55 using std::setprecision;
56 using std::fixed;
57 using boost::shared_ptr;
58 using boost::algorithm::is_any_of;
59 using boost::algorithm::split;
60 using boost::thread;
61 using boost::bind;
62 using boost::scoped_array;
63 using boost::optional;
64 using libdcp::Size;
65 using libdcp::raw_convert;
66
67 Server::Server (shared_ptr<Log> log, bool verbose)
68         : _log (log)
69         , _verbose (verbose)
70 {
71
72 }
73
74 /** @param after_read Filled in with gettimeofday() after reading the input from the network.
75  *  @param after_encode Filled in with gettimeofday() after encoding the image.
76  */
77 int
78 Server::process (shared_ptr<Socket> socket, struct timeval& after_read, struct timeval& after_encode)
79 {
80         uint32_t length = socket->read_uint32 ();
81         scoped_array<char> buffer (new char[length]);
82         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
83
84         string s (buffer.get());
85         shared_ptr<cxml::Document> xml (new cxml::Document ("EncodingRequest"));
86         xml->read_string (s);
87         if (xml->number_child<int> ("Version") != SERVER_LINK_VERSION) {
88                 cerr << "Mismatched server/client versions\n";
89                 LOG_ERROR_NC ("Mismatched server/client versions");
90                 return -1;
91         }
92
93         shared_ptr<PlayerVideoFrame> pvf (new PlayerVideoFrame (xml, socket, _log));
94
95         DCPVideoFrame dcp_video_frame (pvf, xml, _log);
96
97         gettimeofday (&after_read, 0);
98         
99         shared_ptr<EncodedData> encoded = dcp_video_frame.encode_locally ();
100
101         gettimeofday (&after_encode, 0);
102         
103         try {
104                 encoded->send (socket);
105         } catch (std::exception& e) {
106                 cerr << "Send failed; frame " << dcp_video_frame.index() << "\n";
107                 LOG_ERROR ("Send failed; frame %1", dcp_video_frame.index());
108                 throw;
109         }
110
111         return dcp_video_frame.index ();
112 }
113
114 void
115 Server::worker_thread ()
116 {
117         while (true) {
118                 boost::mutex::scoped_lock lock (_worker_mutex);
119                 while (_queue.empty ()) {
120                         _empty_condition.wait (lock);
121                 }
122
123                 shared_ptr<Socket> socket = _queue.front ();
124                 _queue.pop_front ();
125                 
126                 lock.unlock ();
127
128                 int frame = -1;
129                 string ip;
130
131                 struct timeval start;
132                 struct timeval after_read;
133                 struct timeval after_encode;
134                 struct timeval end;
135                 
136                 gettimeofday (&start, 0);
137                 
138                 try {
139                         frame = process (socket, after_read, after_encode);
140                         ip = socket->socket().remote_endpoint().address().to_string();
141                 } catch (std::exception& e) {
142                         cerr << "Error: " << e.what() << "\n";
143                         LOG_ERROR ("Error: %1", e.what());
144                 }
145
146                 gettimeofday (&end, 0);
147
148                 socket.reset ();
149                 
150                 lock.lock ();
151
152                 if (frame >= 0) {
153                         struct timeval end;
154                         gettimeofday (&end, 0);
155
156                         SafeStringStream message;
157                         message.precision (2);
158                         message << fixed
159                                 << "Encoded frame " << frame << " from " << ip << ": "
160                                 << "receive " << (seconds(after_read) - seconds(start)) << "s "
161                                 << "encode " << (seconds(after_encode) - seconds(after_read)) << "s "
162                                 << "send " << (seconds(end) - seconds(after_encode)) << "s.";
163                                                    
164                         if (_verbose) {
165                                 cout << message.str() << "\n";
166                         }
167
168                         LOG_GENERAL_NC (message.str ());
169                 }
170                 
171                 _full_condition.notify_all ();
172         }
173 }
174
175 void
176 Server::run (int num_threads)
177 {
178         LOG_GENERAL ("Server starting with %1 threads", num_threads);
179         if (_verbose) {
180                 cout << "DCP-o-matic server starting with " << num_threads << " threads.\n";
181         }
182         
183         for (int i = 0; i < num_threads; ++i) {
184                 _worker_threads.push_back (new thread (bind (&Server::worker_thread, this)));
185         }
186
187         _broadcast.thread = new thread (bind (&Server::broadcast_thread, this));
188         
189         boost::asio::io_service io_service;
190
191         boost::asio::ip::tcp::acceptor acceptor (
192                 io_service,
193                 boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), Config::instance()->server_port_base ())
194                 );
195         
196         while (true) {
197                 shared_ptr<Socket> socket (new Socket);
198                 acceptor.accept (socket->socket ());
199
200                 boost::mutex::scoped_lock lock (_worker_mutex);
201                 
202                 /* Wait until the queue has gone down a bit */
203                 while (int (_queue.size()) >= num_threads * 2) {
204                         _full_condition.wait (lock);
205                 }
206                 
207                 _queue.push_back (socket);
208                 _empty_condition.notify_all ();
209         }
210 }
211
212 void
213 Server::broadcast_thread ()
214 try
215 {
216         boost::asio::io_service io_service;
217
218         boost::asio::ip::address address = boost::asio::ip::address_v4::any ();
219         boost::asio::ip::udp::endpoint listen_endpoint (address, Config::instance()->server_port_base() + 1);
220
221         _broadcast.socket = new boost::asio::ip::udp::socket (io_service);
222         _broadcast.socket->open (listen_endpoint.protocol ());
223         _broadcast.socket->bind (listen_endpoint);
224
225         _broadcast.socket->async_receive_from (
226                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
227                 _broadcast.send_endpoint,
228                 boost::bind (&Server::broadcast_received, this)
229                 );
230
231         io_service.run ();
232 }
233 catch (...)
234 {
235         store_current ();
236 }
237
238 void
239 Server::broadcast_received ()
240 {
241         _broadcast.buffer[sizeof(_broadcast.buffer) - 1] = '\0';
242
243         if (strcmp (_broadcast.buffer, DCPOMATIC_HELLO) == 0) {
244                 /* Reply to the client saying what we can do */
245                 xmlpp::Document doc;
246                 xmlpp::Element* root = doc.create_root_node ("ServerAvailable");
247                 root->add_child("Threads")->add_child_text (raw_convert<string> (_worker_threads.size ()));
248                 string xml = doc.write_to_string ("UTF-8");
249
250                 shared_ptr<Socket> socket (new Socket);
251                 try {
252                         socket->connect (boost::asio::ip::tcp::endpoint (_broadcast.send_endpoint.address(), Config::instance()->server_port_base() + 1));
253                         socket->write (xml.length() + 1);
254                         socket->write ((uint8_t *) xml.c_str(), xml.length() + 1);
255                 } catch (...) {
256
257                 }
258         }
259                 
260         _broadcast.socket->async_receive_from (
261                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
262                 _broadcast.send_endpoint, boost::bind (&Server::broadcast_received, this)
263                 );
264 }