A couple of potential fixes for 4K.
[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 <libdcp/rec709_linearised_gamma_lut.h>
47 #include <libdcp/srgb_linearised_gamma_lut.h>
48 #include <libdcp/gamma_lut.h>
49 #include <libdcp/xyz_frame.h>
50 #include <libdcp/rgb_xyz.h>
51 #include <libdcp/colour_matrix.h>
52 #include <libcxml/cxml.h>
53 #include "film.h"
54 #include "dcp_video_frame.h"
55 #include "config.h"
56 #include "exceptions.h"
57 #include "server.h"
58 #include "util.h"
59 #include "scaler.h"
60 #include "image.h"
61 #include "log.h"
62 #include "cross.h"
63
64 #include "i18n.h"
65
66 using std::string;
67 using std::stringstream;
68 using std::cout;
69 using boost::shared_ptr;
70 using boost::lexical_cast;
71 using libdcp::Size;
72
73 #define DCI_COEFFICENT (48.0 / 52.37)
74
75 /** Construct a DCP video frame.
76  *  @param input Input image.
77  *  @param f Index of the frame within the DCP.
78  *  @param bw J2K bandwidth to use (see Config::j2k_bandwidth ())
79  *  @param l Log to write to.
80  */
81 DCPVideoFrame::DCPVideoFrame (
82         shared_ptr<const Image> image, int f, Eyes eyes, ColourConversion c, int dcp_fps, int bw, Resolution r, shared_ptr<Log> l
83         )
84         : _image (image)
85         , _frame (f)
86         , _eyes (eyes)
87         , _conversion (c)
88         , _frames_per_second (dcp_fps)
89         , _j2k_bandwidth (bw)
90         , _resolution (r)
91         , _log (l)
92 {
93         
94 }
95
96 DCPVideoFrame::DCPVideoFrame (shared_ptr<const Image> image, shared_ptr<const cxml::Node> node, shared_ptr<Log> log)
97         : _image (image)
98         , _log (log)
99 {
100         _frame = node->number_child<int> ("Frame");
101         string const eyes = node->string_child ("Eyes");
102         if (eyes == "Both") {
103                 _eyes = EYES_BOTH;
104         } else if (eyes == "Left") {
105                 _eyes = EYES_LEFT;
106         } else if (eyes == "Right") {
107                 _eyes = EYES_RIGHT;
108         } else {
109                 assert (false);
110         }
111         _conversion = ColourConversion (node->node_child ("ColourConversion"));
112         _frames_per_second = node->number_child<int> ("FramesPerSecond");
113         _j2k_bandwidth = node->number_child<int> ("J2KBandwidth");
114         _resolution = Resolution (node->optional_number_child<int>("J2KBandwidth").get_value_or (RESOLUTION_2K));
115 }
116
117 /** J2K-encode this frame on the local host.
118  *  @return Encoded data.
119  */
120 shared_ptr<EncodedData>
121 DCPVideoFrame::encode_locally ()
122 {
123         shared_ptr<libdcp::LUT> in_lut;
124         if (_conversion.input_gamma_linearised) {
125                 in_lut = libdcp::SRGBLinearisedGammaLUT::cache.get (12, _conversion.input_gamma);
126         } else {
127                 in_lut = libdcp::GammaLUT::cache.get (12, _conversion.input_gamma);
128         }
129
130         /* XXX: libdcp should probably use boost */
131         
132         double matrix[3][3];
133         for (int i = 0; i < 3; ++i) {
134                 for (int j = 0; j < 3; ++j) {
135                         matrix[i][j] = _conversion.matrix (i, j);
136                 }
137         }
138         
139         shared_ptr<libdcp::XYZFrame> xyz = libdcp::rgb_to_xyz (
140                 _image,
141                 in_lut,
142                 libdcp::GammaLUT::cache.get (16, 1 / _conversion.output_gamma),
143                 matrix
144                 );
145                 
146         /* Set the max image and component sizes based on frame_rate */
147         int max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
148         if (_eyes == EYES_LEFT || _eyes == EYES_RIGHT) {
149                 /* In 3D we have only half the normal bandwidth per eye */
150                 max_cs_len /= 2;
151         }
152         int const max_comp_size = max_cs_len / 1.25;
153
154         /* get a J2K compressor handle */
155         opj_cinfo_t* cinfo = opj_create_compress (CODEC_J2K);
156         if (cinfo == 0) {
157                 throw EncodeError (N_("could not create JPEG2000 encoder"));
158         }
159
160         /* Set encoding parameters to default values */
161         opj_cparameters_t parameters;
162         opj_set_default_encoder_parameters (&parameters);
163
164         /* Set default cinema parameters */
165         parameters.tile_size_on = false;
166         parameters.cp_tdx = 1;
167         parameters.cp_tdy = 1;
168         
169         /* Tile part */
170         parameters.tp_flag = 'C';
171         parameters.tp_on = 1;
172         
173         /* Tile and Image shall be at (0,0) */
174         parameters.cp_tx0 = 0;
175         parameters.cp_ty0 = 0;
176         parameters.image_offset_x0 = 0;
177         parameters.image_offset_y0 = 0;
178
179         /* Codeblock size = 32x32 */
180         parameters.cblockw_init = 32;
181         parameters.cblockh_init = 32;
182         parameters.csty |= 0x01;
183         
184         /* The progression order shall be CPRL */
185         parameters.prog_order = CPRL;
186         
187         /* No ROI */
188         parameters.roi_compno = -1;
189         
190         parameters.subsampling_dx = 1;
191         parameters.subsampling_dy = 1;
192         
193         /* 9-7 transform */
194         parameters.irreversible = 1;
195         
196         parameters.tcp_rates[0] = 0;
197         parameters.tcp_numlayers++;
198         parameters.cp_disto_alloc = 1;
199         parameters.cp_rsiz = _resolution == RESOLUTION_2K ? CINEMA2K : CINEMA4K;
200         parameters.cp_comment = strdup (N_("DCP-o-matic"));
201         parameters.cp_cinema = _resolution == RESOLUTION_2K ? CINEMA2K_24 : CINEMA4K_24;
202
203         /* 3 components, so use MCT */
204         parameters.tcp_mct = 1;
205         
206         /* set max image */
207         parameters.max_comp_size = max_comp_size;
208         parameters.tcp_rates[0] = ((float) (3 * xyz->size().width * xyz->size().height * 12)) / (max_cs_len * 8);
209
210         /* Set event manager to null (openjpeg 1.3 bug) */
211         cinfo->event_mgr = 0;
212
213         /* Setup the encoder parameters using the current image and user parameters */
214         opj_setup_encoder (cinfo, &parameters, xyz->opj_image ());
215
216         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
217         if (cio == 0) {
218                 opj_destroy_compress (cinfo);
219                 throw EncodeError (N_("could not open JPEG2000 stream"));
220         }
221
222         int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
223         if (r == 0) {
224                 opj_cio_close (cio);
225                 opj_destroy_compress (cinfo);
226                 throw EncodeError (N_("JPEG2000 encoding failed"));
227         }
228
229         switch (_eyes) {
230         case EYES_BOTH:
231                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for mono"), _frame));
232                 break;
233         case EYES_LEFT:
234                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for L"), _frame));
235                 break;
236         case EYES_RIGHT:
237                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for R"), _frame));
238                 break;
239         default:
240                 break;
241         }
242
243         shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
244
245         opj_cio_close (cio);
246         free (parameters.cp_comment);
247         opj_destroy_compress (cinfo);
248
249         return enc;
250 }
251
252 /** Send this frame to a remote server for J2K encoding, then read the result.
253  *  @param serv Server to send to.
254  *  @return Encoded data.
255  */
256 shared_ptr<EncodedData>
257 DCPVideoFrame::encode_remotely (ServerDescription serv)
258 {
259         boost::asio::io_service io_service;
260         boost::asio::ip::tcp::resolver resolver (io_service);
261         boost::asio::ip::tcp::resolver::query query (serv.host_name(), boost::lexical_cast<string> (Config::instance()->server_port_base ()));
262         boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
263
264         shared_ptr<Socket> socket (new Socket);
265
266         socket->connect (*endpoint_iterator);
267
268         xmlpp::Document doc;
269         xmlpp::Element* root = doc.create_root_node ("EncodingRequest");
270
271         root->add_child("Version")->add_child_text (lexical_cast<string> (SERVER_LINK_VERSION));
272         root->add_child("Width")->add_child_text (lexical_cast<string> (_image->size().width));
273         root->add_child("Height")->add_child_text (lexical_cast<string> (_image->size().height));
274         add_metadata (root);
275
276         stringstream xml;
277         doc.write_to_stream (xml, "UTF-8");
278
279         _log->log (String::compose (
280                            N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
281                            _image->pixel_format(), _image->components(),
282                            _image->lines(0), _image->lines(1), _image->lines(2),
283                            _image->line_size()[0], _image->line_size()[1], _image->line_size()[2]
284                            ));
285
286         socket->write (xml.str().length() + 1);
287         socket->write ((uint8_t *) xml.str().c_str(), xml.str().length() + 1);
288
289         _image->write_to_socket (socket);
290
291         shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
292         socket->read (e->data(), e->size());
293
294         _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
295         
296         return e;
297 }
298
299 void
300 DCPVideoFrame::add_metadata (xmlpp::Element* el) const
301 {
302         el->add_child("Frame")->add_child_text (lexical_cast<string> (_frame));
303
304         switch (_eyes) {
305         case EYES_BOTH:
306                 el->add_child("Eyes")->add_child_text ("Both");
307                 break;
308         case EYES_LEFT:
309                 el->add_child("Eyes")->add_child_text ("Left");
310                 break;
311         case EYES_RIGHT:
312                 el->add_child("Eyes")->add_child_text ("Right");
313                 break;
314         default:
315                 assert (false);
316         }
317         
318         _conversion.as_xml (el->add_child("ColourConversion"));
319
320         el->add_child("FramesPerSecond")->add_child_text (lexical_cast<string> (_frames_per_second));
321         el->add_child("J2KBandwidth")->add_child_text (lexical_cast<string> (_j2k_bandwidth));
322         el->add_child("Resolution")->add_child_text (lexical_cast<string> (int (_resolution)));
323 }
324
325 EncodedData::EncodedData (int s)
326         : _data (new uint8_t[s])
327         , _size (s)
328 {
329
330 }
331
332 EncodedData::EncodedData (boost::filesystem::path file)
333 {
334         _size = boost::filesystem::file_size (file);
335         _data = new uint8_t[_size];
336
337         FILE* f = fopen (file.string().c_str(), N_("rb"));
338         if (!f) {
339                 throw FileError (_("could not open file for reading"), file);
340         }
341         
342         size_t const r = fread (_data, 1, _size, f);
343         if (r != size_t (_size)) {
344                 fclose (f);
345                 throw FileError (_("could not read encoded data"), file);
346         }
347                 
348         fclose (f);
349 }
350
351
352 EncodedData::~EncodedData ()
353 {
354         delete[] _data;
355 }
356
357 /** Write this data to a J2K file.
358  *  @param Film Film.
359  *  @param frame DCP frame index.
360  */
361 void
362 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
363 {
364         boost::filesystem::path const tmp_j2c = film->j2c_path (frame, eyes, true);
365
366         FILE* f = fopen (tmp_j2c.string().c_str (), N_("wb"));
367         
368         if (!f) {
369                 throw WriteFileError (tmp_j2c, errno);
370         }
371
372         fwrite (_data, 1, _size, f);
373         fclose (f);
374
375         boost::filesystem::path const real_j2c = film->j2c_path (frame, eyes, false);
376
377         /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
378         boost::filesystem::rename (tmp_j2c, real_j2c);
379 }
380
381 void
382 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, libdcp::FrameInfo fin) const
383 {
384         boost::filesystem::path const info = film->info_path (frame, eyes);
385         FILE* h = fopen_boost (info, "w");
386         fin.write (h);
387         fclose (h);
388 }
389
390 /** Send this data to a socket.
391  *  @param socket Socket
392  */
393 void
394 EncodedData::send (shared_ptr<Socket> socket)
395 {
396         socket->write (_size);
397         socket->write (_data, _size);
398 }
399
400 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
401         : EncodedData (s)
402 {
403         memcpy (_data, d, s);
404 }
405
406 /** @param s Size of data in bytes */
407 RemotelyEncodedData::RemotelyEncodedData (int s)
408         : EncodedData (s)
409 {
410
411 }