Merge master and multifarious hackery.
[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 "subtitle.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 boost::shared_ptr;
48 using boost::algorithm::is_any_of;
49 using boost::algorithm::split;
50 using boost::thread;
51 using boost::bind;
52 using boost::scoped_array;
53 using libdcp::Size;
54
55 ServerDescription::ServerDescription (shared_ptr<const cxml::Node> node)
56 {
57         _host_name = node->string_child ("HostName");
58         _threads = node->number_child<int> ("Threads");
59 }
60
61 void
62 ServerDescription::as_xml (xmlpp::Node* root) const
63 {
64         root->add_child("HostName")->add_child_text (_host_name);
65         root->add_child("Threads")->add_child_text (boost::lexical_cast<string> (_threads));
66 }
67
68 /** Create a server description from a string of metadata returned from as_metadata().
69  *  @param v Metadata.
70  *  @return ServerDescription, or 0.
71  */
72 ServerDescription *
73 ServerDescription::create_from_metadata (string v)
74 {
75         vector<string> b;
76         split (b, v, is_any_of (N_(" ")));
77
78         if (b.size() != 2) {
79                 return 0;
80         }
81
82         return new ServerDescription (b[0], atoi (b[1].c_str ()));
83 }
84
85 Server::Server (shared_ptr<Log> log)
86         : _log (log)
87 {
88
89 }
90
91 int
92 Server::process (shared_ptr<Socket> socket)
93 {
94         uint32_t length = socket->read_uint32 ();
95         scoped_array<char> buffer (new char[length]);
96         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
97         
98         stringstream s (buffer.get());
99         multimap<string, string> kv = read_key_value (s);
100
101         if (get_required_string (kv, N_("encode")) != N_("please")) {
102                 return -1;
103         }
104
105         libdcp::Size in_size (get_required_int (kv, N_("input_width")), get_required_int (kv, N_("input_height")));
106         int pixel_format_int = get_required_int (kv, N_("input_pixel_format"));
107         libdcp::Size out_size (get_required_int (kv, N_("output_width")), get_required_int (kv, N_("output_height")));
108         int padding = get_required_int (kv, N_("padding"));
109         int subtitle_offset = get_required_int (kv, N_("subtitle_offset"));
110         float subtitle_scale = get_required_float (kv, N_("subtitle_scale"));
111         string scaler_id = get_required_string (kv, N_("scaler"));
112         int frame = get_required_int (kv, N_("frame"));
113         int frames_per_second = get_required_int (kv, N_("frames_per_second"));
114         int colour_lut_index = get_required_int (kv, N_("colour_lut"));
115         int j2k_bandwidth = get_required_int (kv, N_("j2k_bandwidth"));
116         Position subtitle_position (get_optional_int (kv, N_("subtitle_x")), get_optional_int (kv, N_("subtitle_y")));
117         libdcp::Size subtitle_size (get_optional_int (kv, N_("subtitle_width")), get_optional_int (kv, N_("subtitle_height")));
118
119         /* This checks that colour_lut_index is within range */
120         colour_lut_index_to_name (colour_lut_index);
121
122         PixelFormat pixel_format = (PixelFormat) pixel_format_int;
123         Scaler const * scaler = Scaler::from_id (scaler_id);
124         
125         shared_ptr<Image> image (new SimpleImage (pixel_format, in_size, true));
126
127         image->read_from_socket (socket);
128
129         shared_ptr<Subtitle> sub;
130         if (subtitle_size.width && subtitle_size.height) {
131                 shared_ptr<Image> subtitle_image (new SimpleImage (PIX_FMT_RGBA, subtitle_size, true));
132                 subtitle_image->read_from_socket (socket);
133                 sub.reset (new Subtitle (subtitle_position, subtitle_image));
134         }
135
136         DCPVideoFrame dcp_video_frame (
137                 image, sub, out_size, padding, subtitle_offset, subtitle_scale,
138                 scaler, frame, frames_per_second, colour_lut_index, j2k_bandwidth, _log
139                 );
140         
141         shared_ptr<EncodedData> encoded = dcp_video_frame.encode_locally ();
142         try {
143                 encoded->send (socket);
144         } catch (std::exception& e) {
145                 _log->log (String::compose (
146                                    N_("Send failed; frame %1, data size %2, pixel format %3, image size %4x%5, %6 components"),
147                                    frame, encoded->size(), image->pixel_format(), image->size().width, image->size().height, image->components()
148                                    )
149                         );
150                 throw;
151         }
152
153         return frame;
154 }
155
156 void
157 Server::worker_thread ()
158 {
159         while (1) {
160                 boost::mutex::scoped_lock lock (_worker_mutex);
161                 while (_queue.empty ()) {
162                         _worker_condition.wait (lock);
163                 }
164
165                 shared_ptr<Socket> socket = _queue.front ();
166                 _queue.pop_front ();
167                 
168                 lock.unlock ();
169
170                 int frame = -1;
171
172                 struct timeval start;
173                 gettimeofday (&start, 0);
174                 
175                 try {
176                         frame = process (socket);
177                 } catch (std::exception& e) {
178                         _log->log (String::compose (N_("Error: %1"), e.what()));
179                 }
180                 
181                 socket.reset ();
182                 
183                 lock.lock ();
184
185                 if (frame >= 0) {
186                         struct timeval end;
187                         gettimeofday (&end, 0);
188                         _log->log (String::compose (N_("Encoded frame %1 in %2"), frame, seconds (end) - seconds (start)));
189                 }
190                 
191                 _worker_condition.notify_all ();
192         }
193 }
194
195 void
196 Server::run (int num_threads)
197 {
198         _log->log (String::compose (N_("Server starting with %1 threads"), num_threads));
199         
200         for (int i = 0; i < num_threads; ++i) {
201                 _worker_threads.push_back (new thread (bind (&Server::worker_thread, this)));
202         }
203
204         boost::asio::io_service io_service;
205         boost::asio::ip::tcp::acceptor acceptor (io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), Config::instance()->server_port ()));
206         while (1) {
207                 shared_ptr<Socket> socket (new Socket);
208                 acceptor.accept (socket->socket ());
209
210                 boost::mutex::scoped_lock lock (_worker_mutex);
211                 
212                 /* Wait until the queue has gone down a bit */
213                 while (int (_queue.size()) >= num_threads * 2) {
214                         _worker_condition.wait (lock);
215                 }
216                 
217                 _queue.push_back (socket);
218                 _worker_condition.notify_all ();
219         }
220 }