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