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