cscript tweak.
[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 "KM_util.h"
32 #include "KM_fileio.h"
33 #include "AS_DCP.h"
34 #include "util.h"
35 #include "exceptions.h"
36 #include "types.h"
37 #include "argb_frame.h"
38 #include "gamma_lut.h"
39
40 using std::string;
41 using std::stringstream;
42 using std::min;
43 using std::max;
44 using boost::shared_ptr;
45 using boost::lexical_cast;
46 using namespace libdcp;
47
48 /** Create a UUID.
49  *  @return UUID.
50  */
51 string
52 libdcp::make_uuid ()
53 {
54         char buffer[64];
55         Kumu::UUID id;
56         Kumu::GenRandomValue (id);
57         id.EncodeHex (buffer, 64);
58         return string (buffer);
59 }
60
61
62 /** Create a digest for a file.
63  *  @param filename File name.
64  *  @return Digest.
65  */
66 string
67 libdcp::make_digest (string filename)
68 {
69         Kumu::FileReader reader;
70         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
71                 boost::throw_exception (FileError ("could not open file to compute digest", filename));
72         }
73         
74         SHA_CTX sha;
75         SHA1_Init (&sha);
76         
77         Kumu::ByteString read_buffer (65536);
78         int done = 0;
79         while (1) {
80                 ui32_t read = 0;
81                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
82                 
83                 if (r == Kumu::RESULT_ENDOFFILE) {
84                         break;
85                 } else if (ASDCP_FAILURE (r)) {
86                         boost::throw_exception (FileError ("could not read file to compute digest", filename));
87                 }
88                 
89                 SHA1_Update (&sha, read_buffer.Data(), read);
90                 done += read;
91         }
92
93         byte_t byte_buffer[20];
94         SHA1_Final (byte_buffer, &sha);
95
96         stringstream s;
97         char digest[64];
98         return Kumu::base64encode (byte_buffer, 20, digest, 64);
99 }
100
101 /** Convert a content kind to a string which can be used in a
102  *  <ContentKind> node.
103  *  @param kind ContentKind.
104  *  @return string.
105  */
106 string
107 libdcp::content_kind_to_string (ContentKind kind)
108 {
109         switch (kind) {
110         case FEATURE:
111                 return "feature";
112         case SHORT:
113                 return "short";
114         case TRAILER:
115                 return "trailer";
116         case TEST:
117                 return "test";
118         case TRANSITIONAL:
119                 return "transitional";
120         case RATING:
121                 return "rating";
122         case TEASER:
123                 return "teaser";
124         case POLICY:
125                 return "policy";
126         case PUBLIC_SERVICE_ANNOUNCEMENT:
127                 return "psa";
128         case ADVERTISEMENT:
129                 return "advertisement";
130         }
131
132         assert (false);
133 }
134
135 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
136  *  Reasonably tolerant about varying case.
137  *  @param type Content kind string.
138  *  @return libdcp ContentKind.
139  */
140 libdcp::ContentKind
141 libdcp::content_kind_from_string (string type)
142 {
143         /* XXX: should probably just convert type to lower-case and have done with it */
144         
145         if (type == "feature") {
146                 return FEATURE;
147         } else if (type == "short") {
148                 return SHORT;
149         } else if (type == "trailer" || type == "Trailer") {
150                 return TRAILER;
151         } else if (type == "test") {
152                 return TEST;
153         } else if (type == "transitional") {
154                 return TRANSITIONAL;
155         } else if (type == "rating") {
156                 return RATING;
157         } else if (type == "teaser" || type == "Teaser") {
158                 return TEASER;
159         } else if (type == "policy") {
160                 return POLICY;
161         } else if (type == "psa") {
162                 return PUBLIC_SERVICE_ANNOUNCEMENT;
163         } else if (type == "advertisement") {
164                 return ADVERTISEMENT;
165         }
166
167         assert (false);
168 }
169
170 /** Decompress a JPEG2000 image to a bitmap.
171  *  @param data JPEG2000 data.
172  *  @param size Size of data in bytes.
173  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
174  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
175  *       1 reduces by (2^1 == 2), ie halving the size of the image.
176  *  This is useful for scaling 4K DCP images down to 2K.
177  *  @return openjpeg image, which the caller must call opj_image_destroy() on.
178  */
179 opj_image_t *
180 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
181 {
182         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
183         opj_dparameters_t parameters;
184         opj_set_default_decoder_parameters (&parameters);
185         parameters.cp_reduce = reduce;
186         opj_setup_decoder (decoder, &parameters);
187         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
188         opj_image_t* image = opj_decode (decoder, cio);
189         if (!image) {
190                 opj_destroy_decompress (decoder);
191                 opj_cio_close (cio);
192                 boost::throw_exception (DCPReadError ("could not decode JPEG2000 codestream of " + lexical_cast<string> (size) + " bytes."));
193         }
194
195         opj_cio_close (cio);
196
197         image->x1 = rint (float(image->x1) / pow (2, reduce));
198         image->y1 = rint (float(image->y1) / pow (2, reduce));
199         return image;
200 }
201
202 /** Convert an openjpeg XYZ image to RGB.
203  *  @param xyz_frame Frame in XYZ.
204  *  @return RGB image.
205  */
206 shared_ptr<ARGBFrame>
207 libdcp::xyz_to_rgb (opj_image_t* xyz_frame, shared_ptr<const GammaLUT> lut_in, shared_ptr<const GammaLUT> lut_out)
208 {
209         float const dci_coefficient = 48.0 / 52.37;
210
211         /* sRGB color matrix for XYZ -> RGB.  This is the same as the one used by the Fraunhofer
212            EasyDCP player, I think.
213         */
214
215         float const colour_matrix[3][3] = {
216                 {  3.24096989631653,   -1.5373831987381,  -0.498610764741898 },
217                 { -0.96924364566803,    1.87596750259399,  0.0415550582110882 },
218                 {  0.0556300804018974, -0.203976958990097, 1.05697154998779 }
219         };
220
221         int const max_colour = pow (2, lut_out->bit_depth()) - 1;
222
223         struct {
224                 double x, y, z;
225         } s;
226         
227         struct {
228                 double r, g, b;
229         } d;
230         
231         int* xyz_x = xyz_frame->comps[0].data;
232         int* xyz_y = xyz_frame->comps[1].data;
233         int* xyz_z = xyz_frame->comps[2].data;
234
235         shared_ptr<ARGBFrame> argb_frame (new ARGBFrame (Size (xyz_frame->x1, xyz_frame->y1)));
236
237         uint8_t* argb = argb_frame->data ();
238         
239         for (int y = 0; y < xyz_frame->y1; ++y) {
240                 uint8_t* argb_line = argb;
241                 for (int x = 0; x < xyz_frame->x1; ++x) {
242
243                         assert (*xyz_x >= 0 && *xyz_y >= 0 && *xyz_z >= 0 && *xyz_x < 4096 && *xyz_x < 4096 && *xyz_z < 4096);
244                         
245                         /* In gamma LUT */
246                         s.x = lut_in->lut()[*xyz_x++];
247                         s.y = lut_in->lut()[*xyz_y++];
248                         s.z = lut_in->lut()[*xyz_z++];
249
250                         /* DCI companding */
251                         s.x /= dci_coefficient;
252                         s.y /= dci_coefficient;
253                         s.z /= dci_coefficient;
254                         
255                         /* XYZ to RGB */
256                         d.r = ((s.x * colour_matrix[0][0]) + (s.y * colour_matrix[0][1]) + (s.z * colour_matrix[0][2]));
257                         d.g = ((s.x * colour_matrix[1][0]) + (s.y * colour_matrix[1][1]) + (s.z * colour_matrix[1][2]));
258                         d.b = ((s.x * colour_matrix[2][0]) + (s.y * colour_matrix[2][1]) + (s.z * colour_matrix[2][2]));
259                         
260                         d.r = min (d.r, 1.0);
261                         d.r = max (d.r, 0.0);
262                         
263                         d.g = min (d.g, 1.0);
264                         d.g = max (d.g, 0.0);
265                         
266                         d.b = min (d.b, 1.0);
267                         d.b = max (d.b, 0.0);
268                         
269                         /* Out gamma LUT */
270                         *argb_line++ = lut_out->lut()[(int) (d.b * max_colour)] * 0xff;
271                         *argb_line++ = lut_out->lut()[(int) (d.g * max_colour)] * 0xff;
272                         *argb_line++ = lut_out->lut()[(int) (d.r * max_colour)] * 0xff;
273                         *argb_line++ = 0xff;
274                 }
275                 
276                 argb += argb_frame->stride ();
277         }
278
279         return argb_frame;
280 }
281
282 /** @param s A string.
283  *  @return true if the string contains only space, newline or tab characters, or is empty.
284  */
285 bool
286 libdcp::empty_or_white_space (string s)
287 {
288         for (size_t i = 0; i < s.length(); ++i) {
289                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
290                         return false;
291                 }
292         }
293
294         return true;
295 }
296
297 bool libdcp::operator== (libdcp::Size const & a, libdcp::Size const & b)
298 {
299         return (a.width == b.width && a.height == b.height);
300 }
301
302 bool libdcp::operator!= (libdcp::Size const & a, libdcp::Size const & b)
303 {
304         return !(a == b);
305 }
306