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