Try to prevent encode server test crashing in valgrind.
[dcpomatic.git] / src / lib / encode_server.cc
1 /*
2     Copyright (C) 2012-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file src/encode_server.cc
22  *  @brief Class to describe a server to which we can send
23  *  encoding work, and a class to implement such a server.
24  */
25
26 #include "encode_server.h"
27 #include "util.h"
28 #include "dcpomatic_socket.h"
29 #include "image.h"
30 #include "dcp_video.h"
31 #include "config.h"
32 #include "cross.h"
33 #include "player_video.h"
34 #include "compose.hpp"
35 #include "log.h"
36 #include "encoded_log_entry.h"
37 #include "version.h"
38 #include <dcp/raw_convert.h>
39 #include <libcxml/cxml.h>
40 #include <libxml++/libxml++.h>
41 #include <boost/algorithm/string.hpp>
42 #include <boost/scoped_array.hpp>
43 #include <boost/foreach.hpp>
44 #ifdef HAVE_VALGRIND_H
45 #include <valgrind/memcheck.h>
46 #endif
47 #include <string>
48 #include <vector>
49 #include <iostream>
50
51 #include "i18n.h"
52
53 #define LOG_GENERAL(...)    _log->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
54 #define LOG_GENERAL_NC(...) _log->log (__VA_ARGS__, LogEntry::TYPE_GENERAL);
55 #define LOG_ERROR(...)      _log->log (String::compose (__VA_ARGS__), LogEntry::TYPE_ERROR);
56 #define LOG_ERROR_NC(...)   _log->log (__VA_ARGS__, LogEntry::TYPE_ERROR);
57
58 using std::string;
59 using std::vector;
60 using std::list;
61 using std::cout;
62 using std::cerr;
63 using std::fixed;
64 using boost::shared_ptr;
65 using boost::thread;
66 using boost::bind;
67 using boost::scoped_array;
68 using boost::optional;
69 using dcp::Size;
70 using dcp::Data;
71 using dcp::raw_convert;
72
73 EncodeServer::EncodeServer (shared_ptr<Log> log, bool verbose, int num_threads)
74 #if !defined(RUNNING_ON_VALGRIND) || RUNNING_ON_VALGRIND == 0
75         : Server (ENCODE_FRAME_PORT)
76 #else
77         : Server (ENCODE_FRAME_PORT, 2400)
78 #endif
79         , _log (log)
80         , _verbose (verbose)
81         , _num_threads (num_threads)
82 {
83
84 }
85
86 EncodeServer::~EncodeServer ()
87 {
88         {
89                 boost::mutex::scoped_lock lm (_mutex);
90                 _terminate = true;
91                 _empty_condition.notify_all ();
92                 _full_condition.notify_all ();
93         }
94
95         BOOST_FOREACH (boost::thread* i, _worker_threads) {
96                 /* Ideally this would be a DCPOMATIC_ASSERT(i->joinable()) but we
97                    can't throw exceptions from a destructor.
98                 */
99                 if (i->joinable ()) {
100                         i->join ();
101                 }
102                 delete i;
103         }
104
105         if (_broadcast.socket) {
106                 _broadcast.socket->close ();
107         }
108         _broadcast.io_service.stop ();
109         if (_broadcast.thread) {
110                 /* Ideally this would be a DCPOMATIC_ASSERT(_broadcast.thread->joinable()) but we
111                    can't throw exceptions from a destructor.
112                 */
113                 if (_broadcast.thread->joinable ()) {
114                         _broadcast.thread->join ();
115                 }
116                 delete _broadcast.thread;
117         }
118 }
119
120 /** @param after_read Filled in with gettimeofday() after reading the input from the network.
121  *  @param after_encode Filled in with gettimeofday() after encoding the image.
122  */
123 int
124 EncodeServer::process (shared_ptr<Socket> socket, struct timeval& after_read, struct timeval& after_encode)
125 {
126         uint32_t length = socket->read_uint32 ();
127         scoped_array<char> buffer (new char[length]);
128         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
129
130         string s (buffer.get());
131         shared_ptr<cxml::Document> xml (new cxml::Document ("EncodingRequest"));
132         xml->read_string (s);
133         /* This is a double-check; the server shouldn't even be on the candidate list
134            if it is the wrong version, but it doesn't hurt to make sure here.
135         */
136         if (xml->number_child<int> ("Version") != SERVER_LINK_VERSION) {
137                 cerr << "Mismatched server/client versions\n";
138                 LOG_ERROR_NC ("Mismatched server/client versions");
139                 return -1;
140         }
141
142         shared_ptr<PlayerVideo> pvf (new PlayerVideo (xml, socket));
143
144         DCPVideo dcp_video_frame (pvf, xml, _log);
145
146         gettimeofday (&after_read, 0);
147
148         Data encoded = dcp_video_frame.encode_locally (boost::bind (&Log::dcp_log, _log.get(), _1, _2));
149
150         gettimeofday (&after_encode, 0);
151
152         try {
153                 socket->write (encoded.size());
154                 socket->write (encoded.data().get(), encoded.size());
155         } catch (std::exception& e) {
156                 cerr << "Send failed; frame " << dcp_video_frame.index() << "\n";
157                 LOG_ERROR ("Send failed; frame %1", dcp_video_frame.index());
158                 throw;
159         }
160
161         return dcp_video_frame.index ();
162 }
163
164 void
165 EncodeServer::worker_thread ()
166 {
167         while (true) {
168                 boost::mutex::scoped_lock lock (_mutex);
169                 while (_queue.empty () && !_terminate) {
170                         _empty_condition.wait (lock);
171                 }
172
173                 if (_terminate) {
174                         return;
175                 }
176
177                 shared_ptr<Socket> socket = _queue.front ();
178                 _queue.pop_front ();
179
180                 lock.unlock ();
181
182                 int frame = -1;
183                 string ip;
184
185                 struct timeval start;
186                 struct timeval after_read;
187                 struct timeval after_encode;
188                 struct timeval end;
189
190                 gettimeofday (&start, 0);
191
192                 try {
193                         frame = process (socket, after_read, after_encode);
194                         ip = socket->socket().remote_endpoint().address().to_string();
195                 } catch (std::exception& e) {
196                         cerr << "Error: " << e.what() << "\n";
197                         LOG_ERROR ("Error: %1", e.what());
198                 }
199
200                 gettimeofday (&end, 0);
201
202                 socket.reset ();
203
204                 lock.lock ();
205
206                 if (frame >= 0) {
207                         struct timeval end;
208                         gettimeofday (&end, 0);
209
210                         shared_ptr<EncodedLogEntry> e (
211                                 new EncodedLogEntry (
212                                         frame, ip,
213                                         seconds(after_read) - seconds(start),
214                                         seconds(after_encode) - seconds(after_read),
215                                         seconds(end) - seconds(after_encode)
216                                         )
217                                 );
218
219                         if (_verbose) {
220                                 cout << e->get() << "\n";
221                         }
222
223                         _log->log (e);
224                 }
225
226                 _full_condition.notify_all ();
227         }
228 }
229
230 void
231 EncodeServer::run ()
232 {
233         LOG_GENERAL ("Server %1 (%2) starting with %3 threads", dcpomatic_version, dcpomatic_git_commit, _num_threads);
234         if (_verbose) {
235                 cout << "DCP-o-matic server starting with " << _num_threads << " threads.\n";
236         }
237
238         for (int i = 0; i < _num_threads; ++i) {
239                 thread* t = new thread (bind (&EncodeServer::worker_thread, this));
240 #ifdef DCPOMATIC_LINUX
241                 pthread_setname_np (t->native_handle(), "encode-server-worker");
242 #endif
243                 _worker_threads.push_back (t);
244         }
245
246         _broadcast.thread = new thread (bind (&EncodeServer::broadcast_thread, this));
247 #ifdef DCPOMATIC_LINUX
248         pthread_setname_np (_broadcast.thread->native_handle(), "encode-server-broadcast");
249 #endif
250
251         Server::run ();
252 }
253
254 void
255 EncodeServer::broadcast_thread ()
256 try
257 {
258         boost::asio::ip::address address = boost::asio::ip::address_v4::any ();
259         boost::asio::ip::udp::endpoint listen_endpoint (address, HELLO_PORT);
260
261         _broadcast.socket = new boost::asio::ip::udp::socket (_broadcast.io_service);
262         _broadcast.socket->open (listen_endpoint.protocol ());
263         _broadcast.socket->bind (listen_endpoint);
264
265         _broadcast.socket->async_receive_from (
266                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
267                 _broadcast.send_endpoint,
268                 boost::bind (&EncodeServer::broadcast_received, this)
269                 );
270
271         _broadcast.io_service.run ();
272 }
273 catch (...)
274 {
275         store_current ();
276 }
277
278 void
279 EncodeServer::broadcast_received ()
280 {
281         _broadcast.buffer[sizeof(_broadcast.buffer) - 1] = '\0';
282
283         if (strcmp (_broadcast.buffer, DCPOMATIC_HELLO) == 0) {
284                 /* Reply to the client saying what we can do */
285                 xmlpp::Document doc;
286                 xmlpp::Element* root = doc.create_root_node ("ServerAvailable");
287                 root->add_child("Threads")->add_child_text (raw_convert<string> (_worker_threads.size ()));
288                 root->add_child("Version")->add_child_text (raw_convert<string> (SERVER_LINK_VERSION));
289                 string xml = doc.write_to_string ("UTF-8");
290
291                 if (_verbose) {
292                         cout << "Offering services to master " << _broadcast.send_endpoint.address().to_string () << "\n";
293                 }
294
295                 try {
296                         shared_ptr<Socket> socket (new Socket);
297                         socket->connect (boost::asio::ip::tcp::endpoint (_broadcast.send_endpoint.address(), MAIN_SERVER_PRESENCE_PORT));
298                         socket->write (xml.length() + 1);
299                         socket->write ((uint8_t *) xml.c_str(), xml.length() + 1);
300                 } catch (...) {
301
302                 }
303
304                 try {
305                         shared_ptr<Socket> socket (new Socket);
306                         socket->connect (boost::asio::ip::tcp::endpoint (_broadcast.send_endpoint.address(), BATCH_SERVER_PRESENCE_PORT));
307                         socket->write (xml.length() + 1);
308                         socket->write ((uint8_t *) xml.c_str(), xml.length() + 1);
309                 } catch (...) {
310
311                 }
312         }
313
314         _broadcast.socket->async_receive_from (
315                 boost::asio::buffer (_broadcast.buffer, sizeof (_broadcast.buffer)),
316                 _broadcast.send_endpoint, boost::bind (&EncodeServer::broadcast_received, this)
317                 );
318 }
319
320 void
321 EncodeServer::handle (shared_ptr<Socket> socket)
322 {
323         boost::mutex::scoped_lock lock (_mutex);
324
325         /* Wait until the queue has gone down a bit */
326         while (_queue.size() >= _worker_threads.size() * 2 && !_terminate) {
327                 _full_condition.wait (lock);
328         }
329
330         _queue.push_back (socket);
331         _empty_condition.notify_all ();
332 }