2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
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.
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.
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.
21 * @brief Utility methods.
25 #include "exceptions.h"
27 #include "argb_frame.h"
28 #include "certificates.h"
29 #include "gamma_lut.h"
30 #include "xyz_frame.h"
31 #include "compose.hpp"
33 #include "KM_fileio.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>
52 using std::stringstream;
59 using boost::shared_ptr;
60 using boost::optional;
61 using boost::function;
62 using boost::algorithm::trim;
73 Kumu::GenRandomValue (id);
74 id.EncodeHex (buffer, 64);
75 return string (buffer);
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.
86 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
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));
97 int const buffer_size = 65536;
98 Kumu::ByteString read_buffer (buffer_size);
100 Kumu::fsize_t done = 0;
101 Kumu::fsize_t const size = reader.Size ();
104 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
106 if (r == Kumu::RESULT_ENDOFFILE) {
108 } else if (ASDCP_FAILURE (r)) {
109 boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
112 SHA1_Update (&sha, read_buffer.Data(), read);
115 progress (float (done) / size);
120 byte_t byte_buffer[SHA_DIGEST_LENGTH];
121 SHA1_Final (byte_buffer, &sha);
124 return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
127 /** Convert a content kind to a string which can be used in a
128 * <ContentKind> node.
129 * @param kind ContentKind.
133 dcp::content_kind_to_string (ContentKind kind)
145 return "transitional";
152 case PUBLIC_SERVICE_ANNOUNCEMENT:
155 return "advertisement";
161 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
162 * Reasonably tolerant about varying case.
163 * @param kind Content kind string.
164 * @return libdcp ContentKind.
167 dcp::content_kind_from_string (string kind)
169 transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
171 if (kind == "feature") {
173 } else if (kind == "short") {
175 } else if (kind == "trailer") {
177 } else if (kind == "test") {
179 } else if (kind == "transitional") {
181 } else if (kind == "rating") {
183 } else if (kind == "teaser") {
185 } else if (kind == "policy") {
187 } else if (kind == "psa") {
188 return PUBLIC_SERVICE_ANNOUNCEMENT;
189 } else if (kind == "advertisement") {
190 return ADVERTISEMENT;
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.
205 shared_ptr<dcp::XYZFrame>
206 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
208 opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
209 opj_dparameters_t parameters;
210 opj_set_default_decoder_parameters (¶meters);
211 parameters.cp_reduce = reduce;
212 opj_setup_decoder (decoder, ¶meters);
213 opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
214 opj_image_t* image = opj_decode (decoder, cio);
216 opj_destroy_decompress (decoder);
218 boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
221 opj_destroy_decompress (decoder);
224 image->x1 = rint (float(image->x1) / pow (2, reduce));
225 image->y1 = rint (float(image->y1) / pow (2, reduce));
226 return shared_ptr<XYZFrame> (new XYZFrame (image));
229 /** @param s A string.
230 * @return true if the string contains only space, newline or tab characters, or is empty.
233 dcp::empty_or_white_space (string s)
235 for (size_t i = 0; i < s.length(); ++i) {
236 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
244 /** Set up various bits that the library needs. Should be called one
245 * by client applications.
250 if (xmlSecInit() < 0) {
251 throw MiscError ("could not initialise xmlsec");
254 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
255 if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
256 throw MiscError ("unable to load default xmlsec-crypto library");
260 if (xmlSecCryptoAppInit(0) < 0) {
261 throw MiscError ("could not initialise crypto");
264 if (xmlSecCryptoInit() < 0) {
265 throw MiscError ("could not initialise xmlsec-crypto");
269 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
271 return (a.width == b.width && a.height == b.height);
274 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
279 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
281 s << a.width << "x" << a.height;
285 /** Decode a base64 string. The base64 decode routine in KM_util.cpp
286 * gives different values to both this and the command-line base64
287 * for some inputs. Not sure why.
289 * @param in base64-encoded string.
290 * @param out Output buffer.
291 * @param out_length Length of output buffer.
292 * @return Number of characters written to the output buffer.
295 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
297 BIO* b64 = BIO_new (BIO_f_base64 ());
299 /* This means the input should have no newlines */
300 BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
302 /* Copy our input string, removing newlines */
303 char in_buffer[in.size() + 1];
305 for (size_t i = 0; i < in.size(); ++i) {
306 if (in[i] != '\n' && in[i] != '\r') {
311 BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
312 bmem = BIO_push (b64, bmem);
313 int const N = BIO_read (bmem, out, out_length);
319 /** @param p Path to open.
320 * @param t mode flags, as for fopen(3).
321 * @return FILE pointer or 0 on error.
323 * Apparently there is no way to create an ofstream using a UTF-8
324 * filename under Windows. We are hence reduced to using fopen
328 dcp::fopen_boost (boost::filesystem::path p, string t)
330 #ifdef LIBDCP_WINDOWS
331 wstring w (t.begin(), t.end());
332 /* c_str() here should give a UTF-16 string */
333 return _wfopen (p.c_str(), w.c_str ());
335 return fopen (p.c_str(), t.c_str ());
339 optional<boost::filesystem::path>
340 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
342 boost::filesystem::path::const_iterator i = root.begin ();
343 boost::filesystem::path::const_iterator j = file.begin ();
345 while (i != root.end() && j != file.end() && *i == *j) {
350 if (i != root.end ()) {
351 return optional<boost::filesystem::path> ();
354 boost::filesystem::path rel;
355 while (j != file.end ()) {
363 dcp::ids_equal (string a, string b)
365 transform (a.begin(), a.end(), a.begin(), ::tolower);
366 transform (b.begin(), b.end(), b.begin(), ::tolower);
373 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
375 uintmax_t len = boost::filesystem::file_size (p);
376 if (len > max_length) {
377 throw MiscError ("Unexpectedly long file");
380 char* c = new char[len + 1];
382 FILE* f = fopen_boost (p, "r");
387 fread (c, 1, len, f);
397 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
398 * @return SHA1 fingerprint of key
401 dcp::private_key_fingerprint (string key)
403 boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
404 boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
406 unsigned char buffer[4096];
407 int const N = base64_decode (key, buffer, sizeof (buffer));
411 SHA1_Update (&sha, buffer, N);
413 SHA1_Final (digest, &sha);
415 char digest_base64[64];
416 return Kumu::base64encode (digest, 20, digest_base64, 64);