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