Merge master and multifarious hackery.
[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 "film.h"
47 #include "dcp_video_frame.h"
48 #include "lut.h"
49 #include "config.h"
50 #include "exceptions.h"
51 #include "server.h"
52 #include "util.h"
53 #include "scaler.h"
54 #include "image.h"
55 #include "log.h"
56 #include "subtitle.h"
57
58 #include "i18n.h"
59
60 using std::string;
61 using std::stringstream;
62 using std::ofstream;
63 using std::cout;
64 using boost::shared_ptr;
65 using libdcp::Size;
66
67 /** Construct a DCP video frame.
68  *  @param input Input image.
69  *  @param out Required size of output, in pixels (including any padding).
70  *  @param s Scaler to use.
71  *  @param p Number of pixels of padding either side of the image.
72  *  @param f Index of the frame within the DCP.
73  *  @param fps Frames per second of the Film's source.
74  *  @param pp FFmpeg post-processing string to use.
75  *  @param clut Colour look-up table to use (see Config::colour_lut_index ())
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> yuv, shared_ptr<Subtitle> sub,
81         Size out, int p, int subtitle_offset, float subtitle_scale,
82         Scaler const * s, int f, int dcp_fps, int clut, int bw, shared_ptr<Log> l
83         )
84         : _input (yuv)
85         , _subtitle (sub)
86         , _out_size (out)
87         , _padding (p)
88         , _subtitle_offset (subtitle_offset)
89         , _subtitle_scale (subtitle_scale)
90         , _scaler (s)
91         , _frame (f)
92         , _frames_per_second (dcp_fps)
93         , _colour_lut (clut)
94         , _j2k_bandwidth (bw)
95         , _log (l)
96         , _image (0)
97         , _parameters (0)
98         , _cinfo (0)
99         , _cio (0)
100 {
101         
102 }
103
104 /** Create a libopenjpeg container suitable for our output image */
105 void
106 DCPVideoFrame::create_openjpeg_container ()
107 {
108         for (int i = 0; i < 3; ++i) {
109                 _cmptparm[i].dx = 1;
110                 _cmptparm[i].dy = 1;
111                 _cmptparm[i].w = _out_size.width;
112                 _cmptparm[i].h = _out_size.height;
113                 _cmptparm[i].x0 = 0;
114                 _cmptparm[i].y0 = 0;
115                 _cmptparm[i].prec = 12;
116                 _cmptparm[i].bpp = 12;
117                 _cmptparm[i].sgnd = 0;
118         }
119
120         _image = opj_image_create (3, &_cmptparm[0], CLRSPC_SRGB);
121         if (_image == 0) {
122                 throw EncodeError (N_("could not create libopenjpeg image"));
123         }
124
125         _image->x0 = 0;
126         _image->y0 = 0;
127         _image->x1 = _out_size.width;
128         _image->y1 = _out_size.height;
129 }
130
131 DCPVideoFrame::~DCPVideoFrame ()
132 {
133         if (_image) {
134                 opj_image_destroy (_image);
135         }
136
137         if (_cio) {
138                 opj_cio_close (_cio);
139         }
140
141         if (_cinfo) {
142                 opj_destroy_compress (_cinfo);
143         }
144
145         if (_parameters) {
146                 free (_parameters->cp_comment);
147         }
148         
149         delete _parameters;
150 }
151
152 /** J2K-encode this frame on the local host.
153  *  @return Encoded data.
154  */
155 shared_ptr<EncodedData>
156 DCPVideoFrame::encode_locally ()
157 {
158         shared_ptr<Image> prepared = _input->scale_and_convert_to_rgb (_out_size, _padding, _scaler, true);
159
160         if (_subtitle) {
161                 Rect tx = subtitle_transformed_area (
162                         float (_out_size.width) / _input->size().width,
163                         float (_out_size.height) / _input->size().height,
164                         _subtitle->area(), _subtitle_offset, _subtitle_scale
165                         );
166
167                 shared_ptr<Image> im = _subtitle->image()->scale (tx.size(), _scaler, true);
168                 prepared->alpha_blend (im, tx.position());
169         }
170
171         create_openjpeg_container ();
172
173         struct {
174                 double r, g, b;
175         } s;
176
177         struct {
178                 double x, y, z;
179         } d;
180
181         /* Copy our RGB into the openjpeg container, converting to XYZ in the process */
182
183         int jn = 0;
184         for (int y = 0; y < _out_size.height; ++y) {
185                 uint8_t* p = prepared->data()[0] + y * prepared->stride()[0];
186                 for (int x = 0; x < _out_size.width; ++x) {
187
188                         /* In gamma LUT (converting 8-bit input to 12-bit) */
189                         s.r = lut_in[_colour_lut][*p++ << 4];
190                         s.g = lut_in[_colour_lut][*p++ << 4];
191                         s.b = lut_in[_colour_lut][*p++ << 4];
192                         
193                         /* RGB to XYZ Matrix */
194                         d.x = ((s.r * color_matrix[_colour_lut][0][0]) +
195                                (s.g * color_matrix[_colour_lut][0][1]) +
196                                (s.b * color_matrix[_colour_lut][0][2]));
197                         
198                         d.y = ((s.r * color_matrix[_colour_lut][1][0]) +
199                                (s.g * color_matrix[_colour_lut][1][1]) +
200                                (s.b * color_matrix[_colour_lut][1][2]));
201                         
202                         d.z = ((s.r * color_matrix[_colour_lut][2][0]) +
203                                (s.g * color_matrix[_colour_lut][2][1]) +
204                                (s.b * color_matrix[_colour_lut][2][2]));
205                         
206                         /* DCI companding */
207                         d.x = d.x * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
208                         d.y = d.y * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
209                         d.z = d.z * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
210                         
211                         /* Out gamma LUT */
212                         _image->comps[0].data[jn] = lut_out[LO_DCI][(int) d.x];
213                         _image->comps[1].data[jn] = lut_out[LO_DCI][(int) d.y];
214                         _image->comps[2].data[jn] = lut_out[LO_DCI][(int) d.z];
215
216                         ++jn;
217                 }
218         }
219
220         /* Set the max image and component sizes based on frame_rate */
221         int const max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
222         int const max_comp_size = max_cs_len / 1.25;
223
224         /* Set encoding parameters to default values */
225         _parameters = new opj_cparameters_t;
226         opj_set_default_encoder_parameters (_parameters);
227
228         /* Set default cinema parameters */
229         _parameters->tile_size_on = false;
230         _parameters->cp_tdx = 1;
231         _parameters->cp_tdy = 1;
232         
233         /* Tile part */
234         _parameters->tp_flag = 'C';
235         _parameters->tp_on = 1;
236         
237         /* Tile and Image shall be at (0,0) */
238         _parameters->cp_tx0 = 0;
239         _parameters->cp_ty0 = 0;
240         _parameters->image_offset_x0 = 0;
241         _parameters->image_offset_y0 = 0;
242
243         /* Codeblock size = 32x32 */
244         _parameters->cblockw_init = 32;
245         _parameters->cblockh_init = 32;
246         _parameters->csty |= 0x01;
247         
248         /* The progression order shall be CPRL */
249         _parameters->prog_order = CPRL;
250         
251         /* No ROI */
252         _parameters->roi_compno = -1;
253         
254         _parameters->subsampling_dx = 1;
255         _parameters->subsampling_dy = 1;
256         
257         /* 9-7 transform */
258         _parameters->irreversible = 1;
259         
260         _parameters->tcp_rates[0] = 0;
261         _parameters->tcp_numlayers++;
262         _parameters->cp_disto_alloc = 1;
263         _parameters->cp_rsiz = CINEMA2K;
264         _parameters->cp_comment = strdup (N_("DCP-o-matic"));
265         _parameters->cp_cinema = CINEMA2K_24;
266
267         /* 3 components, so use MCT */
268         _parameters->tcp_mct = 1;
269         
270         /* set max image */
271         _parameters->max_comp_size = max_comp_size;
272         _parameters->tcp_rates[0] = ((float) (3 * _image->comps[0].w * _image->comps[0].h * _image->comps[0].prec)) / (max_cs_len * 8);
273
274         /* get a J2K compressor handle */
275         _cinfo = opj_create_compress (CODEC_J2K);
276         if (_cinfo == 0) {
277                 throw EncodeError (N_("could not create JPEG2000 encoder"));
278         }
279
280         /* Set event manager to null (openjpeg 1.3 bug) */
281         _cinfo->event_mgr = 0;
282
283         /* Setup the encoder parameters using the current image and user parameters */
284         opj_setup_encoder (_cinfo, _parameters, _image);
285
286         _cio = opj_cio_open ((opj_common_ptr) _cinfo, 0, 0);
287         if (_cio == 0) {
288                 throw EncodeError (N_("could not open JPEG2000 stream"));
289         }
290
291         int const r = opj_encode (_cinfo, _cio, _image, 0);
292         if (r == 0) {
293                 throw EncodeError (N_("JPEG2000 encoding failed"));
294         }
295
296         _log->log (String::compose (N_("Finished locally-encoded frame %1"), _frame));
297         
298         return shared_ptr<EncodedData> (new LocallyEncodedData (_cio->buffer, cio_tell (_cio)));
299 }
300
301 /** Send this frame to a remote server for J2K encoding, then read the result.
302  *  @param serv Server to send to.
303  *  @return Encoded data.
304  */
305 shared_ptr<EncodedData>
306 DCPVideoFrame::encode_remotely (ServerDescription const * serv)
307 {
308         boost::asio::io_service io_service;
309         boost::asio::ip::tcp::resolver resolver (io_service);
310         boost::asio::ip::tcp::resolver::query query (serv->host_name(), boost::lexical_cast<string> (Config::instance()->server_port ()));
311         boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
312
313         shared_ptr<Socket> socket (new Socket);
314
315         socket->connect (*endpoint_iterator);
316
317         stringstream s;
318         s << N_("encode please\n")
319           << N_("input_width ") << _input->size().width << N_("\n")
320           << N_("input_height ") << _input->size().height << N_("\n")
321           << N_("input_pixel_format ") << _input->pixel_format() << N_("\n")
322           << N_("output_width ") << _out_size.width << N_("\n")
323           << N_("output_height ") << _out_size.height << N_("\n")
324           << N_("padding ") <<  _padding << N_("\n")
325           << N_("subtitle_offset ") << _subtitle_offset << N_("\n")
326           << N_("subtitle_scale ") << _subtitle_scale << N_("\n")
327           << N_("scaler ") << _scaler->id () << N_("\n")
328           << N_("frame ") << _frame << N_("\n")
329           << N_("frames_per_second ") << _frames_per_second << N_("\n");
330
331         s << N_("colour_lut ") << _colour_lut << N_("\n")
332           << N_("j2k_bandwidth ") << _j2k_bandwidth << N_("\n");
333
334         if (_subtitle) {
335                 s << N_("subtitle_x ") << _subtitle->position().x << N_("\n")
336                   << N_("subtitle_y ") << _subtitle->position().y << N_("\n")
337                   << N_("subtitle_width ") << _subtitle->image()->size().width << N_("\n")
338                   << N_("subtitle_height ") << _subtitle->image()->size().height << N_("\n");
339         }
340
341         _log->log (String::compose (
342                            N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
343                            _input->pixel_format(), _input->components(),
344                            _input->lines(0), _input->lines(1), _input->lines(2),
345                            _input->line_size()[0], _input->line_size()[1], _input->line_size()[2]
346                            ));
347
348         socket->write (s.str().length() + 1);
349         socket->write ((uint8_t *) s.str().c_str(), s.str().length() + 1);
350
351         _input->write_to_socket (socket);
352         if (_subtitle) {
353                 _subtitle->image()->write_to_socket (socket);
354         }
355
356         shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
357         socket->read (e->data(), e->size());
358
359         _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
360         
361         return e;
362 }
363
364 EncodedData::EncodedData (int s)
365         : _data (new uint8_t[s])
366         , _size (s)
367 {
368
369 }
370
371 EncodedData::EncodedData (string file)
372 {
373         _size = boost::filesystem::file_size (file);
374         _data = new uint8_t[_size];
375
376         FILE* f = fopen (file.c_str(), N_("rb"));
377         if (!f) {
378                 throw FileError (_("could not open file for reading"), file);
379         }
380         
381         fread (_data, 1, _size, f);
382         fclose (f);
383 }
384
385
386 EncodedData::~EncodedData ()
387 {
388         delete[] _data;
389 }
390
391 /** Write this data to a J2K file.
392  *  @param Film Film.
393  *  @param frame DCP frame index.
394  */
395 void
396 EncodedData::write (shared_ptr<const Film> film, int frame) const
397 {
398         string const tmp_j2c = film->j2c_path (frame, true);
399
400         FILE* f = fopen (tmp_j2c.c_str (), N_("wb"));
401         
402         if (!f) {
403                 throw WriteFileError (tmp_j2c, errno);
404         }
405
406         fwrite (_data, 1, _size, f);
407         fclose (f);
408
409         string const real_j2c = film->j2c_path (frame, false);
410
411         /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
412         boost::filesystem::rename (tmp_j2c, real_j2c);
413 }
414
415 void
416 EncodedData::write_info (shared_ptr<const Film> film, int frame, libdcp::FrameInfo fin) const
417 {
418         string const info = film->info_path (frame);
419         ofstream h (info.c_str());
420         fin.write (h);
421 }
422
423 /** Send this data to a socket.
424  *  @param socket Socket
425  */
426 void
427 EncodedData::send (shared_ptr<Socket> socket)
428 {
429         socket->write (_size);
430         socket->write (_data, _size);
431 }
432
433 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
434         : EncodedData (s)
435 {
436         memcpy (_data, d, s);
437 }
438
439 /** @param s Size of data in bytes */
440 RemotelyEncodedData::RemotelyEncodedData (int s)
441         : EncodedData (s)
442 {
443
444 }