Merge master.
[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 "util.h"
25 #include "exceptions.h"
26 #include "types.h"
27 #include "argb_frame.h"
28 #include "certificates.h"
29 #include "gamma_lut.h"
30 #include "xyz_frame.h"
31 #include "compose.hpp"
32 #include "KM_util.h"
33 #include "KM_fileio.h"
34 #include "AS_DCP.h"
35 #include <xmlsec/xmldsig.h>
36 #include <xmlsec/dl.h>
37 #include <xmlsec/app.h>
38 #include <xmlsec/crypto.h>
39 #include <libxml++/nodes/element.h>
40 #include <libxml++/document.h>
41 #include <openssl/sha.h>
42 #include <boost/filesystem.hpp>
43 #include <stdexcept>
44 #include <sstream>
45 #include <iostream>
46 #include <iomanip>
47
48 using std::string;
49 using std::wstring;
50 using std::cout;
51 using std::stringstream;
52 using std::min;
53 using std::max;
54 using std::list;
55 using std::setw;
56 using std::setfill;
57 using std::ostream;
58 using boost::shared_ptr;
59 using boost::optional;
60 using boost::function;
61 using namespace dcp;
62
63 /** Create a UUID.
64  *  @return UUID.
65  */
66 string
67 dcp::make_uuid ()
68 {
69         char buffer[64];
70         Kumu::UUID id;
71         Kumu::GenRandomValue (id);
72         id.EncodeHex (buffer, 64);
73         return string (buffer);
74 }
75
76
77 /** Create a digest for a file.
78  *  @param filename File name.
79  *  @param progress Optional progress reporting function.  The function will be called
80  *  with a progress value between 0 and 1.
81  *  @return Digest.
82  */
83 string
84 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
85 {
86         Kumu::FileReader reader;
87         Kumu::Result_t r = reader.OpenRead (filename.string().c_str ());
88         if (ASDCP_FAILURE (r)) {
89                 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
90         }
91         
92         SHA_CTX sha;
93         SHA1_Init (&sha);
94
95         int const buffer_size = 65536;
96         Kumu::ByteString read_buffer (buffer_size);
97
98         Kumu::fsize_t done = 0;
99         Kumu::fsize_t const size = reader.Size ();
100         while (1) {
101                 ui32_t read = 0;
102                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
103                 
104                 if (r == Kumu::RESULT_ENDOFFILE) {
105                         break;
106                 } else if (ASDCP_FAILURE (r)) {
107                         boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
108                 }
109                 
110                 SHA1_Update (&sha, read_buffer.Data(), read);
111
112                 if (progress) {
113                         progress (float (done) / size);
114                         done += read;
115                 }
116         }
117
118         byte_t byte_buffer[SHA_DIGEST_LENGTH];
119         SHA1_Final (byte_buffer, &sha);
120
121         char digest[64];
122         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
123 }
124
125 /** Convert a content kind to a string which can be used in a
126  *  &lt;ContentKind&gt; node.
127  *  @param kind ContentKind.
128  *  @return string.
129  */
130 string
131 dcp::content_kind_to_string (ContentKind kind)
132 {
133         switch (kind) {
134         case FEATURE:
135                 return "feature";
136         case SHORT:
137                 return "short";
138         case TRAILER:
139                 return "trailer";
140         case TEST:
141                 return "test";
142         case TRANSITIONAL:
143                 return "transitional";
144         case RATING:
145                 return "rating";
146         case TEASER:
147                 return "teaser";
148         case POLICY:
149                 return "policy";
150         case PUBLIC_SERVICE_ANNOUNCEMENT:
151                 return "psa";
152         case ADVERTISEMENT:
153                 return "advertisement";
154         }
155
156         assert (false);
157 }
158
159 /** Convert a string from a &lt;ContentKind&gt; node to a libdcp ContentKind.
160  *  Reasonably tolerant about varying case.
161  *  @param kind Content kind string.
162  *  @return libdcp ContentKind.
163  */
164 dcp::ContentKind
165 dcp::content_kind_from_string (string kind)
166 {
167         transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
168         
169         if (kind == "feature") {
170                 return FEATURE;
171         } else if (kind == "short") {
172                 return SHORT;
173         } else if (kind == "trailer") {
174                 return TRAILER;
175         } else if (kind == "test") {
176                 return TEST;
177         } else if (kind == "transitional") {
178                 return TRANSITIONAL;
179         } else if (kind == "rating") {
180                 return RATING;
181         } else if (kind == "teaser") {
182                 return TEASER;
183         } else if (kind == "policy") {
184                 return POLICY;
185         } else if (kind == "psa") {
186                 return PUBLIC_SERVICE_ANNOUNCEMENT;
187         } else if (kind == "advertisement") {
188                 return ADVERTISEMENT;
189         }
190
191         assert (false);
192 }
193
194 /** Decompress a JPEG2000 image to a bitmap.
195  *  @param data JPEG2000 data.
196  *  @param size Size of data in bytes.
197  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
198  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
199  *       1 reduces by (2^1 == 2), ie halving the size of the image.
200  *  This is useful for scaling 4K DCP images down to 2K.
201  *  @return XYZ image.
202  */
203 shared_ptr<dcp::XYZFrame>
204 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
205 {
206         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
207         opj_dparameters_t parameters;
208         opj_set_default_decoder_parameters (&parameters);
209         parameters.cp_reduce = reduce;
210         opj_setup_decoder (decoder, &parameters);
211         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
212         opj_image_t* image = opj_decode (decoder, cio);
213         if (!image) {
214                 opj_destroy_decompress (decoder);
215                 opj_cio_close (cio);
216                 boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
217         }
218
219         opj_destroy_decompress (decoder);
220         opj_cio_close (cio);
221
222         image->x1 = rint (float(image->x1) / pow (2, reduce));
223         image->y1 = rint (float(image->y1) / pow (2, reduce));
224         return shared_ptr<XYZFrame> (new XYZFrame (image));
225 }
226
227 /** @param s A string.
228  *  @return true if the string contains only space, newline or tab characters, or is empty.
229  */
230 bool
231 dcp::empty_or_white_space (string s)
232 {
233         for (size_t i = 0; i < s.length(); ++i) {
234                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
235                         return false;
236                 }
237         }
238
239         return true;
240 }
241
242 /** Set up various bits that the library needs.  Should be called one
243  *  by client applications.
244  */
245 void
246 dcp::init ()
247 {
248         if (xmlSecInit() < 0) {
249                 throw MiscError ("could not initialise xmlsec");
250         }
251
252 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
253         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
254                 throw MiscError ("unable to load default xmlsec-crypto library");
255         }
256 #endif  
257
258         if (xmlSecCryptoAppInit(0) < 0) {
259                 throw MiscError ("could not initialise crypto");
260         }
261
262         if (xmlSecCryptoInit() < 0) {
263                 throw MiscError ("could not initialise xmlsec-crypto");
264         }
265 }
266
267 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
268 {
269         return (a.width == b.width && a.height == b.height);
270 }
271
272 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
273 {
274         return !(a == b);
275 }
276
277 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
278 {
279         s << a.width << "x" << a.height;
280         return s;
281 }
282
283 /** Decode a base64 string.  The base64 decode routine in KM_util.cpp
284  *  gives different values to both this and the command-line base64
285  *  for some inputs.  Not sure why.
286  *
287  *  @param in base64-encoded string.
288  *  @param out Output buffer.
289  *  @param out_length Length of output buffer.
290  *  @return Number of characters written to the output buffer.
291  */
292 int
293 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
294 {
295         BIO* b64 = BIO_new (BIO_f_base64 ());
296
297         /* This means the input should have no newlines */
298         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
299
300         /* Copy our input string, removing newlines */
301         char in_buffer[in.size() + 1];
302         char* p = in_buffer;
303         for (size_t i = 0; i < in.size(); ++i) {
304                 if (in[i] != '\n' && in[i] != '\r') {
305                         *p++ = in[i];
306                 }
307         }
308                 
309         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
310         bmem = BIO_push (b64, bmem);
311         int const N = BIO_read (bmem, out, out_length);
312         BIO_free_all (bmem);
313
314         return N;
315 }
316
317 /** Convert a struct tm to a string of the form
318  *  2014-01-26T21:39:00+01:00
319  *  @param tm struct tm.
320  *  @return Time as a string.
321  */
322 string
323 dcp::tm_to_string (struct tm* tm)
324 {
325         char buffer[64];
326         strftime (buffer, 64, "%Y-%m-%dT%H:%M:%S", tm);
327
328         int offset = 0;
329
330 #ifdef LIBDCP_POSIX
331         offset = tm->tm_gmtoff / 60;
332 #else
333         TIME_ZONE_INFORMATION tz;
334         GetTimeZoneInformation (&tz);
335         offset = tz.Bias;
336 #endif
337         
338         return string (buffer) + utc_offset_to_string (offset);
339 }
340
341 /** @param b Offset from UTC to local time in minutes.
342  *  @return string of the form e.g. -01:00.
343  */
344 string
345 dcp::utc_offset_to_string (int b)
346 {
347         bool const negative = (b < 0);
348         b = negative ? -b : b;
349
350         int const hours = b / 60;
351         int const minutes = b % 60;
352
353         stringstream o;
354         if (negative) {
355                 o << "-";
356         } else {
357                 o << "+";
358         }
359
360         o << setw(2) << setfill('0') << hours << ":" << setw(2) << setfill('0') << minutes;
361         return o.str ();
362 }
363
364 /** Convert a boost::posix_time::ptime to a string of the form
365  *  2014-01-26T21:39:00+01:00.
366  *  @param t boost::posix_time::ptime.
367  *  @return Time as a string.
368  */
369 string
370 dcp::ptime_to_string (boost::posix_time::ptime t)
371 {
372         struct tm t_tm = boost::posix_time::to_tm (t);
373         return tm_to_string (&t_tm);
374 }
375
376
377 /** @param p Path to open.
378  *  @param t mode flags, as for fopen(3).
379  *  @return FILE pointer or 0 on error.
380  *
381  *  Apparently there is no way to create an ofstream using a UTF-8
382  *  filename under Windows.  We are hence reduced to using fopen
383  *  with this wrapper.
384  */
385 FILE *
386 dcp::fopen_boost (boost::filesystem::path p, string t)
387 {
388 #ifdef LIBDCP_WINDOWS
389         wstring w (t.begin(), t.end());
390         /* c_str() here should give a UTF-16 string */
391         return _wfopen (p.c_str(), w.c_str ());
392 #else
393         return fopen (p.c_str(), t.c_str ());
394 #endif
395 }
396
397 optional<boost::filesystem::path>
398 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
399 {
400         boost::filesystem::path::const_iterator i = root.begin ();
401         boost::filesystem::path::const_iterator j = file.begin ();
402
403         while (i != root.end() && j != file.end() && *i == *j) {
404                 ++i;
405                 ++j;
406         }
407
408         if (i != root.end ()) {
409                 return optional<boost::filesystem::path> ();
410         }
411
412         boost::filesystem::path rel;
413         while (j != file.end ()) {
414                 rel /= *j++;
415         }
416
417         return rel;
418 }