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/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>
54 #include "dcp_video_frame.h"
56 #include "exceptions.h"
67 using std::stringstream;
69 using boost::shared_ptr;
70 using boost::lexical_cast;
73 #define DCI_COEFFICENT (48.0 / 52.37)
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.
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
88 , _frames_per_second (dcp_fps)
96 DCPVideoFrame::DCPVideoFrame (shared_ptr<const Image> image, shared_ptr<const cxml::Node> node, shared_ptr<Log> log)
100 _frame = node->number_child<int> ("Frame");
101 string const eyes = node->string_child ("Eyes");
102 if (eyes == "Both") {
104 } else if (eyes == "Left") {
106 } else if (eyes == "Right") {
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));
117 /** J2K-encode this frame on the local host.
118 * @return Encoded data.
120 shared_ptr<EncodedData>
121 DCPVideoFrame::encode_locally ()
123 shared_ptr<libdcp::LUT> in_lut;
124 if (_conversion.input_gamma_linearised) {
125 in_lut = libdcp::SRGBLinearisedGammaLUT::cache.get (12, _conversion.input_gamma);
127 in_lut = libdcp::GammaLUT::cache.get (12, _conversion.input_gamma);
130 /* XXX: libdcp should probably use boost */
133 for (int i = 0; i < 3; ++i) {
134 for (int j = 0; j < 3; ++j) {
135 matrix[i][j] = _conversion.matrix (i, j);
139 shared_ptr<libdcp::XYZFrame> xyz = libdcp::rgb_to_xyz (
142 libdcp::GammaLUT::cache.get (16, 1 / _conversion.output_gamma),
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 */
152 int const max_comp_size = max_cs_len / 1.25;
154 /* get a J2K compressor handle */
155 opj_cinfo_t* cinfo = opj_create_compress (CODEC_J2K);
157 throw EncodeError (N_("could not create JPEG2000 encoder"));
160 /* Set encoding parameters to default values */
161 opj_cparameters_t parameters;
162 opj_set_default_encoder_parameters (¶meters);
164 /* Set default cinema parameters */
165 parameters.tile_size_on = false;
166 parameters.cp_tdx = 1;
167 parameters.cp_tdy = 1;
170 parameters.tp_flag = 'C';
171 parameters.tp_on = 1;
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;
179 /* Codeblock size = 32x32 */
180 parameters.cblockw_init = 32;
181 parameters.cblockh_init = 32;
182 parameters.csty |= 0x01;
184 /* The progression order shall be CPRL */
185 parameters.prog_order = CPRL;
188 parameters.roi_compno = -1;
190 parameters.subsampling_dx = 1;
191 parameters.subsampling_dy = 1;
194 parameters.irreversible = 1;
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;
218 parameters.cp_comment = strdup (N_("DCP-o-matic"));
219 parameters.cp_cinema = _resolution == RESOLUTION_2K ? CINEMA2K_24 : CINEMA4K_24;
221 /* 3 components, so use MCT */
222 parameters.tcp_mct = 1;
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);
228 /* Set event manager to null (openjpeg 1.3 bug) */
229 cinfo->event_mgr = 0;
231 /* Setup the encoder parameters using the current image and user parameters */
232 opj_setup_encoder (cinfo, ¶meters, xyz->opj_image ());
234 opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
236 opj_destroy_compress (cinfo);
237 throw EncodeError (N_("could not open JPEG2000 stream"));
240 int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
243 opj_destroy_compress (cinfo);
244 throw EncodeError (N_("JPEG2000 encoding failed"));
249 _log->log (String::compose (N_("Finished locally-encoded frame %1 for mono"), _frame));
252 _log->log (String::compose (N_("Finished locally-encoded frame %1 for L"), _frame));
255 _log->log (String::compose (N_("Finished locally-encoded frame %1 for R"), _frame));
261 shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
264 free (parameters.cp_comment);
265 opj_destroy_compress (cinfo);
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.
274 shared_ptr<EncodedData>
275 DCPVideoFrame::encode_remotely (ServerDescription serv)
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);
282 shared_ptr<Socket> socket (new Socket);
284 socket->connect (*endpoint_iterator);
287 xmlpp::Element* root = doc.create_root_node ("EncodingRequest");
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));
295 doc.write_to_stream (xml, "UTF-8");
297 _log->log (String::compose (
298 N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
299 _image->pixel_format(), _image->components(),
300 _image->lines(0), _image->lines(1), _image->lines(2),
301 _image->line_size()[0], _image->line_size()[1], _image->line_size()[2]
304 socket->write (xml.str().length() + 1);
305 socket->write ((uint8_t *) xml.str().c_str(), xml.str().length() + 1);
307 _image->write_to_socket (socket);
309 shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
310 socket->read (e->data(), e->size());
312 _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
318 DCPVideoFrame::add_metadata (xmlpp::Element* el) const
320 el->add_child("Frame")->add_child_text (lexical_cast<string> (_frame));
324 el->add_child("Eyes")->add_child_text ("Both");
327 el->add_child("Eyes")->add_child_text ("Left");
330 el->add_child("Eyes")->add_child_text ("Right");
336 _conversion.as_xml (el->add_child("ColourConversion"));
338 el->add_child("FramesPerSecond")->add_child_text (lexical_cast<string> (_frames_per_second));
339 el->add_child("J2KBandwidth")->add_child_text (lexical_cast<string> (_j2k_bandwidth));
340 el->add_child("Resolution")->add_child_text (lexical_cast<string> (int (_resolution)));
343 EncodedData::EncodedData (int s)
344 : _data (new uint8_t[s])
350 EncodedData::EncodedData (boost::filesystem::path file)
352 _size = boost::filesystem::file_size (file);
353 _data = new uint8_t[_size];
355 FILE* f = fopen_boost (file, "rb");
357 throw FileError (_("could not open file for reading"), file);
360 size_t const r = fread (_data, 1, _size, f);
361 if (r != size_t (_size)) {
363 throw FileError (_("could not read encoded data"), file);
370 EncodedData::~EncodedData ()
375 /** Write this data to a J2K file.
377 * @param frame DCP frame index.
380 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
382 boost::filesystem::path const tmp_j2c = film->j2c_path (frame, eyes, true);
384 FILE* f = fopen_boost (tmp_j2c, "wb");
387 throw WriteFileError (tmp_j2c, errno);
390 fwrite (_data, 1, _size, f);
393 boost::filesystem::path const real_j2c = film->j2c_path (frame, eyes, false);
395 /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
396 boost::filesystem::rename (tmp_j2c, real_j2c);
400 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, libdcp::FrameInfo fin) const
402 boost::filesystem::path const info = film->info_path (frame, eyes);
403 FILE* h = fopen_boost (info, "w");
408 /** Send this data to a socket.
409 * @param socket Socket
412 EncodedData::send (shared_ptr<Socket> socket)
414 socket->write (_size);
415 socket->write (_data, _size);
418 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
421 memcpy (_data, d, s);
424 /** @param s Size of data in bytes */
425 RemotelyEncodedData::RemotelyEncodedData (int s)