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