4ac3685c4cd9ab9c5087ce20ac5c45d6cc85d89c
[libdcp.git] / src / util.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/util.cc
21  *  @brief Utility methods.
22  */
23
24 #include <stdexcept>
25 #include <sstream>
26 #include <iostream>
27 #include <iomanip>
28 #include <boost/filesystem.hpp>
29 #include <boost/lexical_cast.hpp>
30 #include <boost/date_time/c_local_time_adjustor.hpp>
31 #include <openssl/sha.h>
32 #include <libxml++/nodes/element.h>
33 #include <libxml++/document.h>
34 #include <xmlsec/xmldsig.h>
35 #include <xmlsec/dl.h>
36 #include <xmlsec/app.h>
37 #include <xmlsec/crypto.h>
38 #include "KM_util.h"
39 #include "KM_fileio.h"
40 #include "AS_DCP.h"
41 #include "util.h"
42 #include "exceptions.h"
43 #include "types.h"
44 #include "argb_frame.h"
45 #include "certificates.h"
46 #include "gamma_lut.h"
47 #include "xyz_frame.h"
48
49 using std::string;
50 using std::wstring;
51 using std::cout;
52 using std::stringstream;
53 using std::min;
54 using std::max;
55 using std::list;
56 using std::setw;
57 using std::setfill;
58 using boost::shared_ptr;
59 using boost::lexical_cast;
60 using namespace libdcp;
61
62 /** Create a UUID.
63  *  @return UUID.
64  */
65 string
66 libdcp::make_uuid ()
67 {
68         char buffer[64];
69         Kumu::UUID id;
70         Kumu::GenRandomValue (id);
71         id.EncodeHex (buffer, 64);
72         return string (buffer);
73 }
74
75
76 /** Create a digest for a file.
77  *  @param filename File name.
78  *  @param progress Pointer to a progress reporting function, or 0.  The function will be called
79  *  with a progress value between 0 and 1.
80  *  @return Digest.
81  */
82 string
83 libdcp::make_digest (string filename, boost::function<void (float)>* progress)
84 {
85         Kumu::FileReader reader;
86         Kumu::Result_t r = reader.OpenRead (filename.c_str ());
87         if (ASDCP_FAILURE (r)) {
88                 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
89         }
90         
91         SHA_CTX sha;
92         SHA1_Init (&sha);
93
94         int const buffer_size = 65536;
95         Kumu::ByteString read_buffer (buffer_size);
96
97         Kumu::fsize_t done = 0;
98         Kumu::fsize_t const size = reader.Size ();
99         while (1) {
100                 ui32_t read = 0;
101                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
102                 
103                 if (r == Kumu::RESULT_ENDOFFILE) {
104                         break;
105                 } else if (ASDCP_FAILURE (r)) {
106                         boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
107                 }
108                 
109                 SHA1_Update (&sha, read_buffer.Data(), read);
110
111                 if (progress) {
112                         (*progress) (float (done) / size);
113                         done += read;
114                 }
115         }
116
117         byte_t byte_buffer[SHA_DIGEST_LENGTH];
118         SHA1_Final (byte_buffer, &sha);
119
120         char digest[64];
121         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
122 }
123
124 /** Convert a content kind to a string which can be used in a
125  *  <ContentKind> node.
126  *  @param kind ContentKind.
127  *  @return string.
128  */
129 string
130 libdcp::content_kind_to_string (ContentKind kind)
131 {
132         switch (kind) {
133         case FEATURE:
134                 return "feature";
135         case SHORT:
136                 return "short";
137         case TRAILER:
138                 return "trailer";
139         case TEST:
140                 return "test";
141         case TRANSITIONAL:
142                 return "transitional";
143         case RATING:
144                 return "rating";
145         case TEASER:
146                 return "teaser";
147         case POLICY:
148                 return "policy";
149         case PUBLIC_SERVICE_ANNOUNCEMENT:
150                 return "psa";
151         case ADVERTISEMENT:
152                 return "advertisement";
153         }
154
155         assert (false);
156 }
157
158 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
159  *  Reasonably tolerant about varying case.
160  *  @param type Content kind string.
161  *  @return libdcp ContentKind.
162  */
163 libdcp::ContentKind
164 libdcp::content_kind_from_string (string type)
165 {
166         transform (type.begin(), type.end(), type.begin(), ::tolower);
167         
168         if (type == "feature") {
169                 return FEATURE;
170         } else if (type == "short") {
171                 return SHORT;
172         } else if (type == "trailer") {
173                 return TRAILER;
174         } else if (type == "test") {
175                 return TEST;
176         } else if (type == "transitional") {
177                 return TRANSITIONAL;
178         } else if (type == "rating") {
179                 return RATING;
180         } else if (type == "teaser") {
181                 return TEASER;
182         } else if (type == "policy") {
183                 return POLICY;
184         } else if (type == "psa") {
185                 return PUBLIC_SERVICE_ANNOUNCEMENT;
186         } else if (type == "advertisement") {
187                 return ADVERTISEMENT;
188         }
189
190         assert (false);
191 }
192
193 /** Decompress a JPEG2000 image to a bitmap.
194  *  @param data JPEG2000 data.
195  *  @param size Size of data in bytes.
196  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
197  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
198  *       1 reduces by (2^1 == 2), ie halving the size of the image.
199  *  This is useful for scaling 4K DCP images down to 2K.
200  *  @return XYZ image.
201  */
202 shared_ptr<libdcp::XYZFrame>
203 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
204 {
205         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
206         opj_dparameters_t parameters;
207         opj_set_default_decoder_parameters (&parameters);
208         parameters.cp_reduce = reduce;
209         opj_setup_decoder (decoder, &parameters);
210         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
211         opj_image_t* image = opj_decode (decoder, cio);
212         if (!image) {
213                 opj_destroy_decompress (decoder);
214                 opj_cio_close (cio);
215                 boost::throw_exception (DCPReadError ("could not decode JPEG2000 codestream of " + lexical_cast<string> (size) + " bytes."));
216         }
217
218         opj_destroy_decompress (decoder);
219         opj_cio_close (cio);
220
221         image->x1 = rint (float(image->x1) / pow (2, reduce));
222         image->y1 = rint (float(image->y1) / pow (2, reduce));
223         return shared_ptr<XYZFrame> (new XYZFrame (image));
224 }
225
226 /** @param s A string.
227  *  @return true if the string contains only space, newline or tab characters, or is empty.
228  */
229 bool
230 libdcp::empty_or_white_space (string s)
231 {
232         for (size_t i = 0; i < s.length(); ++i) {
233                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
234                         return false;
235                 }
236         }
237
238         return true;
239 }
240
241 void
242 libdcp::init ()
243 {
244         if (xmlSecInit() < 0) {
245                 throw MiscError ("could not initialise xmlsec");
246         }
247
248 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
249         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
250                 throw MiscError ("unable to load default xmlsec-crypto library");
251         }
252 #endif  
253
254         if (xmlSecCryptoAppInit(0) < 0) {
255                 throw MiscError ("could not initialise crypto");
256         }
257
258         if (xmlSecCryptoInit() < 0) {
259                 throw MiscError ("could not initialise xmlsec-crypto");
260         }
261 }
262
263 bool libdcp::operator== (libdcp::Size const & a, libdcp::Size const & b)
264 {
265         return (a.width == b.width && a.height == b.height);
266 }
267
268 bool libdcp::operator!= (libdcp::Size const & a, libdcp::Size const & b)
269 {
270         return !(a == b);
271 }
272
273 /** The base64 decode routine in KM_util.cpp gives different values to both
274  *  this and the command-line base64 for some inputs.  Not sure why.
275  */
276 int
277 libdcp::base64_decode (string const & in, unsigned char* out, int out_length)
278 {
279         BIO* b64 = BIO_new (BIO_f_base64 ());
280
281         /* This means the input should have no newlines */
282         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
283
284         /* Copy our input string, removing newlines */
285         char in_buffer[in.size() + 1];
286         char* p = in_buffer;
287         for (size_t i = 0; i < in.size(); ++i) {
288                 if (in[i] != '\n' && in[i] != '\r') {
289                         *p++ = in[i];
290                 }
291         }
292                 
293         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
294         bmem = BIO_push (b64, bmem);
295         int const N = BIO_read (bmem, out, out_length);
296         BIO_free_all (bmem);
297
298         return N;
299 }
300
301 /** @param tm Local time.
302  *  @return String of the form 2014-04-02T18:05:23+04:00, where the UTC offset is derived
303  *  from the current system time zone.
304  */
305 string
306 libdcp::tm_to_string (struct tm* tm)
307 {
308         char buffer[64];
309         strftime (buffer, 64, "%Y-%m-%dT%H:%M:%S", tm);
310
311         /* Compute current UTC offset */
312         boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
313         boost::posix_time::ptime const now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
314
315         return string (buffer) + utc_offset_to_string (now - utc_now);
316 }
317
318 /** @param b Offset from UTC to local time.
319  *  @return string of the form e.g. -01:00.
320  */
321 string
322 libdcp::utc_offset_to_string (boost::posix_time::time_duration b)
323 {
324         bool const negative = b.is_negative ();
325         if (negative) {
326                 b = boost::posix_time::time_duration (-b.hours(), b.minutes(), 0, 0);
327         }
328
329         stringstream o;
330         if (negative) {
331                 o << "-";
332         } else {
333                 o << "+";
334         }
335
336         o << setw(2) << setfill('0') << b.hours() << ":" << setw(2) << setfill('0') << b.minutes();
337         return o.str ();
338 }
339
340 string
341 libdcp::ptime_to_string (boost::posix_time::ptime t)
342 {
343         struct tm t_tm = boost::posix_time::to_tm (t);
344         return tm_to_string (&t_tm);
345 }
346
347
348 /* Apparently there is no way to create an ofstream using a UTF-8
349    filename under Windows.  We are hence reduced to using fopen
350    with this wrapper.
351 */
352 FILE *
353 libdcp::fopen_boost (boost::filesystem::path p, string t)
354 {
355 #ifdef LIBDCP_WINDOWS
356         wstring w (t.begin(), t.end());
357         /* c_str() here should give a UTF-16 string */
358         return _wfopen (p.c_str(), w.c_str ());
359 #else
360         return fopen (p.c_str(), t.c_str ());
361 #endif
362 }