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