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