Take DCP-o-matic's version of Data class.
[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
29 using std::min;
30 using std::pow;
31 using boost::shared_ptr;
32 using boost::shared_array;
33 using namespace dcp;
34
35 shared_ptr<dcp::OpenJPEGImage>
36 dcp::decompress_j2k (Data data, int reduce)
37 {
38         return dcp::decompress_j2k (data.data().get(), data.size(), reduce);
39 }
40
41 class ReadBuffer
42 {
43 public:
44         ReadBuffer (uint8_t* data, int64_t size)
45                 : _data (data)
46                 , _size (size)
47                 , _offset (0)
48         {}
49
50         OPJ_SIZE_T read (void* buffer, OPJ_SIZE_T nb_bytes)
51         {
52                 int64_t N = min (nb_bytes, _size - _offset);
53                 memcpy (buffer, _data + _offset, N);
54                 _offset += N;
55                 return N;
56         }
57
58 private:
59         uint8_t* _data;
60         OPJ_SIZE_T _size;
61         OPJ_SIZE_T _offset;
62 };
63
64 static OPJ_SIZE_T
65 read_function (void* buffer, OPJ_SIZE_T nb_bytes, void* data)
66 {
67         return reinterpret_cast<ReadBuffer*>(data)->read (buffer, nb_bytes);
68 }
69
70 static void
71 read_free_function (void* data)
72 {
73         delete reinterpret_cast<ReadBuffer*>(data);
74 }
75
76 /** Decompress a JPEG2000 image to a bitmap.
77  *  @param data JPEG2000 data.
78  *  @param size Size of data in bytes.
79  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
80  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
81  *       1 reduces by (2^1 == 2), ie halving the size of the image.
82  *  This is useful for scaling 4K DCP images down to 2K.
83  *  @return OpenJPEGImage.
84  */
85 shared_ptr<dcp::OpenJPEGImage>
86 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
87 {
88         uint8_t const jp2_magic[] = {
89                 0x00,
90                 0x00,
91                 0x00,
92                 0x0c,
93                 'j',
94                 'P',
95                 0x20,
96                 0x20
97         };
98
99         OPJ_CODEC_FORMAT format = OPJ_CODEC_J2K;
100         if (size >= int (sizeof (jp2_magic)) && memcmp (data, jp2_magic, sizeof (jp2_magic)) == 0) {
101                 format = OPJ_CODEC_JP2;
102         }
103
104         opj_codec_t* decoder = opj_create_decompress (format);
105         if (!decoder) {
106                 boost::throw_exception (DCPReadError ("could not create JPEG2000 decompresser"));
107         }
108         opj_dparameters_t parameters;
109         opj_set_default_decoder_parameters (&parameters);
110         parameters.cp_reduce = reduce;
111         opj_setup_decoder (decoder, &parameters);
112
113         opj_stream_t* stream = opj_stream_default_create (OPJ_TRUE);
114         if (!stream) {
115                 throw MiscError ("could not create JPEG2000 stream");
116         }
117
118         opj_stream_set_read_function (stream, read_function);
119         ReadBuffer* buffer = new ReadBuffer (data, size);
120         opj_stream_set_user_data (stream, buffer, read_free_function);
121         opj_stream_set_user_data_length (stream, size);
122
123         opj_image_t* image = 0;
124         opj_read_header (stream, decoder, &image);
125         if (opj_decode (decoder, stream, image) == OPJ_FALSE) {
126                 opj_destroy_codec (decoder);
127                 opj_stream_destroy (stream);
128                 if (format == OPJ_CODEC_J2K) {
129                         boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
130                 } else {
131                         boost::throw_exception (DCPReadError (String::compose ("could not decode JP2 file of %1 bytes.", size)));
132                 }
133         }
134
135         opj_destroy_codec (decoder);
136         opj_stream_destroy (stream);
137
138         image->x1 = rint (float(image->x1) / pow (2, reduce));
139         image->y1 = rint (float(image->y1) / pow (2, reduce));
140         return shared_ptr<OpenJPEGImage> (new OpenJPEGImage (image));
141 }
142
143 class WriteBuffer
144 {
145 public:
146 /* XXX: is there a better strategy for this? */
147 #define MAX_J2K_SIZE (1024 * 1024 * 2)
148         WriteBuffer ()
149                 : _data (shared_array<uint8_t> (new uint8_t[MAX_J2K_SIZE]), MAX_J2K_SIZE)
150                 , _offset (0)
151         {}
152
153         OPJ_SIZE_T write (void* buffer, OPJ_SIZE_T nb_bytes)
154         {
155                 DCP_ASSERT ((_offset + nb_bytes) < MAX_J2K_SIZE);
156                 memcpy (_data.data().get() + _offset, buffer, nb_bytes);
157                 _offset += nb_bytes;
158                 return nb_bytes;
159         }
160
161         Data data () const {
162                 return _data;
163         }
164
165 private:
166         Data _data;
167         OPJ_SIZE_T _offset;
168 };
169
170 static OPJ_SIZE_T
171 write_function (void* buffer, OPJ_SIZE_T nb_bytes, void* data)
172 {
173         return reinterpret_cast<WriteBuffer*>(data)->write (buffer, nb_bytes);
174 }
175
176 static void
177 write_free_function (void* data)
178 {
179         delete reinterpret_cast<WriteBuffer*>(data);
180 }
181
182 Data
183 dcp::compress_j2k (shared_ptr<const OpenJPEGImage> xyz, int bandwidth, int frames_per_second, bool threed, bool fourk)
184 {
185         /* XXX: should probably use opj_set_*_handler */
186
187         /* Set the max image and component sizes based on frame_rate */
188         int max_cs_len = ((float) bandwidth) / 8 / frames_per_second;
189         if (threed) {
190                 /* In 3D we have only half the normal bandwidth per eye */
191                 max_cs_len /= 2;
192         }
193         int const max_comp_size = max_cs_len / 1.25;
194
195         /* get a J2K compressor handle */
196         opj_codec_t* encoder = opj_create_compress (OPJ_CODEC_J2K);
197         if (encoder == 0) {
198                 throw MiscError ("could not create JPEG2000 encoder");
199         }
200
201         /* Set encoding parameters to default values */
202         opj_cparameters_t parameters;
203         opj_set_default_encoder_parameters (&parameters);
204
205         /* Set default cinema parameters */
206         parameters.tile_size_on = OPJ_FALSE;
207         parameters.cp_tdx = 1;
208         parameters.cp_tdy = 1;
209
210         /* Tile part */
211         parameters.tp_flag = 'C';
212         parameters.tp_on = 1;
213
214         /* Tile and Image shall be at (0,0) */
215         parameters.cp_tx0 = 0;
216         parameters.cp_ty0 = 0;
217         parameters.image_offset_x0 = 0;
218         parameters.image_offset_y0 = 0;
219
220         /* Codeblock size = 32x32 */
221         parameters.cblockw_init = 32;
222         parameters.cblockh_init = 32;
223         parameters.csty |= 0x01;
224
225         /* The progression order shall be CPRL */
226         parameters.prog_order = OPJ_CPRL;
227
228         /* No ROI */
229         parameters.roi_compno = -1;
230
231         parameters.subsampling_dx = 1;
232         parameters.subsampling_dy = 1;
233
234         /* 9-7 transform */
235         parameters.irreversible = 1;
236
237         parameters.tcp_rates[0] = 0;
238         parameters.tcp_numlayers++;
239         parameters.cp_disto_alloc = 1;
240         parameters.cp_rsiz = fourk ? OPJ_CINEMA4K : OPJ_CINEMA2K;
241         if (fourk) {
242                 parameters.numpocs = 2;
243                 parameters.POC[0].tile = 1;
244                 parameters.POC[0].resno0 = 0;
245                 parameters.POC[0].compno0 = 0;
246                 parameters.POC[0].layno1 = 1;
247                 parameters.POC[0].resno1 = parameters.numresolution - 1;
248                 parameters.POC[0].compno1 = 3;
249                 parameters.POC[0].prg1 = OPJ_CPRL;
250                 parameters.POC[1].tile = 1;
251                 parameters.POC[1].resno0 = parameters.numresolution - 1;
252                 parameters.POC[1].compno0 = 0;
253                 parameters.POC[1].layno1 = 1;
254                 parameters.POC[1].resno1 = parameters.numresolution;
255                 parameters.POC[1].compno1 = 3;
256                 parameters.POC[1].prg1 = OPJ_CPRL;
257         }
258
259         parameters.cp_comment = strdup ("libdcp");
260         parameters.cp_cinema = fourk ? OPJ_CINEMA4K_24 : OPJ_CINEMA2K_24;
261
262         /* 3 components, so use MCT */
263         parameters.tcp_mct = 1;
264
265         /* set max image */
266         parameters.max_comp_size = max_comp_size;
267         parameters.tcp_rates[0] = ((float) (3 * xyz->size().width * xyz->size().height * 12)) / (max_cs_len * 8);
268
269         /* Setup the encoder parameters using the current image and user parameters */
270         opj_setup_encoder (encoder, &parameters, xyz->opj_image());
271
272         opj_stream_t* stream = opj_stream_default_create (OPJ_FALSE);
273         if (!stream) {
274                 throw MiscError ("could not create JPEG2000 stream");
275         }
276
277         opj_stream_set_write_function (stream, write_function);
278         WriteBuffer* buffer = new WriteBuffer ();
279         opj_stream_set_user_data (stream, buffer, write_free_function);
280
281         if (!opj_start_compress (encoder, xyz->opj_image(), stream)) {
282                 throw MiscError ("could not start JPEG2000 encoding");
283         }
284
285         if (!opj_encode (encoder, stream)) {
286                 opj_destroy_codec (encoder);
287                 opj_stream_destroy (stream);
288                 throw MiscError ("JPEG2000 encoding failed");
289         }
290
291         if (!opj_end_compress (encoder, stream)) {
292                 throw MiscError ("could not end JPEG2000 encoding");
293         }
294
295         Data enc (buffer->data ());
296
297         free (parameters.cp_comment);
298         opj_destroy_codec (encoder);
299         opj_stream_destroy (stream);
300
301         return enc;
302 }