Merge master.
[dcpomatic.git] / src / lib / dcp_video_frame.cc
1 /*
2     Copyright (C) 2012-2014 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 <openssl/md5.h>
47 #include <dcp/gamma_lut.h>
48 #include <dcp/xyz_frame.h>
49 #include <dcp/rgb_xyz.h>
50 #include <dcp/colour_matrix.h>
51 #include <dcp/raw_convert.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 #include "cross.h"
63 #include "player_video_frame.h"
64
65 #define LOG_GENERAL(...) _log->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
66
67 #include "i18n.h"
68
69 using std::string;
70 using std::stringstream;
71 using std::cout;
72 using boost::shared_ptr;
73 using boost::lexical_cast;
74 using dcp::Size;
75 using dcp::raw_convert;
76
77 #define DCI_COEFFICENT (48.0 / 52.37)
78
79 /** Construct a DCP video frame.
80  *  @param frame Input frame.
81  *  @param index Index of the frame within the DCP.
82  *  @param bw J2K bandwidth to use (see Config::j2k_bandwidth ())
83  *  @param l Log to write to.
84  */
85 DCPVideoFrame::DCPVideoFrame (
86         shared_ptr<const PlayerVideoFrame> frame, int index, int dcp_fps, int bw, Resolution r, shared_ptr<Log> l
87         )
88         : _frame (frame)
89         , _index (index)
90         , _frames_per_second (dcp_fps)
91         , _j2k_bandwidth (bw)
92         , _resolution (r)
93         , _log (l)
94 {
95         
96 }
97
98 DCPVideoFrame::DCPVideoFrame (shared_ptr<const PlayerVideoFrame> frame, shared_ptr<const cxml::Node> node, shared_ptr<Log> log)
99         : _frame (frame)
100         , _log (log)
101 {
102         _index = node->number_child<int> ("Index");
103         _frames_per_second = node->number_child<int> ("FramesPerSecond");
104         _j2k_bandwidth = node->number_child<int> ("J2KBandwidth");
105         _resolution = Resolution (node->optional_number_child<int>("Resolution").get_value_or (RESOLUTION_2K));
106 }
107
108 /** J2K-encode this frame on the local host.
109  *  @return Encoded data.
110  */
111 shared_ptr<EncodedData>
112 DCPVideoFrame::encode_locally ()
113 {
114         shared_ptr<dcp::GammaLUT> in_lut = dcp::GammaLUT::cache.get (
115                 12, _frame->colour_conversion().input_gamma, _frame->colour_conversion().input_gamma_linearised
116                 );
117         
118         /* XXX: libdcp should probably use boost */
119         
120         double matrix[3][3];
121         for (int i = 0; i < 3; ++i) {
122                 for (int j = 0; j < 3; ++j) {
123                         matrix[i][j] = _frame->colour_conversion().matrix (i, j);
124                 }
125         }
126
127         shared_ptr<dcp::XYZFrame> xyz = dcp::rgb_to_xyz (
128                 _frame->image(),
129                 in_lut,
130                 dcp::GammaLUT::cache.get (16, 1 / _frame->colour_conversion().output_gamma, false),
131                 matrix
132                 );
133
134         {
135                 MD5_CTX md5_context;
136                 MD5_Init (&md5_context);
137                 MD5_Update (&md5_context, xyz->data(0), 1998 * 1080 * 4);
138                 MD5_Update (&md5_context, xyz->data(1), 1998 * 1080 * 4);
139                 MD5_Update (&md5_context, xyz->data(2), 1998 * 1080 * 4);
140                 unsigned char digest[MD5_DIGEST_LENGTH];
141                 MD5_Final (digest, &md5_context);
142                 
143                 stringstream s;
144                 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
145                         s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
146                 }
147         }
148
149         /* Set the max image and component sizes based on frame_rate */
150         int max_cs_len = ((float) _j2k_bandwidth) / 8 / _frames_per_second;
151         if (_frame->eyes() == EYES_LEFT || _frame->eyes() == EYES_RIGHT) {
152                 /* In 3D we have only half the normal bandwidth per eye */
153                 max_cs_len /= 2;
154         }
155         int const max_comp_size = max_cs_len / 1.25;
156
157         /* get a J2K compressor handle */
158         opj_cinfo_t* cinfo = opj_create_compress (CODEC_J2K);
159         if (cinfo == 0) {
160                 throw EncodeError (N_("could not create JPEG2000 encoder"));
161         }
162
163         /* Set encoding parameters to default values */
164         opj_cparameters_t parameters;
165         opj_set_default_encoder_parameters (&parameters);
166
167         /* Set default cinema parameters */
168         parameters.tile_size_on = false;
169         parameters.cp_tdx = 1;
170         parameters.cp_tdy = 1;
171         
172         /* Tile part */
173         parameters.tp_flag = 'C';
174         parameters.tp_on = 1;
175         
176         /* Tile and Image shall be at (0,0) */
177         parameters.cp_tx0 = 0;
178         parameters.cp_ty0 = 0;
179         parameters.image_offset_x0 = 0;
180         parameters.image_offset_y0 = 0;
181
182         /* Codeblock size = 32x32 */
183         parameters.cblockw_init = 32;
184         parameters.cblockh_init = 32;
185         parameters.csty |= 0x01;
186         
187         /* The progression order shall be CPRL */
188         parameters.prog_order = CPRL;
189         
190         /* No ROI */
191         parameters.roi_compno = -1;
192         
193         parameters.subsampling_dx = 1;
194         parameters.subsampling_dy = 1;
195         
196         /* 9-7 transform */
197         parameters.irreversible = 1;
198         
199         parameters.tcp_rates[0] = 0;
200         parameters.tcp_numlayers++;
201         parameters.cp_disto_alloc = 1;
202         parameters.cp_rsiz = _resolution == RESOLUTION_2K ? CINEMA2K : CINEMA4K;
203         if (_resolution == RESOLUTION_4K) {
204                 parameters.numpocs = 2;
205                 parameters.POC[0].tile = 1;
206                 parameters.POC[0].resno0 = 0; 
207                 parameters.POC[0].compno0 = 0;
208                 parameters.POC[0].layno1 = 1;
209                 parameters.POC[0].resno1 = parameters.numresolution - 1;
210                 parameters.POC[0].compno1 = 3;
211                 parameters.POC[0].prg1 = CPRL;
212                 parameters.POC[1].tile = 1;
213                 parameters.POC[1].resno0 = parameters.numresolution - 1; 
214                 parameters.POC[1].compno0 = 0;
215                 parameters.POC[1].layno1 = 1;
216                 parameters.POC[1].resno1 = parameters.numresolution;
217                 parameters.POC[1].compno1 = 3;
218                 parameters.POC[1].prg1 = CPRL;
219         }
220         
221         parameters.cp_comment = strdup (N_("DCP-o-matic"));
222         parameters.cp_cinema = _resolution == RESOLUTION_2K ? CINEMA2K_24 : CINEMA4K_24;
223
224         /* 3 components, so use MCT */
225         parameters.tcp_mct = 1;
226         
227         /* set max image */
228         parameters.max_comp_size = max_comp_size;
229         parameters.tcp_rates[0] = ((float) (3 * xyz->size().width * xyz->size().height * 12)) / (max_cs_len * 8);
230
231         /* Set event manager to null (openjpeg 1.3 bug) */
232         cinfo->event_mgr = 0;
233
234         /* Setup the encoder parameters using the current image and user parameters */
235         opj_setup_encoder (cinfo, &parameters, xyz->opj_image ());
236
237         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) cinfo, 0, 0);
238         if (cio == 0) {
239                 opj_destroy_compress (cinfo);
240                 throw EncodeError (N_("could not open JPEG2000 stream"));
241         }
242
243         int const r = opj_encode (cinfo, cio, xyz->opj_image(), 0);
244         if (r == 0) {
245                 opj_cio_close (cio);
246                 opj_destroy_compress (cinfo);
247                 throw EncodeError (N_("JPEG2000 encoding failed"));
248         }
249
250         switch (_frame->eyes()) {
251         case EYES_BOTH:
252                 LOG_GENERAL (N_("Finished locally-encoded frame %1 for mono"), _index);
253                 break;
254         case EYES_LEFT:
255                 LOG_GENERAL (N_("Finished locally-encoded frame %1 for L"), _index);
256                 break;
257         case EYES_RIGHT:
258                 LOG_GENERAL (N_("Finished locally-encoded frame %1 for R"), _index);
259                 break;
260         default:
261                 break;
262         }
263
264         shared_ptr<EncodedData> enc (new LocallyEncodedData (cio->buffer, cio_tell (cio)));
265
266         opj_cio_close (cio);
267         free (parameters.cp_comment);
268         opj_destroy_compress (cinfo);
269
270         return enc;
271 }
272
273 /** Send this frame to a remote server for J2K encoding, then read the result.
274  *  @param serv Server to send to.
275  *  @return Encoded data.
276  */
277 shared_ptr<EncodedData>
278 DCPVideoFrame::encode_remotely (ServerDescription serv)
279 {
280         boost::asio::io_service io_service;
281         boost::asio::ip::tcp::resolver resolver (io_service);
282         boost::asio::ip::tcp::resolver::query query (serv.host_name(), raw_convert<string> (Config::instance()->server_port_base ()));
283         boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
284
285         shared_ptr<Socket> socket (new Socket);
286
287         socket->connect (*endpoint_iterator);
288
289         /* Collect all XML metadata */
290         xmlpp::Document doc;
291         xmlpp::Element* root = doc.create_root_node ("EncodingRequest");
292         root->add_child("Version")->add_child_text (raw_convert<string> (SERVER_LINK_VERSION));
293         add_metadata (root);
294
295         LOG_GENERAL (N_("Sending frame %1 to remote"), _index);
296         
297         /* Send XML metadata */
298         stringstream xml;
299         doc.write_to_stream (xml, "UTF-8");
300         socket->write (xml.str().length() + 1);
301         socket->write ((uint8_t *) xml.str().c_str(), xml.str().length() + 1);
302
303         /* Send binary data */
304         _frame->send_binary (socket);
305
306         /* Read the response (JPEG2000-encoded data); this blocks until the data
307            is ready and sent back.
308         */
309         shared_ptr<EncodedData> e (new RemotelyEncodedData (socket->read_uint32 ()));
310         socket->read (e->data(), e->size());
311
312         LOG_GENERAL (N_("Finished remotely-encoded frame %1"), _index);
313         
314         return e;
315 }
316
317 void
318 DCPVideoFrame::add_metadata (xmlpp::Element* el) const
319 {
320         el->add_child("Index")->add_child_text (raw_convert<string> (_index));
321         el->add_child("FramesPerSecond")->add_child_text (raw_convert<string> (_frames_per_second));
322         el->add_child("J2KBandwidth")->add_child_text (raw_convert<string> (_j2k_bandwidth));
323         el->add_child("Resolution")->add_child_text (raw_convert<string> (int (_resolution)));
324         _frame->add_metadata (el);
325 }
326
327 Eyes
328 DCPVideoFrame::eyes () const
329 {
330         return _frame->eyes ();
331 }
332
333 EncodedData::EncodedData (int s)
334         : _data (new uint8_t[s])
335         , _size (s)
336 {
337
338 }
339
340 EncodedData::EncodedData (boost::filesystem::path file)
341 {
342         _size = boost::filesystem::file_size (file);
343         _data = new uint8_t[_size];
344
345         FILE* f = fopen_boost (file, "rb");
346         if (!f) {
347                 throw FileError (_("could not open file for reading"), file);
348         }
349         
350         size_t const r = fread (_data, 1, _size, f);
351         if (r != size_t (_size)) {
352                 fclose (f);
353                 throw FileError (_("could not read encoded data"), file);
354         }
355                 
356         fclose (f);
357 }
358
359
360 EncodedData::~EncodedData ()
361 {
362         delete[] _data;
363 }
364
365 /** Write this data to a J2K file.
366  *  @param Film Film.
367  *  @param frame DCP frame index.
368  */
369 void
370 EncodedData::write (shared_ptr<const Film> film, int frame, Eyes eyes) const
371 {
372         boost::filesystem::path const tmp_j2c = film->j2c_path (frame, eyes, true);
373
374         FILE* f = fopen_boost (tmp_j2c, "wb");
375         
376         if (!f) {
377                 throw WriteFileError (tmp_j2c, errno);
378         }
379
380         fwrite (_data, 1, _size, f);
381         fclose (f);
382
383         boost::filesystem::path const real_j2c = film->j2c_path (frame, eyes, false);
384
385         /* Rename the file from foo.j2c.tmp to foo.j2c now that it is complete */
386         boost::filesystem::rename (tmp_j2c, real_j2c);
387 }
388
389 void
390 EncodedData::write_info (shared_ptr<const Film> film, int frame, Eyes eyes, dcp::FrameInfo fin) const
391 {
392         boost::filesystem::path const info = film->info_path (frame, eyes);
393         FILE* h = fopen_boost (info, "w");
394         fin.write (h);
395         fclose (h);
396 }
397
398 /** Send this data to a socket.
399  *  @param socket Socket
400  */
401 void
402 EncodedData::send (shared_ptr<Socket> socket)
403 {
404         socket->write (_size);
405         socket->write (_data, _size);
406 }
407
408 LocallyEncodedData::LocallyEncodedData (uint8_t* d, int s)
409         : EncodedData (s)
410 {
411         memcpy (_data, d, s);
412 }
413
414 /** @param s Size of data in bytes */
415 RemotelyEncodedData::RemotelyEncodedData (int s)
416         : EncodedData (s)
417 {
418
419 }