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