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