Try to fix build on OS X.
[libdcp.git] / src / j2k.cc
1 /*
2     Copyright (C) 2012-2015 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 #include "j2k.h"
21 #include "exceptions.h"
22 #include "openjpeg_image.h"
23 #include "data.h"
24 #include "dcp_assert.h"
25 #include "compose.hpp"
26 #include <openjpeg.h>
27 #include <cmath>
28 #include <iostream>
29
30 using std::min;
31 using std::pow;
32 using boost::shared_ptr;
33 using boost::shared_array;
34 using namespace dcp;
35
36 shared_ptr<dcp::OpenJPEGImage>
37 dcp::decompress_j2k (Data data, int reduce)
38 {
39         return dcp::decompress_j2k (data.data().get(), data.size(), reduce);
40 }
41
42 class ReadBuffer
43 {
44 public:
45         ReadBuffer (uint8_t* data, int64_t size)
46                 : _data (data)
47                 , _size (size)
48                 , _offset (0)
49         {}
50
51         OPJ_SIZE_T read (void* buffer, OPJ_SIZE_T nb_bytes)
52         {
53                 int64_t N = min (nb_bytes, _size - _offset);
54                 memcpy (buffer, _data + _offset, N);
55                 _offset += N;
56                 return N;
57         }
58
59 private:
60         uint8_t* _data;
61         OPJ_SIZE_T _size;
62         OPJ_SIZE_T _offset;
63 };
64
65 static OPJ_SIZE_T
66 read_function (void* buffer, OPJ_SIZE_T nb_bytes, void* data)
67 {
68         return reinterpret_cast<ReadBuffer*>(data)->read (buffer, nb_bytes);
69 }
70
71 static void
72 read_free_function (void* data)
73 {
74         delete reinterpret_cast<ReadBuffer*>(data);
75 }
76
77 /** Decompress a JPEG2000 image to a bitmap.
78  *  @param data JPEG2000 data.
79  *  @param size Size of data in bytes.
80  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
81  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
82  *       1 reduces by (2^1 == 2), ie halving the size of the image.
83  *  This is useful for scaling 4K DCP images down to 2K.
84  *  @return OpenJPEGImage.
85  */
86 shared_ptr<dcp::OpenJPEGImage>
87 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
88 {
89         uint8_t const jp2_magic[] = {
90                 0x00,
91                 0x00,
92                 0x00,
93                 0x0c,
94                 'j',
95                 'P',
96                 0x20,
97                 0x20
98         };
99
100         OPJ_CODEC_FORMAT format = OPJ_CODEC_J2K;
101         if (size >= int (sizeof (jp2_magic)) && memcmp (data, jp2_magic, sizeof (jp2_magic)) == 0) {
102                 format = OPJ_CODEC_JP2;
103         }
104
105         opj_codec_t* decoder = opj_create_decompress (format);
106         if (!decoder) {
107                 boost::throw_exception (DCPReadError ("could not create JPEG2000 decompresser"));
108         }
109         opj_dparameters_t parameters;
110         opj_set_default_decoder_parameters (&parameters);
111         parameters.cp_reduce = reduce;
112         opj_setup_decoder (decoder, &parameters);
113
114         opj_stream_t* stream = opj_stream_default_create (OPJ_TRUE);
115         if (!stream) {
116                 throw MiscError ("could not create JPEG2000 stream");
117         }
118
119         opj_stream_set_read_function (stream, read_function);
120         ReadBuffer* buffer = new ReadBuffer (data, size);
121         opj_stream_set_user_data (stream, buffer, read_free_function);
122         opj_stream_set_user_data_length (stream, size);
123
124         opj_image_t* image = 0;
125         opj_read_header (stream, decoder, &image);
126         if (opj_decode (decoder, stream, image) == OPJ_FALSE) {
127                 opj_destroy_codec (decoder);
128                 opj_stream_destroy (stream);
129                 if (format == OPJ_CODEC_J2K) {
130                         boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
131                 } else {
132                         boost::throw_exception (DCPReadError (String::compose ("could not decode JP2 file of %1 bytes.", size)));
133                 }
134         }
135
136         opj_destroy_codec (decoder);
137         opj_stream_destroy (stream);
138
139         image->x1 = rint (float(image->x1) / pow (2.0f, reduce));
140         image->y1 = rint (float(image->y1) / pow (2.0f, reduce));
141         return shared_ptr<OpenJPEGImage> (new OpenJPEGImage (image));
142 }
143
144 class WriteBuffer
145 {
146 public:
147 /* XXX: is there a better strategy for this? */
148 #define MAX_J2K_SIZE (1024 * 1024 * 2)
149         WriteBuffer ()
150                 : _data (shared_array<uint8_t> (new uint8_t[MAX_J2K_SIZE]), MAX_J2K_SIZE)
151                 , _offset (0)
152         {
153                 _data.set_size (0);
154         }
155
156         OPJ_SIZE_T write (void* buffer, OPJ_SIZE_T nb_bytes)
157         {
158                 DCP_ASSERT ((_offset + nb_bytes) < MAX_J2K_SIZE);
159                 memcpy (_data.data().get() + _offset, buffer, nb_bytes);
160                 _offset += nb_bytes;
161                 if (_offset > OPJ_SIZE_T (_data.size())) {
162                         _data.set_size (_offset);
163                 }
164                 return nb_bytes;
165         }
166
167         OPJ_BOOL seek (OPJ_SIZE_T nb_bytes)
168         {
169                 _offset = nb_bytes;
170                 return OPJ_TRUE;
171         }
172
173         Data data () const
174         {
175                 return _data;
176         }
177
178 private:
179         Data _data;
180         OPJ_SIZE_T _offset;
181 };
182
183 static OPJ_SIZE_T
184 write_function (void* buffer, OPJ_SIZE_T nb_bytes, void* data)
185 {
186         return reinterpret_cast<WriteBuffer*>(data)->write (buffer, nb_bytes);
187 }
188
189 static void
190 write_free_function (void* data)
191 {
192         delete reinterpret_cast<WriteBuffer*>(data);
193 }
194
195 static OPJ_BOOL
196 seek_function (OPJ_OFF_T nb_bytes, void* data)
197 {
198         return reinterpret_cast<WriteBuffer*>(data)->seek (nb_bytes);
199 }
200
201 static void
202 error_callback (char const * msg, void *)
203 {
204         throw MiscError (msg);
205 }
206
207 Data
208 dcp::compress_j2k (shared_ptr<const OpenJPEGImage> xyz, int bandwidth, int frames_per_second, bool threed, bool fourk)
209 {
210         /* get a J2K compressor handle */
211         opj_codec_t* encoder = opj_create_compress (OPJ_CODEC_J2K);
212         if (encoder == 0) {
213                 throw MiscError ("could not create JPEG2000 encoder");
214         }
215
216         opj_set_error_handler (encoder, error_callback, 0);
217
218         /* Set encoding parameters to default values */
219         opj_cparameters_t parameters;
220         opj_set_default_encoder_parameters (&parameters);
221         parameters.rsiz = fourk ? OPJ_PROFILE_CINEMA_4K : OPJ_PROFILE_CINEMA_2K;
222         parameters.cp_comment = strdup ("libdcp");
223
224         /* set max image */
225         parameters.max_cs_size = (bandwidth / 8) / frames_per_second;
226         if (threed) {
227                 /* In 3D we have only half the normal bandwidth per eye */
228                 parameters.max_cs_size /= 2;
229         }
230         parameters.max_comp_size = parameters.max_cs_size / 1.25;
231         parameters.tcp_numlayers = 1;
232
233         /* Setup the encoder parameters using the current image and user parameters */
234         opj_setup_encoder (encoder, &parameters, xyz->opj_image());
235
236         opj_stream_t* stream = opj_stream_default_create (OPJ_FALSE);
237         if (!stream) {
238                 throw MiscError ("could not create JPEG2000 stream");
239         }
240
241         opj_stream_set_write_function (stream, write_function);
242         opj_stream_set_seek_function (stream, seek_function);
243         WriteBuffer* buffer = new WriteBuffer ();
244         opj_stream_set_user_data (stream, buffer, write_free_function);
245
246         if (!opj_start_compress (encoder, xyz->opj_image(), stream)) {
247                 throw MiscError ("could not start JPEG2000 encoding");
248         }
249
250         if (!opj_encode (encoder, stream)) {
251                 opj_destroy_codec (encoder);
252                 opj_stream_destroy (stream);
253                 throw MiscError ("JPEG2000 encoding failed");
254         }
255
256         if (!opj_end_compress (encoder, stream)) {
257                 opj_destroy_codec (encoder);
258                 opj_stream_destroy (stream);
259                 throw MiscError ("could not end JPEG2000 encoding");
260         }
261
262         Data enc (buffer->data ());
263
264         free (parameters.cp_comment);
265         opj_destroy_codec (encoder);
266         opj_stream_destroy (stream);
267
268         return enc;
269 }