Very basics of colour conversion configuration.
[dcpomatic.git] / src / lib / dcp_video_frame.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3     Taken from code Copyright (C) 2010-2011 Terrence Meiczinger
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 /** @file  src/dcp_video_frame.cc
22  *  @brief A single frame of video destined for a DCP.
23  *
24  *  Given an Image and some settings, this class knows how to encode
25  *  the image to J2K either on the local host or on a remote server.
26  *
27  *  Objects of this class are used for the queue that we keep
28  *  of images that require encoding.
29  */
30
31 #include <stdint.h>
32 #include <cstring>
33 #include <cstdlib>
34 #include <stdexcept>
35 #include <cstdio>
36 #include <iomanip>
37 #include <sstream>
38 #include <iostream>
39 #include <fstream>
40 #include <unistd.h>
41 #include <errno.h>
42 #include <boost/array.hpp>
43 #include <boost/asio.hpp>
44 #include <boost/filesystem.hpp>
45 #include <boost/lexical_cast.hpp>
46 #include <libdcp/rec709_linearised_gamma_lut.h>
47 #include <libdcp/srgb_linearised_gamma_lut.h>
48 #include <libdcp/gamma_lut.h>
49 #include <libdcp/xyz_frame.h>
50 #include <libdcp/rgb_xyz.h>
51 #include <libdcp/colour_matrix.h>
52 #include "film.h"
53 #include "dcp_video_frame.h"
54 #include "config.h"
55 #include "exceptions.h"
56 #include "server.h"
57 #include "util.h"
58 #include "scaler.h"
59 #include "image.h"
60 #include "log.h"
61
62 #include "i18n.h"
63
64 using std::string;
65 using std::stringstream;
66 using std::ofstream;
67 using std::cout;
68 using boost::shared_ptr;
69 using libdcp::Size;
70
71 #define DCI_COEFFICENT (48.0 / 52.37)
72
73 /** Construct a DCP video frame.
74  *  @param input Input image.
75  *  @param f Index of the frame within the DCP.
76  *  @param bw J2K bandwidth to use (see Config::j2k_bandwidth ())
77  *  @param l Log to write to.
78  */
79 DCPVideoFrame::DCPVideoFrame (
80         shared_ptr<const Image> image, int f, Eyes eyes, int dcp_fps, int bw, shared_ptr<Log> l
81         )
82         : _image (image)
83         , _frame (f)
84         , _eyes (eyes)
85         , _frames_per_second (dcp_fps)
86         , _j2k_bandwidth (bw)
87         , _log (l)
88 {
89         
90 }
91
92 /** J2K-encode this frame on the local host.
93  *  @return Encoded data.
94  */
95 shared_ptr<EncodedData>
96 DCPVideoFrame::encode_locally ()
97 {
98         shared_ptr<libdcp::XYZFrame> xyz = libdcp::rgb_to_xyz (
99                 _image,
100                 libdcp::SRGBLinearisedGammaLUT::cache.get (12, 2.4),
101                 libdcp::GammaLUT::cache.get (16, 1 / 2.6),
102                 libdcp::colour_matrix::srgb_to_xyz
103                 );
104                 
105         /* Set the max image and component sizes based on frame_rate */
106         int max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
107         if (_eyes == EYES_LEFT || _eyes == EYES_RIGHT) {
108                 /* In 3D we have only half the normal bandwidth per eye */
109                 max_cs_len /= 2;
110         }
111         int const max_comp_size = max_cs_len / 1.25;
112
113         /* get a J2K compressor handle */
114         opj_cinfo_t* cinfo = opj_create_compress (CODEC_J2K);
115         if (cinfo == 0) {
116                 throw EncodeError (N_("could not create JPEG2000 encoder"));
117         }
118
119         /* Set encoding parameters to default values */
120         opj_cparameters_t parameters;
121         opj_set_default_encoder_parameters (&parameters);
122
123         /* Set default cinema parameters */
124         parameters.tile_size_on = false;
125         parameters.cp_tdx = 1;
126         parameters.cp_tdy = 1;
127         
128         /* Tile part */
129         parameters.tp_flag = 'C';
130         parameters.tp_on = 1;
131         
132         /* Tile and Image shall be at (0,0) */
133         parameters.cp_tx0 = 0;
134         parameters.cp_ty0 = 0;
135         parameters.image_offset_x0 = 0;
136         parameters.image_offset_y0 = 0;
137
138         /* Codeblock size = 32x32 */
139         parameters.cblockw_init = 32;
140         parameters.cblockh_init = 32;
141         parameters.csty |= 0x01;
142         
143         /* The progression order shall be CPRL */
144         parameters.prog_order = CPRL;
145         
146         /* No ROI */
147         parameters.roi_compno = -1;
148         
149         parameters.subsampling_dx = 1;
150         parameters.subsampling_dy = 1;
151         
152         /* 9-7 transform */
153         parameters.irreversible = 1;
154         
155         parameters.tcp_rates[0] = 0;
156         parameters.tcp_numlayers++;
157         parameters.cp_disto_alloc = 1;
158         parameters.cp_rsiz = CINEMA2K;
159         parameters.cp_comment = strdup (N_("DCP-o-matic"));
160         parameters.cp_cinema = CINEMA2K_24;
161
162         /* 3 components, so use MCT */
163         parameters.tcp_mct = 1;
164         
165         /* set max image */
166         parameters.max_comp_size = max_comp_size;
167         parameters.tcp_rates[0] = ((float) (3 * xyz->size().width * xyz->size().height * 12)) / (max_cs_len * 8);
168
169         /* Set event manager to null (openjpeg 1.3 bug) */
170         cinfo->event_mgr = 0;
171
172         /* Setup the encoder parameters using the current image and user parameters */
173         opj_setup_encoder (cinfo, &parameters, xyz->opj_image ());
174
175         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
176         if (cio == 0) {
177                 opj_destroy_compress (cinfo);
178                 throw EncodeError (N_("could not open JPEG2000 stream"));
179         }
180
181         int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
182         if (r == 0) {
183                 opj_cio_close (cio);
184                 opj_destroy_compress (cinfo);
185                 throw EncodeError (N_("JPEG2000 encoding failed"));
186         }
187
188         switch (_eyes) {
189         case EYES_BOTH:
190                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for mono"), _frame));
191                 break;
192         case EYES_LEFT:
193                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for L"), _frame));
194                 break;
195         case EYES_RIGHT:
196                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for R"), _frame));
197                 break;
198         default:
199                 break;
200         }
201
202         shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
203
204         opj_cio_close (cio);
205         free (parameters.cp_comment);
206         opj_destroy_compress (cinfo);
207
208         return enc;
209 }
210
211 /** Send this frame to a remote server for J2K encoding, then read the result.
212  *  @param serv Server to send to.
213  *  @return Encoded data.
214  */
215 shared_ptr<EncodedData>
216 DCPVideoFrame::encode_remotely (boost::shared_ptr<const ServerDescription> serv)
217 {
218         boost::asio::io_service io_service;
219         boost::asio::ip::tcp::resolver resolver (io_service);
220         boost::asio::ip::tcp::resolver::query query (serv->host_name(), boost::lexical_cast<string> (Config::instance()->server_port ()));
221         boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
222
223         shared_ptr<Socket> socket (new Socket);
224
225         socket->connect (*endpoint_iterator);
226
227         stringstream s;
228         s << "encode please\n"
229           << "width " << _image->size().width << "\n"
230           << "height " << _image->size().height << "\n"
231           << "eyes " << static_cast<int> (_eyes) << "\n"
232           << "frame " << _frame << "\n"
233           << "frames_per_second " << _frames_per_second << "\n"
234           << "j2k_bandwidth " << _j2k_bandwidth << "\n";
235
236         _log->log (String::compose (
237                            N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
238                            _image->pixel_format(), _image->components(),
239                            _image->lines(0), _image->lines(1), _image->lines(2),
240                            _image->line_size()[0], _image->line_size()[1], _image->line_size()[2]
241                            ));
242
243         socket->write (s.str().length() + 1);
244         socket->write ((uint8_t *) s.str().c_str(), s.str().length() + 1);
245
246         _image->write_to_socket (socket);
247
248         shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
249         socket->read (e->data(), e->size());
250
251         _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
252         
253         return e;
254 }
255
256 EncodedData::EncodedData (int s)
257         : _data (new uint8_t[s])
258         , _size (s)
259 {
260
261 }
262
263 EncodedData::EncodedData (string file)
264 {
265         _size = boost::filesystem::file_size (file);
266         _data = new uint8_t[_size];
267
268         FILE* f = fopen (file.c_str(), N_("rb"));
269         if (!f) {
270                 throw FileError (_("could not open file for reading"), file);
271         }
272         
273         size_t const r = fread (_data, 1, _size, f);
274         if (r != size_t (_size)) {
275                 fclose (f);
276                 throw FileError (_("could not read encoded data"), file);
277         }
278                 
279         fclose (f);
280 }
281
282
283 EncodedData::~EncodedData ()
284 {
285         delete[] _data;
286 }
287
288 /** Write this data to a J2K file.
289  *  @param Film Film.
290  *  @param frame DCP frame index.
291  */
292 void
293 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
294 {
295         string const tmp_j2c = film->j2c_path (frame, eyes, true);
296
297         FILE* f = fopen (tmp_j2c.c_str (), N_("wb"));
298         
299         if (!f) {
300                 throw WriteFileError (tmp_j2c, errno);
301         }
302
303         fwrite (_data, 1, _size, f);
304         fclose (f);
305
306         string const real_j2c = film->j2c_path (frame, eyes, false);
307
308         /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
309         boost::filesystem::rename (tmp_j2c, real_j2c);
310 }
311
312 void
313 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, libdcp::FrameInfo fin) const
314 {
315         string const info = film->info_path (frame, eyes);
316         ofstream h (info.c_str());
317         fin.write (h);
318 }
319
320 /** Send this data to a socket.
321  *  @param socket Socket
322  */
323 void
324 EncodedData::send (shared_ptr<Socket> socket)
325 {
326         socket->write (_size);
327         socket->write (_data, _size);
328 }
329
330 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
331         : EncodedData (s)
332 {
333         memcpy (_data, d, s);
334 }
335
336 /** @param s Size of data in bytes */
337 RemotelyEncodedData::RemotelyEncodedData (int s)
338         : EncodedData (s)
339 {
340
341 }