tm_to_string() should use 24 hour clock.
[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::cout;
50 using std::stringstream;
51 using std::min;
52 using std::max;
53 using std::list;
54 using std::setw;
55 using std::setfill;
56 using boost::shared_ptr;
57 using boost::lexical_cast;
58 using namespace libdcp;
59
60 /** Create a UUID.
61  *  @return UUID.
62  */
63 string
64 libdcp::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 libdcp::make_digest (string filename, boost::function<void (float)>* progress)
82 {
83         Kumu::FileReader reader;
84         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
85                 boost::throw_exception (FileError ("could not open file to compute digest", filename));
86         }
87         
88         SHA_CTX sha;
89         SHA1_Init (&sha);
90
91         int const buffer_size = 65536;
92         Kumu::ByteString read_buffer (buffer_size);
93
94         Kumu::fsize_t done = 0;
95         Kumu::fsize_t const size = reader.Size ();
96         while (1) {
97                 ui32_t read = 0;
98                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
99                 
100                 if (r == Kumu::RESULT_ENDOFFILE) {
101                         break;
102                 } else if (ASDCP_FAILURE (r)) {
103                         boost::throw_exception (FileError ("could not read file to compute digest", filename));
104                 }
105                 
106                 SHA1_Update (&sha, read_buffer.Data(), read);
107
108                 if (progress) {
109                         (*progress) (float (done) / size);
110                         done += read;
111                 }
112         }
113
114         byte_t byte_buffer[SHA_DIGEST_LENGTH];
115         SHA1_Final (byte_buffer, &sha);
116
117         char digest[64];
118         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
119 }
120
121 /** Convert a content kind to a string which can be used in a
122  *  <ContentKind> node.
123  *  @param kind ContentKind.
124  *  @return string.
125  */
126 string
127 libdcp::content_kind_to_string (ContentKind kind)
128 {
129         switch (kind) {
130         case FEATURE:
131                 return "feature";
132         case SHORT:
133                 return "short";
134         case TRAILER:
135                 return "trailer";
136         case TEST:
137                 return "test";
138         case TRANSITIONAL:
139                 return "transitional";
140         case RATING:
141                 return "rating";
142         case TEASER:
143                 return "teaser";
144         case POLICY:
145                 return "policy";
146         case PUBLIC_SERVICE_ANNOUNCEMENT:
147                 return "psa";
148         case ADVERTISEMENT:
149                 return "advertisement";
150         }
151
152         assert (false);
153 }
154
155 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
156  *  Reasonably tolerant about varying case.
157  *  @param type Content kind string.
158  *  @return libdcp ContentKind.
159  */
160 libdcp::ContentKind
161 libdcp::content_kind_from_string (string type)
162 {
163         /* XXX: should probably just convert type to lower-case and have done with it */
164         
165         if (type == "feature") {
166                 return FEATURE;
167         } else if (type == "short") {
168                 return SHORT;
169         } else if (type == "trailer" || type == "Trailer") {
170                 return TRAILER;
171         } else if (type == "test") {
172                 return TEST;
173         } else if (type == "transitional") {
174                 return TRANSITIONAL;
175         } else if (type == "rating") {
176                 return RATING;
177         } else if (type == "teaser" || type == "Teaser") {
178                 return TEASER;
179         } else if (type == "policy") {
180                 return POLICY;
181         } else if (type == "psa") {
182                 return PUBLIC_SERVICE_ANNOUNCEMENT;
183         } else if (type == "advertisement") {
184                 return ADVERTISEMENT;
185         }
186
187         assert (false);
188 }
189
190 /** Decompress a JPEG2000 image to a bitmap.
191  *  @param data JPEG2000 data.
192  *  @param size Size of data in bytes.
193  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
194  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
195  *       1 reduces by (2^1 == 2), ie halving the size of the image.
196  *  This is useful for scaling 4K DCP images down to 2K.
197  *  @return XYZ image.
198  */
199 shared_ptr<libdcp::XYZFrame>
200 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
201 {
202         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
203         opj_dparameters_t parameters;
204         opj_set_default_decoder_parameters (&parameters);
205         parameters.cp_reduce = reduce;
206         opj_setup_decoder (decoder, &parameters);
207         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
208         opj_image_t* image = opj_decode (decoder, cio);
209         if (!image) {
210                 opj_destroy_decompress (decoder);
211                 opj_cio_close (cio);
212                 boost::throw_exception (DCPReadError ("could not decode JPEG2000 codestream of " + lexical_cast<string> (size) + " bytes."));
213         }
214
215         opj_cio_close (cio);
216
217         image->x1 = rint (float(image->x1) / pow (2, reduce));
218         image->y1 = rint (float(image->y1) / pow (2, reduce));
219         return shared_ptr<XYZFrame> (new XYZFrame (image));
220 }
221
222 /** @param s A string.
223  *  @return true if the string contains only space, newline or tab characters, or is empty.
224  */
225 bool
226 libdcp::empty_or_white_space (string s)
227 {
228         for (size_t i = 0; i < s.length(); ++i) {
229                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
230                         return false;
231                 }
232         }
233
234         return true;
235 }
236
237 void
238 libdcp::init ()
239 {
240         if (xmlSecInit() < 0) {
241                 throw MiscError ("could not initialise xmlsec");
242         }
243
244 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
245         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
246                 throw MiscError ("unable to load default xmlsec-crypto library");
247         }
248 #endif  
249
250         if (xmlSecCryptoAppInit(0) < 0) {
251                 throw MiscError ("could not initialise crypto");
252         }
253
254         if (xmlSecCryptoInit() < 0) {
255                 throw MiscError ("could not initialise xmlsec-crypto");
256         }
257 }
258
259 bool libdcp::operator== (libdcp::Size const & a, libdcp::Size const & b)
260 {
261         return (a.width == b.width && a.height == b.height);
262 }
263
264 bool libdcp::operator!= (libdcp::Size const & a, libdcp::Size const & b)
265 {
266         return !(a == b);
267 }
268
269 /** The base64 decode routine in KM_util.cpp gives different values to both
270  *  this and the command-line base64 for some inputs.  Not sure why.
271  */
272 int
273 libdcp::base64_decode (string const & in, unsigned char* out, int out_length)
274 {
275         BIO* b64 = BIO_new (BIO_f_base64 ());
276
277         /* This means the input should have no newlines */
278         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
279
280         /* Copy our input string, removing newlines */
281         char in_buffer[in.size() + 1];
282         char* p = in_buffer;
283         for (size_t i = 0; i < in.size(); ++i) {
284                 if (in[i] != '\n' && in[i] != '\r') {
285                         *p++ = in[i];
286                 }
287         }
288                 
289         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
290         bmem = BIO_push (b64, bmem);
291         int const N = BIO_read (bmem, out, out_length);
292         BIO_free_all (bmem);
293
294         return N;
295 }
296
297 string
298 libdcp::tm_to_string (struct tm* tm)
299 {
300         char buffer[64];
301         strftime (buffer, 64, "%Y-%m-%dT%H:%M:%S", tm);
302
303         int offset = 0;
304
305 #ifdef LIBDCP_POSIX
306         offset = tm->tm_gmtoff / 60;
307 #else
308         TIME_ZONE_INFORMATION tz;
309         GetTimeZoneInformation (&tz);
310         offset = tz.Bias;
311 #endif
312         
313         return string (buffer) + utc_offset_to_string (offset);
314 }
315
316 /** @param b Offset from UTC to local time in minutes.
317  *  @return string of the form e.g. -01:00.
318  */
319 string
320 libdcp::utc_offset_to_string (int b)
321 {
322         bool const negative = (b < 0);
323         b = negative ? -b : b;
324
325         int const hours = b / 60;
326         int const minutes = b % 60;
327
328         stringstream o;
329         if (negative) {
330                 o << "-";
331         } else {
332                 o << "+";
333         }
334
335         o << setw(2) << setfill('0') << hours << ":" << setw(2) << setfill('0') << minutes;
336         return o.str ();
337 }
338
339 string
340 libdcp::ptime_to_string (boost::posix_time::ptime t)
341 {
342         struct tm t_tm = boost::posix_time::to_tm (t);
343         return tm_to_string (&t_tm);
344 }