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>
47 #include "dcp_video_frame.h"
50 #include "exceptions.h"
60 using std::stringstream;
63 using boost::shared_ptr;
66 /** Construct a DCP video frame.
67 * @param input Input image.
68 * @param f Index of the frame within the DCP.
69 * @param clut Colour look-up table to use (see Config::colour_lut_index ())
70 * @param bw J2K bandwidth to use (see Config::j2k_bandwidth ())
71 * @param l Log to write to.
73 DCPVideoFrame::DCPVideoFrame (
74 shared_ptr<const Image> image, int f, int dcp_fps, int clut, int bw, shared_ptr<Log> l
78 , _frames_per_second (dcp_fps)
90 /** Create a libopenjpeg container suitable for our output image */
92 DCPVideoFrame::create_openjpeg_container ()
94 for (int i = 0; i < 3; ++i) {
97 _cmptparm[i].w = _image->size().width;
98 _cmptparm[i].h = _image->size().height;
101 _cmptparm[i].prec = 12;
102 _cmptparm[i].bpp = 12;
103 _cmptparm[i].sgnd = 0;
106 _opj_image = opj_image_create (3, &_cmptparm[0], CLRSPC_SRGB);
107 if (_opj_image == 0) {
108 throw EncodeError (N_("could not create libopenjpeg image"));
113 _opj_image->x1 = _image->size().width;
114 _opj_image->y1 = _image->size().height;
117 DCPVideoFrame::~DCPVideoFrame ()
120 opj_image_destroy (_opj_image);
124 opj_cio_close (_cio);
128 opj_destroy_compress (_cinfo);
132 free (_parameters->cp_comment);
138 /** J2K-encode this frame on the local host.
139 * @return Encoded data.
141 shared_ptr<EncodedData>
142 DCPVideoFrame::encode_locally ()
144 create_openjpeg_container ();
154 /* Copy our RGB into the openjpeg container, converting to XYZ in the process */
157 for (int y = 0; y < _image->size().height; ++y) {
158 uint8_t* p = _image->data()[0] + y * _image->stride()[0];
159 for (int x = 0; x < _image->size().width; ++x) {
161 /* In gamma LUT (converting 8-bit input to 12-bit) */
162 s.r = lut_in[_colour_lut][*p++ << 4];
163 s.g = lut_in[_colour_lut][*p++ << 4];
164 s.b = lut_in[_colour_lut][*p++ << 4];
166 /* RGB to XYZ Matrix */
167 d.x = ((s.r * color_matrix[_colour_lut][0][0]) +
168 (s.g * color_matrix[_colour_lut][0][1]) +
169 (s.b * color_matrix[_colour_lut][0][2]));
171 d.y = ((s.r * color_matrix[_colour_lut][1][0]) +
172 (s.g * color_matrix[_colour_lut][1][1]) +
173 (s.b * color_matrix[_colour_lut][1][2]));
175 d.z = ((s.r * color_matrix[_colour_lut][2][0]) +
176 (s.g * color_matrix[_colour_lut][2][1]) +
177 (s.b * color_matrix[_colour_lut][2][2]));
180 d.x = d.x * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
181 d.y = d.y * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
182 d.z = d.z * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
185 _opj_image->comps[0].data[jn] = lut_out[LO_DCI][(int) d.x];
186 _opj_image->comps[1].data[jn] = lut_out[LO_DCI][(int) d.y];
187 _opj_image->comps[2].data[jn] = lut_out[LO_DCI][(int) d.z];
193 /* Set the max image and component sizes based on frame_rate */
194 int const max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
195 int const max_comp_size = max_cs_len / 1.25;
197 /* Set encoding parameters to default values */
198 _parameters = new opj_cparameters_t;
199 opj_set_default_encoder_parameters (_parameters);
201 /* Set default cinema parameters */
202 _parameters->tile_size_on = false;
203 _parameters->cp_tdx = 1;
204 _parameters->cp_tdy = 1;
207 _parameters->tp_flag = 'C';
208 _parameters->tp_on = 1;
210 /* Tile and Image shall be at (0,0) */
211 _parameters->cp_tx0 = 0;
212 _parameters->cp_ty0 = 0;
213 _parameters->image_offset_x0 = 0;
214 _parameters->image_offset_y0 = 0;
216 /* Codeblock size = 32x32 */
217 _parameters->cblockw_init = 32;
218 _parameters->cblockh_init = 32;
219 _parameters->csty |= 0x01;
221 /* The progression order shall be CPRL */
222 _parameters->prog_order = CPRL;
225 _parameters->roi_compno = -1;
227 _parameters->subsampling_dx = 1;
228 _parameters->subsampling_dy = 1;
231 _parameters->irreversible = 1;
233 _parameters->tcp_rates[0] = 0;
234 _parameters->tcp_numlayers++;
235 _parameters->cp_disto_alloc = 1;
236 _parameters->cp_rsiz = CINEMA2K;
237 _parameters->cp_comment = strdup (N_("DCP-o-matic"));
238 _parameters->cp_cinema = CINEMA2K_24;
240 /* 3 components, so use MCT */
241 _parameters->tcp_mct = 1;
244 _parameters->max_comp_size = max_comp_size;
245 _parameters->tcp_rates[0] = ((float) (3 * _opj_image->comps[0].w * _opj_image->comps[0].h * _opj_image->comps[0].prec)) / (max_cs_len * 8);
247 /* get a J2K compressor handle */
248 _cinfo = opj_create_compress (CODEC_J2K);
250 throw EncodeError (N_("could not create JPEG2000 encoder"));
253 /* Set event manager to null (openjpeg 1.3 bug) */
254 _cinfo->event_mgr = 0;
256 /* Setup the encoder parameters using the current image and user parameters */
257 opj_setup_encoder (_cinfo, _parameters, _opj_image);
259 _cio = opj_cio_open ((opj_common_ptr) _cinfo, 0, 0);
261 throw EncodeError (N_("could not open JPEG2000 stream"));
264 int const r = opj_encode (_cinfo, _cio, _opj_image, 0);
266 throw EncodeError (N_("JPEG2000 encoding failed"));
269 _log->log (String::compose (N_("Finished locally-encoded frame %1"), _frame));
271 return shared_ptr<EncodedData> (new LocallyEncodedData (_cio->buffer, cio_tell (_cio)));
274 /** Send this frame to a remote server for J2K encoding, then read the result.
275 * @param serv Server to send to.
276 * @return Encoded data.
278 shared_ptr<EncodedData>
279 DCPVideoFrame::encode_remotely (ServerDescription const * serv)
281 boost::asio::io_service io_service;
282 boost::asio::ip::tcp::resolver resolver (io_service);
283 boost::asio::ip::tcp::resolver::query query (serv->host_name(), boost::lexical_cast<string> (Config::instance()->server_port ()));
284 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
286 shared_ptr<Socket> socket (new Socket);
288 socket->connect (*endpoint_iterator);
291 s << N_("encode please\n")
292 << N_("width ") << _image->size().width << N_("\n")
293 << N_("height ") << _image->size().height << N_("\n")
294 << N_("frame ") << _frame << N_("\n")
295 << N_("frames_per_second ") << _frames_per_second << N_("\n")
296 << N_("colour_lut ") << _colour_lut << N_("\n")
297 << N_("j2k_bandwidth ") << _j2k_bandwidth << N_("\n");
299 _log->log (String::compose (
300 N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
301 _image->pixel_format(), _image->components(),
302 _image->lines(0), _image->lines(1), _image->lines(2),
303 _image->line_size()[0], _image->line_size()[1], _image->line_size()[2]
306 socket->write (s.str().length() + 1);
307 socket->write ((uint8_t *) s.str().c_str(), s.str().length() + 1);
309 _image->write_to_socket (socket);
311 shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
312 socket->read (e->data(), e->size());
314 _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
319 EncodedData::EncodedData (int s)
320 : _data (new uint8_t[s])
326 EncodedData::EncodedData (string file)
328 _size = boost::filesystem::file_size (file);
329 _data = new uint8_t[_size];
331 FILE* f = fopen (file.c_str(), N_("rb"));
333 throw FileError (_("could not open file for reading"), file);
336 fread (_data, 1, _size, f);
341 EncodedData::~EncodedData ()
346 /** Write this data to a J2K file.
348 * @param frame DCP frame index.
351 EncodedData::write (shared_ptr<const Film> film, int frame) const
353 string const tmp_j2c = film->j2c_path (frame, true);
355 FILE* f = fopen (tmp_j2c.c_str (), N_("wb"));
358 throw WriteFileError (tmp_j2c, errno);
361 fwrite (_data, 1, _size, f);
364 string const real_j2c = film->j2c_path (frame, false);
366 /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
367 boost::filesystem::rename (tmp_j2c, real_j2c);
371 EncodedData::write_info (shared_ptr<const Film> film, int frame, libdcp::FrameInfo fin) const
373 string const info = film->info_path (frame);
374 ofstream h (info.c_str());
378 /** Send this data to a socket.
379 * @param socket Socket
382 EncodedData::send (shared_ptr<Socket> socket)
384 socket->write (_size);
385 socket->write (_data, _size);
388 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
391 memcpy (_data, d, s);
394 /** @param s Size of data in bytes */
395 RemotelyEncodedData::RemotelyEncodedData (int s)