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