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"
51 #include "exceptions.h"
62 using std::stringstream;
65 using boost::shared_ptr;
68 /** Construct a DCP video frame.
69 * @param input Input image.
70 * @param out Required size of output, in pixels (including any padding).
71 * @param s Scaler to use.
72 * @param p Number of pixels of padding either side of the image.
73 * @param f Index of the frame within the DCP's intrinsic duration.
74 * @param fps Frames per second of the Film's source.
75 * @param pp FFmpeg post-processing string to use.
76 * @param clut Colour look-up table to use (see Config::colour_lut_index ())
77 * @param bw J2K bandwidth to use (see Config::j2k_bandwidth ())
78 * @param l Log to write to.
80 DCPVideoFrame::DCPVideoFrame (
81 shared_ptr<const Image> yuv, shared_ptr<Subtitle> sub,
82 Size out, int p, int subtitle_offset, float subtitle_scale,
83 Scaler const * s, int f, float fps, string pp, int clut, int bw, Log* l
89 , _subtitle_offset (subtitle_offset)
90 , _subtitle_scale (subtitle_scale)
93 , _frames_per_second (DCPFrameRate(fps).frames_per_second)
106 /** Create a libopenjpeg container suitable for our output image */
108 DCPVideoFrame::create_openjpeg_container ()
110 for (int i = 0; i < 3; ++i) {
113 _cmptparm[i].w = _out_size.width;
114 _cmptparm[i].h = _out_size.height;
117 _cmptparm[i].prec = 12;
118 _cmptparm[i].bpp = 12;
119 _cmptparm[i].sgnd = 0;
122 _image = opj_image_create (3, &_cmptparm[0], CLRSPC_SRGB);
124 throw EncodeError (N_("could not create libopenjpeg image"));
129 _image->x1 = _out_size.width;
130 _image->y1 = _out_size.height;
133 DCPVideoFrame::~DCPVideoFrame ()
136 opj_image_destroy (_image);
140 opj_cio_close (_cio);
144 opj_destroy_compress (_cinfo);
148 free (_parameters->cp_comment);
154 /** J2K-encode this frame on the local host.
155 * @return Encoded data.
157 shared_ptr<EncodedData>
158 DCPVideoFrame::encode_locally ()
160 if (!_post_process.empty ()) {
161 _input = _input->post_process (_post_process, true);
164 shared_ptr<Image> prepared = _input->scale_and_convert_to_rgb (_out_size, _padding, _scaler, true);
167 Rect tx = subtitle_transformed_area (
168 float (_out_size.width) / _input->size().width,
169 float (_out_size.height) / _input->size().height,
170 _subtitle->area(), _subtitle_offset, _subtitle_scale
173 shared_ptr<Image> im = _subtitle->image()->scale (tx.size(), _scaler, true);
174 prepared->alpha_blend (im, tx.position());
177 create_openjpeg_container ();
187 /* Copy our RGB into the openjpeg container, converting to XYZ in the process */
190 for (int y = 0; y < _out_size.height; ++y) {
191 uint8_t* p = prepared->data()[0] + y * prepared->stride()[0];
192 for (int x = 0; x < _out_size.width; ++x) {
194 /* In gamma LUT (converting 8-bit input to 12-bit) */
195 s.r = lut_in[_colour_lut][*p++ << 4];
196 s.g = lut_in[_colour_lut][*p++ << 4];
197 s.b = lut_in[_colour_lut][*p++ << 4];
199 /* RGB to XYZ Matrix */
200 d.x = ((s.r * color_matrix[_colour_lut][0][0]) +
201 (s.g * color_matrix[_colour_lut][0][1]) +
202 (s.b * color_matrix[_colour_lut][0][2]));
204 d.y = ((s.r * color_matrix[_colour_lut][1][0]) +
205 (s.g * color_matrix[_colour_lut][1][1]) +
206 (s.b * color_matrix[_colour_lut][1][2]));
208 d.z = ((s.r * color_matrix[_colour_lut][2][0]) +
209 (s.g * color_matrix[_colour_lut][2][1]) +
210 (s.b * color_matrix[_colour_lut][2][2]));
213 d.x = d.x * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
214 d.y = d.y * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
215 d.z = d.z * DCI_COEFFICENT * (DCI_LUT_SIZE - 1);
218 _image->comps[0].data[jn] = lut_out[LO_DCI][(int) d.x];
219 _image->comps[1].data[jn] = lut_out[LO_DCI][(int) d.y];
220 _image->comps[2].data[jn] = lut_out[LO_DCI][(int) d.z];
226 /* Set the max image and component sizes based on frame_rate */
227 int const max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
228 int const max_comp_size = max_cs_len / 1.25;
230 /* Set encoding parameters to default values */
231 _parameters = new opj_cparameters_t;
232 opj_set_default_encoder_parameters (_parameters);
234 /* Set default cinema parameters */
235 _parameters->tile_size_on = false;
236 _parameters->cp_tdx = 1;
237 _parameters->cp_tdy = 1;
240 _parameters->tp_flag = 'C';
241 _parameters->tp_on = 1;
243 /* Tile and Image shall be at (0,0) */
244 _parameters->cp_tx0 = 0;
245 _parameters->cp_ty0 = 0;
246 _parameters->image_offset_x0 = 0;
247 _parameters->image_offset_y0 = 0;
249 /* Codeblock size = 32x32 */
250 _parameters->cblockw_init = 32;
251 _parameters->cblockh_init = 32;
252 _parameters->csty |= 0x01;
254 /* The progression order shall be CPRL */
255 _parameters->prog_order = CPRL;
258 _parameters->roi_compno = -1;
260 _parameters->subsampling_dx = 1;
261 _parameters->subsampling_dy = 1;
264 _parameters->irreversible = 1;
266 _parameters->tcp_rates[0] = 0;
267 _parameters->tcp_numlayers++;
268 _parameters->cp_disto_alloc = 1;
269 _parameters->cp_rsiz = CINEMA2K;
270 _parameters->cp_comment = strdup (N_("DVD-o-matic"));
271 _parameters->cp_cinema = CINEMA2K_24;
273 /* 3 components, so use MCT */
274 _parameters->tcp_mct = 1;
277 _parameters->max_comp_size = max_comp_size;
278 _parameters->tcp_rates[0] = ((float) (3 * _image->comps[0].w * _image->comps[0].h * _image->comps[0].prec)) / (max_cs_len * 8);
280 /* get a J2K compressor handle */
281 _cinfo = opj_create_compress (CODEC_J2K);
283 throw EncodeError (N_("could not create JPEG2000 encoder"));
286 /* Set event manager to null (openjpeg 1.3 bug) */
287 _cinfo->event_mgr = 0;
289 /* Setup the encoder parameters using the current image and user parameters */
290 opj_setup_encoder (_cinfo, _parameters, _image);
292 _cio = opj_cio_open ((opj_common_ptr) _cinfo, 0, 0);
294 throw EncodeError (N_("could not open JPEG2000 stream"));
297 int const r = opj_encode (_cinfo, _cio, _image, 0);
299 throw EncodeError (N_("JPEG2000 encoding failed"));
302 _log->log (String::compose (N_("Finished locally-encoded frame %1"), _frame));
304 return shared_ptr<EncodedData> (new LocallyEncodedData (_cio->buffer, cio_tell (_cio)));
307 /** Send this frame to a remote server for J2K encoding, then read the result.
308 * @param serv Server to send to.
309 * @return Encoded data.
311 shared_ptr<EncodedData>
312 DCPVideoFrame::encode_remotely (ServerDescription const * serv)
314 boost::asio::io_service io_service;
315 boost::asio::ip::tcp::resolver resolver (io_service);
316 boost::asio::ip::tcp::resolver::query query (serv->host_name(), boost::lexical_cast<string> (Config::instance()->server_port ()));
317 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
319 shared_ptr<Socket> socket (new Socket);
321 socket->connect (*endpoint_iterator);
324 s << N_("encode please\n")
325 << N_("input_width ") << _input->size().width << N_("\n")
326 << N_("input_height ") << _input->size().height << N_("\n")
327 << N_("input_pixel_format ") << _input->pixel_format() << N_("\n")
328 << N_("output_width ") << _out_size.width << N_("\n")
329 << N_("output_height ") << _out_size.height << N_("\n")
330 << N_("padding ") << _padding << N_("\n")
331 << N_("subtitle_offset ") << _subtitle_offset << N_("\n")
332 << N_("subtitle_scale ") << _subtitle_scale << N_("\n")
333 << N_("scaler ") << _scaler->id () << N_("\n")
334 << N_("frame ") << _frame << N_("\n")
335 << N_("frames_per_second ") << _frames_per_second << N_("\n");
337 if (!_post_process.empty()) {
338 s << N_("post_process ") << _post_process << N_("\n");
341 s << N_("colour_lut ") << _colour_lut << N_("\n")
342 << N_("j2k_bandwidth ") << _j2k_bandwidth << N_("\n");
345 s << N_("subtitle_x ") << _subtitle->position().x << N_("\n")
346 << N_("subtitle_y ") << _subtitle->position().y << N_("\n")
347 << N_("subtitle_width ") << _subtitle->image()->size().width << N_("\n")
348 << N_("subtitle_height ") << _subtitle->image()->size().height << N_("\n");
351 _log->log (String::compose (
352 N_("Sending to remote; pixel format %1, components %2, lines (%3,%4,%5), line sizes (%6,%7,%8)"),
353 _input->pixel_format(), _input->components(),
354 _input->lines(0), _input->lines(1), _input->lines(2),
355 _input->line_size()[0], _input->line_size()[1], _input->line_size()[2]
358 socket->write (s.str().length() + 1);
359 socket->write ((uint8_t *) s.str().c_str(), s.str().length() + 1);
361 _input->write_to_socket (socket);
363 _subtitle->image()->write_to_socket (socket);
366 shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
367 socket->read (e->data(), e->size());
369 _log->log (String::compose (N_("Finished remotely-encoded frame %1"), _frame));
374 EncodedData::EncodedData (int s)
375 : _data (new uint8_t[s])
381 EncodedData::EncodedData (string file)
383 _size = boost::filesystem::file_size (file);
384 _data = new uint8_t[_size];
386 FILE* f = fopen (file.c_str(), N_("rb"));
388 throw FileError (_("could not open file for reading"), file);
391 fread (_data, 1, _size, f);
396 EncodedData::~EncodedData ()
401 /** Write this data to a J2K file.
403 * @param frame DCP frame index.
406 EncodedData::write (shared_ptr<const Film> film, int frame) const
408 string const tmp_j2c = film->j2c_path (frame, true);
410 FILE* f = fopen (tmp_j2c.c_str (), N_("wb"));
413 throw WriteFileError (tmp_j2c, errno);
416 fwrite (_data, 1, _size, f);
419 string const real_j2c = film->j2c_path (frame, false);
421 /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
422 boost::filesystem::rename (tmp_j2c, real_j2c);
426 EncodedData::write_info (shared_ptr<const Film> film, int frame, libdcp::FrameInfo fin) const
428 string const info = film->info_path (frame);
429 ofstream h (info.c_str());
433 /** Send this data to a socket.
434 * @param socket Socket
437 EncodedData::send (shared_ptr<Socket> socket)
439 socket->write (_size);
440 socket->write (_data, _size);
443 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
446 memcpy (_data, d, s);
449 /** @param s Size of data in bytes */
450 RemotelyEncodedData::RemotelyEncodedData (int s)