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