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