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