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