Trim openjpeg.h includes.
[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 "certificate.h"
28 #include "openjpeg_image.h"
29 #include "dcp_assert.h"
30 #include "compose.hpp"
31 #include "KM_util.h"
32 #include "KM_fileio.h"
33 #include "AS_DCP.h"
34 #include <openjpeg.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 <boost/algorithm/string.hpp>
44 #include <stdexcept>
45 #include <sstream>
46 #include <iostream>
47 #include <iomanip>
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 std::ostream;
59 using boost::shared_ptr;
60 using boost::optional;
61 using boost::function;
62 using boost::algorithm::trim;
63 using namespace dcp;
64
65 /** Create a UUID.
66  *  @return UUID.
67  */
68 string
69 dcp::make_uuid ()
70 {
71         char buffer[64];
72         Kumu::UUID id;
73         Kumu::GenRandomValue (id);
74         id.EncodeHex (buffer, 64);
75         return string (buffer);
76 }
77
78
79 /** Create a digest for a file.
80  *  @param filename File name.
81  *  @param progress Optional progress reporting function.  The function will be called
82  *  with a progress value between 0 and 1.
83  *  @return Digest.
84  */
85 string
86 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
87 {
88         Kumu::FileReader reader;
89         Kumu::Result_t r = reader.OpenRead (filename.string().c_str ());
90         if (ASDCP_FAILURE (r)) {
91                 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
92         }
93
94         SHA_CTX sha;
95         SHA1_Init (&sha);
96
97         int const buffer_size = 65536;
98         Kumu::ByteString read_buffer (buffer_size);
99
100         Kumu::fsize_t done = 0;
101         Kumu::fsize_t const size = reader.Size ();
102         while (1) {
103                 ui32_t read = 0;
104                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
105
106                 if (r == Kumu::RESULT_ENDOFFILE) {
107                         break;
108                 } else if (ASDCP_FAILURE (r)) {
109                         boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
110                 }
111
112                 SHA1_Update (&sha, read_buffer.Data(), read);
113
114                 if (progress) {
115                         progress (float (done) / size);
116                         done += read;
117                 }
118         }
119
120         byte_t byte_buffer[SHA_DIGEST_LENGTH];
121         SHA1_Final (byte_buffer, &sha);
122
123         char digest[64];
124         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
125 }
126
127 /** Convert a content kind to a string which can be used in a
128  *  &lt;ContentKind&gt; node.
129  *  @param kind ContentKind.
130  *  @return string.
131  */
132 string
133 dcp::content_kind_to_string (ContentKind kind)
134 {
135         switch (kind) {
136         case FEATURE:
137                 return "feature";
138         case SHORT:
139                 return "short";
140         case TRAILER:
141                 return "trailer";
142         case TEST:
143                 return "test";
144         case TRANSITIONAL:
145                 return "transitional";
146         case RATING:
147                 return "rating";
148         case TEASER:
149                 return "teaser";
150         case POLICY:
151                 return "policy";
152         case PUBLIC_SERVICE_ANNOUNCEMENT:
153                 return "psa";
154         case ADVERTISEMENT:
155                 return "advertisement";
156         }
157
158         DCP_ASSERT (false);
159 }
160
161 /** Convert a string from a &lt;ContentKind&gt; node to a libdcp ContentKind.
162  *  Reasonably tolerant about varying case.
163  *  @param kind Content kind string.
164  *  @return libdcp ContentKind.
165  */
166 dcp::ContentKind
167 dcp::content_kind_from_string (string kind)
168 {
169         transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
170
171         if (kind == "feature") {
172                 return FEATURE;
173         } else if (kind == "short") {
174                 return SHORT;
175         } else if (kind == "trailer") {
176                 return TRAILER;
177         } else if (kind == "test") {
178                 return TEST;
179         } else if (kind == "transitional") {
180                 return TRANSITIONAL;
181         } else if (kind == "rating") {
182                 return RATING;
183         } else if (kind == "teaser") {
184                 return TEASER;
185         } else if (kind == "policy") {
186                 return POLICY;
187         } else if (kind == "psa") {
188                 return PUBLIC_SERVICE_ANNOUNCEMENT;
189         } else if (kind == "advertisement") {
190                 return ADVERTISEMENT;
191         }
192
193         DCP_ASSERT (false);
194 }
195
196 /** Decompress a JPEG2000 image to a bitmap.
197  *  @param data JPEG2000 data.
198  *  @param size Size of data in bytes.
199  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
200  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
201  *       1 reduces by (2^1 == 2), ie halving the size of the image.
202  *  This is useful for scaling 4K DCP images down to 2K.
203  *  @return OpenJPEGImage.
204  */
205 shared_ptr<dcp::OpenJPEGImage>
206 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
207 {
208         uint8_t const jp2_magic[] = {
209                 0x00,
210                 0x00,
211                 0x00,
212                 0x0c,
213                 'j',
214                 'P',
215                 0x20,
216                 0x20
217         };
218
219         OPJ_CODEC_FORMAT format = CODEC_J2K;
220         if (size >= int (sizeof (jp2_magic)) && memcmp (data, jp2_magic, sizeof (jp2_magic)) == 0) {
221                 format = CODEC_JP2;
222         }
223
224         opj_dinfo_t* decoder = opj_create_decompress (format);
225         if (!decoder) {
226                 boost::throw_exception (DCPReadError ("could not create JPEG2000 decompresser"));
227         }
228         opj_dparameters_t parameters;
229         opj_set_default_decoder_parameters (&parameters);
230         parameters.cp_reduce = reduce;
231         opj_setup_decoder (decoder, &parameters);
232         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
233         if (!cio) {
234                 boost::throw_exception (DCPReadError ("could not create JPEG2000 memory stream"));
235         }
236         opj_image_t* image = opj_decode (decoder, cio);
237         if (!image) {
238                 opj_destroy_decompress (decoder);
239                 opj_cio_close (cio);
240                 if (format == CODEC_J2K) {
241                         boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
242                 } else {
243                         boost::throw_exception (DCPReadError (String::compose ("could not decode JP2 file of %1 bytes.", size)));
244                 }
245         }
246
247         opj_destroy_decompress (decoder);
248         opj_cio_close (cio);
249
250         image->x1 = rint (float(image->x1) / pow (2, reduce));
251         image->y1 = rint (float(image->y1) / pow (2, reduce));
252         return shared_ptr<OpenJPEGImage> (new OpenJPEGImage (image));
253 }
254
255 /** @param s A string.
256  *  @return true if the string contains only space, newline or tab characters, or is empty.
257  */
258 bool
259 dcp::empty_or_white_space (string s)
260 {
261         for (size_t i = 0; i < s.length(); ++i) {
262                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
263                         return false;
264                 }
265         }
266
267         return true;
268 }
269
270 /** Set up various bits that the library needs.  Should be called one
271  *  by client applications.
272  */
273 void
274 dcp::init ()
275 {
276         if (xmlSecInit() < 0) {
277                 throw MiscError ("could not initialise xmlsec");
278         }
279
280 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
281         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
282                 throw MiscError ("unable to load default xmlsec-crypto library");
283         }
284 #endif
285
286         if (xmlSecCryptoAppInit(0) < 0) {
287                 throw MiscError ("could not initialise crypto");
288         }
289
290         if (xmlSecCryptoInit() < 0) {
291                 throw MiscError ("could not initialise xmlsec-crypto");
292         }
293 }
294
295 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
296 {
297         return (a.width == b.width && a.height == b.height);
298 }
299
300 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
301 {
302         return !(a == b);
303 }
304
305 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
306 {
307         s << a.width << "x" << a.height;
308         return s;
309 }
310
311 /** Decode a base64 string.  The base64 decode routine in KM_util.cpp
312  *  gives different values to both this and the command-line base64
313  *  for some inputs.  Not sure why.
314  *
315  *  @param in base64-encoded string.
316  *  @param out Output buffer.
317  *  @param out_length Length of output buffer.
318  *  @return Number of characters written to the output buffer.
319  */
320 int
321 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
322 {
323         BIO* b64 = BIO_new (BIO_f_base64 ());
324
325         /* This means the input should have no newlines */
326         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
327
328         /* Copy our input string, removing newlines */
329         char in_buffer[in.size() + 1];
330         char* p = in_buffer;
331         for (size_t i = 0; i < in.size(); ++i) {
332                 if (in[i] != '\n' && in[i] != '\r') {
333                         *p++ = in[i];
334                 }
335         }
336
337         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
338         bmem = BIO_push (b64, bmem);
339         int const N = BIO_read (bmem, out, out_length);
340         BIO_free_all (bmem);
341
342         return N;
343 }
344
345 /** @param p Path to open.
346  *  @param t mode flags, as for fopen(3).
347  *  @return FILE pointer or 0 on error.
348  *
349  *  Apparently there is no way to create an ofstream using a UTF-8
350  *  filename under Windows.  We are hence reduced to using fopen
351  *  with this wrapper.
352  */
353 FILE *
354 dcp::fopen_boost (boost::filesystem::path p, string t)
355 {
356 #ifdef LIBDCP_WINDOWS
357         wstring w (t.begin(), t.end());
358         /* c_str() here should give a UTF-16 string */
359         return _wfopen (p.c_str(), w.c_str ());
360 #else
361         return fopen (p.c_str(), t.c_str ());
362 #endif
363 }
364
365 optional<boost::filesystem::path>
366 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
367 {
368         boost::filesystem::path::const_iterator i = root.begin ();
369         boost::filesystem::path::const_iterator j = file.begin ();
370
371         while (i != root.end() && j != file.end() && *i == *j) {
372                 ++i;
373                 ++j;
374         }
375
376         if (i != root.end ()) {
377                 return optional<boost::filesystem::path> ();
378         }
379
380         boost::filesystem::path rel;
381         while (j != file.end ()) {
382                 rel /= *j++;
383         }
384
385         return rel;
386 }
387
388 bool
389 dcp::ids_equal (string a, string b)
390 {
391         transform (a.begin(), a.end(), a.begin(), ::tolower);
392         transform (b.begin(), b.end(), b.begin(), ::tolower);
393         trim (a);
394         trim (b);
395         return a == b;
396 }
397
398 string
399 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
400 {
401         uintmax_t len = boost::filesystem::file_size (p);
402         if (len > max_length) {
403                 throw MiscError ("Unexpectedly long file");
404         }
405
406         char* c = new char[len + 1];
407
408         FILE* f = fopen_boost (p, "r");
409         if (!f) {
410                 return "";
411         }
412
413         fread (c, 1, len, f);
414         fclose (f);
415         c[len] = '\0';
416
417         string s (c);
418         delete[] c;
419
420         return s;
421 }
422
423 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
424  *  @return SHA1 fingerprint of key
425  */
426 string
427 dcp::private_key_fingerprint (string key)
428 {
429         boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
430         boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
431
432         unsigned char buffer[4096];
433         int const N = base64_decode (key, buffer, sizeof (buffer));
434
435         SHA_CTX sha;
436         SHA1_Init (&sha);
437         SHA1_Update (&sha, buffer, N);
438         uint8_t digest[20];
439         SHA1_Final (digest, &sha);
440
441         char digest_base64[64];
442         return Kumu::base64encode (digest, 20, digest_base64, 64);
443 }
444
445 xmlpp::Node *
446 dcp::find_child (xmlpp::Node const * node, string name)
447 {
448         xmlpp::Node::NodeList c = node->get_children ();
449         xmlpp::Node::NodeList::iterator i = c.begin();
450         while (i != c.end() && (*i)->get_name() != name) {
451                 ++i;
452         }
453
454         DCP_ASSERT (i != c.end ());
455         return *i;
456 }