2 Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3 Taken from code Copyright (C) 2010-2011 Terrence Meiczinger
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.
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.
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.
21 /** @file src/dcp_video_frame.cc
22 * @brief A single frame of video destined for a DCP.
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.
27 * Objects of this class are used for the queue that we keep
28 * of images that require encoding.
42 #include <boost/array.hpp>
43 #include <boost/asio.hpp>
44 #include <boost/filesystem.hpp>
45 #include <boost/lexical_cast.hpp>
46 #include <libdcp/gamma_lut.h>
47 #include <libdcp/xyz_frame.h>
48 #include <libdcp/rgb_xyz.h>
49 #include <libdcp/colour_matrix.h>
50 #include <libcxml/cxml.h>
52 #include "dcp_video_frame.h"
54 #include "exceptions.h"
65 using std::stringstream;
67 using boost::shared_ptr;
68 using boost::lexical_cast;
71 #define DCI_COEFFICENT (48.0 / 52.37)
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.
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
86 , _frames_per_second (dcp_fps)
94 DCPVideoFrame::DCPVideoFrame (shared_ptr<const Image> image, shared_ptr<const cxml::Node> node, shared_ptr<Log> log)
98 _frame = node->number_child<int> ("Frame");
99 string const eyes = node->string_child ("Eyes");
100 if (eyes == "Both") {
102 } else if (eyes == "Left") {
104 } else if (eyes == "Right") {
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));
115 /** J2K-encode this frame on the local host.
116 * @return Encoded data.
118 shared_ptr<EncodedData>
119 DCPVideoFrame::encode_locally ()
121 shared_ptr<dcp::GammaLUT> in_lut;
122 in_lut = dcp::GammaLUT::cache.get (12, _conversion.input_gamma, _conversion.input_gamma_linearised);
124 /* XXX: libdcp should probably use boost */
127 for (int i = 0; i < 3; ++i) {
128 for (int j = 0; j < 3; ++j) {
129 matrix[i][j] = _conversion.matrix (i, j);
133 shared_ptr<dcp::XYZFrame> xyz = dcp::rgb_to_xyz (
136 dcp::GammaLUT::cache.get (16, 1 / _conversion.output_gamma, false),
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 */
146 int const max_comp_size = max_cs_len / 1.25;
148 /* get a J2K compressor handle */
149 opj_cinfo_t* cinfo = opj_create_compress (CODEC_J2K);
151 throw EncodeError (N_("could not create JPEG2000 encoder"));
154 /* Set encoding parameters to default values */
155 opj_cparameters_t parameters;
156 opj_set_default_encoder_parameters (¶meters);
158 /* Set default cinema parameters */
159 parameters.tile_size_on = false;
160 parameters.cp_tdx = 1;
161 parameters.cp_tdy = 1;
164 parameters.tp_flag = 'C';
165 parameters.tp_on = 1;
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;
173 /* Codeblock size = 32x32 */
174 parameters.cblockw_init = 32;
175 parameters.cblockh_init = 32;
176 parameters.csty |= 0x01;
178 /* The progression order shall be CPRL */
179 parameters.prog_order = CPRL;
182 parameters.roi_compno = -1;
184 parameters.subsampling_dx = 1;
185 parameters.subsampling_dy = 1;
188 parameters.irreversible = 1;
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;
212 parameters.cp_comment = strdup (N_("DCP-o-matic"));
213 parameters.cp_cinema = _resolution == RESOLUTION_2K ? CINEMA2K_24 : CINEMA4K_24;
215 /* 3 components, so use MCT */
216 parameters.tcp_mct = 1;
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);
222 /* Set event manager to null (openjpeg 1.3 bug) */
223 cinfo->event_mgr = 0;
225 /* Setup the encoder parameters using the current image and user parameters */
226 opj_setup_encoder (cinfo, ¶meters, xyz->opj_image ());
228 opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
230 opj_destroy_compress (cinfo);
231 throw EncodeError (N_("could not open JPEG2000 stream"));
234 int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
237 opj_destroy_compress (cinfo);
238 throw EncodeError (N_("JPEG2000 encoding failed"));
243 _log->log (String::compose (N_("Finished locally-encoded frame %1 for mono"), _frame));
246 _log->log (String::compose (N_("Finished locally-encoded frame %1 for L"), _frame));
249 _log->log (String::compose (N_("Finished locally-encoded frame %1 for R"), _frame));
255 shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
258 free (parameters.cp_comment);
259 opj_destroy_compress (cinfo);
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.
268 shared_ptr<EncodedData>
269 DCPVideoFrame::encode_remotely (ServerDescription serv)
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);
276 shared_ptr<Socket> socket (new Socket);
278 socket->connect (*endpoint_iterator);
281 xmlpp::Element* root = doc.create_root_node ("EncodingRequest");
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));
289 doc.write_to_stream (xml, "UTF-8");
291 _log->log (String::compose (
292 N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
293 _image->pixel_format(), _image->components(),
294 _image->lines(0), _image->lines(1), _image->lines(2),
295 _image->line_size()[0], _image->line_size()[1], _image->line_size()[2]
298 socket->write (xml.str().length() + 1);
299 socket->write ((uint8_t *) xml.str().c_str(), xml.str().length() + 1);
301 _image->write_to_socket (socket);
303 shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
304 socket->read (e->data(), e->size());
306 _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
312 DCPVideoFrame::add_metadata (xmlpp::Element* el) const
314 el->add_child("Frame")->add_child_text (lexical_cast<string> (_frame));
318 el->add_child("Eyes")->add_child_text ("Both");
321 el->add_child("Eyes")->add_child_text ("Left");
324 el->add_child("Eyes")->add_child_text ("Right");
330 _conversion.as_xml (el->add_child("ColourConversion"));
332 el->add_child("FramesPerSecond")->add_child_text (lexical_cast<string> (_frames_per_second));
333 el->add_child("J2KBandwidth")->add_child_text (lexical_cast<string> (_j2k_bandwidth));
334 el->add_child("Resolution")->add_child_text (lexical_cast<string> (int (_resolution)));
337 EncodedData::EncodedData (int s)
338 : _data (new uint8_t[s])
344 EncodedData::EncodedData (boost::filesystem::path file)
346 _size = boost::filesystem::file_size (file);
347 _data = new uint8_t[_size];
349 FILE* f = fopen_boost (file, "rb");
351 throw FileError (_("could not open file for reading"), file);
354 size_t const r = fread (_data, 1, _size, f);
355 if (r != size_t (_size)) {
357 throw FileError (_("could not read encoded data"), file);
364 EncodedData::~EncodedData ()
369 /** Write this data to a J2K file.
371 * @param frame DCP frame index.
374 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
376 boost::filesystem::path const tmp_j2c = film->j2c_path (frame, eyes, true);
378 FILE* f = fopen_boost (tmp_j2c, "wb");
381 throw WriteFileError (tmp_j2c, errno);
384 fwrite (_data, 1, _size, f);
387 boost::filesystem::path const real_j2c = film->j2c_path (frame, eyes, false);
389 /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
390 boost::filesystem::rename (tmp_j2c, real_j2c);
394 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, dcp::FrameInfo fin) const
396 boost::filesystem::path const info = film->info_path (frame, eyes);
397 FILE* h = fopen_boost (info, "w");
402 /** Send this data to a socket.
403 * @param socket Socket
406 EncodedData::send (shared_ptr<Socket> socket)
408 socket->write (_size);
409 socket->write (_data, _size);
412 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
415 memcpy (_data, d, s);
418 /** @param s Size of data in bytes */
419 RemotelyEncodedData::RemotelyEncodedData (int s)