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