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