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