Don't overlap simultaneous video content in the timeline. Fix keep-aligned for separ...
[dcpomatic.git] / src / lib / dcp_video_frame.cc
1 /*
2     Copyright (C) 2012-2014 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>("Resolution").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         if (_resolution == RESOLUTION_4K) {
201                 parameters.numpocs = 2;
202                 parameters.POC[0].tile = 1;
203                 parameters.POC[0].resno0 = 0; 
204                 parameters.POC[0].compno0 = 0;
205                 parameters.POC[0].layno1 = 1;
206                 parameters.POC[0].resno1 = parameters.numresolution - 1;
207                 parameters.POC[0].compno1 = 3;
208                 parameters.POC[0].prg1 = CPRL;
209                 parameters.POC[1].tile = 1;
210                 parameters.POC[1].resno0 = parameters.numresolution - 1; 
211                 parameters.POC[1].compno0 = 0;
212                 parameters.POC[1].layno1 = 1;
213                 parameters.POC[1].resno1 = parameters.numresolution;
214                 parameters.POC[1].compno1 = 3;
215                 parameters.POC[1].prg1 = CPRL;
216         }
217         
218         parameters.cp_comment = strdup (N_("DCP-o-matic"));
219         parameters.cp_cinema = _resolution == RESOLUTION_2K ? CINEMA2K_24 : CINEMA4K_24;
220
221         /* 3 components, so use MCT */
222         parameters.tcp_mct = 1;
223         
224         /* set max image */
225         parameters.max_comp_size = max_comp_size;
226         parameters.tcp_rates[0] = ((float) (3 * xyz->size().width * xyz->size().height * 12)) / (max_cs_len * 8);
227
228         /* Set event manager to null (openjpeg 1.3 bug) */
229         cinfo->event_mgr = 0;
230
231         /* Setup the encoder parameters using the current image and user parameters */
232         opj_setup_encoder (cinfo, &parameters, xyz->opj_image ());
233
234         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
235         if (cio == 0) {
236                 opj_destroy_compress (cinfo);
237                 throw EncodeError (N_("could not open JPEG2000 stream"));
238         }
239
240         int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
241         if (r == 0) {
242                 opj_cio_close (cio);
243                 opj_destroy_compress (cinfo);
244                 throw EncodeError (N_("JPEG2000 encoding failed"));
245         }
246
247         switch (_eyes) {
248         case EYES_BOTH:
249                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for mono"), _frame));
250                 break;
251         case EYES_LEFT:
252                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for L"), _frame));
253                 break;
254         case EYES_RIGHT:
255                 _log->log (String::compose (N_("Finished locally-encoded frame %1 for R"), _frame));
256                 break;
257         default:
258                 break;
259         }
260
261         shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
262
263         opj_cio_close (cio);
264         free (parameters.cp_comment);
265         opj_destroy_compress (cinfo);
266
267         return enc;
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 serv)
276 {
277         boost::asio::io_service io_service;
278         boost::asio::ip::tcp::resolver resolver (io_service);
279         boost::asio::ip::tcp::resolver::query query (serv.host_name(), boost::lexical_cast<string> (Config::instance()->server_port_base ()));
280         boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
281
282         shared_ptr<Socket> socket (new Socket);
283
284         socket->connect (*endpoint_iterator);
285
286         xmlpp::Document doc;
287         xmlpp::Element* root = doc.create_root_node ("EncodingRequest");
288
289         root->add_child("Version")->add_child_text (lexical_cast<string> (SERVER_LINK_VERSION));
290         root->add_child("Width")->add_child_text (lexical_cast<string> (_image->size().width));
291         root->add_child("Height")->add_child_text (lexical_cast<string> (_image->size().height));
292         add_metadata (root);
293
294         stringstream xml;
295         doc.write_to_stream (xml, "UTF-8");
296
297         _log->log (String::compose (N_("Sending frame %1 to remote"), _frame));
298
299         socket->write (xml.str().length() + 1);
300         socket->write ((uint8_t *) xml.str().c_str(), xml.str().length() + 1);
301
302         _image->write_to_socket (socket);
303
304         shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
305         socket->read (e->data(), e->size());
306
307         _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
308         
309         return e;
310 }
311
312 void
313 DCPVideoFrame::add_metadata (xmlpp::Element* el) const
314 {
315         el->add_child("Frame")->add_child_text (lexical_cast<string> (_frame));
316
317         switch (_eyes) {
318         case EYES_BOTH:
319                 el->add_child("Eyes")->add_child_text ("Both");
320                 break;
321         case EYES_LEFT:
322                 el->add_child("Eyes")->add_child_text ("Left");
323                 break;
324         case EYES_RIGHT:
325                 el->add_child("Eyes")->add_child_text ("Right");
326                 break;
327         default:
328                 assert (false);
329         }
330         
331         _conversion.as_xml (el->add_child("ColourConversion"));
332
333         el->add_child("FramesPerSecond")->add_child_text (lexical_cast<string> (_frames_per_second));
334         el->add_child("J2KBandwidth")->add_child_text (lexical_cast<string> (_j2k_bandwidth));
335         el->add_child("Resolution")->add_child_text (lexical_cast<string> (int (_resolution)));
336 }
337
338 EncodedData::EncodedData (int s)
339         : _data (new uint8_t[s])
340         , _size (s)
341 {
342
343 }
344
345 EncodedData::EncodedData (boost::filesystem::path file)
346 {
347         _size = boost::filesystem::file_size (file);
348         _data = new uint8_t[_size];
349
350         FILE* f = fopen_boost (file, "rb");
351         if (!f) {
352                 throw FileError (_("could not open file for reading"), file);
353         }
354         
355         size_t const r = fread (_data, 1, _size, f);
356         if (r != size_t (_size)) {
357                 fclose (f);
358                 throw FileError (_("could not read encoded data"), file);
359         }
360                 
361         fclose (f);
362 }
363
364
365 EncodedData::~EncodedData ()
366 {
367         delete[] _data;
368 }
369
370 /** Write this data to a J2K file.
371  *  @param Film Film.
372  *  @param frame DCP frame index.
373  */
374 void
375 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
376 {
377         boost::filesystem::path const tmp_j2c = film->j2c_path (frame, eyes, true);
378
379         FILE* f = fopen_boost (tmp_j2c, "wb");
380         
381         if (!f) {
382                 throw WriteFileError (tmp_j2c, errno);
383         }
384
385         fwrite (_data, 1, _size, f);
386         fclose (f);
387
388         boost::filesystem::path const real_j2c = film->j2c_path (frame, eyes, false);
389
390         /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
391         boost::filesystem::rename (tmp_j2c, real_j2c);
392 }
393
394 void
395 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, libdcp::FrameInfo fin) const
396 {
397         boost::filesystem::path const info = film->info_path (frame, eyes);
398         FILE* h = fopen_boost (info, "w");
399         fin.write (h);
400         fclose (h);
401 }
402
403 /** Send this data to a socket.
404  *  @param socket Socket
405  */
406 void
407 EncodedData::send (shared_ptr<Socket> socket)
408 {
409         socket->write (_size);
410         socket->write (_data, _size);
411 }
412
413 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
414         : EncodedData (s)
415 {
416         memcpy (_data, d, s);
417 }
418
419 /** @param s Size of data in bytes */
420 RemotelyEncodedData::RemotelyEncodedData (int s)
421         : EncodedData (s)
422 {
423
424 }