Server broadcasts presence to subnet (untested).
[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 boost::shared_ptr;
49 using boost::algorithm::is_any_of;
50 using boost::algorithm::split;
51 using boost::thread;
52 using boost::bind;
53 using boost::scoped_array;
54 using boost::optional;
55 using libdcp::Size;
56
57 ServerDescription::ServerDescription (shared_ptr<const cxml::Node> node)
58 {
59         _host_name = node->string_child ("HostName");
60         _threads = node->number_child<int> ("Threads");
61 }
62
63 void
64 ServerDescription::as_xml (xmlpp::Node* root) const
65 {
66         root->add_child("HostName")->add_child_text (_host_name);
67         root->add_child("Threads")->add_child_text (boost::lexical_cast<string> (_threads));
68 }
69
70 /** Create a server description from a string of metadata returned from as_metadata().
71  *  @param v Metadata.
72  *  @return ServerDescription, or 0.
73  */
74 optional<ServerDescription>
75 ServerDescription::create_from_metadata (string v)
76 {
77         vector<string> b;
78         split (b, v, is_any_of (N_(" ")));
79
80         if (b.size() != 2) {
81                 return optional<ServerDescription> ();
82         }
83
84         return ServerDescription (b[0], atoi (b[1].c_str ()));
85 }
86
87 Server::Server (shared_ptr<Log> log)
88         : _log (log)
89 {
90
91 }
92
93 int
94 Server::process (shared_ptr<Socket> socket)
95 {
96         uint32_t length = socket->read_uint32 ();
97         scoped_array<char> buffer (new char[length]);
98         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
99         
100         stringstream s (buffer.get());
101         shared_ptr<cxml::Document> xml (new cxml::Document ("EncodingRequest"));
102         xml->read_stream (s);
103         if (xml->number_child<int> ("Version") != SERVER_LINK_VERSION) {
104                 _log->log ("Mismatched server/client versions");
105                 return -1;
106         }
107
108         libdcp::Size size (
109                 xml->number_child<int> ("Width"), xml->number_child<int> ("Height")
110                 );
111
112         shared_ptr<Image> image (new Image (PIX_FMT_RGB24, size, true));
113
114         image->read_from_socket (socket);
115         DCPVideoFrame dcp_video_frame (image, xml, _log);
116         
117         shared_ptr<EncodedData> encoded = dcp_video_frame.encode_locally ();
118         try {
119                 encoded->send (socket);
120         } catch (std::exception& e) {
121                 _log->log (String::compose (
122                                    "Send failed; frame %1, data size %2, pixel format %3, image size %4x%5, %6 components",
123                                    dcp_video_frame.frame(), encoded->size(), image->pixel_format(), image->size().width, image->size().height, image->components()
124                                    )
125                         );
126                 throw;
127         }
128
129         return dcp_video_frame.frame ();
130 }
131
132 void
133 Server::worker_thread ()
134 {
135         while (1) {
136                 boost::mutex::scoped_lock lock (_worker_mutex);
137                 while (_queue.empty ()) {
138                         _worker_condition.wait (lock);
139                 }
140
141                 shared_ptr<Socket> socket = _queue.front ();
142                 _queue.pop_front ();
143                 
144                 lock.unlock ();
145
146                 int frame = -1;
147
148                 struct timeval start;
149                 gettimeofday (&start, 0);
150                 
151                 try {
152                         frame = process (socket);
153                 } catch (std::exception& e) {
154                         _log->log (String::compose (N_("Error: %1"), e.what()));
155                 }
156                 
157                 socket.reset ();
158                 
159                 lock.lock ();
160
161                 if (frame >= 0) {
162                         struct timeval end;
163                         gettimeofday (&end, 0);
164                         _log->log (String::compose (N_("Encoded frame %1 in %2"), frame, seconds (end) - seconds (start)));
165                 }
166                 
167                 _worker_condition.notify_all ();
168         }
169 }
170
171 void
172 Server::run (int num_threads)
173 {
174         _log->log (String::compose (N_("Server starting with %1 threads"), num_threads));
175         
176         for (int i = 0; i < num_threads; ++i) {
177                 _worker_threads.push_back (new thread (bind (&Server::worker_thread, this)));
178         }
179
180         boost::asio::io_service io_service;
181
182         /* Broadcast our presence on our interfaces */
183         list<string> interfaces = network_interfaces ();
184         for (list<string>::iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
185                 boost::system::error_code error;
186
187                 boost::asio::ip::udp::socket socket (io_service);
188                 socket.open (boost::asio::ip::udp::v4(), error);
189                 if (error) {
190                         break;
191                 }
192
193                 socket.set_option (boost::asio::ip::udp::socket::reuse_address (true));
194                 socket.set_option (boost::asio::socket_base::broadcast (true));
195         
196                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), Config::instance()->server_port ());
197
198                 string const data = DCPOMATIC_HELLO;
199                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
200                 socket.close (error);
201         }
202
203         /* Wait to be given things to do */
204         boost::asio::ip::tcp::acceptor acceptor (io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), Config::instance()->server_port ()));
205         while (1) {
206                 shared_ptr<Socket> socket (new Socket);
207                 acceptor.accept (socket->socket ());
208
209                 boost::mutex::scoped_lock lock (_worker_mutex);
210                 
211                 /* Wait until the queue has gone down a bit */
212                 while (int (_queue.size()) >= num_threads * 2) {
213                         _worker_condition.wait (lock);
214                 }
215                 
216                 _queue.push_back (socket);
217                 _worker_condition.notify_all ();
218         }
219 }