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