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