2de55b5e495c3fa5c0f00f9f479df57c1a97c624
[openjpeg.git] / libopenjpeg / j2k.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * Copyright (c) 2006-2007, Parvatha Elangovan
9  * Copyright (c) 2010-2011, Kaori Hagihara
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include "opj_includes.h"
35
36 /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
37 /*@{*/
38
39 /** @name Local static functions */
40 /*@{*/
41
42 /**
43  * Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
44  */
45 void j2k_setup_header_reading (opj_j2k_v2_t *p_j2k);
46
47 /**
48  * The read header procedure.
49  */
50 opj_bool j2k_read_header_procedure(
51                                                             opj_j2k_v2_t *p_j2k,
52                                                                 struct opj_stream_private *p_stream,
53                                                                 struct opj_event_mgr * p_manager);
54
55 /**
56  * The default decoding validation procedure without any extension.
57  *
58  * @param       p_j2k                   the jpeg2000 codec to validate.
59  * @param       p_stream                                the input stream to validate.
60  * @param       p_manager               the user event manager.
61  *
62  * @return true if the parameters are correct.
63  */
64 opj_bool j2k_decoding_validation (
65                                                                 opj_j2k_v2_t * p_j2k,
66                                                                 opj_stream_private_t *p_stream,
67                                                                 opj_event_mgr_t * p_manager
68                                                         );
69
70 /**
71  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
72  * are valid. Developpers wanting to extend the library can add their own validation procedures.
73  */
74 static void j2k_setup_decoding_validation (opj_j2k_v2_t *p_j2k);
75
76 /**
77  * Builds the tcd decoder to use to decode tile.
78  */
79 opj_bool j2k_build_decoder (
80                                                 opj_j2k_v2_t * p_j2k,
81                                                 opj_stream_private_t *p_stream,
82                                                 opj_event_mgr_t * p_manager
83                                                 );
84
85 /**
86  * Excutes the given procedures on the given codec.
87  *
88  * @param       p_procedure_list        the list of procedures to execute
89  * @param       p_j2k                                   the jpeg2000 codec to execute the procedures on.
90  * @param       p_stream                                        the stream to execute the procedures on.
91  * @param       p_manager                       the user manager.
92  *
93  * @return      true                            if all the procedures were successfully executed.
94  */
95 static opj_bool j2k_exec (
96                                         opj_j2k_v2_t * p_j2k,
97                                         opj_procedure_list_t * p_procedure_list,
98                                         opj_stream_private_t *p_stream,
99                                         opj_event_mgr_t * p_manager
100                                   );
101
102 /**
103  * Copies the decoding tile parameters onto all the tile parameters.
104  * Creates also the tile decoder.
105  */
106 opj_bool j2k_copy_default_tcp_and_create_tcd (  opj_j2k_v2_t * p_j2k,
107                                                                                                 opj_stream_private_t *p_stream,
108                                                                                                 opj_event_mgr_t * p_manager );
109
110 /**
111  * Reads the lookup table containing all the marker, status and action, and returns the handler associated
112  * with the marker value.
113  * @param       p_id            Marker value to look up
114  *
115  * @return      the handler associated with the id.
116 */
117 static const struct opj_dec_memory_marker_handler * j2k_get_marker_handler (OPJ_UINT32 p_id);
118
119 /**
120  * Destroys a tile coding parameter structure.
121  *
122  * @param       p_tcp           the tile coding parameter to destroy.
123  */
124 static void j2k_tcp_destroy (opj_tcp_v2_t *p_tcp);
125
126 /**
127  * Destroys a codestream index structure.
128  *
129  * @param       p_cstr_ind      the codestream index parameter to destroy.
130  */
131 static void j2k_destroy_cstr_index (opj_codestream_index_t* p_cstr_ind);
132
133 /**
134  * Destroys a coding parameter structure.
135  *
136  * @param       p_cp            the coding parameter to destroy.
137  */
138 static void j2k_cp_destroy (opj_cp_v2_t *p_cp);
139
140
141 /**
142  * Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
143  * @param       p_header_data   the data contained in the COM box.
144  * @param       p_j2k                   the jpeg2000 codec.
145  * @param       p_header_size   the size of the data contained in the COM marker.
146  * @param       p_manager               the user event manager.
147 */
148 static opj_bool j2k_read_SPCod_SPCoc(
149                                                         opj_j2k_v2_t *p_j2k,
150                                                         OPJ_UINT32 compno,
151                                                         OPJ_BYTE * p_header_data,
152                                                         OPJ_UINT32 * p_header_size,
153                                                         struct opj_event_mgr * p_manager
154                                                         );
155
156 /**
157  * Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
158  *
159  * @param       p_tile_no               the tile to output.
160  * @param       p_comp_no               the component number to output.
161  * @param       p_data                  the data buffer.
162  * @param       p_header_size   pointer to the size of the data buffer, it is changed by the function.
163  * @param       p_j2k                           J2K codec.
164  * @param       p_manager               the user event manager.
165  *
166 */
167 static opj_bool j2k_read_SQcd_SQcc(
168                                                         opj_j2k_v2_t *p_j2k,
169                                                         OPJ_UINT32 compno,
170                                                         OPJ_BYTE * p_header_data,
171                                                         OPJ_UINT32 * p_header_size,
172                                                         struct opj_event_mgr * p_manager
173                                         );
174
175 /**
176  * Copies the tile component parameters of all the component from the first tile component.
177  *
178  * @param               p_j2k           the J2k codec.
179  */
180 static void j2k_copy_tile_component_parameters(
181                                                         opj_j2k_v2_t *p_j2k
182                                                         );
183
184 /**
185  * Copies the tile quantization parameters of all the component from the first tile component.
186  *
187  * @param               p_j2k           the J2k codec.
188  */
189 static void j2k_copy_tile_quantization_parameters(
190                                                         opj_j2k_v2_t *p_j2k
191                                                         );
192
193 /**
194  * Reads the tiles.
195  */
196 opj_bool j2k_decode_tiles (             opj_j2k_v2_t *p_j2k,
197                                                                 opj_stream_private_t *p_stream,
198                                                                 opj_event_mgr_t * p_manager);
199
200 static opj_bool j2k_update_image_data (opj_tcd_v2_t * p_tcd, OPJ_BYTE * p_data);
201
202
203 /*
204  * -----------------------------------------------------------------------
205  * -----------------------------------------------------------------------
206  * -----------------------------------------------------------------------
207  */
208
209 /**
210 Write the SOC marker (Start Of Codestream)
211 @param j2k J2K handle
212 */
213 static void j2k_write_soc(opj_j2k_t *j2k);
214 /**
215 Read the SOC marker (Start of Codestream)
216 @param j2k J2K handle
217 */
218 static void j2k_read_soc(opj_j2k_t *j2k);
219
220 /**
221  * Reads a SOC marker (Start of Codestream)
222  * @param       p_header_data   the data contained in the SOC box.
223  * @param       jp2                             the jpeg2000 file codec.
224  * @param       p_header_size   the size of the data contained in the SOC marker.
225  * @param       p_manager               the user event manager.
226 */
227 static opj_bool j2k_read_soc_v2(
228                                         opj_j2k_v2_t *p_j2k,
229                                         struct opj_stream_private *p_stream,
230                                         struct opj_event_mgr * p_manager
231                                  );
232
233 /**
234 Write the SIZ marker (image and tile size)
235 @param j2k J2K handle
236 */
237 static void j2k_write_siz(opj_j2k_t *j2k);
238 /**
239 Read the SIZ marker (image and tile size)
240 @param j2k J2K handle
241 */
242 static void j2k_read_siz(opj_j2k_t *j2k);
243
244 /**
245  * Reads a SIZ marker (image and tile size)
246  * @param       p_header_data   the data contained in the SIZ box.
247  * @param       jp2                             the jpeg2000 file codec.
248  * @param       p_header_size   the size of the data contained in the SIZ marker.
249  * @param       p_manager               the user event manager.
250 */
251 static opj_bool j2k_read_siz_v2 (
252                                                   opj_j2k_v2_t *p_j2k,
253                                                   OPJ_BYTE * p_header_data,
254                                                   OPJ_UINT32 p_header_size,
255                                                   struct opj_event_mgr * p_manager
256                                         );
257
258 /**
259 Write the COM marker (comment)
260 @param j2k J2K handle
261 */
262 static void j2k_write_com(opj_j2k_t *j2k);
263 /**
264 Read the COM marker (comment)
265 @param j2k J2K handle
266 */
267 static void j2k_read_com(opj_j2k_t *j2k);
268 /**
269  * Reads a COM marker (comments)
270  * @param       p_header_data   the data contained in the COM box.
271  * @param       jp2                             the jpeg2000 file codec.
272  * @param       p_header_size   the size of the data contained in the COM marker.
273  * @param       p_manager               the user event manager.
274 */
275 static opj_bool j2k_read_com_v2 (
276                                         opj_j2k_v2_t *p_j2k,
277                                         OPJ_BYTE * p_header_data,
278                                         OPJ_UINT32 p_header_size,
279                                         struct opj_event_mgr * p_manager
280                                         );
281 /**
282 Write the value concerning the specified component in the marker COD and COC
283 @param j2k J2K handle
284 @param compno Number of the component concerned by the information written
285 */
286 static void j2k_write_cox(opj_j2k_t *j2k, int compno);
287 /**
288 Read the value concerning the specified component in the marker COD and COC
289 @param j2k J2K handle
290 @param compno Number of the component concerned by the information read
291 */
292 static void j2k_read_cox(opj_j2k_t *j2k, int compno);
293 /**
294 Write the COD marker (coding style default)
295 @param j2k J2K handle
296 */
297 static void j2k_write_cod(opj_j2k_t *j2k);
298 /**
299 Read the COD marker (coding style default)
300 @param j2k J2K handle
301 */
302 static void j2k_read_cod(opj_j2k_t *j2k);
303
304 /**
305  * Reads a COD marker (Coding Styke defaults)
306  * @param       p_header_data   the data contained in the COD box.
307  * @param       p_j2k                   the jpeg2000 codec.
308  * @param       p_header_size   the size of the data contained in the COD marker.
309  * @param       p_manager               the user event manager.
310 */
311 static opj_bool j2k_read_cod_v2 (
312                                         opj_j2k_v2_t *p_j2k,
313                                         OPJ_BYTE * p_header_data,
314                                         OPJ_UINT32 p_header_size,
315                                         struct opj_event_mgr * p_manager
316                                         );
317
318 /**
319 Write the COC marker (coding style component)
320 @param j2k J2K handle
321 @param compno Number of the component concerned by the information written
322 */
323 static void j2k_write_coc(opj_j2k_t *j2k, int compno);
324 /**
325 Read the COC marker (coding style component)
326 @param j2k J2K handle
327 */
328 static void j2k_read_coc(opj_j2k_t *j2k);
329
330 /**
331  * Reads a COC marker (Coding Style Component)
332  * @param       p_header_data   the data contained in the COC box.
333  * @param       p_j2k                   the jpeg2000 codec.
334  * @param       p_header_size   the size of the data contained in the COC marker.
335  * @param       p_manager               the user event manager.
336 */
337 static opj_bool j2k_read_coc_v2 (
338                                         opj_j2k_v2_t *p_j2k,
339                                         OPJ_BYTE * p_header_data,
340                                         OPJ_UINT32 p_header_size,
341                                         struct opj_event_mgr * p_manager
342                                         );
343
344 /**
345 Write the value concerning the specified component in the marker QCD and QCC
346 @param j2k J2K handle
347 @param compno Number of the component concerned by the information written
348 */
349 static void j2k_write_qcx(opj_j2k_t *j2k, int compno);
350 /**
351 Read the value concerning the specified component in the marker QCD and QCC
352 @param j2k J2K handle
353 @param compno Number of the component concern by the information read
354 @param len Length of the information in the QCX part of the marker QCD/QCC
355 */
356 static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len);
357 /**
358 Write the QCD marker (quantization default)
359 @param j2k J2K handle
360 */
361 static void j2k_write_qcd(opj_j2k_t *j2k);
362 /**
363 Read the QCD marker (quantization default)
364 @param j2k J2K handle
365 */
366 static void j2k_read_qcd(opj_j2k_t *j2k);
367
368 /**
369  * Reads a QCD marker (Quantization defaults)
370  * @param       p_header_data   the data contained in the QCD box.
371  * @param       p_j2k                   the jpeg2000 codec.
372  * @param       p_header_size   the size of the data contained in the QCD marker.
373  * @param       p_manager               the user event manager.
374 */
375 static opj_bool j2k_read_qcd_v2 (
376                                         opj_j2k_v2_t *p_j2k,
377                                         OPJ_BYTE * p_header_data,
378                                         OPJ_UINT32 p_header_size,
379                                         struct opj_event_mgr * p_manager
380                                         );
381
382 /**
383 Write the QCC marker (quantization component)
384 @param j2k J2K handle
385 @param compno Number of the component concerned by the information written
386 */
387 static void j2k_write_qcc(opj_j2k_t *j2k, int compno);
388 /**
389 Read the QCC marker (quantization component)
390 @param j2k J2K handle
391 */
392 static void j2k_read_qcc(opj_j2k_t *j2k);
393 /**
394  * Reads a QCC marker (Quantization component)
395  * @param       p_header_data   the data contained in the QCC box.
396  * @param       p_j2k                   the jpeg2000 codec.
397  * @param       p_header_size   the size of the data contained in the QCC marker.
398  * @param       p_manager               the user event manager.
399 */
400 static opj_bool j2k_read_qcc_v2(
401                                                         opj_j2k_v2_t *p_j2k,
402                                                         OPJ_BYTE * p_header_data,
403                                                         OPJ_UINT32 p_header_size,
404                                                         struct opj_event_mgr * p_manager);
405
406 /**
407 Write the POC marker (progression order change)
408 @param j2k J2K handle
409 */
410 static void j2k_write_poc(opj_j2k_t *j2k);
411 /**
412 Read the POC marker (progression order change)
413 @param j2k J2K handle
414 */
415 static void j2k_read_poc(opj_j2k_t *j2k);
416 /**
417  * Reads a POC marker (Progression Order Change)
418  *
419  * @param       p_header_data   the data contained in the POC box.
420  * @param       p_j2k                   the jpeg2000 codec.
421  * @param       p_header_size   the size of the data contained in the POC marker.
422  * @param       p_manager               the user event manager.
423 */
424 static opj_bool j2k_read_poc_v2 (
425                                                 opj_j2k_v2_t *p_j2k,
426                                                 OPJ_BYTE * p_header_data,
427                                                 OPJ_UINT32 p_header_size,
428                                                 struct opj_event_mgr * p_manager
429                                         );
430 /**
431 Read the CRG marker (component registration)
432 @param j2k J2K handle
433 */
434 static void j2k_read_crg(opj_j2k_t *j2k);
435 /**
436  * Reads a CRG marker (Component registration)
437  *
438  * @param       p_header_data   the data contained in the TLM box.
439  * @param       p_j2k                   the jpeg2000 codec.
440  * @param       p_header_size   the size of the data contained in the TLM marker.
441  * @param       p_manager               the user event manager.
442 */
443 static opj_bool j2k_read_crg_v2 (
444                                                 opj_j2k_v2_t *p_j2k,
445                                                 OPJ_BYTE * p_header_data,
446                                                 OPJ_UINT32 p_header_size,
447                                                 struct opj_event_mgr * p_manager
448                                         );
449 /**
450 Read the TLM marker (tile-part lengths)
451 @param j2k J2K handle
452 */
453 static void j2k_read_tlm(opj_j2k_t *j2k);
454 /**
455  * Reads a TLM marker (Tile Length Marker)
456  *
457  * @param       p_header_data   the data contained in the TLM box.
458  * @param       p_j2k                   the jpeg2000 codec.
459  * @param       p_header_size   the size of the data contained in the TLM marker.
460  * @param       p_manager               the user event manager.
461 */
462 static opj_bool j2k_read_tlm_v2 (
463                                                 opj_j2k_v2_t *p_j2k,
464                                                 OPJ_BYTE * p_header_data,
465                                                 OPJ_UINT32 p_header_size,
466                                                 struct opj_event_mgr * p_manager
467                                         );
468 /**
469 Read the PLM marker (packet length, main header)
470 @param j2k J2K handle
471 */
472 static void j2k_read_plm(opj_j2k_t *j2k);
473
474 /**
475  * Reads a PLM marker (Packet length, main header marker)
476  *
477  * @param       p_header_data   the data contained in the TLM box.
478  * @param       p_j2k                   the jpeg2000 codec.
479  * @param       p_header_size   the size of the data contained in the TLM marker.
480  * @param       p_manager               the user event manager.
481 */
482 static opj_bool j2k_read_plm_v2 (
483                                                 opj_j2k_v2_t *p_j2k,
484                                                 OPJ_BYTE * p_header_data,
485                                                 OPJ_UINT32 p_header_size,
486                                                 struct opj_event_mgr * p_manager
487                                         );
488 /**
489 Read the PLT marker (packet length, tile-part header)
490 @param j2k J2K handle
491 */
492 static void j2k_read_plt(opj_j2k_t *j2k);
493 /**
494  * Reads a PLT marker (Packet length, tile-part header)
495  *
496  * @param       p_header_data   the data contained in the PLT box.
497  * @param       p_j2k                   the jpeg2000 codec.
498  * @param       p_header_size   the size of the data contained in the PLT marker.
499  * @param       p_manager               the user event manager.
500 */
501 static opj_bool j2k_read_plt_v2 (
502                                                 opj_j2k_v2_t *p_j2k,
503                                                 OPJ_BYTE * p_header_data,
504                                                 OPJ_UINT32 p_header_size,
505                                                 struct opj_event_mgr * p_manager
506                                         );
507 /**
508 Read the PPM marker (packet packet headers, main header)
509 @param j2k J2K handle
510 */
511 static void j2k_read_ppm(opj_j2k_t *j2k);
512 /**
513  * Reads a PPM marker (Packed packet headers, main header)
514  *
515  * @param       p_header_data   the data contained in the POC box.
516  * @param       p_j2k                   the jpeg2000 codec.
517  * @param       p_header_size   the size of the data contained in the POC marker.
518  * @param       p_manager               the user event manager.
519 */
520 static opj_bool j2k_read_ppm_v2 (
521                                                 opj_j2k_v2_t *p_j2k,
522                                                 OPJ_BYTE * p_header_data,
523                                                 OPJ_UINT32 p_header_size,
524                                                 struct opj_event_mgr * p_manager
525                                         );
526
527 static opj_bool j2k_read_ppm_v3 (
528                                                 opj_j2k_v2_t *p_j2k,
529                                                 OPJ_BYTE * p_header_data,
530                                                 OPJ_UINT32 p_header_size,
531                                                 struct opj_event_mgr * p_manager
532                                         );
533
534 /**
535 Read the PPT marker (packet packet headers, tile-part header)
536 @param j2k J2K handle
537 */
538 static void j2k_read_ppt(opj_j2k_t *j2k);
539 /**
540  * Reads a PPT marker (Packed packet headers, tile-part header)
541  *
542  * @param       p_header_data   the data contained in the PPT box.
543  * @param       p_j2k                   the jpeg2000 codec.
544  * @param       p_header_size   the size of the data contained in the PPT marker.
545  * @param       p_manager               the user event manager.
546 */
547 static opj_bool j2k_read_ppt_v2 (
548                                                 opj_j2k_v2_t *p_j2k,
549                                                 OPJ_BYTE * p_header_data,
550                                                 OPJ_UINT32 p_header_size,
551                                                 struct opj_event_mgr * p_manager
552                                         );
553 /**
554 Write the TLM marker (Mainheader)
555 @param j2k J2K handle
556 */
557 static void j2k_write_tlm(opj_j2k_t *j2k);
558 /**
559 Write the SOT marker (start of tile-part)
560 @param j2k J2K handle
561 */
562 static void j2k_write_sot(opj_j2k_t *j2k);
563 /**
564 Read the SOT marker (start of tile-part)
565 @param j2k J2K handle
566 */
567 static void j2k_read_sot(opj_j2k_t *j2k);
568
569 /**
570  * Reads a PPT marker (Packed packet headers, tile-part header)
571  *
572  * @param       p_header_data   the data contained in the PPT box.
573  * @param       p_j2k                   the jpeg2000 codec.
574  * @param       p_header_size   the size of the data contained in the PPT marker.
575  * @param       p_manager               the user event manager.
576 */
577 static opj_bool j2k_read_sot_v2 (
578                                                 opj_j2k_v2_t *p_j2k,
579                                                 OPJ_BYTE * p_header_data,
580                                                 OPJ_UINT32 p_header_size,
581                                                 struct opj_event_mgr * p_manager
582                                         );
583 /**
584 Write the SOD marker (start of data)
585 @param j2k J2K handle
586 @param tile_coder Pointer to a TCD handle
587 */
588 static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder);
589 /**
590 Read the SOD marker (start of data)
591 @param j2k J2K handle
592 */
593 static void j2k_read_sod(opj_j2k_t *j2k);
594
595 /**
596  * Reads a SOD marker (Start Of Data)
597  *
598  * @param       p_header_data   the data contained in the SOD box.
599  * @param       p_j2k                   the jpeg2000 codec.
600  * @param       p_header_size   the size of the data contained in the SOD marker.
601  * @param       p_manager               the user event manager.
602 */
603 static opj_bool j2k_read_sod_v2 (
604                                                 opj_j2k_v2_t *p_j2k,
605                                                 struct opj_stream_private *p_stream,
606                                                 struct opj_event_mgr * p_manager
607                                         );
608
609 /**
610 Write the RGN marker (region-of-interest)
611 @param j2k J2K handle
612 @param compno Number of the component concerned by the information written
613 @param tileno Number of the tile concerned by the information written
614 */
615 static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno);
616 /**
617 Read the RGN marker (region-of-interest)
618 @param j2k J2K handle
619 */
620 static void j2k_read_rgn(opj_j2k_t *j2k);
621
622 /**
623  * Reads a RGN marker (Region Of Interest)
624  *
625  * @param       p_header_data   the data contained in the POC box.
626  * @param       p_j2k                   the jpeg2000 codec.
627  * @param       p_header_size   the size of the data contained in the POC marker.
628  * @param       p_manager               the user event manager.
629 */
630 static opj_bool j2k_read_rgn_v2 (
631                                                 opj_j2k_v2_t *p_j2k,
632                                                 OPJ_BYTE * p_header_data,
633                                                 OPJ_UINT32 p_header_size,
634                                                 struct opj_event_mgr * p_manager
635                                         ) ;
636
637 /**
638 Write the EOC marker (end of codestream)
639 @param j2k J2K handle
640 */
641 static void j2k_write_eoc(opj_j2k_t *j2k);
642 /**
643 Read the EOC marker (end of codestream)
644 @param j2k J2K handle
645 */
646 static void j2k_read_eoc(opj_j2k_t *j2k);
647
648 /**
649  * Reads a EOC marker (End Of Codestream)
650  *
651  * @param       p_header_data   the data contained in the SOD box.
652  * @param       p_j2k                   the jpeg2000 codec.
653  * @param       p_header_size   the size of the data contained in the SOD marker.
654  * @param       p_manager               the user event manager.
655 */
656 static opj_bool j2k_read_eoc_v2 (
657                                             opj_j2k_v2_t *p_j2k,
658                                                 struct opj_stream_private *p_stream,
659                                                 struct opj_event_mgr * p_manager
660                                         ) ;
661
662 /**
663 Read an unknown marker
664 @param j2k J2K handle
665 */
666 static void j2k_read_unk(opj_j2k_t *j2k);
667 /**
668 Add main header marker information
669 @param cstr_info Codestream information structure
670 @param type marker type
671 @param pos byte offset of marker segment
672 @param len length of marker segment
673  */
674 static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len);
675
676 static void j2k_add_mhmarker_v2(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_UINT32 pos, OPJ_UINT32 len) ;
677 /**
678 Add tile header marker information
679 @param tileno tile index number
680 @param cstr_info Codestream information structure
681 @param type marker type
682 @param pos byte offset of marker segment
683 @param len length of marker segment
684  */
685 static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len);
686
687
688 /**
689  * Reads an unknown marker
690  *
691  * @param       p_stream                the stream object to read from.
692  * @param       p_j2k                   the jpeg2000 codec.
693  * @param       p_manager               the user event manager.
694  *
695  * @return      true                    if the marker could be deduced.
696 */
697 static opj_bool j2k_read_unk_v2 (       opj_j2k_v2_t *p_j2k,
698                                                                         struct opj_stream_private *p_stream,
699                                                                         OPJ_UINT32 *output_marker,
700                                                                         struct opj_event_mgr * p_manager );
701
702 /**
703  * Copy the image header from the jpeg2000 codec into an external image_header
704  *
705  * @param       p_j2k                   the jpeg2000 codec.
706  * @param       p_image_header  the external empty image header
707  *
708  * @return      true                    if the image header is correctly copy.
709  */
710 static opj_bool j2k_copy_img_header(opj_j2k_v2_t* p_j2k, opj_image_t* p_image);
711
712
713 static void j2k_dump_MH_info(opj_j2k_v2_t* p_j2k, FILE* out_stream);
714
715 static void j2k_dump_MH_index(opj_j2k_v2_t* p_j2k, FILE* out_stream);
716
717 static opj_codestream_index_t* j2k_create_cstr_index(void);
718
719 /*@}*/
720
721 /*@}*/
722
723 /* ----------------------------------------------------------------------- */
724 typedef struct j2k_prog_order{
725         OPJ_PROG_ORDER enum_prog;
726         char str_prog[5];
727 }j2k_prog_order_t;
728
729 j2k_prog_order_t j2k_prog_order_list[] = {
730         {CPRL, "CPRL"},
731         {LRCP, "LRCP"},
732         {PCRL, "PCRL"},
733         {RLCP, "RLCP"},
734         {RPCL, "RPCL"},
735         {(OPJ_PROG_ORDER)-1, ""}
736 };
737
738 typedef struct opj_dec_memory_marker_handler
739 {
740         /** marker value */
741         OPJ_UINT32 id;
742         /** value of the state when the marker can appear */
743         OPJ_UINT32 states;
744         /** action linked to the marker */
745         opj_bool (*handler) (
746                                         opj_j2k_v2_t *p_j2k,
747                                         OPJ_BYTE * p_header_data,
748                                         OPJ_UINT32 p_header_size,
749                                         struct opj_event_mgr * p_manager
750                                                 );
751 }
752 opj_dec_memory_marker_handler_t;
753
754 const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
755 {
756 #ifdef TODO_MS
757   {J2K_MS_SOT, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPHSOT, j2k_read_sot},
758   {J2K_MS_COD, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_cod},
759   {J2K_MS_COC, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_coc},
760   {J2K_MS_RGN, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_rgn},
761   {J2K_MS_QCD, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_qcd},
762   {J2K_MS_QCC, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_qcc},
763   {J2K_MS_POC, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_poc},
764   {J2K_MS_SIZ, J2K_DEC_STATE_MHSIZ , j2k_read_siz},
765   {J2K_MS_TLM, J2K_DEC_STATE_MH, j2k_read_tlm},
766   {J2K_MS_PLM, J2K_DEC_STATE_MH, j2k_read_plm},
767   {J2K_MS_PLT, J2K_DEC_STATE_TPH, j2k_read_plt},
768   {J2K_MS_PPM, J2K_DEC_STATE_MH, j2k_read_ppm},
769   {J2K_MS_PPT, J2K_DEC_STATE_TPH, j2k_read_ppt},
770   {J2K_MS_SOP, 0, 0},
771   {J2K_MS_CRG, J2K_DEC_STATE_MH, j2k_read_crg},
772   {J2K_MS_COM, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_com},
773   {J2K_MS_MCT, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_mct},
774   {J2K_MS_CBD, J2K_DEC_STATE_MH , j2k_read_cbd},
775   {J2K_MS_MCC, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_mcc},
776   {J2K_MS_MCO, J2K_DEC_STATE_MH | J2K_DEC_STATE_TPH, j2k_read_mco},
777 #endif
778   {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot_v2},
779   {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod_v2},
780   {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc_v2},
781   {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn_v2},
782   {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd_v2},
783   {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc_v2},
784   {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc_v2},
785   {J2K_MS_SIZ, J2K_STATE_MHSIZ , j2k_read_siz_v2},
786   {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm_v2},
787   {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm_v2},
788   {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt_v2},
789   {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm_v3},
790   {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt_v2},
791   {J2K_MS_SOP, 0, 0},
792   {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg_v2},
793   {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com_v2},
794 #ifdef TODO_MS /* FIXME */
795   {J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_mct},
796   {J2K_MS_CBD, J2K_STATE_MH , j2k_read_cbd},
797   {J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_mcc},
798   {J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_mco},
799 #endif
800 #ifdef USE_JPWL
801 #ifdef TODO_MS /* FIXME */
802   {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
803   {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
804   {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
805   {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
806 #endif
807 #endif /* USE_JPWL */
808 #ifdef USE_JPSEC
809   {J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
810   {J2K_MS_INSEC, 0, j2k_read_insec}
811 #endif /* USE_JPSEC */
812   {J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}//j2k_read_unk_v2}
813 };
814
815
816
817 char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
818         j2k_prog_order_t *po;
819         for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
820                 if(po->enum_prog == prg_order){
821                         break;
822                 }
823         }
824         return po->str_prog;
825 }
826
827 /* ----------------------------------------------------------------------- */
828 static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){
829         char *prog;
830         int i;
831         int tpnum=1,tpend=0;
832         opj_tcp_t *tcp = &cp->tcps[tileno];
833         prog = j2k_convert_progression_order(tcp->prg);
834         
835         if(cp->tp_on == 1){
836                 for(i=0;i<4;i++){
837                         if(tpend!=1){
838                                 if( cp->tp_flag == prog[i] ){
839                                         tpend=1;cp->tp_pos=i;
840                                 }
841                                 switch(prog[i]){
842                                 case 'C':
843                                         tpnum= tpnum * tcp->pocs[pino].compE;
844                                         break;
845                                 case 'R':
846                                         tpnum= tpnum * tcp->pocs[pino].resE;
847                                         break;
848                                 case 'P':
849                                         tpnum= tpnum * tcp->pocs[pino].prcE;
850                                         break;
851                                 case 'L':
852                                         tpnum= tpnum * tcp->pocs[pino].layE;
853                                         break;
854                                 }
855                         }
856                 }
857         }else{
858                 tpnum=1;
859         }
860         return tpnum;
861 }
862
863 /**     mem allocation for TLM marker*/
864 int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){
865         int pino,tileno,totnum_tp=0;
866
867         OPJ_ARG_NOT_USED(img_numcomp);
868
869         j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int));
870         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
871                 int cur_totnum_tp = 0;
872                 opj_tcp_t *tcp = &cp->tcps[tileno];
873                 for(pino = 0; pino <= tcp->numpocs; pino++) {
874                         int tp_num=0;
875                         opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS);
876                         if(!pi) { return -1;}
877                         tp_num = j2k_get_num_tp(cp,pino,tileno);
878                         totnum_tp = totnum_tp + tp_num;
879                         cur_totnum_tp = cur_totnum_tp + tp_num;
880                         pi_destroy(pi, cp, tileno);
881                 }
882                 j2k->cur_totnum_tp[tileno] = cur_totnum_tp;
883                 /* INDEX >> */
884                 if (j2k->cstr_info) {
885                         j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp;
886                         j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
887                 }
888                 /* << INDEX */
889         }
890         return totnum_tp;
891 }
892
893 static void j2k_write_soc(opj_j2k_t *j2k) {
894         opj_cio_t *cio = j2k->cio;
895         cio_write(cio, J2K_MS_SOC, 2);
896
897         if(j2k->cstr_info)
898           j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio), 0);
899
900 /* UniPG>> */
901 #ifdef USE_JPWL
902
903         /* update markers struct */
904         j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2);
905 #endif /* USE_JPWL */
906 /* <<UniPG */
907 }
908
909 static void j2k_read_soc(opj_j2k_t *j2k) {      
910         j2k->state = J2K_STATE_MHSIZ;
911         /* Index */
912         if (j2k->cstr_info) {
913                 j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2;
914                 j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start;
915         }
916 }
917
918 /**
919  * Reads a SOC marker (Start of Codestream)
920  * @param       p_header_data   the data contained in the SOC box.
921  * @param       jp2                             the jpeg2000 file codec.
922  * @param       p_header_size   the size of the data contained in the SOC marker.
923  * @param       p_manager               the user event manager.
924 */
925 static opj_bool j2k_read_soc_v2(        opj_j2k_v2_t *p_j2k,
926                                                                         struct opj_stream_private *p_stream,
927                                                                         struct opj_event_mgr * p_manager )
928 {
929         OPJ_BYTE l_data [2];
930         OPJ_UINT32 l_marker;
931
932         /* preconditions */
933         assert(p_j2k != 00);
934         assert(p_manager != 00);
935         assert(p_stream != 00);
936
937         if (opj_stream_read_data(p_stream,l_data,2,p_manager) != 2) {
938                 return OPJ_FALSE;
939         }
940
941         opj_read_bytes(l_data,&l_marker,2);
942         if (l_marker != J2K_MS_SOC) {
943                 return OPJ_FALSE;
944         }
945
946         /* Next marker should be a SIZ marker in the main header */
947         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
948
949         /* FIXME move it in a index structure included in p_j2k*/
950         p_j2k->cstr_index->main_head_start = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
951
952         opj_event_msg_v2(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n", p_j2k->cstr_index->main_head_start);
953
954         /* Add the marker to the codestream index*/
955         j2k_add_mhmarker_v2(p_j2k->cstr_index, J2K_MS_SOC, p_j2k->cstr_index->main_head_start, 2);
956
957         return OPJ_TRUE;
958 }
959
960 static void j2k_write_siz(opj_j2k_t *j2k) {
961         int i;
962         int lenp, len;
963
964         opj_cio_t *cio = j2k->cio;
965         opj_image_t *image = j2k->image;
966         opj_cp_t *cp = j2k->cp;
967
968         cio_write(cio, J2K_MS_SIZ, 2);  /* SIZ */
969         lenp = cio_tell(cio);
970         cio_skip(cio, 2);
971         cio_write(cio, cp->rsiz, 2);                    /* Rsiz (capabilities) */
972         cio_write(cio, image->x1, 4);   /* Xsiz */
973         cio_write(cio, image->y1, 4);   /* Ysiz */
974         cio_write(cio, image->x0, 4);   /* X0siz */
975         cio_write(cio, image->y0, 4);   /* Y0siz */
976         cio_write(cio, cp->tdx, 4);             /* XTsiz */
977         cio_write(cio, cp->tdy, 4);             /* YTsiz */
978         cio_write(cio, cp->tx0, 4);             /* XT0siz */
979         cio_write(cio, cp->ty0, 4);             /* YT0siz */
980         cio_write(cio, image->numcomps, 2);     /* Csiz */
981         for (i = 0; i < image->numcomps; i++) {
982                 cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1);      /* Ssiz_i */
983                 cio_write(cio, image->comps[i].dx, 1);  /* XRsiz_i */
984                 cio_write(cio, image->comps[i].dy, 1);  /* YRsiz_i */
985         }
986         len = cio_tell(cio) - lenp;
987         cio_seek(cio, lenp);
988         cio_write(cio, len, 2);         /* Lsiz */
989         cio_seek(cio, lenp + len);
990         
991         if(j2k->cstr_info)
992           j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SIZ, lenp, len);
993 }
994
995 static void j2k_read_siz(opj_j2k_t *j2k) {
996         int len, i;
997         
998         opj_cio_t *cio = j2k->cio;
999         opj_image_t *image = j2k->image;
1000         opj_cp_t *cp = j2k->cp;
1001         
1002         len = cio_read(cio, 2);                 /* Lsiz */
1003         cio_read(cio, 2);                               /* Rsiz (capabilities) */
1004         image->x1 = cio_read(cio, 4);   /* Xsiz */
1005         image->y1 = cio_read(cio, 4);   /* Ysiz */
1006         image->x0 = cio_read(cio, 4);   /* X0siz */
1007         image->y0 = cio_read(cio, 4);   /* Y0siz */
1008         cp->tdx = cio_read(cio, 4);             /* XTsiz */
1009         cp->tdy = cio_read(cio, 4);             /* YTsiz */
1010         cp->tx0 = cio_read(cio, 4);             /* XT0siz */
1011         cp->ty0 = cio_read(cio, 4);             /* YT0siz */
1012         
1013         if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
1014                 opj_event_msg(j2k->cinfo, EVT_ERROR,
1015                                                                         "%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
1016                                                                         image->x0,image->x1,image->y0,image->y1);
1017                 return;
1018         }
1019         
1020         image->numcomps = cio_read(cio, 2);     /* Csiz */
1021
1022 #ifdef USE_JPWL
1023         if (j2k->cp->correct) {
1024                 /* if JPWL is on, we check whether TX errors have damaged
1025                   too much the SIZ parameters */
1026                 if (!(image->x1 * image->y1)) {
1027                         opj_event_msg(j2k->cinfo, EVT_ERROR,
1028                                 "JPWL: bad image size (%d x %d)\n",
1029                                 image->x1, image->y1);
1030                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1031                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1032                                 return;
1033                         }
1034                 }
1035                 if (image->numcomps != ((len - 38) / 3)) {
1036                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1037                                 "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
1038                                 image->numcomps, ((len - 38) / 3));
1039                         if (!JPWL_ASSUME) {
1040                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1041                                 return;
1042                         }
1043                         /* we try to correct */
1044                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n");
1045                         if (image->numcomps < ((len - 38) / 3)) {
1046                                 len = 38 + 3 * image->numcomps;
1047                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
1048                                         len);                           
1049                         } else {
1050                                 image->numcomps = ((len - 38) / 3);
1051                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
1052                                         image->numcomps);                               
1053                         }
1054                 }
1055
1056                 /* update components number in the jpwl_exp_comps filed */
1057                 cp->exp_comps = image->numcomps;
1058         }
1059 #endif /* USE_JPWL */
1060
1061         image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
1062         for (i = 0; i < image->numcomps; i++) {
1063                 int tmp, w, h;
1064                 tmp = cio_read(cio, 1);         /* Ssiz_i */
1065                 image->comps[i].prec = (tmp & 0x7f) + 1;
1066                 image->comps[i].sgnd = tmp >> 7;
1067                 image->comps[i].dx = cio_read(cio, 1);  /* XRsiz_i */
1068                 image->comps[i].dy = cio_read(cio, 1);  /* YRsiz_i */
1069                 
1070 #ifdef USE_JPWL
1071                 if (j2k->cp->correct) {
1072                 /* if JPWL is on, we check whether TX errors have damaged
1073                         too much the SIZ parameters, again */
1074                         if (!(image->comps[i].dx * image->comps[i].dy)) {
1075                                 opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1076                                         "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
1077                                         i, i, image->comps[i].dx, image->comps[i].dy);
1078                                 if (!JPWL_ASSUME) {
1079                                         opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1080                                         return;
1081                                 }
1082                                 /* we try to correct */
1083                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
1084                                 if (!image->comps[i].dx) {
1085                                         image->comps[i].dx = 1;
1086                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
1087                                                 i, image->comps[i].dx);
1088                                 }
1089                                 if (!image->comps[i].dy) {
1090                                         image->comps[i].dy = 1;
1091                                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
1092                                                 i, image->comps[i].dy);
1093                                 }
1094                         }
1095                         
1096                 }
1097 #endif /* USE_JPWL */
1098
1099                 /* TODO: unused ? */
1100                 w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
1101                 h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
1102
1103                 image->comps[i].resno_decoded = 0;      /* number of resolution decoded */
1104                 image->comps[i].factor = cp->reduce; /* reducing factor per component */
1105         }
1106         
1107         cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
1108         cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
1109
1110 #ifdef USE_JPWL
1111         if (j2k->cp->correct) {
1112                 /* if JPWL is on, we check whether TX errors have damaged
1113                   too much the SIZ parameters */
1114                 if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) {
1115                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1116                                 "JPWL: bad number of tiles (%d x %d)\n",
1117                                 cp->tw, cp->th);
1118                         if (!JPWL_ASSUME) {
1119                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1120                                 return;
1121                         }
1122                         /* we try to correct */
1123                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
1124                         if (cp->tw < 1) {
1125                                 cp->tw= 1;
1126                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
1127                                         cp->tw);
1128                         }
1129                         if (cp->tw > cp->max_tiles) {
1130                                 cp->tw= 1;
1131                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n"
1132                                         "- setting %d tiles in x => HYPOTHESIS!!!\n",
1133                                         cp->max_tiles, cp->tw);
1134                         }
1135                         if (cp->th < 1) {
1136                                 cp->th= 1;
1137                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
1138                                         cp->th);
1139                         }
1140                         if (cp->th > cp->max_tiles) {
1141                                 cp->th= 1;
1142                                 opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
1143                                         "- setting %d tiles in y => HYPOTHESIS!!!\n",
1144                                         cp->max_tiles, cp->th);
1145                         }
1146                 }
1147         }
1148 #endif /* USE_JPWL */
1149
1150         cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
1151         cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
1152         cp->tileno_size = 0;
1153         
1154 #ifdef USE_JPWL
1155         if (j2k->cp->correct) {
1156                 if (!cp->tcps) {
1157                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1158                                 "JPWL: could not alloc tcps field of cp\n");
1159                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1160                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1161                                 return;
1162                         }
1163                 }
1164         }
1165 #endif /* USE_JPWL */
1166
1167         for (i = 0; i < cp->tw * cp->th; i++) {
1168                 cp->tcps[i].POC = 0;
1169                 cp->tcps[i].numpocs = 0;
1170                 cp->tcps[i].first = 1;
1171         }
1172         
1173         /* Initialization for PPM marker */
1174         cp->ppm = 0;
1175         cp->ppm_data = NULL;
1176         cp->ppm_data_first = NULL;
1177         cp->ppm_previous = 0;
1178         cp->ppm_store = 0;
1179
1180         j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
1181         for (i = 0; i < cp->tw * cp->th; i++) {
1182                 cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t));
1183         }       
1184         j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*));
1185         j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int));
1186         j2k->state = J2K_STATE_MH;
1187
1188         /* Index */
1189         if (j2k->cstr_info) {
1190                 opj_codestream_info_t *cstr_info = j2k->cstr_info;
1191                 cstr_info->image_w = image->x1 - image->x0;
1192                 cstr_info->image_h = image->y1 - image->y0;
1193                 cstr_info->numcomps = image->numcomps;
1194                 cstr_info->tw = cp->tw;
1195                 cstr_info->th = cp->th;
1196                 cstr_info->tile_x = cp->tdx;    
1197                 cstr_info->tile_y = cp->tdy;    
1198                 cstr_info->tile_Ox = cp->tx0;   
1199                 cstr_info->tile_Oy = cp->ty0;                   
1200                 cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t));              
1201         }
1202 }
1203
1204
1205 /**
1206  * Reads a SIZ marker (image and tile size)
1207  * @param       p_header_data   the data contained in the SIZ box.
1208  * @param       jp2                             the jpeg2000 file codec.
1209  * @param       p_header_size   the size of the data contained in the SIZ marker.
1210  * @param       p_manager               the user event manager.
1211 */
1212 opj_bool j2k_read_siz_v2 (
1213                                     opj_j2k_v2_t *p_j2k,
1214                                         OPJ_BYTE * p_header_data,
1215                                         OPJ_UINT32 p_header_size,
1216                                         struct opj_event_mgr * p_manager
1217                                         )
1218 {
1219         OPJ_UINT32 l_size, i;
1220         OPJ_UINT32 l_nb_comp;
1221         OPJ_UINT32 l_nb_comp_remain;
1222         OPJ_UINT32 l_remaining_size;
1223         OPJ_UINT32 l_nb_tiles;
1224         OPJ_UINT32 l_tmp;
1225         opj_image_t *l_image = 00;
1226         opj_cp_v2_t *l_cp = 00;
1227         opj_image_comp_t * l_img_comp = 00;
1228         opj_tcp_v2_t * l_current_tile_param = 00;
1229
1230         // preconditions
1231         assert(p_j2k != 00);
1232         assert(p_manager != 00);
1233         assert(p_header_data != 00);
1234
1235         l_image = p_j2k->m_image;
1236         l_cp = &(p_j2k->m_cp);
1237
1238         // minimum size == 39 - 3 (= minimum component parameter)
1239         if (p_header_size < 36) {
1240                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
1241                 return OPJ_FALSE;
1242         }
1243
1244         l_remaining_size = p_header_size - 36;
1245         l_nb_comp = l_remaining_size / 3;
1246         l_nb_comp_remain = l_remaining_size % 3;
1247         if (l_nb_comp_remain != 0){
1248                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
1249                 return OPJ_FALSE;
1250         }
1251
1252         l_size = p_header_size + 2;                                                                             /* Lsiz */
1253
1254         opj_read_bytes(p_header_data,&l_tmp ,2);                                                /* Rsiz (capabilities) */
1255         p_header_data+=2;
1256         l_cp->rsiz = (OPJ_RSIZ_CAPABILITIES) l_tmp;
1257         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4);   /* Xsiz */
1258         p_header_data+=4;
1259         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4);   /* Ysiz */
1260         p_header_data+=4;
1261         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4);   /* X0siz */
1262         p_header_data+=4;
1263         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4);   /* Y0siz */
1264         p_header_data+=4;
1265         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx, 4);             /* XTsiz */
1266         p_header_data+=4;
1267         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy, 4);             /* YTsiz */
1268         p_header_data+=4;
1269         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0, 4);             /* XT0siz */
1270         p_header_data+=4;
1271         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0, 4);             /* YT0siz */
1272         p_header_data+=4;
1273         opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp, 2);                 /* Csiz */
1274         p_header_data+=2;
1275         if (l_tmp < 16385)
1276                 l_image->numcomps = (OPJ_UINT16) l_tmp;
1277         else {
1278                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
1279                 return OPJ_FALSE;
1280         }
1281
1282         if (l_image->numcomps != l_nb_comp) {
1283                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n", l_image->numcomps, l_nb_comp);
1284                 return OPJ_FALSE;
1285         }
1286
1287 #ifdef USE_JPWL
1288         if (l_cp->correct) {
1289                 /* if JPWL is on, we check whether TX errors have damaged
1290                   too much the SIZ parameters */
1291                 if (!(l_image->x1 * l_image->y1)) {
1292                         opj_event_msg_v2(p_manager, EVT_ERROR,
1293                                 "JPWL: bad image size (%d x %d)\n",
1294                                 l_image->x1, l_image->y1);
1295                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1296                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
1297                                 return OPJ_FALSE;
1298                         }
1299                 }
1300
1301         /* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
1302                 if (l_image->numcomps != ((len - 38) / 3)) {
1303                         opj_event_msg_v2(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1304                                 "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
1305                                 l_image->numcomps, ((len - 38) / 3));
1306                         if (!JPWL_ASSUME) {
1307                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
1308                                 return OPJ_FALSE;
1309                         }
1310         */              /* we try to correct */
1311         /*              opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust this\n");
1312                         if (l_image->numcomps < ((len - 38) / 3)) {
1313                                 len = 38 + 3 * l_image->numcomps;
1314                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
1315                                         len);
1316                         } else {
1317                                 l_image->numcomps = ((len - 38) / 3);
1318                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
1319                                         l_image->numcomps);
1320                         }
1321                 }
1322         */
1323
1324                 /* update components number in the jpwl_exp_comps filed */
1325                 l_cp->exp_comps = l_image->numcomps;
1326         }
1327 #endif /* USE_JPWL */
1328
1329         // Allocate the resulting image components
1330         l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps, sizeof(opj_image_comp_t));
1331         if (l_image->comps == 00){
1332                 l_image->numcomps = 0;
1333                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1334                 return OPJ_FALSE;
1335         }
1336
1337         memset(l_image->comps,0,l_image->numcomps * sizeof(opj_image_comp_t));
1338         l_img_comp = l_image->comps;
1339
1340         // Read the component information
1341         for (i = 0; i < l_image->numcomps; ++i){
1342                 OPJ_UINT32 tmp;
1343                 opj_read_bytes(p_header_data,&tmp,1);   /* Ssiz_i */
1344                 ++p_header_data;
1345                 l_img_comp->prec = (tmp & 0x7f) + 1;
1346                 l_img_comp->sgnd = tmp >> 7;
1347                 opj_read_bytes(p_header_data,&tmp,1);   /* XRsiz_i */
1348                 ++p_header_data;
1349                 l_img_comp->dx = (OPJ_INT32)tmp; // should be between 1 and 255
1350                 opj_read_bytes(p_header_data,&tmp,1);   /* YRsiz_i */
1351                 ++p_header_data;
1352                 l_img_comp->dy = (OPJ_INT32)tmp; // should be between 1 and 255
1353
1354 #ifdef USE_JPWL
1355                 if (l_cp->correct) {
1356                 /* if JPWL is on, we check whether TX errors have damaged
1357                         too much the SIZ parameters, again */
1358                         if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
1359                                 opj_event_msg_v2(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1360                                         "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
1361                                         i, i, l_image->comps[i].dx, l_image->comps[i].dy);
1362                                 if (!JPWL_ASSUME) {
1363                                         opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
1364                                         return OPJ_FALSE;
1365                                 }
1366                                 /* we try to correct */
1367                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust them\n");
1368                                 if (!l_image->comps[i].dx) {
1369                                         l_image->comps[i].dx = 1;
1370                                         opj_event_msg_v2(p_manager, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
1371                                                 i, l_image->comps[i].dx);
1372                                 }
1373                                 if (!l_image->comps[i].dy) {
1374                                         l_image->comps[i].dy = 1;
1375                                         opj_event_msg_v2(p_manager, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
1376                                                 i, l_image->comps[i].dy);
1377                                 }
1378                         }
1379                 }
1380 #endif /* USE_JPWL */
1381                 l_img_comp->resno_decoded = 0;                                                          /* number of resolution decoded */
1382                 l_img_comp->factor = l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
1383                 ++l_img_comp;
1384         }
1385
1386         // Compute the number of tiles
1387         l_cp->tw = int_ceildiv(l_image->x1 - l_cp->tx0, l_cp->tdx);
1388         l_cp->th = int_ceildiv(l_image->y1 - l_cp->ty0, l_cp->tdy);
1389         l_nb_tiles = l_cp->tw * l_cp->th;
1390
1391         // Define the tiles which will be decoded
1392         if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
1393                 p_j2k->m_specific_param.m_decoder.m_start_tile_x = (p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
1394                 p_j2k->m_specific_param.m_decoder.m_start_tile_y = (p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
1395                 p_j2k->m_specific_param.m_decoder.m_end_tile_x = int_ceildiv((p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0), l_cp->tdx);
1396                 p_j2k->m_specific_param.m_decoder.m_end_tile_y = int_ceildiv((p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0), l_cp->tdy);
1397         }
1398         else {
1399                 p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
1400                 p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
1401                 p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
1402                 p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
1403         }
1404
1405 #ifdef USE_JPWL
1406         if (l_cp->correct) {
1407                 /* if JPWL is on, we check whether TX errors have damaged
1408                   too much the SIZ parameters */
1409                 if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) || (l_cp->th > l_cp->max_tiles)) {
1410                         opj_event_msg_v2(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1411                                 "JPWL: bad number of tiles (%d x %d)\n",
1412                                 l_cp->tw, l_cp->th);
1413                         if (!JPWL_ASSUME) {
1414                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
1415                                 return OPJ_FALSE;
1416                         }
1417                         /* we try to correct */
1418                         opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust them\n");
1419                         if (l_cp->tw < 1) {
1420                                 l_cp->tw= 1;
1421                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
1422                                                 l_cp->tw);
1423                         }
1424                         if (l_cp->tw > l_cp->max_tiles) {
1425                                 l_cp->tw= 1;
1426                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- too large x, increase expectance of %d\n"
1427                                         "- setting %d tiles in x => HYPOTHESIS!!!\n",
1428                                         l_cp->max_tiles, l_cp->tw);
1429                         }
1430                         if (l_cp->th < 1) {
1431                                 l_cp->th= 1;
1432                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
1433                                                 l_cp->th);
1434                         }
1435                         if (l_cp->th > l_cp->max_tiles) {
1436                                 l_cp->th= 1;
1437                                 opj_event_msg_v2(p_manager, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
1438                                         "- setting %d tiles in y => HYPOTHESIS!!!\n",
1439                                         l_cp->max_tiles, l_cp->th);
1440                         }
1441                 }
1442         }
1443 #endif /* USE_JPWL */
1444
1445         /* memory allocations */
1446         l_cp->tcps = (opj_tcp_v2_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_v2_t));
1447         if (l_cp->tcps == 00) {
1448                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1449                 return OPJ_FALSE;
1450         }
1451         memset(l_cp->tcps,0,l_nb_tiles*sizeof(opj_tcp_t));
1452
1453 #ifdef USE_JPWL
1454         if (l_cp->correct) {
1455                 if (!l_cp->tcps) {
1456                         opj_event_msg_v2(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1457                                 "JPWL: could not alloc tcps field of cp\n");
1458                         if (!JPWL_ASSUME || JPWL_ASSUME) {
1459                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
1460                                 return OPJ_FALSE;
1461                         }
1462                 }
1463         }
1464 #endif /* USE_JPWL */
1465
1466         p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
1467                         (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
1468         if(p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps  == 00) {
1469                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1470                 return OPJ_FALSE;
1471         }
1472         memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps ,0,l_image->numcomps*sizeof(opj_tccp_t));
1473
1474         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
1475                         (opj_mct_data_t*)opj_malloc(J2K_MCT_DEFAULT_NB_RECORDS * sizeof(opj_mct_data_t));
1476
1477         if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
1478                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1479                 return OPJ_FALSE;
1480         }
1481         memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records,0,J2K_MCT_DEFAULT_NB_RECORDS * sizeof(opj_mct_data_t));
1482         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records = J2K_MCT_DEFAULT_NB_RECORDS;
1483
1484         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
1485                         (opj_simple_mcc_decorrelation_data_t*)
1486                         opj_malloc(J2K_MCC_DEFAULT_NB_RECORDS * sizeof(opj_simple_mcc_decorrelation_data_t));
1487
1488         if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
1489                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1490                 return OPJ_FALSE;
1491         }
1492         memset(p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records,0,J2K_MCC_DEFAULT_NB_RECORDS * sizeof(opj_simple_mcc_decorrelation_data_t));
1493         p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records = J2K_MCC_DEFAULT_NB_RECORDS;
1494
1495         /* set up default dc level shift */
1496         for (i=0;i<l_image->numcomps;++i) {
1497                 if (! l_image->comps[i].sgnd) {
1498                         p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1);
1499                 }
1500         }
1501
1502         l_current_tile_param = l_cp->tcps;
1503         for     (i = 0; i < l_nb_tiles; ++i) {
1504                 l_current_tile_param->tccps = (opj_tccp_t*) opj_malloc(l_image->numcomps * sizeof(opj_tccp_t));
1505                 if (l_current_tile_param->tccps == 00) {
1506                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
1507                         return OPJ_FALSE;
1508                 }
1509                 memset(l_current_tile_param->tccps,0,l_image->numcomps * sizeof(opj_tccp_t));
1510
1511                 ++l_current_tile_param;
1512         }
1513
1514         p_j2k->m_specific_param.m_decoder.m_state =  J2K_STATE_MH; // FIXME J2K_DEC_STATE_MH;
1515         opj_image_comp_header_update(l_image,l_cp);
1516
1517         return OPJ_TRUE;
1518 }
1519
1520
1521
1522 static void j2k_write_com(opj_j2k_t *j2k) {
1523         unsigned int i;
1524         int lenp, len;
1525
1526         if(j2k->cp->comment) {
1527                 opj_cio_t *cio = j2k->cio;
1528                 char *comment = j2k->cp->comment;
1529
1530                 cio_write(cio, J2K_MS_COM, 2);
1531                 lenp = cio_tell(cio);
1532                 cio_skip(cio, 2);
1533                 cio_write(cio, 1, 2);           /* General use (IS 8859-15:1999 (Latin) values) */
1534                 for (i = 0; i < strlen(comment); i++) {
1535                         cio_write(cio, comment[i], 1);
1536                 }
1537                 len = cio_tell(cio) - lenp;
1538                 cio_seek(cio, lenp);
1539                 cio_write(cio, len, 2);
1540                 cio_seek(cio, lenp + len);
1541
1542                 
1543                 if(j2k->cstr_info)
1544                   j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COM, lenp, len);
1545
1546         }
1547 }
1548
1549 static void j2k_read_com(opj_j2k_t *j2k) {
1550         int len;
1551         
1552         opj_cio_t *cio = j2k->cio;
1553
1554         len = cio_read(cio, 2);
1555         cio_skip(cio, len - 2);  
1556 }
1557 /**
1558  * Reads a COM marker (comments)
1559  * @param       p_header_data   the data contained in the COM box.
1560  * @param       jp2                             the jpeg2000 file codec.
1561  * @param       p_header_size   the size of the data contained in the COM marker.
1562  * @param       p_manager               the user event manager.
1563 */
1564 opj_bool j2k_read_com_v2 (
1565                                         opj_j2k_v2_t *p_j2k,
1566                                         OPJ_BYTE * p_header_data,
1567                                         OPJ_UINT32 p_header_size,
1568                                         struct opj_event_mgr * p_manager
1569                                         )
1570 {
1571         // preconditions
1572         assert(p_j2k != 00);
1573         assert(p_manager != 00);
1574         assert(p_header_data != 00);
1575
1576         return OPJ_TRUE;
1577 }
1578
1579 static void j2k_write_cox(opj_j2k_t *j2k, int compno) {
1580         int i;
1581
1582         opj_cp_t *cp = j2k->cp;
1583         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
1584         opj_tccp_t *tccp = &tcp->tccps[compno];
1585         opj_cio_t *cio = j2k->cio;
1586         
1587         cio_write(cio, tccp->numresolutions - 1, 1);    /* SPcox (D) */
1588         cio_write(cio, tccp->cblkw - 2, 1);                             /* SPcox (E) */
1589         cio_write(cio, tccp->cblkh - 2, 1);                             /* SPcox (F) */
1590         cio_write(cio, tccp->cblksty, 1);                               /* SPcox (G) */
1591         cio_write(cio, tccp->qmfbid, 1);                                /* SPcox (H) */
1592         
1593         if (tccp->csty & J2K_CCP_CSTY_PRT) {
1594                 for (i = 0; i < tccp->numresolutions; i++) {
1595                         cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1);        /* SPcox (I_i) */
1596                 }
1597         }
1598 }
1599
1600 static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
1601         int i;
1602
1603         opj_cp_t *cp = j2k->cp;
1604         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
1605         opj_tccp_t *tccp = &tcp->tccps[compno];
1606         opj_cio_t *cio = j2k->cio;
1607
1608         tccp->numresolutions = cio_read(cio, 1) + 1;    /* SPcox (D) */
1609
1610         // If user wants to remove more resolutions than the codestream contains, return error
1611         if (cp->reduce >= tccp->numresolutions) {
1612                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
1613                                         "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
1614                 j2k->state |= J2K_STATE_ERR;
1615         }
1616
1617         tccp->cblkw = cio_read(cio, 1) + 2;     /* SPcox (E) */
1618         tccp->cblkh = cio_read(cio, 1) + 2;     /* SPcox (F) */
1619         tccp->cblksty = cio_read(cio, 1);       /* SPcox (G) */
1620         tccp->qmfbid = cio_read(cio, 1);        /* SPcox (H) */
1621         if (tccp->csty & J2K_CP_CSTY_PRT) {
1622                 for (i = 0; i < tccp->numresolutions; i++) {
1623                         int tmp = cio_read(cio, 1);     /* SPcox (I_i) */
1624                         tccp->prcw[i] = tmp & 0xf;
1625                         tccp->prch[i] = tmp >> 4;
1626                 }
1627         }
1628
1629         /* INDEX >> */
1630         if(j2k->cstr_info && compno == 0) {
1631                 for (i = 0; i < tccp->numresolutions; i++) {
1632                         if (tccp->csty & J2K_CP_CSTY_PRT) {
1633                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i];
1634                                 j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i];
1635                         }
1636                         else {
1637                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
1638                                 j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
1639                         }
1640                 }
1641         }
1642         /* << INDEX */
1643 }
1644
1645 static void j2k_write_cod(opj_j2k_t *j2k) {
1646         opj_cp_t *cp = NULL;
1647         opj_tcp_t *tcp = NULL;
1648         int lenp, len;
1649
1650         opj_cio_t *cio = j2k->cio;
1651         
1652         cio_write(cio, J2K_MS_COD, 2);  /* COD */
1653         
1654         lenp = cio_tell(cio);
1655         cio_skip(cio, 2);
1656         
1657         cp = j2k->cp;
1658         tcp = &cp->tcps[j2k->curtileno];
1659
1660         cio_write(cio, tcp->csty, 1);           /* Scod */
1661         cio_write(cio, tcp->prg, 1);            /* SGcod (A) */
1662         cio_write(cio, tcp->numlayers, 2);      /* SGcod (B) */
1663         cio_write(cio, tcp->mct, 1);            /* SGcod (C) */
1664         
1665         j2k_write_cox(j2k, 0);
1666         len = cio_tell(cio) - lenp;
1667         cio_seek(cio, lenp);
1668         cio_write(cio, len, 2);         /* Lcod */
1669         cio_seek(cio, lenp + len);
1670
1671         if(j2k->cstr_info)
1672           j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COD, lenp, len);
1673
1674 }
1675
1676 static void j2k_read_cod(opj_j2k_t *j2k) {
1677         int len, i, pos;
1678         
1679         opj_cio_t *cio = j2k->cio;
1680         opj_cp_t *cp = j2k->cp;
1681         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
1682         opj_image_t *image = j2k->image;
1683         
1684         len = cio_read(cio, 2);                         /* Lcod */
1685         tcp->csty = cio_read(cio, 1);           /* Scod */
1686         tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);            /* SGcod (A) */
1687         tcp->numlayers = cio_read(cio, 2);      /* SGcod (B) */
1688         tcp->mct = cio_read(cio, 1);            /* SGcod (C) */
1689         
1690         pos = cio_tell(cio);
1691         for (i = 0; i < image->numcomps; i++) {
1692                 tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT;
1693                 cio_seek(cio, pos);
1694                 j2k_read_cox(j2k, i);
1695         }
1696
1697         /* Index */
1698         if (j2k->cstr_info) {
1699                 opj_codestream_info_t *cstr_info = j2k->cstr_info;
1700                 cstr_info->prog = tcp->prg;
1701                 cstr_info->numlayers = tcp->numlayers;
1702                 cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
1703                 for (i = 0; i < image->numcomps; i++) {
1704                         cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1;
1705                 }
1706         }
1707 }
1708
1709 /**
1710  * Reads a COD marker (Coding Styke defaults)
1711  * @param       p_header_data   the data contained in the COD box.
1712  * @param       p_j2k                   the jpeg2000 codec.
1713  * @param       p_header_size   the size of the data contained in the COD marker.
1714  * @param       p_manager               the user event manager.
1715 */
1716 opj_bool j2k_read_cod_v2 (
1717                                         opj_j2k_v2_t *p_j2k,
1718                                         OPJ_BYTE * p_header_data,
1719                                         OPJ_UINT32 p_header_size,
1720                                         struct opj_event_mgr * p_manager
1721                                         )
1722 {
1723         // loop
1724         OPJ_UINT32 i;
1725         OPJ_UINT32 l_tmp;
1726         opj_cp_v2_t *l_cp = 00;
1727         opj_tcp_v2_t *l_tcp = 00;
1728         opj_image_t *l_image = 00;
1729
1730         /* preconditions */
1731         assert(p_header_data != 00);
1732         assert(p_j2k != 00);
1733         assert(p_manager != 00);
1734
1735         l_image = p_j2k->m_image;
1736         l_cp = &(p_j2k->m_cp);
1737
1738         /* If we are in the first tile-part header of the current tile */
1739         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
1740                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
1741                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
1742
1743         /* Make sure room is sufficient */
1744         if (p_header_size < 5) {
1745                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COD marker\n");
1746                 return OPJ_FALSE;
1747         }
1748
1749         opj_read_bytes(p_header_data,&l_tcp->csty,1);           /* Scod */
1750         ++p_header_data;
1751         opj_read_bytes(p_header_data,&l_tmp,1);                         /* SGcod (A) */
1752         ++p_header_data;
1753         l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
1754         opj_read_bytes(p_header_data,&l_tcp->numlayers,2);      /* SGcod (B) */
1755         p_header_data+=2;
1756
1757         // If user didn't set a number layer to decode take the max specify in the codestream.
1758         if      (l_cp->m_specific_param.m_dec.m_layer) {
1759                 l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
1760         }
1761         else {
1762                 l_tcp->num_layers_to_decode = l_tcp->numlayers;
1763         }
1764
1765         opj_read_bytes(p_header_data,&l_tcp->mct,1);            /* SGcod (C) */
1766         ++p_header_data;
1767
1768         p_header_size -= 5;
1769         for     (i = 0; i < l_image->numcomps; ++i) {
1770                 l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
1771         }
1772
1773         if (! j2k_read_SPCod_SPCoc(p_j2k,0,p_header_data,&p_header_size,p_manager)) {
1774                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COD marker\n");
1775                 return OPJ_FALSE;
1776         }
1777
1778         if (p_header_size != 0) {
1779                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COD marker\n");
1780                 return OPJ_FALSE;
1781         }
1782
1783         /* Apply the coding style to other components of the current tile or the m_default_tcp*/
1784         j2k_copy_tile_component_parameters(p_j2k);
1785
1786         /* Index */
1787 #ifdef WIP_REMOVE_MSD
1788         if (p_j2k->cstr_info) {
1789                 //opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;
1790                 p_j2k->cstr_info->prog = l_tcp->prg;
1791                 p_j2k->cstr_info->numlayers = l_tcp->numlayers;
1792                 p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(l_image->numcomps * sizeof(OPJ_UINT32));
1793                 for     (i = 0; i < l_image->numcomps; ++i) {
1794                         p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
1795                 }
1796         }
1797 #endif
1798
1799         return OPJ_TRUE;
1800 }
1801
1802 static void j2k_write_coc(opj_j2k_t *j2k, int compno) {
1803         int lenp, len;
1804
1805         opj_cp_t *cp = j2k->cp;
1806         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
1807         opj_image_t *image = j2k->image;
1808         opj_cio_t *cio = j2k->cio;
1809         
1810         cio_write(cio, J2K_MS_COC, 2);  /* COC */
1811         lenp = cio_tell(cio);
1812         cio_skip(cio, 2);
1813         cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
1814         cio_write(cio, tcp->tccps[compno].csty, 1);     /* Scoc */
1815         j2k_write_cox(j2k, compno);
1816         len = cio_tell(cio) - lenp;
1817         cio_seek(cio, lenp);
1818         cio_write(cio, len, 2);                 /* Lcoc */
1819         cio_seek(cio, lenp + len);
1820 }
1821
1822 static void j2k_read_coc(opj_j2k_t *j2k) {
1823         int len, compno;
1824
1825         opj_cp_t *cp = j2k->cp;
1826         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
1827         opj_image_t *image = j2k->image;
1828         opj_cio_t *cio = j2k->cio;
1829         
1830         len = cio_read(cio, 2);         /* Lcoc */
1831         compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2); /* Ccoc */
1832         tcp->tccps[compno].csty = cio_read(cio, 1);     /* Scoc */
1833         j2k_read_cox(j2k, compno);
1834 }
1835
1836 /**
1837  * Reads a COC marker (Coding Style Component)
1838  * @param       p_header_data   the data contained in the COC box.
1839  * @param       p_j2k                   the jpeg2000 codec.
1840  * @param       p_header_size   the size of the data contained in the COC marker.
1841  * @param       p_manager               the user event manager.
1842 */
1843 opj_bool j2k_read_coc_v2 (
1844                                         opj_j2k_v2_t *p_j2k,
1845                                         OPJ_BYTE * p_header_data,
1846                                         OPJ_UINT32 p_header_size,
1847                                         struct opj_event_mgr * p_manager
1848                                         )
1849 {
1850         opj_cp_v2_t *l_cp = NULL;
1851         opj_tcp_v2_t *l_tcp = NULL;
1852         opj_image_t *l_image = NULL;
1853         OPJ_UINT32 l_comp_room;
1854         OPJ_UINT32 l_comp_no;
1855
1856         // preconditions
1857         assert(p_header_data != 00);
1858         assert(p_j2k != 00);
1859         assert(p_manager != 00);
1860
1861         l_cp = &(p_j2k->m_cp);
1862         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ) ? /*FIXME J2K_DEC_STATE_TPH*/
1863                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
1864                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
1865         l_image = p_j2k->m_image;
1866
1867         l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
1868
1869         // make sure room is sufficient
1870         if (p_header_size < l_comp_room + 1) {
1871                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COC marker\n");
1872                 return OPJ_FALSE;
1873         }
1874         p_header_size -= l_comp_room + 1;
1875
1876         opj_read_bytes(p_header_data,&l_comp_no,l_comp_room);                   /* Ccoc */
1877         p_header_data += l_comp_room;
1878         if (l_comp_no >= l_image->numcomps) {
1879                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COC marker (bad number of components)\n");
1880                 return OPJ_FALSE;
1881         }
1882
1883         opj_read_bytes(p_header_data,&l_tcp->tccps[l_comp_no].csty,1);                  /* Scoc */
1884         ++p_header_data ;
1885
1886         if (! j2k_read_SPCod_SPCoc(p_j2k,l_comp_no,p_header_data,&p_header_size,p_manager)) {
1887                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COC marker\n");
1888                 return OPJ_FALSE;
1889         }
1890
1891         if (p_header_size != 0) {
1892                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading COC marker\n");
1893                 return OPJ_FALSE;
1894         }
1895         return OPJ_TRUE;
1896 }
1897
1898 static void j2k_write_qcx(opj_j2k_t *j2k, int compno) {
1899         int bandno, numbands;
1900         int expn, mant;
1901         
1902         opj_cp_t *cp = j2k->cp;
1903         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
1904         opj_tccp_t *tccp = &tcp->tccps[compno];
1905         opj_cio_t *cio = j2k->cio;
1906         
1907         cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);        /* Sqcx */
1908         numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
1909         
1910         for (bandno = 0; bandno < numbands; bandno++) {
1911                 expn = tccp->stepsizes[bandno].expn;
1912                 mant = tccp->stepsizes[bandno].mant;
1913                 
1914                 if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
1915                         cio_write(cio, expn << 3, 1);   /* SPqcx_i */
1916                 } else {
1917                         cio_write(cio, (expn << 11) + mant, 2); /* SPqcx_i */
1918                 }
1919         }
1920 }
1921
1922 static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
1923         int tmp;
1924         int bandno, numbands;
1925
1926         opj_cp_t *cp = j2k->cp;
1927         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
1928         opj_tccp_t *tccp = &tcp->tccps[compno];
1929         opj_cio_t *cio = j2k->cio;
1930
1931         tmp = cio_read(cio, 1);         /* Sqcx */
1932         tccp->qntsty = tmp & 0x1f;
1933         tccp->numgbits = tmp >> 5;
1934         numbands = (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 
1935                 1 : ((tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);
1936
1937 #ifdef USE_JPWL
1938         if (j2k->cp->correct) {
1939
1940                 /* if JPWL is on, we check whether there are too many subbands */
1941                 if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
1942                         opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
1943                                 "JPWL: bad number of subbands in Sqcx (%d)\n",
1944                                 numbands);
1945                         if (!JPWL_ASSUME) {
1946                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
1947                                 return;
1948                         }
1949                         /* we try to correct */
1950                         numbands = 1;
1951                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"
1952                                 "- setting number of bands to %d => HYPOTHESIS!!!\n",
1953                                 numbands);
1954                 };
1955
1956         };
1957
1958 #else
1959         /* We check whether there are too many subbands */
1960         if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
1961                 opj_event_msg(j2k->cinfo, EVT_WARNING ,
1962                                         "bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n"
1963                                     "- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS);
1964         }
1965
1966 #endif /* USE_JPWL */
1967
1968         for (bandno = 0; bandno < numbands; bandno++) {
1969                 int expn, mant;
1970                 if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
1971                         expn = cio_read(cio, 1) >> 3;   /* SPqcx_i */
1972                         mant = 0;
1973                 } else {
1974                         tmp = cio_read(cio, 2); /* SPqcx_i */
1975                         expn = tmp >> 11;
1976                         mant = tmp & 0x7ff;
1977                 }
1978                 if (bandno < J2K_MAXBANDS){
1979                         tccp->stepsizes[bandno].expn = expn;
1980                         tccp->stepsizes[bandno].mant = mant;
1981                 }
1982         }
1983         
1984         /* Add Antonin : if scalar_derived -> compute other stepsizes */
1985         if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
1986                 for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
1987                         tccp->stepsizes[bandno].expn = 
1988                                 ((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? 
1989                                         (tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0;
1990                         tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;
1991                 }
1992         }
1993         /* ddA */
1994 }
1995
1996 static void j2k_write_qcd(opj_j2k_t *j2k) {
1997         int lenp, len;
1998
1999         opj_cio_t *cio = j2k->cio;
2000         
2001         cio_write(cio, J2K_MS_QCD, 2);  /* QCD */
2002         lenp = cio_tell(cio);
2003         cio_skip(cio, 2);
2004         j2k_write_qcx(j2k, 0);
2005         len = cio_tell(cio) - lenp;
2006         cio_seek(cio, lenp);
2007         cio_write(cio, len, 2);                 /* Lqcd */
2008         cio_seek(cio, lenp + len);
2009
2010         if(j2k->cstr_info)
2011           j2k_add_mhmarker(j2k->cstr_info, J2K_MS_QCD, lenp, len);
2012 }
2013
2014 static void j2k_read_qcd(opj_j2k_t *j2k) {
2015         int len, i, pos;
2016
2017         opj_cio_t *cio = j2k->cio;
2018         opj_image_t *image = j2k->image;
2019         
2020         len = cio_read(cio, 2);         /* Lqcd */
2021         pos = cio_tell(cio);
2022         for (i = 0; i < image->numcomps; i++) {
2023                 cio_seek(cio, pos);
2024                 j2k_read_qcx(j2k, i, len - 2);
2025         }
2026 }
2027
2028 /**
2029  * Reads a QCD marker (Quantization defaults)
2030  * @param       p_header_data   the data contained in the QCD box.
2031  * @param       p_j2k                   the jpeg2000 codec.
2032  * @param       p_header_size   the size of the data contained in the QCD marker.
2033  * @param       p_manager               the user event manager.
2034 */
2035 opj_bool j2k_read_qcd_v2 (
2036                                     opj_j2k_v2_t *p_j2k,
2037                                         OPJ_BYTE * p_header_data,
2038                                         OPJ_UINT32 p_header_size,
2039                                         struct opj_event_mgr * p_manager
2040                                         )
2041 {
2042         /* preconditions */
2043         assert(p_header_data != 00);
2044         assert(p_j2k != 00);
2045         assert(p_manager != 00);
2046
2047         if (! j2k_read_SQcd_SQcc(p_j2k,0,p_header_data,&p_header_size,p_manager)) {
2048                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCD marker\n");
2049                 return OPJ_FALSE;
2050         }
2051
2052         if (p_header_size != 0) {
2053                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCD marker\n");
2054                 return OPJ_FALSE;
2055         }
2056
2057         /* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
2058         j2k_copy_tile_quantization_parameters(p_j2k);
2059
2060         return OPJ_TRUE;
2061 }
2062
2063 static void j2k_write_qcc(opj_j2k_t *j2k, int compno) {
2064         int lenp, len;
2065
2066         opj_cio_t *cio = j2k->cio;
2067         
2068         cio_write(cio, J2K_MS_QCC, 2);  /* QCC */
2069         lenp = cio_tell(cio);
2070         cio_skip(cio, 2);
2071         cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2);    /* Cqcc */
2072         j2k_write_qcx(j2k, compno);
2073         len = cio_tell(cio) - lenp;
2074         cio_seek(cio, lenp);
2075         cio_write(cio, len, 2);                 /* Lqcc */
2076         cio_seek(cio, lenp + len);
2077 }
2078
2079 static void j2k_read_qcc(opj_j2k_t *j2k) {
2080         int len, compno;
2081         int numcomp = j2k->image->numcomps;
2082         opj_cio_t *cio = j2k->cio;
2083
2084         len = cio_read(cio, 2); /* Lqcc */
2085         compno = cio_read(cio, numcomp <= 256 ? 1 : 2); /* Cqcc */
2086
2087 #ifdef USE_JPWL
2088         if (j2k->cp->correct) {
2089
2090                 static int backup_compno = 0;
2091
2092                 /* compno is negative or larger than the number of components!!! */
2093                 if ((compno < 0) || (compno >= numcomp)) {
2094                         opj_event_msg(j2k->cinfo, EVT_ERROR,
2095                                 "JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
2096                                 compno, numcomp);
2097                         if (!JPWL_ASSUME) {
2098                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
2099                                 return;
2100                         }
2101                         /* we try to correct */
2102                         compno = backup_compno % numcomp;
2103                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
2104                                 "- setting component number to %d\n",
2105                                 compno);
2106                 }
2107
2108                 /* keep your private count of tiles */
2109                 backup_compno++;
2110         };
2111 #endif /* USE_JPWL */
2112
2113         j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
2114 }
2115
2116 /**
2117  * Reads a QCC marker (Quantization component)
2118  * @param       p_header_data   the data contained in the QCC box.
2119  * @param       p_j2k                   the jpeg2000 codec.
2120  * @param       p_header_size   the size of the data contained in the QCC marker.
2121  * @param       p_manager               the user event manager.
2122 */
2123 opj_bool j2k_read_qcc_v2(       opj_j2k_v2_t *p_j2k,
2124                                                         OPJ_BYTE * p_header_data,
2125                                                         OPJ_UINT32 p_header_size,
2126                                                         struct opj_event_mgr * p_manager)
2127 {
2128         OPJ_UINT32 l_num_comp,l_comp_no;
2129
2130         /* preconditions */
2131         assert(p_header_data != 00);
2132         assert(p_j2k != 00);
2133         assert(p_manager != 00);
2134
2135         l_num_comp = p_j2k->m_image->numcomps;
2136
2137         if (l_num_comp <= 256) {
2138                 if (p_header_size < 1) {
2139                         opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCC marker\n");
2140                         return OPJ_FALSE;
2141                 }
2142                 opj_read_bytes(p_header_data,&l_comp_no,1);
2143                 ++p_header_data;
2144                 --p_header_size;
2145         }
2146         else {
2147                 if (p_header_size < 2) {
2148                         opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCC marker\n");
2149                         return OPJ_FALSE;
2150                 }
2151                 opj_read_bytes(p_header_data,&l_comp_no,2);
2152                 p_header_data+=2;
2153                 p_header_size-=2;
2154         }
2155
2156 #ifdef USE_JPWL
2157         if (p_j2k->m_cp.correct) {
2158
2159                 static OPJ_UINT32 backup_compno = 0;
2160
2161                 /* compno is negative or larger than the number of components!!! */
2162                 if ((l_comp_no < 0) || (l_comp_no >= l_num_comp)) {
2163                         opj_event_msg_v2(p_manager, EVT_ERROR,
2164                                 "JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
2165                                 l_comp_no, l_num_comp);
2166                         if (!JPWL_ASSUME) {
2167                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
2168                                 return OPJ_FALSE;
2169                         }
2170                         /* we try to correct */
2171                         l_comp_no = backup_compno % l_num_comp;
2172                         opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust this\n"
2173                                 "- setting component number to %d\n",
2174                                 l_comp_no);
2175                 }
2176
2177                 /* keep your private count of tiles */
2178                 backup_compno++;
2179         };
2180 #endif /* USE_JPWL */
2181
2182         if (! j2k_read_SQcd_SQcc(p_j2k,l_comp_no,p_header_data,&p_header_size,p_manager)) {
2183                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCC marker\n");
2184                 return OPJ_FALSE;
2185         }
2186
2187         if (p_header_size != 0) {
2188                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading QCC marker\n");
2189                 return OPJ_FALSE;
2190         }
2191
2192         return OPJ_TRUE;
2193 }
2194
2195
2196 static void j2k_write_poc(opj_j2k_t *j2k) {
2197         int len, numpchgs, i;
2198
2199         int numcomps = j2k->image->numcomps;
2200         
2201         opj_cp_t *cp = j2k->cp;
2202         opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
2203         opj_tccp_t *tccp = &tcp->tccps[0];
2204         opj_cio_t *cio = j2k->cio;
2205
2206         numpchgs = 1 + tcp->numpocs;
2207         cio_write(cio, J2K_MS_POC, 2);  /* POC  */
2208         len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;
2209         cio_write(cio, len, 2);         /* Lpoc */
2210         for (i = 0; i < numpchgs; i++) {
2211                 opj_poc_t *poc = &tcp->pocs[i];
2212                 cio_write(cio, poc->resno0, 1); /* RSpoc_i */
2213                 cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));        /* CSpoc_i */
2214                 cio_write(cio, poc->layno1, 2); /* LYEpoc_i */
2215                 poc->layno1 = int_min(poc->layno1, tcp->numlayers);
2216                 cio_write(cio, poc->resno1, 1); /* REpoc_i */
2217                 poc->resno1 = int_min(poc->resno1, tccp->numresolutions);
2218                 cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));        /* CEpoc_i */
2219                 poc->compno1 = int_min(poc->compno1, numcomps);
2220                 cio_write(cio, poc->prg, 1);    /* Ppoc_i */
2221         }
2222 }
2223
2224 static void j2k_read_poc(opj_j2k_t *j2k) {
2225         int len, numpchgs, i, old_poc;
2226
2227         int numcomps = j2k->image->numcomps;
2228         
2229         opj_cp_t *cp = j2k->cp;
2230         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
2231         opj_cio_t *cio = j2k->cio;
2232         
2233         old_poc = tcp->POC ? tcp->numpocs + 1 : 0;
2234         tcp->POC = 1;
2235         len = cio_read(cio, 2);         /* Lpoc */
2236         numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
2237         
2238         for (i = old_poc; i < numpchgs + old_poc; i++) {
2239                 opj_poc_t *poc;
2240                 poc = &tcp->pocs[i];
2241                 poc->resno0 = cio_read(cio, 1); /* RSpoc_i */
2242                 poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);  /* CSpoc_i */
2243                 poc->layno1 = cio_read(cio, 2);    /* LYEpoc_i */
2244                 poc->resno1 = cio_read(cio, 1);    /* REpoc_i */
2245                 poc->compno1 = int_min(
2246                         cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);       /* CEpoc_i */
2247                 poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);    /* Ppoc_i */
2248         }
2249         
2250         tcp->numpocs = numpchgs + old_poc - 1;
2251 }
2252
2253 /**
2254  * Reads a POC marker (Progression Order Change)
2255  *
2256  * @param       p_header_data   the data contained in the POC box.
2257  * @param       p_j2k                   the jpeg2000 codec.
2258  * @param       p_header_size   the size of the data contained in the POC marker.
2259  * @param       p_manager               the user event manager.
2260 */
2261 opj_bool j2k_read_poc_v2 (
2262                                                 opj_j2k_v2_t *p_j2k,
2263                                                 OPJ_BYTE * p_header_data,
2264                                                 OPJ_UINT32 p_header_size,
2265                                                 struct opj_event_mgr * p_manager)
2266 {
2267         OPJ_UINT32 i, l_nb_comp, l_tmp;
2268         opj_image_t * l_image = 00;
2269         OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
2270         OPJ_UINT32 l_chunk_size, l_comp_room;
2271
2272         opj_cp_v2_t *l_cp = 00;
2273         opj_tcp_v2_t *l_tcp = 00;
2274         opj_poc_t *l_current_poc = 00;
2275
2276         /* preconditions */
2277         assert(p_header_data != 00);
2278         assert(p_j2k != 00);
2279         assert(p_manager != 00);
2280
2281         l_image = p_j2k->m_image;
2282         l_nb_comp = l_image->numcomps;
2283         if (l_nb_comp <= 256) {
2284                 l_comp_room = 1;
2285         }
2286         else {
2287                 l_comp_room = 2;
2288         }
2289         l_chunk_size = 5 + 2 * l_comp_room;
2290         l_current_poc_nb = p_header_size / l_chunk_size;
2291         l_current_poc_remaining = p_header_size % l_chunk_size;
2292
2293         if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
2294                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading POC marker\n");
2295                 return OPJ_FALSE;
2296         }
2297
2298         l_cp = &(p_j2k->m_cp);
2299         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
2300                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
2301                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
2302         l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
2303         l_current_poc_nb += l_old_poc_nb;
2304
2305         assert(l_current_poc_nb < 32);
2306
2307         /* now poc is in use.*/
2308         l_tcp->POC = 1;
2309
2310         l_current_poc = &l_tcp->pocs[l_old_poc_nb];
2311         for     (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
2312                 opj_read_bytes(p_header_data,&(l_current_poc->resno0),1);                               /* RSpoc_i */
2313                 ++p_header_data;
2314                 opj_read_bytes(p_header_data,&(l_current_poc->compno0),l_comp_room);    /* CSpoc_i */
2315                 p_header_data+=l_comp_room;
2316                 opj_read_bytes(p_header_data,&(l_current_poc->layno1),2);                               /* LYEpoc_i */
2317                 p_header_data+=2;
2318                 opj_read_bytes(p_header_data,&(l_current_poc->resno1),1);                               /* REpoc_i */
2319                 ++p_header_data;
2320                 opj_read_bytes(p_header_data,&(l_current_poc->compno1),l_comp_room);    /* CEpoc_i */
2321                 p_header_data+=l_comp_room;
2322                 opj_read_bytes(p_header_data,&l_tmp,1);                                                                 /* Ppoc_i */
2323                 ++p_header_data;
2324                 l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
2325                 /* make sure comp is in acceptable bounds */
2326                 l_current_poc->compno1 = uint_min(l_current_poc->compno1, l_nb_comp);
2327                 ++l_current_poc;
2328         }
2329
2330         l_tcp->numpocs = l_current_poc_nb - 1;
2331         return OPJ_TRUE;
2332 }
2333
2334 static void j2k_read_crg(opj_j2k_t *j2k) {
2335         int len, i, Xcrg_i, Ycrg_i;
2336         
2337         opj_cio_t *cio = j2k->cio;
2338         int numcomps = j2k->image->numcomps;
2339         
2340         len = cio_read(cio, 2);                 /* Lcrg */
2341         for (i = 0; i < numcomps; i++) {
2342                 Xcrg_i = cio_read(cio, 2);      /* Xcrg_i */
2343                 Ycrg_i = cio_read(cio, 2);      /* Ycrg_i */
2344         }
2345 }
2346
2347 /**
2348  * Reads a CRG marker (Component registration)
2349  *
2350  * @param       p_header_data   the data contained in the TLM box.
2351  * @param       p_j2k                   the jpeg2000 codec.
2352  * @param       p_header_size   the size of the data contained in the TLM marker.
2353  * @param       p_manager               the user event manager.
2354 */
2355 opj_bool j2k_read_crg_v2 (
2356                                                 opj_j2k_v2_t *p_j2k,
2357                                                 OPJ_BYTE * p_header_data,
2358                                                 OPJ_UINT32 p_header_size,
2359                                                 struct opj_event_mgr * p_manager
2360                                         )
2361 {
2362         OPJ_UINT32 l_nb_comp;
2363         // preconditions
2364         assert(p_header_data != 00);
2365         assert(p_j2k != 00);
2366         assert(p_manager != 00);
2367
2368         l_nb_comp = p_j2k->m_image->numcomps;
2369
2370         if (p_header_size != l_nb_comp *4) {
2371                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading CRG marker\n");
2372                 return OPJ_FALSE;
2373         }
2374         /* Do not care of this at the moment since only local variables are set here */
2375         /*
2376         for
2377                 (i = 0; i < l_nb_comp; ++i)
2378         {
2379                 opj_read_bytes(p_header_data,&l_Xcrg_i,2);                              // Xcrg_i
2380                 p_header_data+=2;
2381                 opj_read_bytes(p_header_data,&l_Ycrg_i,2);                              // Xcrg_i
2382                 p_header_data+=2;
2383         }
2384         */
2385         return OPJ_TRUE;
2386 }
2387
2388 static void j2k_read_tlm(opj_j2k_t *j2k) {
2389         int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
2390         long int Ttlm_i, Ptlm_i;
2391
2392         opj_cio_t *cio = j2k->cio;
2393         
2394         len = cio_read(cio, 2);         /* Ltlm */
2395         Ztlm = cio_read(cio, 1);        /* Ztlm */
2396         Stlm = cio_read(cio, 1);        /* Stlm */
2397         ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
2398         SP = (Stlm >> 6) & 0x01;
2399         tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
2400         for (i = 0; i < tile_tlm; i++) {
2401                 Ttlm_i = cio_read(cio, ST);     /* Ttlm_i */
2402                 Ptlm_i = cio_read(cio, SP ? 4 : 2);     /* Ptlm_i */
2403         }
2404 }
2405
2406 /**
2407  * Reads a TLM marker (Tile Length Marker)
2408  *
2409  * @param       p_header_data   the data contained in the TLM box.
2410  * @param       p_j2k                   the jpeg2000 codec.
2411  * @param       p_header_size   the size of the data contained in the TLM marker.
2412  * @param       p_manager               the user event manager.
2413 */
2414 opj_bool j2k_read_tlm_v2 (
2415                                                 opj_j2k_v2_t *p_j2k,
2416                                                 OPJ_BYTE * p_header_data,
2417                                                 OPJ_UINT32 p_header_size,
2418                                                 struct opj_event_mgr * p_manager
2419                                         )
2420 {
2421         OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp, l_tot_num_tp_remaining, l_quotient, l_Ptlm_size;
2422         // preconditions
2423         assert(p_header_data != 00);
2424         assert(p_j2k != 00);
2425         assert(p_manager != 00);
2426
2427         if (p_header_size < 2) {
2428                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading TLM marker\n");
2429                 return OPJ_FALSE;
2430         }
2431         p_header_size -= 2;
2432
2433         opj_read_bytes(p_header_data,&l_Ztlm,1);                                /* Ztlm */
2434         ++p_header_data;
2435         opj_read_bytes(p_header_data,&l_Stlm,1);                                /* Stlm */
2436         ++p_header_data;
2437
2438         l_ST = ((l_Stlm >> 4) & 0x3);
2439         l_SP = (l_Stlm >> 6) & 0x1;
2440
2441         l_Ptlm_size = (l_SP + 1) * 2;
2442         l_quotient = l_Ptlm_size + l_ST;
2443
2444         l_tot_num_tp = p_header_size / l_quotient;
2445         l_tot_num_tp_remaining = p_header_size % l_quotient;
2446
2447         if (l_tot_num_tp_remaining != 0) {
2448                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading TLM marker\n");
2449                 return OPJ_FALSE;
2450         }
2451         /* FIXME Do not care of this at the moment since only local variables are set here */
2452         /*
2453         for
2454                 (i = 0; i < l_tot_num_tp; ++i)
2455         {
2456                 opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST);                           // Ttlm_i
2457                 p_header_data += l_ST;
2458                 opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size);            // Ptlm_i
2459                 p_header_data += l_Ptlm_size;
2460         }*/
2461         return OPJ_TRUE;
2462 }
2463
2464 static void j2k_read_plm(opj_j2k_t *j2k) {
2465         int len, i, Zplm, Nplm, add, packet_len = 0;
2466         
2467         opj_cio_t *cio = j2k->cio;
2468
2469         len = cio_read(cio, 2);         /* Lplm */
2470         Zplm = cio_read(cio, 1);        /* Zplm */
2471         len -= 3;
2472         while (len > 0) {
2473                 Nplm = cio_read(cio, 4);                /* Nplm */
2474                 len -= 4;
2475                 for (i = Nplm; i > 0; i--) {
2476                         add = cio_read(cio, 1);
2477                         len--;
2478                         packet_len = (packet_len << 7) + add;   /* Iplm_ij */
2479                         if ((add & 0x80) == 0) {
2480                                 /* New packet */
2481                                 packet_len = 0;
2482                         }
2483                         if (len <= 0)
2484                                 break;
2485                 }
2486         }
2487 }
2488
2489 /**
2490  * Reads a PLM marker (Packet length, main header marker)
2491  *
2492  * @param       p_header_data   the data contained in the TLM box.
2493  * @param       p_j2k                   the jpeg2000 codec.
2494  * @param       p_header_size   the size of the data contained in the TLM marker.
2495  * @param       p_manager               the user event manager.
2496 */
2497 opj_bool j2k_read_plm_v2 (
2498                                                 opj_j2k_v2_t *p_j2k,
2499                                                 OPJ_BYTE * p_header_data,
2500                                                 OPJ_UINT32 p_header_size,
2501                                                 struct opj_event_mgr * p_manager
2502                                         )
2503 {
2504         // preconditions
2505         assert(p_header_data != 00);
2506         assert(p_j2k != 00);
2507         assert(p_manager != 00);
2508
2509         if (p_header_size < 1) {
2510                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PLM marker\n");
2511                 return OPJ_FALSE;
2512         }
2513         /* Do not care of this at the moment since only local variables are set here */
2514         /*
2515         opj_read_bytes(p_header_data,&l_Zplm,1);                                        // Zplm
2516         ++p_header_data;
2517         --p_header_size;
2518
2519         while
2520                 (p_header_size > 0)
2521         {
2522                 opj_read_bytes(p_header_data,&l_Nplm,1);                                // Nplm
2523                 ++p_header_data;
2524                 p_header_size -= (1+l_Nplm);
2525                 if
2526                         (p_header_size < 0)
2527                 {
2528                         opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
2529                         return false;
2530                 }
2531                 for
2532                         (i = 0; i < l_Nplm; ++i)
2533                 {
2534                         opj_read_bytes(p_header_data,&l_tmp,1);                         // Iplm_ij
2535                         ++p_header_data;
2536                         // take only the last seven bytes
2537                         l_packet_len |= (l_tmp & 0x7f);
2538                         if
2539                                 (l_tmp & 0x80)
2540                         {
2541                                 l_packet_len <<= 7;
2542                         }
2543                         else
2544                         {
2545                 // store packet length and proceed to next packet
2546                                 l_packet_len = 0;
2547                         }
2548                 }
2549                 if
2550                         (l_packet_len != 0)
2551                 {
2552                         opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
2553                         return false;
2554                 }
2555         }
2556         */
2557         return OPJ_TRUE;
2558 }
2559
2560 static void j2k_read_plt(opj_j2k_t *j2k) {
2561         int len, i, Zplt, packet_len = 0, add;
2562         
2563         opj_cio_t *cio = j2k->cio;
2564         
2565         len = cio_read(cio, 2);         /* Lplt */
2566         Zplt = cio_read(cio, 1);        /* Zplt */
2567         for (i = len - 3; i > 0; i--) {
2568                 add = cio_read(cio, 1);
2569                 packet_len = (packet_len << 7) + add;   /* Iplt_i */
2570                 if ((add & 0x80) == 0) {
2571                         /* New packet */
2572                         packet_len = 0;
2573                 }
2574         }
2575 }
2576
2577 /**
2578  * Reads a PLT marker (Packet length, tile-part header)
2579  *
2580  * @param       p_header_data   the data contained in the PLT box.
2581  * @param       p_j2k                   the jpeg2000 codec.
2582  * @param       p_header_size   the size of the data contained in the PLT marker.
2583  * @param       p_manager               the user event manager.
2584 */
2585 opj_bool j2k_read_plt_v2 (
2586                                                 opj_j2k_v2_t *p_j2k,
2587                                                 OPJ_BYTE * p_header_data,
2588                                                 OPJ_UINT32 p_header_size,
2589                                                 struct opj_event_mgr * p_manager
2590                                         )
2591 {
2592         OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
2593
2594         // preconditions
2595         assert(p_header_data != 00);
2596         assert(p_j2k != 00);
2597         assert(p_manager != 00);
2598
2599         if (p_header_size < 1) {
2600                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PLM marker\n");
2601                 return OPJ_FALSE;
2602         }
2603
2604         opj_read_bytes(p_header_data,&l_Zplt,1);                /* Zplt */
2605         ++p_header_data;
2606         --p_header_size;
2607
2608         for (i = 0; i < p_header_size; ++i) {
2609                 opj_read_bytes(p_header_data,&l_tmp,1);         /* Iplt_ij */
2610                 ++p_header_data;
2611                 // take only the last seven bytes
2612                 l_packet_len |= (l_tmp & 0x7f);
2613                 if (l_tmp & 0x80) {
2614                         l_packet_len <<= 7;
2615                 }
2616                 else {
2617             // store packet length and proceed to next packet
2618                         l_packet_len = 0;
2619                 }
2620         }
2621
2622         if (l_packet_len != 0) {
2623                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PLM marker\n");
2624                 return OPJ_FALSE;
2625         }
2626
2627         return OPJ_TRUE;
2628 }
2629
2630 static void j2k_read_ppm(opj_j2k_t *j2k) {
2631         int len, Z_ppm, i, j;
2632         int N_ppm;
2633
2634         opj_cp_t *cp = j2k->cp;
2635         opj_cio_t *cio = j2k->cio;
2636         
2637         len = cio_read(cio, 2);
2638         cp->ppm = 1;
2639         
2640         Z_ppm = cio_read(cio, 1);       /* Z_ppm */
2641         len -= 3;
2642         while (len > 0) {
2643                 if (cp->ppm_previous == 0) {
2644                         N_ppm = cio_read(cio, 4);       /* N_ppm */
2645                         len -= 4;
2646                 } else {
2647                         N_ppm = cp->ppm_previous;
2648                 }
2649                 j = cp->ppm_store;
2650                 if (Z_ppm == 0) {       /* First PPM marker */
2651                         cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));
2652                         cp->ppm_data_first = cp->ppm_data;
2653                         cp->ppm_len = N_ppm;
2654                 } else {                        /* NON-first PPM marker */
2655                         cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +     cp->ppm_store) * sizeof(unsigned char));
2656
2657 #ifdef USE_JPWL
2658                         /* this memory allocation check could be done even in non-JPWL cases */
2659                         if (cp->correct) {
2660                                 if (!cp->ppm_data) {
2661                                         opj_event_msg(j2k->cinfo, EVT_ERROR,
2662                                                 "JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n",
2663                                                 cio_tell(cio));
2664                                         if (!JPWL_ASSUME || JPWL_ASSUME) {
2665                                                 opj_free(cp->ppm_data);
2666                                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
2667                                                 return;
2668                                         }
2669                                 }
2670                         }
2671 #endif
2672
2673                         cp->ppm_data_first = cp->ppm_data;
2674                         cp->ppm_len = N_ppm + cp->ppm_store;
2675                 }
2676                 for (i = N_ppm; i > 0; i--) {   /* Read packet header */
2677                         cp->ppm_data[j] = cio_read(cio, 1);
2678                         j++;
2679                         len--;
2680                         if (len == 0)
2681                                 break;                  /* Case of non-finished packet header in present marker but finished in next one */
2682                 }
2683                 cp->ppm_previous = i - 1;
2684                 cp->ppm_store = j;
2685         }
2686 }
2687 /**
2688  * Reads a PPM marker (Packed packet headers, main header)
2689  *
2690  * @param       p_header_data   the data contained in the POC box.
2691  * @param       p_j2k                   the jpeg2000 codec.
2692  * @param       p_header_size   the size of the data contained in the POC marker.
2693  * @param       p_manager               the user event manager.
2694 */
2695 opj_bool j2k_read_ppm_v2 (
2696                                                 opj_j2k_v2_t *p_j2k,
2697                                                 OPJ_BYTE * p_header_data,
2698                                                 OPJ_UINT32 p_header_size,
2699                                                 struct opj_event_mgr * p_manager
2700                                         )
2701 {
2702
2703         opj_cp_v2_t *l_cp = 00;
2704         OPJ_UINT32 l_remaining_data, l_Z_ppm, l_N_ppm;
2705
2706         // preconditions
2707         assert(p_header_data != 00);
2708         assert(p_j2k != 00);
2709         assert(p_manager != 00);
2710
2711         if (p_header_size < 1) {
2712                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPM marker\n");
2713                 return OPJ_FALSE;
2714         }
2715
2716         l_cp = &(p_j2k->m_cp);
2717         l_cp->ppm = 1;
2718
2719         opj_read_bytes(p_header_data,&l_Z_ppm,1);               /* Z_ppm */
2720         ++p_header_data;
2721         --p_header_size;
2722
2723         // First PPM marker
2724         if (l_Z_ppm == 0) {
2725                 if (p_header_size < 4) {
2726                         opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPM marker\n");
2727                         return OPJ_FALSE;
2728                 }
2729
2730                 opj_read_bytes(p_header_data,&l_N_ppm,4);               /* N_ppm */
2731                 p_header_data+=4;
2732                 p_header_size-=4;
2733
2734                 /* First PPM marker: Initialization */
2735                 l_cp->ppm_len = l_N_ppm;
2736                 l_cp->ppm_data_size = 0;
2737
2738                 l_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_cp->ppm_len);
2739                 if (l_cp->ppm_buffer == 00) {
2740                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading ppm marker\n");
2741                         return OPJ_FALSE;
2742                 }
2743                 memset(l_cp->ppm_buffer,0,l_cp->ppm_len);
2744
2745                 l_cp->ppm_data = l_cp->ppm_buffer;
2746         }
2747
2748         while (1) {
2749                 if (l_cp->ppm_data_size == l_cp->ppm_len) {
2750                         if (p_header_size >= 4) {
2751                                 // read a N_ppm
2752                                 opj_read_bytes(p_header_data,&l_N_ppm,4);               /* N_ppm */
2753                                 p_header_data+=4;
2754                                 p_header_size-=4;
2755                                 l_cp->ppm_len += l_N_ppm ;
2756
2757                                 l_cp->ppm_buffer = (OPJ_BYTE *) opj_realloc(l_cp->ppm_buffer, l_cp->ppm_len);
2758                                 if (l_cp->ppm_buffer == 00) {
2759                                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading ppm marker\n");
2760                                         return OPJ_FALSE;
2761                                 }
2762                                 memset(l_cp->ppm_buffer+l_cp->ppm_data_size,0,l_N_ppm);
2763
2764                                 l_cp->ppm_data = l_cp->ppm_buffer;
2765                         }
2766                         else {
2767                                 return OPJ_FALSE;
2768                         }
2769                 }
2770
2771                 l_remaining_data = l_cp->ppm_len - l_cp->ppm_data_size;
2772
2773                 if (l_remaining_data <= p_header_size) {
2774                         /* we must store less information than available in the packet */
2775                         memcpy(l_cp->ppm_buffer + l_cp->ppm_data_size , p_header_data , l_remaining_data);
2776                         l_cp->ppm_data_size = l_cp->ppm_len;
2777                         p_header_size -= l_remaining_data;
2778                         p_header_data += l_remaining_data;
2779                 }
2780                 else {
2781                         memcpy(l_cp->ppm_buffer + l_cp->ppm_data_size , p_header_data , p_header_size);
2782                         l_cp->ppm_data_size += p_header_size;
2783                         p_header_data += p_header_size;
2784                         p_header_size = 0;
2785                         break;
2786                 }
2787         }
2788
2789         return OPJ_TRUE;
2790 }
2791
2792
2793
2794 /**
2795  * Reads a PPM marker (Packed packet headers, main header)
2796  *
2797  * @param       p_header_data   the data contained in the POC box.
2798  * @param       p_j2k                   the jpeg2000 codec.
2799  * @param       p_header_size   the size of the data contained in the POC marker.
2800  * @param       p_manager               the user event manager.
2801 */
2802 opj_bool j2k_read_ppm_v3 (
2803                                                 opj_j2k_v2_t *p_j2k,
2804                                                 OPJ_BYTE * p_header_data,
2805                                                 OPJ_UINT32 p_header_size,
2806                                                 struct opj_event_mgr * p_manager
2807                                         )
2808 {
2809         opj_cp_v2_t *l_cp = 00;
2810         OPJ_UINT32 l_remaining_data, l_Z_ppm, l_N_ppm;
2811
2812         // preconditions
2813         assert(p_header_data != 00);
2814         assert(p_j2k != 00);
2815         assert(p_manager != 00);
2816
2817         // Minimum size of PPM marker is equal to the size of Zppm element
2818         if (p_header_size < 1) {
2819                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPM marker\n");
2820                 return OPJ_FALSE;
2821         }
2822
2823         l_cp = &(p_j2k->m_cp);
2824         l_cp->ppm = 1;
2825
2826         opj_read_bytes(p_header_data,&l_Z_ppm,1);               /* Z_ppm */
2827         ++p_header_data;
2828         --p_header_size;
2829
2830         // First PPM marker
2831         if (l_Z_ppm == 0) {
2832                 // We need now at least the Nppm^0 element
2833                 if (p_header_size < 4) {
2834                         opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPM marker\n");
2835                         return OPJ_FALSE;
2836                 }
2837
2838                 opj_read_bytes(p_header_data,&l_N_ppm,4);               /* First N_ppm */
2839                 p_header_data+=4;
2840                 p_header_size-=4;
2841
2842                 /* First PPM marker: Initialization */
2843                 l_cp->ppm_len = l_N_ppm;
2844                 l_cp->ppm_data_read = 0;
2845
2846                 l_cp->ppm_data = (OPJ_BYTE *) opj_malloc(l_cp->ppm_len);
2847                 if (l_cp->ppm_data == 00) {
2848                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading ppm marker\n");
2849                         return OPJ_FALSE;
2850                 }
2851                 memset(l_cp->ppm_data,0,l_cp->ppm_len);
2852
2853                 l_cp->ppm_data_current = l_cp->ppm_data;
2854
2855                 //l_cp->ppm_data = l_cp->ppm_buffer;
2856         }
2857         else {
2858                 if (p_header_size < 4) {
2859                         opj_event_msg_v2(p_manager, EVT_WARNING, "Empty PPM marker\n");
2860                         return OPJ_TRUE;
2861                 }
2862                 else {
2863                         // Uncompleted Ippm series in the previous PPM marker?
2864                         if (l_cp->ppm_data_read < l_cp->ppm_len) {
2865                                 // Get the place where add the remaining Ippm series
2866                                 l_cp->ppm_data_current = &(l_cp->ppm_data[l_cp->ppm_data_read]);
2867                                 l_N_ppm = l_cp->ppm_len - l_cp->ppm_data_read;
2868                         }
2869                         else {
2870                                 opj_read_bytes(p_header_data,&l_N_ppm,4);               /* First N_ppm */
2871                                 p_header_data+=4;
2872                                 p_header_size-=4;
2873
2874                                 // Increase the size of ppm_data to add the new Ippm series
2875                                 l_cp->ppm_data = (OPJ_BYTE *) opj_realloc(l_cp->ppm_data, l_cp->ppm_len + l_N_ppm);
2876
2877                                 // Keep the position of the place where concatenate the new series
2878                                 l_cp->ppm_data_current = &(l_cp->ppm_data[l_cp->ppm_len]);
2879                                 l_cp->ppm_len += l_N_ppm;
2880                         }
2881                 }
2882         }
2883
2884         l_remaining_data = p_header_size;
2885
2886         while (l_remaining_data >= l_N_ppm) {
2887                 // read a complete Ippm series
2888                 memcpy(l_cp->ppm_data_current, p_header_data, l_N_ppm);
2889                 p_header_size -= l_N_ppm;
2890                 p_header_data += l_N_ppm;
2891
2892                 l_cp->ppm_data_read += l_N_ppm; // Increase the number of data read
2893
2894                 if (p_header_size)
2895                 {
2896                         opj_read_bytes(p_header_data,&l_N_ppm,4);               /* N_ppm^i */
2897                         p_header_data+=4;
2898                         p_header_size-=4;
2899                 }
2900                 else {
2901                         l_remaining_data = p_header_size;
2902                         break;
2903                 }
2904
2905                 l_remaining_data = p_header_size;
2906
2907                 // Next Ippm series is a complete series ?
2908                 if (l_remaining_data > l_N_ppm) {
2909                         // Increase the size of ppm_data to add the new Ippm series
2910                         l_cp->ppm_data = (OPJ_BYTE *) opj_realloc(l_cp->ppm_data, l_cp->ppm_len + l_N_ppm);
2911
2912                         // Keep the position of the place where concatenate the new series
2913                         l_cp->ppm_data_current = &(l_cp->ppm_data[l_cp->ppm_len]);
2914                         l_cp->ppm_len += l_N_ppm;
2915                 }
2916
2917         }
2918
2919         // Need to read an incomplete Ippm series
2920         if (l_remaining_data) {
2921                 l_cp->ppm_data = (OPJ_BYTE *) opj_realloc(l_cp->ppm_data, l_cp->ppm_len + l_N_ppm);
2922
2923                 // Keep the position of the place where concatenate the new series
2924                 l_cp->ppm_data_current = &(l_cp->ppm_data[l_cp->ppm_len]);
2925                 l_cp->ppm_len += l_N_ppm;
2926
2927                 // Read incomplete Ippm series
2928                 memcpy(l_cp->ppm_data_current, p_header_data, l_remaining_data);
2929                 p_header_size -= l_remaining_data;
2930                 p_header_data += l_remaining_data;
2931
2932                 l_cp->ppm_data_read += l_remaining_data; // Increase the number of data read
2933         }
2934
2935 #ifdef CLEAN_MSD
2936
2937                 if (l_cp->ppm_data_size == l_cp->ppm_len) {
2938                         if (p_header_size >= 4) {
2939                                 // read a N_ppm
2940                                 opj_read_bytes(p_header_data,&l_N_ppm,4);               /* N_ppm */
2941                                 p_header_data+=4;
2942                                 p_header_size-=4;
2943                                 l_cp->ppm_len += l_N_ppm ;
2944
2945                                 l_cp->ppm_buffer = (OPJ_BYTE *) opj_realloc(l_cp->ppm_buffer, l_cp->ppm_len);
2946                                 if (l_cp->ppm_buffer == 00) {
2947                                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading ppm marker\n");
2948                                         return OPJ_FALSE;
2949                                 }
2950                                 memset(l_cp->ppm_buffer+l_cp->ppm_data_size,0,l_N_ppm);
2951
2952                                 l_cp->ppm_data = l_cp->ppm_buffer;
2953                         }
2954                         else {
2955                                 return OPJ_FALSE;
2956                         }
2957                 }
2958
2959                 l_remaining_data = l_cp->ppm_len - l_cp->ppm_data_size;
2960
2961                 if (l_remaining_data <= p_header_size) {
2962                         /* we must store less information than available in the packet */
2963                         memcpy(l_cp->ppm_buffer + l_cp->ppm_data_size , p_header_data , l_remaining_data);
2964                         l_cp->ppm_data_size = l_cp->ppm_len;
2965                         p_header_size -= l_remaining_data;
2966                         p_header_data += l_remaining_data;
2967                 }
2968                 else {
2969                         memcpy(l_cp->ppm_buffer + l_cp->ppm_data_size , p_header_data , p_header_size);
2970                         l_cp->ppm_data_size += p_header_size;
2971                         p_header_data += p_header_size;
2972                         p_header_size = 0;
2973                         break;
2974                 }
2975         }
2976 #endif
2977         return OPJ_TRUE;
2978 }
2979
2980 static void j2k_read_ppt(opj_j2k_t *j2k) {
2981         int len, Z_ppt, i, j = 0;
2982
2983         opj_cp_t *cp = j2k->cp;
2984         opj_tcp_t *tcp = cp->tcps + j2k->curtileno;
2985         opj_cio_t *cio = j2k->cio;
2986
2987         len = cio_read(cio, 2);
2988         Z_ppt = cio_read(cio, 1);
2989         tcp->ppt = 1;
2990         if (Z_ppt == 0) {               /* First PPT marker */
2991                 tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));
2992                 tcp->ppt_data_first = tcp->ppt_data;
2993                 tcp->ppt_store = 0;
2994                 tcp->ppt_len = len - 3;
2995         } else {                        /* NON-first PPT marker */
2996                 tcp->ppt_data = (unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
2997                 tcp->ppt_data_first = tcp->ppt_data;
2998                 tcp->ppt_len = len - 3 + tcp->ppt_store;
2999         }
3000         j = tcp->ppt_store;
3001         for (i = len - 3; i > 0; i--) {
3002                 tcp->ppt_data[j] = cio_read(cio, 1);
3003                 j++;
3004         }
3005         tcp->ppt_store = j;
3006 }
3007
3008 /**
3009  * Reads a PPT marker (Packed packet headers, tile-part header)
3010  *
3011  * @param       p_header_data   the data contained in the PPT box.
3012  * @param       p_j2k                   the jpeg2000 codec.
3013  * @param       p_header_size   the size of the data contained in the PPT marker.
3014  * @param       p_manager               the user event manager.
3015 */
3016 opj_bool j2k_read_ppt_v2 (      opj_j2k_v2_t *p_j2k,
3017                                                         OPJ_BYTE * p_header_data,
3018                                                         OPJ_UINT32 p_header_size,
3019                                                         struct opj_event_mgr * p_manager )
3020 {
3021         opj_cp_v2_t *l_cp = 00;
3022         opj_tcp_v2_t *l_tcp = 00;
3023         OPJ_UINT32 l_Z_ppt;
3024
3025         /* preconditions */
3026         assert(p_header_data != 00);
3027         assert(p_j2k != 00);
3028         assert(p_manager != 00);
3029
3030         /* We need to have the Z_ppt element at minimum */
3031         if (p_header_size < 1) {
3032                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPT marker\n");
3033                 return OPJ_FALSE;
3034         }
3035
3036         l_cp = &(p_j2k->m_cp);
3037         if (l_cp->ppm){
3038                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
3039                 return OPJ_FALSE;
3040         }
3041
3042         l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
3043         l_tcp->ppt = 1;
3044
3045         opj_read_bytes(p_header_data,&l_Z_ppt,1);               /* Z_ppt */
3046         ++p_header_data;
3047         --p_header_size;
3048
3049         /* Allocate buffer to read the packet header */
3050         if (l_Z_ppt == 0) {
3051                 /* First PPT marker */
3052                 l_tcp->ppt_data_size = 0;
3053                 l_tcp->ppt_len = p_header_size;
3054
3055                 l_tcp->ppt_buffer = (OPJ_BYTE *) opj_calloc(l_tcp->ppt_len, sizeof(OPJ_BYTE) );
3056                 if (l_tcp->ppt_buffer == 00) {
3057                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading PPT marker\n");
3058                         return OPJ_FALSE;
3059                 }
3060                 l_tcp->ppt_data = l_tcp->ppt_buffer;
3061
3062                 /* memset(l_tcp->ppt_buffer,0,l_tcp->ppt_len); */
3063         }
3064         else {
3065                 l_tcp->ppt_len += p_header_size;
3066
3067                 l_tcp->ppt_buffer = (OPJ_BYTE *) opj_realloc(l_tcp->ppt_buffer,l_tcp->ppt_len);
3068                 if (l_tcp->ppt_buffer == 00) {
3069                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory reading PPT marker\n");
3070                         return OPJ_FALSE;
3071                 }
3072                 l_tcp->ppt_data = l_tcp->ppt_buffer;
3073
3074                 memset(l_tcp->ppt_buffer+l_tcp->ppt_data_size,0,p_header_size);
3075         }
3076
3077         /* Read packet header from buffer */
3078         memcpy(l_tcp->ppt_buffer+l_tcp->ppt_data_size,p_header_data,p_header_size);
3079
3080         l_tcp->ppt_data_size += p_header_size;
3081
3082         return OPJ_TRUE;
3083 }
3084
3085 static void j2k_write_tlm(opj_j2k_t *j2k){
3086         int lenp;
3087         opj_cio_t *cio = j2k->cio;
3088         j2k->tlm_start = cio_tell(cio);
3089         cio_write(cio, J2K_MS_TLM, 2);/* TLM */
3090         lenp = 4 + (5*j2k->totnum_tp);
3091         cio_write(cio,lenp,2);                          /* Ltlm */
3092         cio_write(cio, 0,1);                                    /* Ztlm=0*/
3093         cio_write(cio,80,1);                                    /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
3094         cio_skip(cio,5*j2k->totnum_tp);
3095 }
3096
3097 static void j2k_write_sot(opj_j2k_t *j2k) {
3098         int lenp, len;
3099
3100         opj_cio_t *cio = j2k->cio;
3101
3102         j2k->sot_start = cio_tell(cio);
3103         cio_write(cio, J2K_MS_SOT, 2);          /* SOT */
3104         lenp = cio_tell(cio);
3105         cio_skip(cio, 2);                                       /* Lsot (further) */
3106         cio_write(cio, j2k->curtileno, 2);      /* Isot */
3107         cio_skip(cio, 4);                                       /* Psot (further in j2k_write_sod) */
3108         cio_write(cio, j2k->cur_tp_num , 1);    /* TPsot */
3109         cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1);          /* TNsot */
3110         len = cio_tell(cio) - lenp;
3111         cio_seek(cio, lenp);
3112         cio_write(cio, len, 2);                         /* Lsot */
3113         cio_seek(cio, lenp + len);
3114
3115         /* UniPG>> */
3116 #ifdef USE_JPWL
3117         /* update markers struct */
3118         j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2);
3119 #endif /* USE_JPWL */
3120         /* <<UniPG */
3121
3122         if( j2k->cstr_info && j2k->cur_tp_num==0){
3123           j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOT, lenp, len);
3124         }
3125 }
3126
3127 static void j2k_read_sot(opj_j2k_t *j2k) {
3128         int len, tileno, totlen, partno, numparts, i;
3129         opj_tcp_t *tcp = NULL;
3130         char status = 0;
3131
3132         opj_cp_t *cp = j2k->cp;
3133         opj_cio_t *cio = j2k->cio;
3134
3135         len = cio_read(cio, 2);
3136         tileno = cio_read(cio, 2);
3137
3138 #ifdef USE_JPWL
3139         if (j2k->cp->correct) {
3140
3141                 static int backup_tileno = 0;
3142
3143                 /* tileno is negative or larger than the number of tiles!!! */
3144                 if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
3145                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3146                                 "JPWL: bad tile number (%d out of a maximum of %d)\n",
3147                                 tileno, (cp->tw * cp->th));
3148                         if (!JPWL_ASSUME) {
3149                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
3150                                 return;
3151                         }
3152                         /* we try to correct */
3153                         tileno = backup_tileno;
3154                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
3155                                 "- setting tile number to %d\n",
3156                                 tileno);
3157                 }
3158
3159                 /* keep your private count of tiles */
3160                 backup_tileno++;
3161         };
3162 #endif /* USE_JPWL */
3163         
3164         if (cp->tileno_size == 0) {
3165                 cp->tileno[cp->tileno_size] = tileno;
3166                 cp->tileno_size++;
3167         } else {
3168                 i = 0;
3169                 while (i < cp->tileno_size && status == 0) {
3170                         status = cp->tileno[i] == tileno ? 1 : 0;
3171                         i++;
3172                 }
3173                 if (status == 0) {
3174                         cp->tileno[cp->tileno_size] = tileno;
3175                         cp->tileno_size++;
3176                 }
3177         }
3178         
3179         totlen = cio_read(cio, 4);
3180
3181 #ifdef USE_JPWL
3182         if (j2k->cp->correct) {
3183
3184                 /* totlen is negative or larger than the bytes left!!! */
3185                 if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
3186                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3187                                 "JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
3188                                 totlen, cio_numbytesleft(cio) + 8);
3189                         if (!JPWL_ASSUME) {
3190                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
3191                                 return;
3192                         }
3193                         /* we try to correct */
3194                         totlen = 0;
3195                         opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
3196                                 "- setting Psot to %d => assuming it is the last tile\n",
3197                                 totlen);
3198                 }
3199
3200         };
3201 #endif /* USE_JPWL */
3202
3203         if (!totlen)
3204                 totlen = cio_numbytesleft(cio) + 8;
3205         
3206         partno = cio_read(cio, 1);
3207         numparts = cio_read(cio, 1);
3208   
3209   if (partno >= numparts) {
3210     opj_event_msg(j2k->cinfo, EVT_WARNING, "SOT marker inconsistency in tile %d: tile-part index greater (%d) than number of tile-parts (%d)\n", tileno, partno, numparts);
3211     numparts = partno+1;
3212   }
3213         
3214         j2k->curtileno = tileno;
3215         j2k->cur_tp_num = partno;
3216         j2k->eot = cio_getbp(cio) - 12 + totlen;
3217         j2k->state = J2K_STATE_TPH;
3218         tcp = &cp->tcps[j2k->curtileno];
3219
3220         /* Index */
3221         if (j2k->cstr_info) {
3222                 if (tcp->first) {
3223                         if (tileno == 0) 
3224                                 j2k->cstr_info->main_head_end = cio_tell(cio) - 13;
3225                         j2k->cstr_info->tile[tileno].tileno = tileno;
3226                         j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12;
3227                         j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1;                             
3228     } else {
3229                         j2k->cstr_info->tile[tileno].end_pos += totlen;
3230                 }
3231     j2k->cstr_info->tile[tileno].num_tps = numparts;
3232     if (numparts)
3233       j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, numparts * sizeof(opj_tp_info_t));
3234     else
3235       j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, 10 * sizeof(opj_tp_info_t)); // Fixme (10)
3236                 j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12;
3237                 j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = 
3238                         j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
3239         }
3240         
3241         if (tcp->first == 1) {          
3242                 /* Initialization PPT */
3243                 opj_tccp_t *tmp = tcp->tccps;
3244                 memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t));
3245                 tcp->ppt = 0;
3246                 tcp->ppt_data = NULL;
3247                 tcp->ppt_data_first = NULL;
3248                 tcp->tccps = tmp;
3249
3250                 for (i = 0; i < j2k->image->numcomps; i++) {
3251                         tcp->tccps[i] = j2k->default_tcp->tccps[i];
3252                 }
3253                 cp->tcps[j2k->curtileno].first = 0;
3254         }
3255 }
3256
3257 /**
3258  * Reads a PPT marker (Packed packet headers, tile-part header)
3259  *
3260  * @param       p_header_data   the data contained in the PPT box.
3261  * @param       p_j2k                   the jpeg2000 codec.
3262  * @param       p_header_size   the size of the data contained in the PPT marker.
3263  * @param       p_manager               the user event manager.
3264 */
3265 opj_bool j2k_read_sot_v2 (
3266                                                 opj_j2k_v2_t *p_j2k,
3267                                                 OPJ_BYTE * p_header_data,
3268                                                 OPJ_UINT32 p_header_size,
3269                                                 struct opj_event_mgr * p_manager
3270                                         )
3271 {
3272
3273         opj_cp_v2_t *l_cp = 00;
3274         opj_tcp_v2_t *l_tcp = 00;
3275         OPJ_UINT32 l_tot_len, l_num_parts = 0;
3276         OPJ_UINT32 l_current_part;
3277         OPJ_UINT32 l_tile_x,l_tile_y;
3278
3279         /* preconditions */
3280         assert(p_header_data != 00);
3281         assert(p_j2k != 00);
3282         assert(p_manager != 00);
3283
3284         /* Size of this marker is fixed = 12 (we have already read marker and its size)*/
3285         if (p_header_size != 8) {
3286                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading SOT marker\n");
3287                 return OPJ_FALSE;
3288         }
3289
3290         l_cp = &(p_j2k->m_cp);
3291         opj_read_bytes(p_header_data,&(p_j2k->m_current_tile_number),2);                /* Isot */
3292         p_header_data+=2;
3293
3294         l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
3295         l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
3296         l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
3297
3298 #ifdef USE_JPWL
3299         if (l_cp->correct) {
3300
3301                 int tileno = p_j2k->m_current_tile_number;
3302                 static int backup_tileno = 0;
3303
3304                 /* tileno is negative or larger than the number of tiles!!! */
3305                 if ((tileno < 0) || (tileno > (l_cp->tw * l_cp->th))) {
3306                         opj_event_msg_v2(p_manager, EVT_ERROR,
3307                                 "JPWL: bad tile number (%d out of a maximum of %d)\n",
3308                                 tileno, (l_cp->tw * l_cp->th));
3309                         if (!JPWL_ASSUME) {
3310                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
3311                                 return OPJ_FALSE;
3312                         }
3313                         /* we try to correct */
3314                         tileno = backup_tileno;
3315                         opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust this\n"
3316                                 "- setting tile number to %d\n",
3317                                 tileno);
3318                 }
3319
3320                 /* keep your private count of tiles */
3321                 backup_tileno++;
3322         };
3323 #endif /* USE_JPWL */
3324
3325         /* look for the tile in the list of already processed tile (in parts). */
3326         /* Optimization possible here with a more complex data structure and with the removing of tiles */
3327         /* since the time taken by this function can only grow at the time */
3328
3329         opj_read_bytes(p_header_data,&l_tot_len,4);             /* Psot */
3330         p_header_data+=4;
3331
3332 #ifdef USE_JPWL
3333         if (l_cp->correct) {
3334
3335                 /* totlen is negative or larger than the bytes left!!! */
3336                 if ((l_tot_len < 0) || (l_tot_len > p_header_size ) ) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
3337                         opj_event_msg_v2(p_manager, EVT_ERROR,
3338                                 "JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
3339                                 l_tot_len, p_header_size ); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
3340                         if (!JPWL_ASSUME) {
3341                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
3342                                 return OPJ_FALSE;
3343                         }
3344                         /* we try to correct */
3345                         l_tot_len = 0;
3346                         opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust this\n"
3347                                 "- setting Psot to %d => assuming it is the last tile\n",
3348                                 l_tot_len);
3349                 }
3350         };
3351 #endif /* USE_JPWL */
3352
3353         /* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
3354         if (!l_tot_len) {
3355                 opj_event_msg_v2(p_manager, EVT_INFO, "Psot value of the current tile-part is equal to zero, "
3356                                 "we assuming it is the last tile-part of the codestream.\n");
3357                 p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
3358         }
3359
3360         opj_read_bytes(p_header_data,&l_current_part ,1);       /* TPsot */
3361         ++p_header_data;
3362
3363         opj_read_bytes(p_header_data,&l_num_parts ,1);          /* TNsot */
3364         ++p_header_data;
3365
3366         if (l_num_parts != 0) { /* Number of tile-part header is provided by this tile-part header */
3367                 /* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
3368                  * tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
3369                 if (l_tcp->m_nb_tile_parts) {
3370                         if (l_current_part >= l_tcp->m_nb_tile_parts){
3371                                 opj_event_msg_v2(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current "
3372                                                 "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts );
3373                                 p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
3374                                 return OPJ_FALSE;
3375                         }
3376                 }
3377                 l_tcp->m_nb_tile_parts = l_num_parts;
3378         }
3379
3380         /* If know the number of tile part header we will check if we didn't read the last*/
3381         if (l_tcp->m_nb_tile_parts) {
3382                 if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) {
3383                         p_j2k->m_specific_param.m_decoder.m_can_decode = 1; /* Process the last tile-part header*/
3384                 }
3385         }
3386
3387         if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part){
3388                 /* Keep the size of data to skip after this marker */
3389                 p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len - 12; /* SOT_marker_size = 12 */
3390         }
3391         else {
3392                 /* FIXME: need to be computed from the number of bytes remaining in the codestream */
3393                 p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
3394         }
3395
3396         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
3397
3398         /* Check if the current tile is outside the area we want decode (in tile index)*/
3399         p_j2k->m_specific_param.m_decoder.m_skip_data =
3400                         (l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
3401                 ||      (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
3402                 ||  (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
3403                 ||      (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
3404
3405         /* Index */
3406
3407         /* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
3408         /* if (p_j2k->cstr_info) {
3409                 if (l_tcp->first) {
3410                         if (tileno == 0) {
3411                                 p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
3412                         }
3413
3414                         p_j2k->cstr_info->tile[tileno].tileno = tileno;
3415                         p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
3416                         p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
3417                         p_j2k->cstr_info->tile[tileno].num_tps = numparts;
3418
3419                         if (numparts) {
3420                                 p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
3421                         }
3422                         else {
3423                                 p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
3424                         }
3425                 }
3426                 else {
3427                         p_j2k->cstr_info->tile[tileno].end_pos += totlen;
3428                 }
3429
3430                 p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
3431                 p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
3432                 p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
3433         }*/
3434         return OPJ_TRUE;
3435 }
3436
3437 static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) {
3438         int l, layno;
3439         int totlen;
3440         opj_tcp_t *tcp = NULL;
3441         opj_codestream_info_t *cstr_info = NULL;
3442         
3443         opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;        /* cast is needed because of conflicts in header inclusions */
3444         opj_cp_t *cp = j2k->cp;
3445         opj_cio_t *cio = j2k->cio;
3446
3447         tcd->tp_num = j2k->tp_num ;
3448         tcd->cur_tp_num = j2k->cur_tp_num;
3449         
3450         cio_write(cio, J2K_MS_SOD, 2);
3451
3452         if( j2k->cstr_info && j2k->cur_tp_num==0){
3453           j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOD, cio_tell(cio), 0);
3454         }
3455
3456         if (j2k->curtileno == 0) {
3457                 j2k->sod_start = cio_tell(cio) + j2k->pos_correction;
3458         }
3459
3460         /* INDEX >> */
3461         cstr_info = j2k->cstr_info;
3462         if (cstr_info) {
3463                 if (!j2k->cur_tp_num ) {
3464                         cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
3465                         j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno;
3466                 }
3467                 else{
3468                         if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio))
3469                                 cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio);
3470                 }
3471                 /* UniPG>> */
3472 #ifdef USE_JPWL
3473                 /* update markers struct */
3474                 j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2);
3475 #endif /* USE_JPWL */
3476                 /* <<UniPG */
3477         }
3478         /* << INDEX */
3479         
3480         tcp = &cp->tcps[j2k->curtileno];
3481         for (layno = 0; layno < tcp->numlayers; layno++) {
3482                 if (tcp->rates[layno]>(j2k->sod_start / (cp->th * cp->tw))) {
3483                         tcp->rates[layno]-=(j2k->sod_start / (cp->th * cp->tw));
3484                 } else if (tcp->rates[layno]) {
3485                         tcp->rates[layno]=1;
3486                 }
3487         }
3488         if(j2k->cur_tp_num == 0){
3489                 tcd->tcd_image->tiles->packno = 0;
3490                 if(cstr_info)
3491                         cstr_info->packno = 0;
3492         }
3493         
3494         l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info);
3495         
3496         /* Writing Psot in SOT marker */
3497         totlen = cio_tell(cio) + l - j2k->sot_start;
3498         cio_seek(cio, j2k->sot_start + 6);
3499         cio_write(cio, totlen, 4);
3500         cio_seek(cio, j2k->sot_start + totlen);
3501         /* Writing Ttlm and Ptlm in TLM marker */
3502         if(cp->cinema){
3503                 cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num));
3504                 cio_write(cio, j2k->curtileno, 1);
3505                 cio_write(cio, totlen, 4);
3506         }
3507         cio_seek(cio, j2k->sot_start + totlen);
3508 }
3509
3510 static void j2k_read_sod(opj_j2k_t *j2k) {
3511         int len, truncate = 0, i;
3512         unsigned char *data = NULL, *data_ptr = NULL;
3513
3514         opj_cio_t *cio = j2k->cio;
3515         int curtileno = j2k->curtileno;
3516
3517         /* Index */
3518         if (j2k->cstr_info) {
3519                 j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
3520                         cio_tell(cio) + j2k->pos_correction - 1;
3521                 if (j2k->cur_tp_num == 0)
3522                         j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
3523                 j2k->cstr_info->packno = 0;
3524         }
3525         
3526         len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);
3527
3528         if (len == cio_numbytesleft(cio) + 1) {
3529                 truncate = 1;           /* Case of a truncate codestream */
3530         }       
3531
3532         data = j2k->tile_data[curtileno];
3533         data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
3534
3535         data_ptr = data + j2k->tile_len[curtileno];
3536         for (i = 0; i < len; i++) {
3537                 data_ptr[i] = cio_read(cio, 1);
3538         }
3539
3540         j2k->tile_len[curtileno] += len;
3541         j2k->tile_data[curtileno] = data;
3542         
3543         if (!truncate) {
3544                 j2k->state = J2K_STATE_TPHSOT;
3545         } else {
3546                 j2k->state = J2K_STATE_NEOC;    /* RAJOUTE !! */
3547         }
3548         j2k->cur_tp_num++;
3549 }
3550
3551 /**
3552  * Reads a SOD marker (Start Of Data)
3553  *
3554  * @param       p_header_data   the data contained in the SOD box.
3555  * @param       p_j2k                   the jpeg2000 codec.
3556  * @param       p_header_size   the size of the data contained in the SOD marker.
3557  * @param       p_manager               the user event manager.
3558 */
3559 opj_bool j2k_read_sod_v2 (
3560                                                 opj_j2k_v2_t *p_j2k,
3561                                                 struct opj_stream_private *p_stream,
3562                                                 struct opj_event_mgr * p_manager
3563                                         )
3564 {
3565         OPJ_UINT32 l_current_read_size;
3566         opj_codestream_index_t * l_cstr_index = 00;
3567         OPJ_BYTE ** l_current_data = 00;
3568         opj_tcp_v2_t * l_tcp = 00;
3569         OPJ_UINT32 * l_tile_len = 00;
3570
3571         /* preconditions */
3572         assert(p_j2k != 00);
3573         assert(p_manager != 00);
3574         assert(p_stream != 00);
3575
3576         l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
3577
3578         if (p_j2k->m_specific_param.m_decoder.m_last_tile_part)
3579                 p_j2k->m_specific_param.m_decoder.m_sot_length = opj_stream_get_number_byte_left(p_stream) - 2;
3580         else
3581                 p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
3582
3583         l_current_data = &(l_tcp->m_data);
3584         l_tile_len = &l_tcp->m_data_size;
3585
3586         if (! *l_current_data) {
3587                 *l_current_data = (OPJ_BYTE*) opj_malloc/*FIXME V2 -> my_opj_malloc*/(p_j2k->m_specific_param.m_decoder.m_sot_length);
3588         }
3589         else {
3590                 *l_current_data = (OPJ_BYTE*) opj_realloc/*FIXME V2 -> my_opj_realloc*/(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length);
3591         }
3592
3593         if (*l_current_data == 00) {
3594                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot decode tile\n");
3595                 return OPJ_FALSE;
3596         }
3597
3598 #ifdef TODO_MSD /* FIXME */
3599         l_cstr_index = p_j2k->cstr_index;
3600
3601         /* Index */
3602         if (l_cstr_index) {
3603                 OPJ_SIZE_T l_current_pos = opj_stream_tell(p_stream)-1;
3604                 l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[p_j2k->m_specific_param.m_encoder.m_current_tile_part_number].tp_end_header = l_current_pos;
3605
3606                 l_cstr_index->packno = 0;
3607         }
3608 #endif
3609
3610         l_current_read_size = opj_stream_read_data(     p_stream,
3611                                                                                                 *l_current_data + *l_tile_len,
3612                                                                                                 p_j2k->m_specific_param.m_decoder.m_sot_length,
3613                                                                                                 p_manager);
3614
3615         if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
3616                 p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
3617         }
3618         else {
3619                 p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
3620         }
3621
3622         *l_tile_len +=  l_current_read_size;
3623
3624         return OPJ_TRUE;
3625 }
3626
3627
3628 static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) {
3629         opj_cp_t *cp = j2k->cp;
3630         opj_tcp_t *tcp = &cp->tcps[tileno];
3631         opj_cio_t *cio = j2k->cio;
3632         int numcomps = j2k->image->numcomps;
3633         
3634         cio_write(cio, J2K_MS_RGN, 2);                                          /* RGN  */
3635         cio_write(cio, numcomps <= 256 ? 5 : 6, 2);                     /* Lrgn */
3636         cio_write(cio, compno, numcomps <= 256 ? 1 : 2);        /* Crgn */
3637         cio_write(cio, 0, 1);                                                           /* Srgn */
3638         cio_write(cio, tcp->tccps[compno].roishift, 1);         /* SPrgn */
3639 }
3640
3641 static void j2k_read_rgn(opj_j2k_t *j2k) {
3642         int len, compno, roisty;
3643
3644         opj_cp_t *cp = j2k->cp;
3645         opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
3646         opj_cio_t *cio = j2k->cio;
3647         int numcomps = j2k->image->numcomps;
3648
3649         len = cio_read(cio, 2);                                                                         /* Lrgn */
3650         compno = cio_read(cio, numcomps <= 256 ? 1 : 2);                        /* Crgn */
3651         roisty = cio_read(cio, 1);                                                                      /* Srgn */
3652
3653 #ifdef USE_JPWL
3654         if (j2k->cp->correct) {
3655                 /* totlen is negative or larger than the bytes left!!! */
3656                 if (compno >= numcomps) {
3657                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3658                                 "JPWL: bad component number in RGN (%d when there are only %d)\n",
3659                                 compno, numcomps);
3660                         if (!JPWL_ASSUME || JPWL_ASSUME) {
3661                                 opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
3662                                 return;
3663                         }
3664                 }
3665         };
3666 #endif /* USE_JPWL */
3667
3668         tcp->tccps[compno].roishift = cio_read(cio, 1);                         /* SPrgn */
3669 }
3670
3671 static void j2k_write_eoc(opj_j2k_t *j2k) {
3672         opj_cio_t *cio = j2k->cio;
3673         /* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */
3674         cio_write(cio, J2K_MS_EOC, 2);
3675
3676 /* UniPG>> */
3677 #ifdef USE_JPWL
3678         /* update markers struct */
3679         j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2);
3680 #endif /* USE_JPWL */
3681 /* <<UniPG */
3682 }
3683
3684 /**
3685  * Reads a RGN marker (Region Of Interest)
3686  *
3687  * @param       p_header_data   the data contained in the POC box.
3688  * @param       p_j2k                   the jpeg2000 codec.
3689  * @param       p_header_size   the size of the data contained in the POC marker.
3690  * @param       p_manager               the user event manager.
3691 */
3692 opj_bool j2k_read_rgn_v2 (
3693                                                 opj_j2k_v2_t *p_j2k,
3694                                                 OPJ_BYTE * p_header_data,
3695                                                 OPJ_UINT32 p_header_size,
3696                                                 struct opj_event_mgr * p_manager
3697                                         )
3698 {
3699         OPJ_UINT32 l_nb_comp;
3700         opj_image_t * l_image = 00;
3701
3702         opj_cp_v2_t *l_cp = 00;
3703         opj_tcp_v2_t *l_tcp = 00;
3704         OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
3705
3706         // preconditions
3707         assert(p_header_data != 00);
3708         assert(p_j2k != 00);
3709         assert(p_manager != 00);
3710
3711         l_image = p_j2k->m_image;
3712         l_nb_comp = l_image->numcomps;
3713
3714         if (l_nb_comp <= 256) {
3715                 l_comp_room = 1; }
3716         else {
3717                 l_comp_room = 2; }
3718
3719         if (p_header_size != 2 + l_comp_room) {
3720                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading RGN marker\n");
3721                 return OPJ_FALSE;
3722         }
3723
3724         l_cp = &(p_j2k->m_cp);
3725         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
3726                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
3727                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
3728
3729         opj_read_bytes(p_header_data,&l_comp_no,l_comp_room);           /* Crgn */
3730         p_header_data+=l_comp_room;
3731         opj_read_bytes(p_header_data,&l_roi_sty,1);                                     /* Srgn */
3732         ++p_header_data;
3733
3734 #ifdef USE_JPWL
3735         if (l_cp->correct) {
3736                 /* totlen is negative or larger than the bytes left!!! */
3737                 if (l_comp_room >= l_nb_comp) {
3738                         opj_event_msg_v2(p_manager, EVT_ERROR,
3739                                 "JPWL: bad component number in RGN (%d when there are only %d)\n",
3740                                 l_comp_room, l_nb_comp);
3741                         if (!JPWL_ASSUME || JPWL_ASSUME) {
3742                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
3743                                 return OPJ_FALSE;
3744                         }
3745                 }
3746         };
3747 #endif /* USE_JPWL */
3748
3749         opj_read_bytes(p_header_data,(OPJ_UINT32 *) (&(l_tcp->tccps[l_comp_no].roishift)),1);   /* SPrgn */
3750         ++p_header_data;
3751
3752         return OPJ_TRUE;
3753
3754 }
3755
3756 static void j2k_read_eoc(opj_j2k_t *j2k) {
3757         int i, tileno;
3758         opj_bool success;
3759
3760         /* if packets should be decoded */
3761         if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
3762                 opj_tcd_t *tcd = tcd_create(j2k->cinfo);
3763                 tcd_malloc_decode(tcd, j2k->image, j2k->cp);
3764                 for (i = 0; i < j2k->cp->tileno_size; i++) {
3765                         tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
3766                         tileno = j2k->cp->tileno[i];
3767                         success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
3768                         opj_free(j2k->tile_data[tileno]);
3769                         j2k->tile_data[tileno] = NULL;
3770                         tcd_free_decode_tile(tcd, i);
3771                         if (success == OPJ_FALSE) {
3772                                 j2k->state |= J2K_STATE_ERR;
3773                                 break;
3774                         }
3775                 }
3776                 tcd_free_decode(tcd);
3777                 tcd_destroy(tcd);
3778         }
3779         /* if packets should not be decoded  */
3780         else {
3781                 for (i = 0; i < j2k->cp->tileno_size; i++) {
3782                         tileno = j2k->cp->tileno[i];
3783                         opj_free(j2k->tile_data[tileno]);
3784                         j2k->tile_data[tileno] = NULL;
3785                 }
3786         }       
3787         if (j2k->state & J2K_STATE_ERR)
3788                 j2k->state = J2K_STATE_MT + J2K_STATE_ERR;
3789         else
3790                 j2k->state = J2K_STATE_MT; 
3791 }
3792
3793 /**
3794  * Reads a EOC marker (End Of Codestream)
3795  *
3796  * @param       p_header_data   the data contained in the SOD box.
3797  * @param       p_j2k                   the jpeg2000 codec.
3798  * @param       p_header_size   the size of the data contained in the SOD marker.
3799  * @param       p_manager               the user event manager.
3800 */
3801 opj_bool j2k_read_eoc_v2 (      opj_j2k_v2_t *p_j2k,
3802                                                         struct opj_stream_private *p_stream,
3803                                                         struct opj_event_mgr * p_manager )
3804 {
3805         OPJ_UINT32 i;
3806         opj_tcd_v2_t * l_tcd = 00;
3807         OPJ_UINT32 l_nb_tiles;
3808         opj_tcp_v2_t * l_tcp = 00;
3809         opj_bool l_success;
3810
3811         /* preconditions */
3812         assert(p_j2k != 00);
3813         assert(p_manager != 00);
3814         assert(p_stream != 00);
3815
3816         l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
3817         l_tcp = p_j2k->m_cp.tcps;
3818
3819         l_tcd = tcd_create_v2(OPJ_TRUE);
3820         if (l_tcd == 00) {
3821                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
3822                 return OPJ_FALSE;
3823         }
3824
3825         for (i = 0; i < l_nb_tiles; ++i) {
3826                 if (l_tcp->m_data) {
3827                         if (! tcd_init_decode_tile(l_tcd, i)) {
3828                                 tcd_destroy_v2(l_tcd);
3829                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
3830                                 return OPJ_FALSE;
3831                         }
3832
3833                         l_success = tcd_decode_tile_v2(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i, p_j2k->cstr_index);
3834                         /* cleanup */
3835
3836                         if (! l_success) {
3837                                 p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
3838                                 break;
3839                         }
3840                 }
3841
3842                 j2k_tcp_destroy(l_tcp);
3843                 ++l_tcp;
3844         }
3845
3846         tcd_destroy_v2(l_tcd);
3847         return OPJ_TRUE;
3848 }
3849
3850 typedef struct opj_dec_mstabent {
3851         /** marker value */
3852         int id;
3853         /** value of the state when the marker can appear */
3854         int states;
3855         /** action linked to the marker */
3856         void (*handler) (opj_j2k_t *j2k);
3857 } opj_dec_mstabent_t;
3858
3859 opj_dec_mstabent_t j2k_dec_mstab[] = {
3860   {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
3861   {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot},
3862   {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
3863   {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
3864   {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
3865   {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod},
3866   {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc},
3867   {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn},
3868   {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd},
3869   {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc},
3870   {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc},
3871   {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
3872   {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
3873   {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
3874   {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
3875   {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
3876   {J2K_MS_SOP, 0, 0},
3877   {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
3878   {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com},
3879
3880 #ifdef USE_JPWL
3881   {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
3882   {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
3883   {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
3884   {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
3885 #endif /* USE_JPWL */
3886 #ifdef USE_JPSEC
3887   {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec},
3888   {J2K_MS_INSEC, 0, j2k_read_insec},
3889 #endif /* USE_JPSEC */
3890
3891   {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk}
3892 };
3893
3894 static void j2k_read_unk(opj_j2k_t *j2k) {
3895         opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n");
3896
3897 #ifdef USE_JPWL
3898         if (j2k->cp->correct) {
3899                 int m = 0, id, i;
3900                 int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id;
3901                 cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
3902                 id = cio_read(j2k->cio, 2);
3903                 opj_event_msg(j2k->cinfo, EVT_ERROR,
3904                         "JPWL: really don't know this marker %x\n",
3905                         id);
3906                 if (!JPWL_ASSUME) {
3907                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3908                                 "- possible synch loss due to uncorrectable codestream errors => giving up\n");
3909                         return;
3910                 }
3911                 /* OK, activate this at your own risk!!! */
3912                 /* we look for the marker at the minimum hamming distance from this */
3913                 while (j2k_dec_mstab[m].id) {
3914                         
3915                         /* 1's where they differ */
3916                         tmp_id = j2k_dec_mstab[m].id ^ id;
3917
3918                         /* compute the hamming distance between our id and the current */
3919                         cur_dist = 0;
3920                         for (i = 0; i < 16; i++) {
3921                                 if ((tmp_id >> i) & 0x0001) {
3922                                         cur_dist++;
3923                                 }
3924                         }
3925
3926                         /* if current distance is smaller, set the minimum */
3927                         if (cur_dist < min_dist) {
3928                                 min_dist = cur_dist;
3929                                 min_id = j2k_dec_mstab[m].id;
3930                         }
3931                         
3932                         /* jump to the next marker */
3933                         m++;
3934                 }
3935
3936                 /* do we substitute the marker? */
3937                 if (min_dist < JPWL_MAXIMUM_HAMMING) {
3938                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3939                                 "- marker %x is at distance %d from the read %x\n",
3940                                 min_id, min_dist, id);
3941                         opj_event_msg(j2k->cinfo, EVT_ERROR,
3942                                 "- trying to substitute in place and crossing fingers!\n");
3943                         cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
3944                         cio_write(j2k->cio, min_id, 2);
3945
3946                         /* rewind */
3947                         cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
3948
3949                 }
3950
3951         };
3952 #endif /* USE_JPWL */
3953
3954 }
3955
3956 /**
3957  * Reads an unknown marker
3958  *
3959  * @param       p_stream                                the stream object to read from.
3960  * @param       p_j2k                   the jpeg2000 codec.
3961  * @param       p_manager               the user event manager.
3962  *
3963  * @return      true                    if the marker could be deduced.
3964 */
3965 opj_bool j2k_read_unk_v2 (      opj_j2k_v2_t *p_j2k,
3966                                                         struct opj_stream_private *p_stream,
3967                                                         OPJ_UINT32 *output_marker,
3968                                                         struct opj_event_mgr * p_manager
3969                                                         )
3970 {
3971         OPJ_UINT32 l_unknown_marker;
3972         const opj_dec_memory_marker_handler_t * l_marker_handler;
3973         OPJ_UINT32 l_size_unk = 2;
3974
3975         // preconditions
3976         assert(p_j2k != 00);
3977         assert(p_manager != 00);
3978         assert(p_stream != 00);
3979
3980         opj_event_msg_v2(p_manager, EVT_WARNING, "Unknown marker\n");
3981
3982         while(1) {
3983                 // Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer
3984                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
3985                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
3986                         return OPJ_FALSE;
3987                 }
3988
3989                 // read 2 bytes as the new marker ID
3990                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_unknown_marker,2);
3991
3992                 if (!(l_unknown_marker < 0xff00)) {
3993
3994                         // Get the marker handler from the marker ID
3995                         l_marker_handler = j2k_get_marker_handler(l_unknown_marker);
3996
3997                         if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
3998                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
3999                                 return OPJ_FALSE;
4000                         }
4001                         else {
4002                                 if (l_marker_handler->id != J2K_MS_UNK) {
4003                                         /* Add the marker to the codestream index*/
4004                                         if (l_marker_handler->id != J2K_MS_SOT)
4005                                                 j2k_add_mhmarker_v2(p_j2k->cstr_index, J2K_MS_UNK,
4006                                                                                         (OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
4007                                                                                         l_size_unk);
4008                                         break; /* next marker is known and well located */
4009                                 }
4010                                 else
4011                                         l_size_unk += 2;
4012                         }
4013                 }
4014         }
4015
4016         *output_marker = l_marker_handler->id ;
4017
4018         return OPJ_TRUE;
4019 }
4020
4021 /**
4022 Read the lookup table containing all the marker, status and action
4023 @param id Marker value
4024 */
4025 static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
4026         opj_dec_mstabent_t *e;
4027         for (e = j2k_dec_mstab; e->id != 0; e++) {
4028                 if (e->id == id) {
4029                         break;
4030                 }
4031         }
4032         return e;
4033 }
4034
4035 /* ----------------------------------------------------------------------- */
4036 /* J2K / JPT decoder interface                                             */
4037 /* ----------------------------------------------------------------------- */
4038
4039 opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) {
4040         opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
4041         if(!j2k)
4042                 return NULL;
4043
4044         j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t));
4045         if(!j2k->default_tcp) {
4046                 opj_free(j2k);
4047                 return NULL;
4048         }
4049
4050         j2k->cinfo = cinfo;
4051         j2k->tile_data = NULL;
4052
4053         return j2k;
4054 }
4055
4056 void j2k_destroy_decompress(opj_j2k_t *j2k) {
4057         int i = 0;
4058
4059         if(j2k->tile_len != NULL) {
4060                 opj_free(j2k->tile_len);
4061         }
4062         if(j2k->tile_data != NULL) {
4063                 opj_free(j2k->tile_data);
4064         }
4065         if(j2k->default_tcp != NULL) {
4066                 opj_tcp_t *default_tcp = j2k->default_tcp;
4067                 if(default_tcp->ppt_data_first != NULL) {
4068                         opj_free(default_tcp->ppt_data_first);
4069                 }
4070                 if(j2k->default_tcp->tccps != NULL) {
4071                         opj_free(j2k->default_tcp->tccps);
4072                 }
4073                 opj_free(j2k->default_tcp);
4074         }
4075         if(j2k->cp != NULL) {
4076                 opj_cp_t *cp = j2k->cp;
4077                 if(cp->tcps != NULL) {
4078                         for(i = 0; i < cp->tw * cp->th; i++) {
4079                                 if(cp->tcps[i].ppt_data_first != NULL) {
4080                                         opj_free(cp->tcps[i].ppt_data_first);
4081                                 }
4082                                 if(cp->tcps[i].tccps != NULL) {
4083                                         opj_free(cp->tcps[i].tccps);
4084                                 }
4085                         }
4086                         opj_free(cp->tcps);
4087                 }
4088                 if(cp->ppm_data_first != NULL) {
4089                         opj_free(cp->ppm_data_first);
4090                 }
4091                 if(cp->tileno != NULL) {
4092                         opj_free(cp->tileno);  
4093                 }
4094                 if(cp->comment != NULL) {
4095                         opj_free(cp->comment);
4096                 }
4097
4098                 opj_free(cp);
4099         }
4100         opj_free(j2k);
4101 }
4102
4103 void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) {
4104         if(j2k && parameters) {
4105                 /* create and initialize the coding parameters structure */
4106                 opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
4107                 cp->reduce = parameters->cp_reduce;     
4108                 cp->layer = parameters->cp_layer;
4109                 cp->limit_decoding = parameters->cp_limit_decoding;
4110
4111 #ifdef USE_JPWL
4112                 cp->correct = parameters->jpwl_correct;
4113                 cp->exp_comps = parameters->jpwl_exp_comps;
4114                 cp->max_tiles = parameters->jpwl_max_tiles;
4115 #endif /* USE_JPWL */
4116
4117
4118                 /* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */
4119                 j2k->cp = cp;
4120         }
4121 }
4122
4123 void j2k_setup_decoder_v2(opj_j2k_v2_t *j2k, opj_dparameters_t *parameters)
4124 {
4125         if(j2k && parameters) {
4126                 j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
4127                 j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
4128
4129 #ifdef USE_JPWL
4130                 j2k->m_cp.correct = parameters->jpwl_correct;
4131                 j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
4132                 j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
4133 #endif /* USE_JPWL */
4134         }
4135 }
4136
4137 opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
4138         opj_image_t *image = NULL;
4139
4140         opj_common_ptr cinfo = j2k->cinfo;      
4141
4142         j2k->cio = cio;
4143         j2k->cstr_info = cstr_info;
4144         if (cstr_info)
4145                 memset(cstr_info, 0, sizeof(opj_codestream_info_t));
4146
4147         /* create an empty image */
4148         image = opj_image_create0();
4149         j2k->image = image;
4150
4151         j2k->state = J2K_STATE_MHSOC;
4152
4153         for (;;) {
4154                 opj_dec_mstabent_t *e;
4155                 int id = cio_read(cio, 2);
4156
4157 #ifdef USE_JPWL
4158                 /* we try to honor JPWL correction power */
4159                 if (j2k->cp->correct) {
4160
4161                         int orig_pos = cio_tell(cio);
4162                         opj_bool status;
4163
4164                         /* call the corrector */
4165                         status = jpwl_correct(j2k);
4166
4167                         /* go back to where you were */
4168                         cio_seek(cio, orig_pos - 2);
4169
4170                         /* re-read the marker */
4171                         id = cio_read(cio, 2);
4172
4173                         /* check whether it begins with ff */
4174                         if (id >> 8 != 0xff) {
4175                                 opj_event_msg(cinfo, EVT_ERROR,
4176                                         "JPWL: possible bad marker %x at %d\n",
4177                                         id, cio_tell(cio) - 2);
4178                                 if (!JPWL_ASSUME) {
4179                                         opj_image_destroy(image);
4180                                         opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n");
4181                                         return 0;
4182                                 }
4183                                 /* we try to correct */
4184                                 id = id | 0xff00;
4185                                 cio_seek(cio, cio_tell(cio) - 2);
4186                                 cio_write(cio, id, 2);
4187                                 opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n"
4188                                         "- setting marker to %x\n",
4189                                         id);
4190                         }
4191
4192                 }
4193 #endif /* USE_JPWL */
4194
4195                 if (id >> 8 != 0xff) {
4196                         opj_image_destroy(image);
4197                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
4198                         return 0;
4199                 }
4200                 e = j2k_dec_mstab_lookup(id);
4201                 // Check if the marker is known
4202                 if (!(j2k->state & e->states)) {
4203                         opj_image_destroy(image);
4204                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
4205                         return 0;
4206                 }
4207                 // Check if the decoding is limited to the main header
4208                 if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) {
4209                         opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n");
4210                         return image;
4211                 }               
4212
4213                 if (e->handler) {
4214                         (*e->handler)(j2k);
4215                 }
4216                 if (j2k->state & J2K_STATE_ERR) 
4217                         return NULL;    
4218
4219                 if (j2k->state == J2K_STATE_MT) {
4220                         break;
4221                 }
4222                 if (j2k->state == J2K_STATE_NEOC) {
4223                         break;
4224                 }
4225         }
4226         if (j2k->state == J2K_STATE_NEOC) {
4227                 j2k_read_eoc(j2k);
4228         }
4229
4230         if (j2k->state != J2K_STATE_MT) {
4231                 opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
4232         }
4233         return image;
4234 }
4235
4236 /*
4237 * Read a JPT-stream and decode file
4238 *
4239 */
4240 opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio,  opj_codestream_info_t *cstr_info) {
4241         opj_image_t *image = NULL;
4242         opj_jpt_msg_header_t header;
4243         int position;
4244         opj_common_ptr cinfo = j2k->cinfo;
4245
4246         OPJ_ARG_NOT_USED(cstr_info);
4247
4248         j2k->cio = cio;
4249
4250         /* create an empty image */
4251         image = opj_image_create0();
4252         j2k->image = image;
4253
4254         j2k->state = J2K_STATE_MHSOC;
4255         
4256         /* Initialize the header */
4257         jpt_init_msg_header(&header);
4258         /* Read the first header of the message */
4259         jpt_read_msg_header(cinfo, cio, &header);
4260         
4261         position = cio_tell(cio);
4262         if (header.Class_Id != 6) {     /* 6 : Main header data-bin message */
4263                 opj_image_destroy(image);
4264                 opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id);
4265                 return 0;
4266         }
4267         
4268         for (;;) {
4269                 opj_dec_mstabent_t *e = NULL;
4270                 int id;
4271                 
4272                 if (!cio_numbytesleft(cio)) {
4273                         j2k_read_eoc(j2k);
4274                         return image;
4275                 }
4276                 /* data-bin read -> need to read a new header */
4277                 if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) {
4278                         jpt_read_msg_header(cinfo, cio, &header);
4279                         position = cio_tell(cio);
4280                         if (header.Class_Id != 4) {     /* 4 : Tile data-bin message */
4281                                 opj_image_destroy(image);
4282                                 opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n");
4283                                 return 0;
4284                         }
4285                 }
4286                 
4287                 id = cio_read(cio, 2);
4288                 if (id >> 8 != 0xff) {
4289                         opj_image_destroy(image);
4290                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
4291                         return 0;
4292                 }
4293                 e = j2k_dec_mstab_lookup(id);
4294                 if (!(j2k->state & e->states)) {
4295                         opj_image_destroy(image);
4296                         opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
4297                         return 0;
4298                 }
4299                 if (e->handler) {
4300                         (*e->handler)(j2k);
4301                 }
4302                 if (j2k->state == J2K_STATE_MT) {
4303                         break;
4304                 }
4305                 if (j2k->state == J2K_STATE_NEOC) {
4306                         break;
4307                 }
4308         }
4309         if (j2k->state == J2K_STATE_NEOC) {
4310                 j2k_read_eoc(j2k);
4311         }
4312         
4313         if (j2k->state != J2K_STATE_MT) {
4314                 opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
4315         }
4316
4317         return image;
4318 }
4319
4320 /* ----------------------------------------------------------------------- */
4321 /* J2K encoder interface                                                       */
4322 /* ----------------------------------------------------------------------- */
4323
4324 opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) {
4325         opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
4326         if(j2k) {
4327                 j2k->cinfo = cinfo;
4328         }
4329         return j2k;
4330 }
4331
4332 opj_j2k_v2_t* j2k_create_compress_v2()
4333 {
4334         opj_j2k_v2_t *l_j2k = (opj_j2k_v2_t*) opj_malloc(sizeof(opj_j2k_v2_t));
4335         if (!l_j2k) {
4336                 return NULL;
4337         }
4338
4339         memset(l_j2k,0,sizeof(opj_j2k_v2_t));
4340
4341         l_j2k->m_is_decoder = 0;
4342         l_j2k->m_cp.m_is_decoder = 0;
4343
4344         l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(J2K_DEFAULT_HEADER_SIZE);
4345         if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
4346                 j2k_destroy(l_j2k);
4347                 return NULL;
4348         }
4349
4350         l_j2k->m_specific_param.m_encoder.m_header_tile_data_size = J2K_DEFAULT_HEADER_SIZE;
4351
4352         // validation list creation
4353         l_j2k->m_validation_list = opj_procedure_list_create();
4354         if (! l_j2k->m_validation_list) {
4355                 j2k_destroy(l_j2k);
4356                 return NULL;
4357         }
4358
4359         // execution list creation
4360         l_j2k->m_procedure_list = opj_procedure_list_create();
4361         if (! l_j2k->m_procedure_list) {
4362                 j2k_destroy(l_j2k);
4363                 return NULL;
4364         }
4365
4366         return l_j2k;
4367 }
4368
4369 void j2k_destroy_compress(opj_j2k_t *j2k) {
4370         int tileno;
4371
4372         if(!j2k) return;
4373         if(j2k->cp != NULL) {
4374                 opj_cp_t *cp = j2k->cp;
4375
4376                 if(cp->comment) {
4377                         opj_free(cp->comment);
4378                 }
4379                 if(cp->matrice) {
4380                         opj_free(cp->matrice);
4381                 }
4382                 for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
4383                         opj_free(cp->tcps[tileno].tccps);
4384                 }
4385                 opj_free(cp->tcps);
4386                 opj_free(cp);
4387         }
4388
4389         opj_free(j2k);
4390 }
4391
4392 void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) {
4393         int i, j, tileno, numpocs_tile;
4394         opj_cp_t *cp = NULL;
4395
4396         if(!j2k || !parameters || ! image) {
4397                 return;
4398         }
4399
4400         /* create and initialize the coding parameters structure */
4401         cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
4402
4403         /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
4404         j2k->cp = cp;
4405
4406         /* set default values for cp */
4407         cp->tw = 1;
4408         cp->th = 1;
4409
4410         /* 
4411         copy user encoding parameters 
4412         */
4413         cp->cinema = parameters->cp_cinema;
4414         cp->max_comp_size =     parameters->max_comp_size;
4415         cp->rsiz   = parameters->cp_rsiz;
4416         cp->disto_alloc = parameters->cp_disto_alloc;
4417         cp->fixed_alloc = parameters->cp_fixed_alloc;
4418         cp->fixed_quality = parameters->cp_fixed_quality;
4419
4420         /* mod fixed_quality */
4421         if(parameters->cp_matrice) {
4422                 size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int);
4423                 cp->matrice = (int *) opj_malloc(array_size);
4424                 memcpy(cp->matrice, parameters->cp_matrice, array_size);
4425         }
4426
4427         /* tiles */
4428         cp->tdx = parameters->cp_tdx;
4429         cp->tdy = parameters->cp_tdy;
4430
4431         /* tile offset */
4432         cp->tx0 = parameters->cp_tx0;
4433         cp->ty0 = parameters->cp_ty0;
4434
4435         /* comment string */
4436         if(parameters->cp_comment) {
4437                 cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);
4438                 if(cp->comment) {
4439                         strcpy(cp->comment, parameters->cp_comment);
4440                 }
4441         }
4442
4443         /*
4444         calculate other encoding parameters
4445         */
4446
4447         if (parameters->tile_size_on) {
4448                 cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
4449                 cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
4450         } else {
4451                 cp->tdx = image->x1 - cp->tx0;
4452                 cp->tdy = image->y1 - cp->ty0;
4453         }
4454
4455         if(parameters->tp_on){
4456                 cp->tp_flag = parameters->tp_flag;
4457                 cp->tp_on = 1;
4458         }
4459         
4460         cp->img_size = 0;
4461         for(i=0;i<image->numcomps ;i++){
4462         cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec);
4463         }
4464
4465
4466 #ifdef USE_JPWL
4467         /*
4468         calculate JPWL encoding parameters
4469         */
4470
4471         if (parameters->jpwl_epc_on) {
4472                 int i;
4473
4474                 /* set JPWL on */
4475                 cp->epc_on = OPJ_TRUE;
4476                 cp->info_on = OPJ_FALSE; /* no informative technique */
4477
4478                 /* set EPB on */
4479                 if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
4480                         cp->epb_on = OPJ_TRUE;
4481                         
4482                         cp->hprot_MH = parameters->jpwl_hprot_MH;
4483                         for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
4484                                 cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
4485                                 cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
4486                         }
4487                         /* if tile specs are not specified, copy MH specs */
4488                         if (cp->hprot_TPH[0] == -1) {
4489                                 cp->hprot_TPH_tileno[0] = 0;
4490                                 cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
4491                         }
4492                         for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
4493                                 cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
4494                                 cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
4495                                 cp->pprot[i] = parameters->jpwl_pprot[i];
4496                         }
4497                 }
4498
4499                 /* set ESD writing */
4500                 if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
4501                         cp->esd_on = OPJ_TRUE;
4502
4503                         cp->sens_size = parameters->jpwl_sens_size;
4504                         cp->sens_addr = parameters->jpwl_sens_addr;
4505                         cp->sens_range = parameters->jpwl_sens_range;
4506
4507                         cp->sens_MH = parameters->jpwl_sens_MH;
4508                         for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
4509                                 cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
4510                                 cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
4511                         }
4512                 }
4513
4514                 /* always set RED writing to false: we are at the encoder */
4515                 cp->red_on = OPJ_FALSE;
4516
4517         } else {
4518                 cp->epc_on = OPJ_FALSE;
4519         }
4520 #endif /* USE_JPWL */
4521
4522
4523         /* initialize the mutiple tiles */
4524         /* ---------------------------- */
4525         cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
4526
4527         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
4528                 opj_tcp_t *tcp = &cp->tcps[tileno];
4529                 tcp->numlayers = parameters->tcp_numlayers;
4530                 for (j = 0; j < tcp->numlayers; j++) {
4531                         if(cp->cinema){
4532                                 if (cp->fixed_quality) {
4533                                         tcp->distoratio[j] = parameters->tcp_distoratio[j];
4534                                 }
4535                                 tcp->rates[j] = parameters->tcp_rates[j];
4536                         }else{
4537                                 if (cp->fixed_quality) {        /* add fixed_quality */
4538                                         tcp->distoratio[j] = parameters->tcp_distoratio[j];
4539                                 } else {
4540                                         tcp->rates[j] = parameters->tcp_rates[j];
4541                                 }
4542                         }
4543                 }
4544                 tcp->csty = parameters->csty;
4545                 tcp->prg = parameters->prog_order;
4546                 tcp->mct = parameters->tcp_mct; 
4547
4548                 numpocs_tile = 0;
4549                 tcp->POC = 0;
4550                 if (parameters->numpocs) {
4551                         /* initialisation of POC */
4552                         tcp->POC = 1;
4553                         for (i = 0; i < parameters->numpocs; i++) {
4554                                 if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {
4555                                         opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
4556                                         tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;
4557                                         tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;
4558                                         tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;
4559                                         tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;
4560                                         tcp_poc->compno1        = parameters->POC[numpocs_tile].compno1;
4561                                         tcp_poc->prg1           = parameters->POC[numpocs_tile].prg1;
4562                                         tcp_poc->tile           = parameters->POC[numpocs_tile].tile;
4563                                         numpocs_tile++;
4564                                 }
4565                         }
4566                         tcp->numpocs = numpocs_tile -1 ;
4567                 }else{ 
4568                         tcp->numpocs = 0;
4569                 }
4570
4571                 tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
4572
4573                 for (i = 0; i < image->numcomps; i++) {
4574                         opj_tccp_t *tccp = &tcp->tccps[i];
4575                         tccp->csty = parameters->csty & 0x01;   /* 0 => one precinct || 1 => custom precinct  */
4576                         tccp->numresolutions = parameters->numresolution;
4577                         tccp->cblkw = int_floorlog2(parameters->cblockw_init);
4578                         tccp->cblkh = int_floorlog2(parameters->cblockh_init);
4579                         tccp->cblksty = parameters->mode;
4580                         tccp->qmfbid = parameters->irreversible ? 0 : 1;
4581                         tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
4582                         tccp->numgbits = 2;
4583                         if (i == parameters->roi_compno) {
4584                                 tccp->roishift = parameters->roi_shift;
4585                         } else {
4586                                 tccp->roishift = 0;
4587                         }
4588
4589                         if(parameters->cp_cinema)
4590                         {
4591                                 //Precinct size for lowest frequency subband=128
4592                                 tccp->prcw[0] = 7;
4593                                 tccp->prch[0] = 7;
4594                                 //Precinct size at all other resolutions = 256
4595                                 for (j = 1; j < tccp->numresolutions; j++) {
4596                                         tccp->prcw[j] = 8;
4597                                         tccp->prch[j] = 8;
4598                                 }
4599                         }else{
4600                                 if (parameters->csty & J2K_CCP_CSTY_PRT) {
4601                                         int p = 0;
4602                                         for (j = tccp->numresolutions - 1; j >= 0; j--) {
4603                                                 if (p < parameters->res_spec) {
4604                                                         
4605                                                         if (parameters->prcw_init[p] < 1) {
4606                                                                 tccp->prcw[j] = 1;
4607                                                         } else {
4608                                                                 tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]);
4609                                                         }
4610                                                         
4611                                                         if (parameters->prch_init[p] < 1) {
4612                                                                 tccp->prch[j] = 1;
4613                                                         }else {
4614                                                                 tccp->prch[j] = int_floorlog2(parameters->prch_init[p]);
4615                                                         }
4616
4617                                                 } else {
4618                                                         int res_spec = parameters->res_spec;
4619                                                         int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
4620                                                         int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
4621                                                         
4622                                                         if (size_prcw < 1) {
4623                                                                 tccp->prcw[j] = 1;
4624                                                         } else {
4625                                                                 tccp->prcw[j] = int_floorlog2(size_prcw);
4626                                                         }
4627                                                         
4628                                                         if (size_prch < 1) {
4629                                                                 tccp->prch[j] = 1;
4630                                                         } else {
4631                                                                 tccp->prch[j] = int_floorlog2(size_prch);
4632                                                         }
4633                                                 }
4634                                                 p++;
4635                                                 /*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */
4636                                         }       //end for
4637                                 } else {
4638                                         for (j = 0; j < tccp->numresolutions; j++) {
4639                                                 tccp->prcw[j] = 15;
4640                                                 tccp->prch[j] = 15;
4641                                         }
4642                                 }
4643                         }
4644
4645                         dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
4646                 }
4647         }
4648 }
4649
4650 opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
4651         int tileno, compno;
4652         opj_cp_t *cp = NULL;
4653
4654         opj_tcd_t *tcd = NULL;  /* TCD component */
4655
4656         j2k->cio = cio; 
4657         j2k->image = image;
4658
4659         cp = j2k->cp;
4660
4661         /* INDEX >> */
4662         j2k->cstr_info = cstr_info;
4663         if (cstr_info) {
4664                 int compno;
4665                 cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t));
4666                 cstr_info->image_w = image->x1 - image->x0;
4667                 cstr_info->image_h = image->y1 - image->y0;
4668                 cstr_info->prog = (&cp->tcps[0])->prg;
4669                 cstr_info->tw = cp->tw;
4670                 cstr_info->th = cp->th;
4671                 cstr_info->tile_x = cp->tdx;    /* new version parser */
4672                 cstr_info->tile_y = cp->tdy;    /* new version parser */
4673                 cstr_info->tile_Ox = cp->tx0;   /* new version parser */
4674                 cstr_info->tile_Oy = cp->ty0;   /* new version parser */
4675                 cstr_info->numcomps = image->numcomps;
4676                 cstr_info->numlayers = (&cp->tcps[0])->numlayers;
4677                 cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
4678                 for (compno=0; compno < image->numcomps; compno++) {
4679                         cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1;
4680                 }
4681                 cstr_info->D_max = 0.0;         /* ADD Marcela */
4682                 cstr_info->main_head_start = cio_tell(cio); /* position of SOC */
4683                 cstr_info->maxmarknum = 100;
4684                 cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t));
4685                 cstr_info->marknum = 0;
4686         }
4687         /* << INDEX */
4688
4689         j2k_write_soc(j2k);
4690         j2k_write_siz(j2k);
4691         j2k_write_cod(j2k);
4692         j2k_write_qcd(j2k);
4693
4694         if(cp->cinema){
4695                 for (compno = 1; compno < image->numcomps; compno++) {
4696                         j2k_write_coc(j2k, compno);
4697                         j2k_write_qcc(j2k, compno);
4698                 }
4699         }
4700
4701         for (compno = 0; compno < image->numcomps; compno++) {
4702                 opj_tcp_t *tcp = &cp->tcps[0];
4703                 if (tcp->tccps[compno].roishift)
4704                         j2k_write_rgn(j2k, compno, 0);
4705         }
4706         if (cp->comment != NULL) {
4707                 j2k_write_com(j2k);
4708         }
4709
4710         j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k);
4711         /* TLM Marker*/
4712         if(cp->cinema){
4713                 j2k_write_tlm(j2k);
4714                 if (cp->cinema == CINEMA4K_24) {
4715                         j2k_write_poc(j2k);
4716                 }
4717         }
4718
4719         /* uncomment only for testing JPSEC marker writing */
4720         /* j2k_write_sec(j2k); */
4721
4722         /* INDEX >> */
4723         if(cstr_info) {
4724                 cstr_info->main_head_end = cio_tell(cio) - 1;
4725         }
4726         /* << INDEX */
4727         /**** Main Header ENDS here ***/
4728
4729         /* create the tile encoder */
4730         tcd = tcd_create(j2k->cinfo);
4731
4732         /* encode each tile */
4733         for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
4734                 int pino;
4735                 int tilepartno=0;
4736                 /* UniPG>> */
4737                 int acc_pack_num = 0;
4738                 /* <<UniPG */
4739
4740
4741                 opj_tcp_t *tcp = &cp->tcps[tileno];
4742                 opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th);
4743
4744                 j2k->curtileno = tileno;
4745                 j2k->cur_tp_num = 0;
4746                 tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno];
4747                 /* initialisation before tile encoding  */
4748                 if (tileno == 0) {
4749                         tcd_malloc_encode(tcd, image, cp, j2k->curtileno);
4750                 } else {
4751                         tcd_init_encode(tcd, image, cp, j2k->curtileno);
4752                 }
4753
4754                 /* INDEX >> */
4755                 if(cstr_info) {
4756                         cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction;
4757                         cstr_info->tile[j2k->curtileno].maxmarknum = 10;
4758                         cstr_info->tile[j2k->curtileno].marker = (opj_marker_info_t *) opj_malloc(cstr_info->tile[j2k->curtileno].maxmarknum * sizeof(opj_marker_info_t));
4759                         cstr_info->tile[j2k->curtileno].marknum = 0;
4760                 }
4761                 /* << INDEX */
4762
4763                 for(pino = 0; pino <= tcp->numpocs; pino++) {
4764                         int tot_num_tp;
4765                         tcd->cur_pino=pino;
4766
4767                         /*Get number of tile parts*/
4768                         tot_num_tp = j2k_get_num_tp(cp,pino,tileno);
4769                         tcd->tp_pos = cp->tp_pos;
4770
4771                         for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){
4772                                 j2k->tp_num = tilepartno;
4773                                 /* INDEX >> */
4774                                 if(cstr_info)
4775                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos =
4776                                         cio_tell(cio) + j2k->pos_correction;
4777                                 /* << INDEX */
4778                                 j2k_write_sot(j2k);
4779
4780                                 if(j2k->cur_tp_num == 0 && cp->cinema == 0){
4781                                         for (compno = 1; compno < image->numcomps; compno++) {
4782                                                 j2k_write_coc(j2k, compno);
4783                                                 j2k_write_qcc(j2k, compno);
4784                                         }
4785                                         if (cp->tcps[tileno].numpocs) {
4786                                                 j2k_write_poc(j2k);
4787                                         }
4788                                 }
4789
4790                                 /* INDEX >> */
4791                                 if(cstr_info)
4792                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
4793                                         cio_tell(cio) + j2k->pos_correction + 1;
4794                                 /* << INDEX */
4795
4796                                 j2k_write_sod(j2k, tcd);
4797
4798                                 /* INDEX >> */
4799                                 if(cstr_info) {
4800                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos =
4801                                                 cio_tell(cio) + j2k->pos_correction - 1;
4802                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack =
4803                                                 acc_pack_num;
4804                                         cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks =
4805                                                 cstr_info->packno - acc_pack_num;
4806                                         acc_pack_num = cstr_info->packno;
4807                                 }
4808                                 /* << INDEX */
4809
4810                                 j2k->cur_tp_num++;
4811                         }                       
4812                 }
4813                 if(cstr_info) {
4814                         cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1;
4815                 }
4816
4817
4818                 /*
4819                 if (tile->PPT) { // BAD PPT !!! 
4820                 FILE *PPT_file;
4821                 int i;
4822                 PPT_file=fopen("PPT","rb");
4823                 fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256);
4824                 for (i=0;i<tile->len_ppt;i++) {
4825                 unsigned char elmt;
4826                 fread(&elmt, 1, 1, PPT_file);
4827                 fwrite(&elmt,1,1,f);
4828                 }
4829                 fclose(PPT_file);
4830                 unlink("PPT");
4831                 }
4832                 */
4833
4834         }
4835
4836         /* destroy the tile encoder */
4837         tcd_free_encode(tcd);
4838         tcd_destroy(tcd);
4839
4840         opj_free(j2k->cur_totnum_tp);
4841
4842         j2k_write_eoc(j2k);
4843
4844         if(cstr_info) {
4845                 cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction;
4846                 /* UniPG>> */
4847                 /* The following adjustment is done to adjust the codestream size */
4848                 /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
4849                 /* the first bunch of bytes is not in the codestream              */
4850                 cstr_info->codestream_size -= cstr_info->main_head_start;
4851                 /* <<UniPG */
4852         }
4853
4854 #ifdef USE_JPWL
4855         /*
4856         preparation of JPWL marker segments
4857         */
4858         if(cp->epc_on) {
4859
4860                 /* encode according to JPWL */
4861                 jpwl_encode(j2k, cio, image);
4862
4863         }
4864 #endif /* USE_JPWL */
4865
4866         return OPJ_TRUE;
4867 }
4868
4869 static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
4870
4871         if (!cstr_info)
4872                 return;
4873
4874         /* expand the list? */
4875         if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {
4876                 cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F);
4877                 cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum);
4878         }
4879
4880         /* add the marker */
4881         cstr_info->marker[cstr_info->marknum].type = type;
4882         cstr_info->marker[cstr_info->marknum].pos = pos;
4883         cstr_info->marker[cstr_info->marknum].len = len;
4884         cstr_info->marknum++;
4885
4886 }
4887
4888 static void j2k_add_mhmarker_v2(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_UINT32 pos, OPJ_UINT32 len) {
4889
4890         if (!cstr_index)
4891                 return;
4892
4893         /* expand the list? */
4894         if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
4895                 cstr_index->maxmarknum = 100 + (int) ((float) cstr_index->maxmarknum * 1.0F);
4896                 cstr_index->marker = (opj_marker_info_t*)opj_realloc(cstr_index->marker, cstr_index->maxmarknum *sizeof(opj_marker_info_t));
4897         }
4898
4899         /* add the marker */
4900         cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
4901         cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
4902         cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
4903         cstr_index->marknum++;
4904
4905 }
4906
4907 static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
4908
4909
4910   opj_marker_info_t *marker;
4911
4912         if (!cstr_info)
4913                 return;
4914
4915         /* expand the list? */
4916         if ((cstr_info->tile[tileno].marknum + 1) > cstr_info->tile[tileno].maxmarknum) {
4917                 cstr_info->tile[tileno].maxmarknum = 100 + (int) ((float) cstr_info->tile[tileno].maxmarknum * 1.0F);
4918                 cstr_info->tile[tileno].marker = (opj_marker_info_t*)opj_realloc(cstr_info->tile[tileno].marker, cstr_info->maxmarknum);
4919         }
4920
4921         marker = &(cstr_info->tile[tileno].marker[cstr_info->tile[tileno].marknum]);
4922
4923         /* add the marker */
4924         marker->type = type;
4925         marker->pos = pos;
4926         marker->len = len;
4927         cstr_info->tile[tileno].marknum++;
4928 }
4929
4930
4931
4932
4933 /*
4934  * -----------------------------------------------------------------------
4935  * -----------------------------------------------------------------------
4936  * -----------------------------------------------------------------------
4937  */
4938
4939 /**
4940  * Ends the decompression procedures and possibiliy add data to be read after the
4941  * codestream.
4942  */
4943 opj_bool j2k_end_decompress(
4944                                                 opj_j2k_v2_t *p_j2k,
4945                                                 opj_stream_private_t *p_stream,
4946                                                 opj_event_mgr_t * p_manager)
4947 {
4948         return OPJ_TRUE;
4949 }
4950
4951 /**
4952  * Reads a jpeg2000 codestream header structure.
4953
4954  *
4955  * @param p_stream the stream to read data from.
4956  * @param p_j2k the jpeg2000 codec.
4957  * @param p_manager the user event manager.
4958  *
4959  * @return true if the box is valid.
4960  */
4961 opj_bool j2k_read_header(       struct opj_stream_private *p_stream,
4962                                                         opj_j2k_v2_t* p_j2k,
4963                                                         opj_image_t* p_image,
4964                                                         struct opj_event_mgr* p_manager )
4965 {
4966         /* preconditions */
4967         assert(p_j2k != 00);
4968         assert(p_stream != 00);
4969         assert(p_image != 00);
4970         assert(p_manager != 00);
4971
4972         /* create an empty image header */
4973         p_j2k->m_image = opj_image_create0();
4974         if (! p_j2k->m_image) {
4975                 return OPJ_FALSE;
4976         }
4977
4978         /* customization of the validation */
4979         j2k_setup_decoding_validation(p_j2k);
4980
4981         /* validation of the parameters codec */
4982         if (! j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream,p_manager)) {
4983                 opj_image_destroy(p_j2k->m_image);
4984                 p_j2k->m_image = NULL;
4985                 return OPJ_FALSE;
4986         }
4987
4988         /* customization of the encoding */
4989         j2k_setup_header_reading(p_j2k);
4990
4991         /* read header */
4992         if (! j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
4993                 opj_image_destroy(p_j2k->m_image);
4994                 p_j2k->m_image = NULL;
4995                 return OPJ_FALSE;
4996         }
4997
4998         if (! j2k_copy_img_header(p_j2k, p_image)){
4999                 opj_image_destroy(p_j2k->m_image);
5000                 p_j2k->m_image = NULL;
5001                 return OPJ_FALSE;
5002         }
5003
5004
5005         return OPJ_TRUE;
5006 }
5007
5008 opj_bool j2k_copy_img_header(opj_j2k_v2_t* p_j2k, opj_image_t* p_image)
5009 {
5010         OPJ_UINT16 compno;
5011
5012         /* preconditions */
5013         assert(p_j2k != 00);
5014         assert(p_image != 00);
5015
5016         p_image->x0 = p_j2k->m_image->x0;
5017         p_image->y0 = p_j2k->m_image->y0;
5018         p_image->x1 = p_j2k->m_image->x1;
5019         p_image->y1 = p_j2k->m_image->y1;
5020
5021         p_image->numcomps = p_j2k->m_image->numcomps;
5022         p_image->comps = (opj_image_comp_t*)opj_malloc(p_image->numcomps * sizeof(opj_image_comp_t));
5023         if (!p_image->comps)
5024                 return OPJ_FALSE;
5025         for (compno=0; compno < p_image->numcomps; compno++){
5026                 memcpy( &(p_image->comps[compno]),
5027                                 &(p_j2k->m_image->comps[compno]),
5028                                 sizeof(opj_image_comp_t));
5029         }
5030
5031         p_image->color_space = p_j2k->m_image->color_space;
5032         p_image->icc_profile_len = p_j2k->m_image->icc_profile_len;
5033         if (!p_image->icc_profile_len) {
5034
5035                 p_image->icc_profile_buf = (unsigned char*)opj_malloc(p_image->icc_profile_len);
5036                 if (!p_image->icc_profile_buf)
5037                         return OPJ_FALSE;
5038                 memcpy( p_image->icc_profile_buf,
5039                                 p_j2k->m_image->icc_profile_buf,
5040                                 p_j2k->m_image->icc_profile_len);
5041         }
5042         else
5043                 p_image->icc_profile_buf = NULL;
5044
5045         return OPJ_TRUE;
5046 }
5047
5048
5049
5050 /**
5051  * Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
5052  */
5053 void j2k_setup_header_reading (opj_j2k_v2_t *p_j2k)
5054 {
5055         // preconditions
5056         assert(p_j2k != 00);
5057
5058         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(void*)j2k_read_header_procedure);
5059
5060         /* DEVELOPER CORNER, add your custom procedures */
5061         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(void*)j2k_copy_default_tcp_and_create_tcd);
5062
5063 }
5064
5065 /**
5066  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
5067  * are valid. Developpers wanting to extend the library can add their own validation procedures.
5068  */
5069 void j2k_setup_decoding_validation (opj_j2k_v2_t *p_j2k)
5070 {
5071         // preconditions
5072         assert(p_j2k != 00);
5073
5074         opj_procedure_list_add_procedure(p_j2k->m_validation_list, (void*)j2k_build_decoder);
5075         opj_procedure_list_add_procedure(p_j2k->m_validation_list, (void*)j2k_decoding_validation);
5076         /* DEVELOPER CORNER, add your custom validation procedure */
5077
5078 }
5079
5080 /**
5081  * Builds the cp decoder parameters to use to decode tile.
5082  */
5083 opj_bool j2k_build_decoder (
5084                                                 opj_j2k_v2_t * p_j2k,
5085                                                 opj_stream_private_t *p_stream,
5086                                                 opj_event_mgr_t * p_manager
5087                                                 )
5088 {
5089         // add here initialization of cp
5090         // copy paste of setup_decoder
5091         return OPJ_TRUE;
5092 }
5093
5094 /**
5095  * The default decoding validation procedure without any extension.
5096  *
5097  * @param       p_j2k                   the jpeg2000 codec to validate.
5098  * @param       p_stream                                the input stream to validate.
5099  * @param       p_manager               the user event manager.
5100  *
5101  * @return true if the parameters are correct.
5102  */
5103 opj_bool j2k_decoding_validation (
5104                                                                 opj_j2k_v2_t *p_j2k,
5105                                                                 opj_stream_private_t *p_stream,
5106                                                                 opj_event_mgr_t * p_manager
5107                                                           )
5108 {
5109         opj_bool l_is_valid = OPJ_TRUE;
5110
5111         // preconditions
5112         assert(p_j2k != 00);
5113         assert(p_stream != 00);
5114         assert(p_manager != 00);
5115
5116
5117         /* STATE checking */
5118         /* make sure the state is at 0 */
5119 #ifdef TODO_MSD
5120         l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
5121 #endif
5122         l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
5123
5124         /* POINTER validation */
5125         /* make sure a p_j2k codec is present */
5126         /* make sure a procedure list is present */
5127         l_is_valid &= (p_j2k->m_procedure_list != 00);
5128         /* make sure a validation list is present */
5129         l_is_valid &= (p_j2k->m_validation_list != 00);
5130
5131         /* PARAMETER VALIDATION */
5132         return l_is_valid;
5133 }
5134
5135 opj_bool j2k_read_header_procedure(     opj_j2k_v2_t *p_j2k,
5136                                                                         struct opj_stream_private *p_stream,
5137                                                                         struct opj_event_mgr * p_manager)
5138 {
5139         OPJ_UINT32 l_current_marker;
5140         OPJ_UINT32 l_marker_size;
5141         const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
5142
5143         /* preconditions */
5144         assert(p_stream != 00);
5145         assert(p_j2k != 00);
5146         assert(p_manager != 00);
5147
5148         /*  We enter in the main header */
5149         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
5150
5151         /* Try to read the SOC marker, the codestream must begin with SOC marker */
5152         if (! j2k_read_soc_v2(p_j2k,p_stream,p_manager)) {
5153                 opj_event_msg_v2(p_manager, EVT_ERROR, "Expected a SOC marker \n");
5154                 return OPJ_FALSE;
5155         }
5156
5157         /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
5158         if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5159                 opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5160                 return OPJ_FALSE;
5161         }
5162
5163         /* Read 2 bytes as the new marker ID */
5164         opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
5165
5166         /* Try to read until the SOT is detected */
5167         while (l_current_marker != J2K_MS_SOT) {
5168
5169                 /* Check if the current marker ID is valid */
5170                 if (l_current_marker < 0xff00) {
5171                         opj_event_msg_v2(p_manager, EVT_ERROR, "We expected read a marker ID (0xff--) instead of %.8x\n", l_current_marker);
5172                         return OPJ_FALSE;
5173                 }
5174
5175                 /* Get the marker handler from the marker ID */
5176                 l_marker_handler = j2k_get_marker_handler(l_current_marker);
5177
5178                 /* Manage case where marker is unknown */
5179                 if (l_marker_handler->id == J2K_MS_UNK) {
5180                         if (! j2k_read_unk_v2(p_j2k, p_stream, &l_current_marker, p_manager)){
5181                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Unknow marker have been detected and generated error.\n");
5182                                 return OPJ_FALSE;
5183                         }
5184
5185                         if (l_current_marker == J2K_MS_SOT)
5186                                 break; /* SOT marker is detected main header is completely read */
5187                         else    /* Get the marker handler from the marker ID */
5188                                 l_marker_handler = j2k_get_marker_handler(l_current_marker);
5189                 }
5190
5191                 /* Check if the marker is known and if it is the right place to find it */
5192                 if (! (p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states) ) {
5193                         opj_event_msg_v2(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
5194                         return OPJ_FALSE;
5195                 }
5196
5197                 /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
5198                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5199                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5200                         return OPJ_FALSE;
5201                 }
5202
5203                 /* read 2 bytes as the marker size */
5204                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_marker_size,2);
5205                 l_marker_size -= 2; // Subtract the size of the marker ID already read
5206
5207                 /* Check if the marker size is compatible with the header data size */
5208                 if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
5209                         p_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE*)
5210                                         opj_realloc(p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size);
5211                         if (p_j2k->m_specific_param.m_decoder.m_header_data == 00) {
5212                                 return OPJ_FALSE;
5213                         }
5214                         p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
5215                 }
5216
5217                 /* Try to read the rest of the marker segment from stream and copy them into the buffer */
5218                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager) != l_marker_size) {
5219                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5220                         return OPJ_FALSE;
5221                 }
5222
5223                 /* Read the marker segment with the correct marker handler */
5224                 if (! (*(l_marker_handler->handler))(p_j2k,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager)) {
5225                         opj_event_msg_v2(p_manager, EVT_ERROR, "Marker handler function failed to read the marker segment\n");
5226                         return OPJ_FALSE;
5227                 }
5228
5229                 /* Add the marker to the codestream index*/
5230                 j2k_add_mhmarker_v2(p_j2k->cstr_index,
5231                                                         l_marker_handler->id,
5232                                                         (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
5233                                                         l_marker_size + 4 );
5234
5235                 /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
5236                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5237                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5238                         return OPJ_FALSE;
5239                 }
5240
5241                 /* read 2 bytes as the new marker ID */
5242                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
5243         }
5244
5245         opj_event_msg_v2(p_manager, EVT_INFO, "Main header has been correctly decode.\n");
5246
5247         /* Position of the last element if the main header */
5248         p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
5249
5250         /* Next step: read a tile-part header */
5251         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
5252
5253         return OPJ_TRUE;
5254 }
5255
5256 /**
5257  * Excutes the given procedures on the given codec.
5258  *
5259  * @param       p_procedure_list        the list of procedures to execute
5260  * @param       p_j2k                                   the jpeg2000 codec to execute the procedures on.
5261  * @param       p_stream                                        the stream to execute the procedures on.
5262  * @param       p_manager                       the user manager.
5263  *
5264  * @return      true                            if all the procedures were successfully executed.
5265  */
5266 opj_bool j2k_exec (     opj_j2k_v2_t * p_j2k,
5267                                         opj_procedure_list_t * p_procedure_list,
5268                                         opj_stream_private_t *p_stream,
5269                                         opj_event_mgr_t * p_manager )
5270 {
5271         opj_bool (** l_procedure) (opj_j2k_v2_t * ,opj_stream_private_t *,opj_event_mgr_t *) = 00;
5272         opj_bool l_result = OPJ_TRUE;
5273         OPJ_UINT32 l_nb_proc, i;
5274
5275         // preconditions
5276         assert(p_procedure_list != 00);
5277         assert(p_j2k != 00);
5278         assert(p_stream != 00);
5279         assert(p_manager != 00);
5280
5281
5282         l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
5283         l_procedure = (opj_bool (**) (opj_j2k_v2_t * ,opj_stream_private_t *,opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
5284
5285         for     (i=0;i<l_nb_proc;++i) {
5286                 l_result = l_result && ((*l_procedure) (p_j2k,p_stream,p_manager));
5287                 ++l_procedure;
5288         }
5289
5290         // and clear the procedure list at the end.
5291         opj_procedure_list_clear(p_procedure_list);
5292         return l_result;
5293 }
5294
5295 /* FIXME DOC*/
5296 opj_bool j2k_copy_default_tcp_and_create_tcd
5297                                                 (
5298                                                 opj_j2k_v2_t * p_j2k,
5299                                                 opj_stream_private_t *p_stream,
5300                                                 opj_event_mgr_t * p_manager
5301                                                 )
5302 {
5303         opj_tcp_v2_t * l_tcp = 00;
5304         opj_tcp_v2_t * l_default_tcp = 00;
5305         OPJ_UINT32 l_nb_tiles;
5306         OPJ_UINT32 i,j;
5307         opj_tccp_t *l_current_tccp = 00;
5308         OPJ_UINT32 l_tccp_size;
5309         OPJ_UINT32 l_mct_size;
5310         opj_image_t * l_image;
5311         OPJ_UINT32 l_mcc_records_size,l_mct_records_size;
5312         opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
5313         opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
5314         OPJ_UINT32 l_offset;
5315
5316         /* preconditions */
5317         assert(p_j2k != 00);
5318         assert(p_stream != 00);
5319         assert(p_manager != 00);
5320
5321         l_image = p_j2k->m_image;
5322         l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
5323         l_tcp = p_j2k->m_cp.tcps;
5324         l_tccp_size = l_image->numcomps * sizeof(opj_tccp_t);
5325         l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
5326         l_mct_size = l_image->numcomps * l_image->numcomps * sizeof(OPJ_FLOAT32);
5327
5328         /* For each tile */
5329         for (i=0; i<l_nb_tiles; ++i) {
5330                 /* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
5331                 l_current_tccp = l_tcp->tccps;
5332                 /*Copy default coding parameters into the current tile coding parameters*/
5333                 memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_v2_t));
5334                 /* Initialize some values of the current tile coding parameters*/
5335                 l_tcp->ppt = 0;
5336                 l_tcp->ppt_data = 00;
5337                 /* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
5338                 l_tcp->tccps = l_current_tccp;
5339
5340                 /* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
5341                 if (l_default_tcp->m_mct_decoding_matrix) {
5342                         l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
5343                         if (! l_tcp->m_mct_decoding_matrix ) {
5344                                 return OPJ_FALSE;
5345                         }
5346                         memcpy(l_tcp->m_mct_decoding_matrix,l_default_tcp->m_mct_decoding_matrix,l_mct_size);
5347                 }
5348
5349                 /* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
5350                 l_mct_records_size = l_default_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t);
5351                 l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
5352                 if (! l_tcp->m_mct_records) {
5353                         return OPJ_FALSE;
5354                 }
5355                 memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records,l_mct_records_size);
5356
5357                 /* Copy the mct record data from dflt_tile_cp to the current tile*/
5358                 l_src_mct_rec = l_default_tcp->m_mct_records;
5359                 l_dest_mct_rec = l_tcp->m_mct_records;
5360
5361                 for (j=0;j<l_default_tcp->m_nb_mct_records;++j) {
5362
5363                         if (l_src_mct_rec->m_data) {
5364
5365                                 l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
5366                                 if(! l_dest_mct_rec->m_data) {
5367                                         return OPJ_FALSE;
5368                                 }
5369                                 memcpy(l_dest_mct_rec->m_data,l_src_mct_rec->m_data,l_src_mct_rec->m_data_size);
5370                         }
5371
5372                         ++l_src_mct_rec;
5373                         ++l_dest_mct_rec;
5374                 }
5375
5376                 /* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
5377                 l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * sizeof(opj_simple_mcc_decorrelation_data_t);
5378                 l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(l_mcc_records_size);
5379                 if (! l_tcp->m_mcc_records) {
5380                         return OPJ_FALSE;
5381                 }
5382                 memcpy(l_tcp->m_mcc_records,l_default_tcp->m_mcc_records,l_mcc_records_size);
5383
5384                 /* Copy the mcc record data from dflt_tile_cp to the current tile*/
5385                 l_src_mcc_rec = l_default_tcp->m_mcc_records;
5386                 l_dest_mcc_rec = l_tcp->m_mcc_records;
5387
5388                 for (j=0;j<l_default_tcp->m_nb_max_mcc_records;++j) {
5389
5390                         if (l_src_mcc_rec->m_decorrelation_array) {
5391                                 l_offset = l_src_mcc_rec->m_decorrelation_array - l_default_tcp->m_mct_records;
5392                                 l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
5393                         }
5394
5395                         if (l_src_mcc_rec->m_offset_array) {
5396                                 l_offset = l_src_mcc_rec->m_offset_array - l_default_tcp->m_mct_records;
5397                                 l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
5398                         }
5399
5400                         ++l_src_mcc_rec;
5401                         ++l_dest_mcc_rec;
5402                 }
5403
5404                 /* Copy all the dflt_tile_compo_cp to the current tile cp */
5405                 memcpy(l_current_tccp,l_default_tcp->tccps,l_tccp_size);
5406
5407                 /* Move to next tile cp*/
5408                 ++l_tcp;
5409         }
5410
5411         /* Create the current tile decoder*/
5412         p_j2k->m_tcd = (opj_tcd_v2_t*)tcd_create_v2(OPJ_TRUE); // FIXME why a cast ?
5413         if (! p_j2k->m_tcd ) {
5414                 return OPJ_FALSE;
5415         }
5416
5417         if ( !tcd_init_v2(p_j2k->m_tcd, l_image, &(p_j2k->m_cp)) ) {
5418                 tcd_destroy_v2(p_j2k->m_tcd);
5419                 p_j2k->m_tcd = 00;
5420                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
5421                 return OPJ_FALSE;
5422         }
5423
5424         return OPJ_TRUE;
5425 }
5426
5427 /**
5428  * Reads the lookup table containing all the marker, status and action, and returns the handler associated
5429  * with the marker value.
5430  * @param       p_id            Marker value to look up
5431  *
5432  * @return      the handler associated with the id.
5433 */
5434 const opj_dec_memory_marker_handler_t * j2k_get_marker_handler (const OPJ_UINT32 p_id)
5435 {
5436         const opj_dec_memory_marker_handler_t *e;
5437         for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
5438                 if (e->id == p_id) {
5439                         break; // we find a handler corresponding to the marker ID
5440                 }
5441         }
5442         return e;
5443 }
5444
5445
5446 /**
5447  * Destroys a jpeg2000 codec.
5448  *
5449  * @param       p_j2k   the jpeg20000 structure to destroy.
5450  */
5451 void j2k_destroy (opj_j2k_v2_t *p_j2k)
5452 {
5453         if (p_j2k == 00) {
5454                 return;
5455         }
5456
5457         if (p_j2k->m_is_decoder) {
5458
5459                 if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
5460                         j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
5461                         opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
5462                         p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
5463                 }
5464
5465                 if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
5466                         opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
5467                         p_j2k->m_specific_param.m_decoder.m_header_data = 00;
5468                         p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
5469                 }
5470         }
5471         else {
5472
5473                 if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
5474                         opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
5475                         p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
5476                 }
5477
5478                 if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
5479                         opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
5480                         p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
5481                         p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
5482                 }
5483
5484                 if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
5485                         opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
5486                         p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
5487                         p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
5488                 }
5489         }
5490
5491         tcd_destroy_v2(p_j2k->m_tcd);
5492
5493         j2k_cp_destroy(&(p_j2k->m_cp));
5494         memset(&(p_j2k->m_cp),0,sizeof(opj_cp_t));
5495
5496         opj_procedure_list_destroy(p_j2k->m_procedure_list);
5497         p_j2k->m_procedure_list = 00;
5498
5499         opj_procedure_list_destroy(p_j2k->m_validation_list);
5500         p_j2k->m_procedure_list = 00;
5501
5502         j2k_destroy_cstr_index(p_j2k->cstr_index);
5503         p_j2k->cstr_index = NULL;
5504
5505         opj_free(p_j2k);
5506 }
5507
5508 void j2k_destroy_cstr_index (opj_codestream_index_t *p_cstr_ind)
5509 {
5510         if (!p_cstr_ind) {
5511                 return;
5512         }
5513
5514         if (p_cstr_ind->marker) {
5515                 opj_free(p_cstr_ind->marker);
5516                 p_cstr_ind->marker = NULL;
5517         }
5518
5519         if (p_cstr_ind->tile_index) {
5520                 // FIXME
5521         }
5522 }
5523
5524
5525
5526 /**
5527  * Destroys a tile coding parameter structure.
5528  *
5529  * @param       p_tcp           the tile coding parameter to destroy.
5530  */
5531 void j2k_tcp_destroy (opj_tcp_v2_t *p_tcp)
5532 {
5533         if (p_tcp == 00) {
5534                 return;
5535         }
5536
5537         if (p_tcp->ppt_buffer != 00) {
5538                 opj_free(p_tcp->ppt_buffer);
5539                 p_tcp->ppt_buffer = 00;
5540         }
5541
5542         if (p_tcp->tccps != 00) {
5543                 opj_free(p_tcp->tccps);
5544                 p_tcp->tccps = 00;
5545         }
5546
5547         if (p_tcp->m_mct_coding_matrix != 00) {
5548                 opj_free(p_tcp->m_mct_coding_matrix);
5549                 p_tcp->m_mct_coding_matrix = 00;
5550         }
5551
5552         if (p_tcp->m_mct_decoding_matrix != 00) {
5553                 opj_free(p_tcp->m_mct_decoding_matrix);
5554                 p_tcp->m_mct_decoding_matrix = 00;
5555         }
5556
5557         if (p_tcp->m_mcc_records) {
5558                 opj_free(p_tcp->m_mcc_records);
5559                 p_tcp->m_mcc_records = 00;
5560                 p_tcp->m_nb_max_mcc_records = 0;
5561                 p_tcp->m_nb_mcc_records = 0;
5562         }
5563
5564         if (p_tcp->m_mct_records) {
5565                 opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
5566                 OPJ_UINT32 i;
5567
5568                 for (i=0;i<p_tcp->m_nb_mct_records;++i) {
5569                         if (l_mct_data->m_data) {
5570                                 opj_free(l_mct_data->m_data);
5571                                 l_mct_data->m_data = 00;
5572                         }
5573
5574                         ++l_mct_data;
5575                 }
5576
5577                 opj_free(p_tcp->m_mct_records);
5578                 p_tcp->m_mct_records = 00;
5579         }
5580
5581         if (p_tcp->mct_norms != 00) {
5582                 opj_free(p_tcp->mct_norms);
5583                 p_tcp->mct_norms = 00;
5584         }
5585
5586         if (p_tcp->m_data) {
5587                 opj_free(p_tcp->m_data);
5588                 p_tcp->m_data = 00;
5589         }
5590 }
5591
5592
5593 /**
5594  * Destroys a coding parameter structure.
5595  *
5596  * @param       p_cp            the coding parameter to destroy.
5597  */
5598 void j2k_cp_destroy (opj_cp_v2_t *p_cp)
5599 {
5600         OPJ_UINT32 l_nb_tiles;
5601         opj_tcp_v2_t * l_current_tile = 00;
5602         OPJ_UINT32 i;
5603
5604         if
5605                 (p_cp == 00)
5606         {
5607                 return;
5608         }
5609         if
5610                 (p_cp->tcps != 00)
5611         {
5612                 l_current_tile = p_cp->tcps;
5613                 l_nb_tiles = p_cp->th * p_cp->tw;
5614
5615                 for
5616                         (i = 0; i < l_nb_tiles; ++i)
5617                 {
5618                         j2k_tcp_destroy(l_current_tile);
5619                         ++l_current_tile;
5620                 }
5621                 opj_free(p_cp->tcps);
5622                 p_cp->tcps = 00;
5623         }
5624         if
5625                 (p_cp->ppm_buffer != 00)
5626         {
5627                 opj_free(p_cp->ppm_buffer);
5628                 p_cp->ppm_buffer = 00;
5629         }
5630         if
5631                 (p_cp->comment != 00)
5632         {
5633                 opj_free(p_cp->comment);
5634                 p_cp->comment = 00;
5635         }
5636         if
5637                 (! p_cp->m_is_decoder)
5638         {
5639                 if
5640                         (p_cp->m_specific_param.m_enc.m_matrice)
5641                 {
5642                         opj_free(p_cp->m_specific_param.m_enc.m_matrice);
5643                         p_cp->m_specific_param.m_enc.m_matrice = 00;
5644                 }
5645         }
5646 }
5647
5648
5649
5650 /**
5651  * Reads a tile header.
5652  * @param       p_j2k           the jpeg2000 codec.
5653  * @param       p_stream                        the stream to write data to.
5654  * @param       p_manager       the user event manager.
5655  */
5656 opj_bool j2k_read_tile_header(  opj_j2k_v2_t * p_j2k,
5657                                                                 OPJ_UINT32 * p_tile_index,
5658                                                                 OPJ_UINT32 * p_data_size,
5659                                                                 OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
5660                                                                 OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
5661                                                                 OPJ_UINT32 * p_nb_comps,
5662                                                                 opj_bool * p_go_on,
5663                                                                 opj_stream_private_t *p_stream,
5664                                                                 opj_event_mgr_t * p_manager )
5665 {
5666         OPJ_UINT32 l_current_marker = J2K_MS_SOT;
5667         OPJ_UINT32 l_marker_size;
5668         const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
5669         opj_tcp_v2_t * l_tcp = NULL;
5670         OPJ_UINT32 l_nb_tiles;
5671
5672         /* preconditions */
5673         assert(p_stream != 00);
5674         assert(p_j2k != 00);
5675         assert(p_manager != 00);
5676
5677         /* Reach the End Of Codestream ?*/
5678         if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC){
5679                 l_current_marker = J2K_MS_EOC;
5680         }
5681         /* We need to encounter a SOT marker (a new tile-part header) */
5682         else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT){
5683                 return OPJ_FALSE;
5684         }
5685
5686         /* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
5687         while ( (!p_j2k->m_specific_param.m_decoder.m_can_decode) && (l_current_marker != J2K_MS_EOC) ) {
5688
5689                 /* Try to read until the Start Of Data is detected */
5690                 while (l_current_marker != J2K_MS_SOD) {
5691
5692                         /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
5693                         if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5694                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5695                                 return OPJ_FALSE;
5696                         }
5697
5698                         /* Read 2 bytes from the buffer as the marker size */
5699                         opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_marker_size,2);
5700
5701                         /* Why this condition? FIXME */
5702                         if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH){
5703                                 p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
5704                         }
5705                         l_marker_size -= 2; /* Subtract the size of the marker ID already read */
5706
5707                         /* Get the marker handler from the marker ID */
5708                         l_marker_handler = j2k_get_marker_handler(l_current_marker);
5709
5710                         /* Check if the marker is known and if it is the right place to find it */
5711                         if (! (p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states) ) {
5712                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
5713                                 return OPJ_FALSE;
5714                         }
5715 /* FIXME manage case of unknown marker as in the main header ? */
5716
5717                         /* Check if the marker size is compatible with the header data size */
5718                         if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
5719                                 p_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE*)
5720                                         opj_realloc(p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size);
5721                                 if (p_j2k->m_specific_param.m_decoder.m_header_data == 00) {
5722                                         return OPJ_FALSE;
5723                                 }
5724                                 p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
5725                         }
5726
5727                         /* Try to read the rest of the marker segment from stream and copy them into the buffer */
5728                         if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager) != l_marker_size) {
5729                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5730                                 return OPJ_FALSE;
5731                         }
5732
5733                         /* Read the marker segment with the correct marker handler */
5734                         if (! (*(l_marker_handler->handler))(p_j2k,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager)) {
5735                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Fail to read the current marker segment (%#x)\n", l_current_marker);
5736                                 return OPJ_FALSE;
5737                         }
5738
5739                         if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
5740                                 /* Skip the rest of the tile part header*/
5741                                 if (opj_stream_skip(p_stream,p_j2k->m_specific_param.m_decoder.m_sot_length,p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
5742                                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5743                                         return OPJ_FALSE;
5744                                 }
5745                                 l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
5746                         }
5747                         else {
5748                                 /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
5749                                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5750                                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5751                                         return OPJ_FALSE;
5752                                 }
5753                                 /* Read 2 bytes from the buffer as the new marker ID */
5754                                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
5755                         }
5756                 }
5757
5758                 /* If we didn't skip data before, we need to read the SOD marker*/
5759                 if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
5760                         /* Try to read the SOD marker and skip data ? FIXME */
5761                         if (! j2k_read_sod_v2(p_j2k, p_stream, p_manager)) {
5762                                 return OPJ_FALSE;
5763                         }
5764
5765                         if (! p_j2k->m_specific_param.m_decoder.m_can_decode){
5766                                 /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
5767                                 if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5768                                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5769                                         return OPJ_FALSE;
5770                                 }
5771
5772                                 /* Read 2 bytes from buffer as the new marker ID */
5773                                 opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
5774                         }
5775                 }
5776                 else {
5777                         /* Indicate we will try to read a new tile-part header*/
5778                         p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
5779                         p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
5780                         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
5781
5782                         /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
5783                         if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
5784                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5785                                 return OPJ_FALSE;
5786                         }
5787
5788                         /* Read 2 bytes from buffer as the new marker ID */
5789                         opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
5790                 }
5791         }
5792
5793         /* Current marker is the EOC marker ?*/
5794         if (l_current_marker == J2K_MS_EOC) {
5795                 if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC ){
5796                         p_j2k->m_current_tile_number = 0;
5797                         p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
5798                 }
5799         }
5800
5801         /* FIXME DOC ???*/
5802         if ( ! p_j2k->m_specific_param.m_decoder.m_can_decode) {
5803                 l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
5804                 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
5805
5806                 while( (p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00) ) {
5807                         ++p_j2k->m_current_tile_number;
5808                         ++l_tcp;
5809                 }
5810
5811                 if (p_j2k->m_current_tile_number == l_nb_tiles) {
5812                         *p_go_on = OPJ_FALSE;
5813                         return OPJ_TRUE;
5814                 }
5815         }
5816
5817         /*FIXME ???*/
5818         if (! tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number)) {
5819                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
5820                 return OPJ_FALSE;
5821         }
5822
5823         opj_event_msg_v2(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
5824                         p_j2k->m_current_tile_number +1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
5825
5826         *p_tile_index = p_j2k->m_current_tile_number;
5827         *p_go_on = OPJ_TRUE;
5828         *p_data_size = tcd_get_decoded_tile_size(p_j2k->m_tcd);
5829         *p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
5830         *p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
5831         *p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
5832         *p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
5833         *p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
5834
5835          p_j2k->m_specific_param.m_decoder.m_state |= 0x0080;// FIXME J2K_DEC_STATE_DATA;
5836
5837         return OPJ_TRUE;
5838 }
5839
5840
5841 opj_bool j2k_decode_tile (      opj_j2k_v2_t * p_j2k,
5842                                                         OPJ_UINT32 p_tile_index,
5843                                                         OPJ_BYTE * p_data,
5844                                                         OPJ_UINT32 p_data_size,
5845                                                         opj_stream_private_t *p_stream,
5846                                                         opj_event_mgr_t * p_manager )
5847 {
5848         OPJ_UINT32 l_current_marker;
5849         OPJ_BYTE l_data [2];
5850         opj_tcp_v2_t * l_tcp;
5851
5852         /* preconditions */
5853         assert(p_stream != 00);
5854         assert(p_j2k != 00);
5855         assert(p_manager != 00);
5856
5857         if ( !(p_j2k->m_specific_param.m_decoder.m_state & 0x0080/*FIXME J2K_DEC_STATE_DATA*/)
5858                 || (p_tile_index != p_j2k->m_current_tile_number) ) {
5859                 return OPJ_FALSE;
5860         }
5861
5862         l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
5863         if (! l_tcp->m_data) {
5864                 j2k_tcp_destroy(&(p_j2k->m_cp.tcps[p_tile_index]));
5865                 return OPJ_FALSE;
5866         }
5867
5868         if (! tcd_decode_tile_v2(       p_j2k->m_tcd,
5869                                                                 l_tcp->m_data,
5870                                                                 l_tcp->m_data_size,
5871                                                                 p_tile_index,
5872                                                                 p_j2k->cstr_index) ) {
5873                 j2k_tcp_destroy(l_tcp);
5874                 p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;//FIXME J2K_DEC_STATE_ERR;
5875                 return OPJ_FALSE;
5876         }
5877
5878         if (! tcd_update_tile_data(p_j2k->m_tcd,p_data,p_data_size)) {
5879                 return OPJ_FALSE;
5880         }
5881
5882         j2k_tcp_destroy(l_tcp);
5883         p_j2k->m_tcd->tcp = 0;
5884
5885         p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
5886         p_j2k->m_specific_param.m_decoder.m_state &= (~ (0x0080));// FIXME J2K_DEC_STATE_DATA);
5887
5888         if (p_j2k->m_specific_param.m_decoder.m_state != 0x0100){ //FIXME J2K_DEC_STATE_EOC)
5889                 if (opj_stream_read_data(p_stream,l_data,2,p_manager) != 2) {
5890                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short\n");
5891                         return OPJ_FALSE;
5892                 }
5893
5894                 opj_read_bytes(l_data,&l_current_marker,2);
5895
5896                 if (l_current_marker == J2K_MS_EOC) {
5897                         p_j2k->m_current_tile_number = 0;
5898                         p_j2k->m_specific_param.m_decoder.m_state =  0x0100;//FIXME J2K_DEC_STATE_EOC;
5899                 }
5900                 else if (l_current_marker != J2K_MS_SOT)
5901                 {
5902                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
5903                         return OPJ_FALSE;
5904                 }
5905         }
5906
5907         return OPJ_TRUE;
5908 }
5909
5910
5911 opj_bool j2k_update_image_data (opj_tcd_v2_t * p_tcd, OPJ_BYTE * p_data)
5912 {
5913         OPJ_UINT32 i,j,k = 0;
5914         OPJ_UINT32 l_width,l_height,l_offset_x,l_offset_y;
5915         opj_image_comp_t * l_img_comp = 00;
5916         opj_tcd_tilecomp_v2_t * l_tilec = 00;
5917         opj_image_t * l_image = 00;
5918         OPJ_UINT32 l_size_comp, l_remaining;
5919         OPJ_UINT32 l_dest_stride;
5920         OPJ_INT32 * l_dest_ptr;
5921         opj_tcd_resolution_v2_t* l_res= 00;
5922
5923
5924         l_tilec = p_tcd->tcd_image->tiles->comps;
5925         l_image = p_tcd->image;
5926         l_img_comp = l_image->comps;
5927
5928         for (i=0;i<p_tcd->image->numcomps;++i) {
5929
5930                 if (!l_img_comp->data) {
5931
5932                         l_img_comp->data = (OPJ_INT32*) opj_malloc(l_img_comp->w * l_img_comp->h * sizeof(OPJ_INT32));
5933                         if (! l_img_comp->data) {
5934                                 return OPJ_FALSE;
5935                         }
5936                         memset(l_img_comp->data,0,l_img_comp->w * l_img_comp->h * sizeof(OPJ_INT32));
5937                 }
5938
5939                 l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
5940                 l_remaining = l_img_comp->prec & 7;  /* (%8) */
5941                 l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
5942
5943                 if (l_remaining) {
5944                         ++l_size_comp;
5945                 }
5946
5947                 if (l_size_comp == 3) {
5948                         l_size_comp = 4;
5949                 }
5950
5951                 l_width = (l_res->x1 - l_res->x0);
5952                 l_height = (l_res->y1 - l_res->y0);
5953
5954                 l_dest_stride = (l_img_comp->w) - l_width;
5955
5956                 l_offset_x = int_ceildivpow2(l_img_comp->x0, l_img_comp->factor);
5957                 l_offset_y = int_ceildivpow2(l_img_comp->y0, l_img_comp->factor);
5958                 l_dest_ptr = l_img_comp->data + (l_res->x0 - l_offset_x) + (l_res->y0 - l_offset_y) * l_img_comp->w;
5959
5960                 switch (l_size_comp) {
5961                         case 1:
5962                                 {
5963                                         OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
5964                                         if (l_img_comp->sgnd) {
5965                                                 for (j=0;j<l_height;++j) {
5966                                                         for (k=0;k<l_width;++k) {
5967                                                                 *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
5968                                                         }
5969
5970                                                         l_dest_ptr += l_dest_stride;
5971                                                 }
5972                                         }
5973                                         else {
5974                                                 for (j=0;j<l_height;++j) {
5975                                                         for (k=0;k<l_width;++k) {
5976                                                                 *(l_dest_ptr++) = (OPJ_INT32) ((*(l_src_ptr++))&0xff);
5977                                                         }
5978
5979                                                         l_dest_ptr += l_dest_stride;
5980                                                 }
5981                                         }
5982
5983                                         p_data = (OPJ_BYTE*) l_src_ptr;
5984                                 }
5985                                 break;
5986                         case 2:
5987                                 {
5988                                         OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
5989
5990                                         if (l_img_comp->sgnd) {
5991                                                 for (j=0;j<l_height;++j) {
5992                                                         for (k=0;k<l_width;++k) {
5993                                                                 *(l_dest_ptr++) = *(l_src_ptr++);
5994                                                         }
5995
5996                                                         l_dest_ptr += l_dest_stride;
5997                                                 }
5998                                         }
5999                                         else {
6000                                                 for (j=0;j<l_height;++j) {
6001                                                         for (k=0;k<l_width;++k) {
6002                                                                 *(l_dest_ptr++) = (*(l_src_ptr++))&0xffff;
6003                                                         }
6004
6005                                                         l_dest_ptr += l_dest_stride;
6006                                                 }
6007                                         }
6008
6009                                         p_data = (OPJ_BYTE*) l_src_ptr;
6010                                 }
6011                                 break;
6012                         case 4:
6013                                 {
6014                                         OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
6015                                         for (j=0;j<l_height;++j) {
6016                                                 for (k=0;k<l_width;++k) {
6017                                                         *(l_dest_ptr++) = (*(l_src_ptr++));
6018                                                 }
6019
6020                                                 l_dest_ptr += l_dest_stride;
6021                                         }
6022
6023                                         p_data = (OPJ_BYTE*) l_src_ptr;
6024                                 }
6025                                 break;
6026                 }
6027
6028                 ++l_img_comp;
6029                 ++l_tilec;
6030         }
6031         return OPJ_TRUE;
6032 }
6033
6034 /**
6035  * Sets the given area to be decoded. This function should be called right after opj_read_header and before any tile header reading.
6036  *
6037  * @param       p_j2k                   the jpeg2000 codec.
6038  * @param       p_start_x               the left position of the rectangle to decode (in image coordinates).
6039  * @param       p_end_x                 the right position of the rectangle to decode (in image coordinates).
6040  * @param       p_start_y               the up position of the rectangle to decode (in image coordinates).
6041  * @param       p_end_y                 the bottom position of the rectangle to decode (in image coordinates).
6042  * @param       p_manager               the user event manager
6043  *
6044  * @return      true                    if the area could be set.
6045  */
6046 opj_bool j2k_set_decode_area(   opj_j2k_v2_t *p_j2k,
6047                                                                 OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
6048                                                                 OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
6049                                                                 struct opj_event_mgr * p_manager )
6050 {
6051         opj_cp_v2_t * l_cp = &(p_j2k->m_cp);
6052
6053         /* Check if we are read the main header */
6054         if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { // FIXME J2K_DEC_STATE_TPHSOT)
6055                 opj_event_msg_v2(p_manager, EVT_ERROR, "Need to decode the main header before begin to decode the remaining codestream");
6056                 return OPJ_FALSE;
6057         }
6058
6059         /* ----- */
6060         /* Check if the positions provided by the user are correct */
6061
6062         /* Left */
6063         if (p_start_x > l_cp->tx0 + l_cp->tw * l_cp->tdx) {
6064                 opj_event_msg_v2(p_manager, EVT_ERROR,
6065                         "Left position of the decoded area (ROI_x0=%d) is outside the tile area (XTOsiz + nb_tw x XTsiz=%d).\n",
6066                         p_start_x, l_cp->tx0 + l_cp->tw * l_cp->tdx);
6067                 return OPJ_FALSE;
6068         }
6069         else if (p_start_x < l_cp->tx0){
6070                 opj_event_msg_v2(p_manager, EVT_WARNING,
6071                                 "Left position of the decoded area (ROI_x0=%d) is outside the tile area (XTOsiz=%d).\n",
6072                                 p_start_x, l_cp->tx0);
6073                 p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
6074         }
6075         else
6076                 p_j2k->m_specific_param.m_decoder.m_start_tile_x = (p_start_x - l_cp->tx0) / l_cp->tdx;
6077
6078         /* Up */
6079         if (p_start_y > l_cp->ty0 + l_cp->th * l_cp->tdy){
6080                 opj_event_msg_v2(p_manager, EVT_ERROR,
6081                                 "Up position of the decoded area (ROI_y0=%d) is outside the tile area (YTOsiz + nb_th x YTsiz=%d).\n",
6082                                 p_start_y, l_cp->ty0 + l_cp->th * l_cp->tdy);
6083                 return OPJ_FALSE;
6084         }
6085         else if (p_start_y < l_cp->ty0){
6086                 opj_event_msg_v2(p_manager, EVT_WARNING,
6087                                 "Up position of the decoded area (ROI_y0=%d) is outside the tile area (YTOsiz=%d).\n",
6088                                 p_start_y, l_cp->ty0);
6089                 p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
6090         }
6091         else
6092                 p_j2k->m_specific_param.m_decoder.m_start_tile_y = (p_start_y - l_cp->ty0) / l_cp->tdy;
6093
6094         /* Right */
6095         if (p_end_x < l_cp->tx0) {
6096                 opj_event_msg_v2(p_manager, EVT_ERROR,
6097                         "Right position of the decoded area (ROI_x1=%d) is outside the tile area (XTOsiz=%d).\n",
6098                         p_end_x, l_cp->tx0);
6099                 return OPJ_FALSE;
6100         }
6101         else if (p_end_x > l_cp->tx0 + l_cp->tw * l_cp->tdx) {
6102                 opj_event_msg_v2(p_manager, EVT_WARNING,
6103                         "Right position of the decoded area (ROI_x1=%d) is outside the tile area (XTOsiz + nb_tw x XTsiz=%d).\n",
6104                         p_end_x, l_cp->tx0 + l_cp->tw * l_cp->tdx);
6105                 p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; // FIXME (-1) ???
6106         }
6107         else
6108                 p_j2k->m_specific_param.m_decoder.m_end_tile_x = int_ceildiv((p_end_x - l_cp->tx0), l_cp->tdx);
6109
6110         /* Bottom */
6111         if (p_end_y < l_cp->ty0) {
6112                 opj_event_msg_v2(p_manager, EVT_ERROR,
6113                         "Right position of the decoded area (ROI_y1=%d) is outside the tile area (YTOsiz=%d).\n",
6114                         p_end_y, l_cp->ty0);
6115                 return OPJ_FALSE;
6116         }
6117         if (p_end_y > l_cp->ty0 + l_cp->th * l_cp->tdy){
6118                 opj_event_msg_v2(p_manager, EVT_WARNING,
6119                         "Bottom position of the decoded area (ROI_y1=%d) is outside the tile area (YTOsiz + nb_th x YTsiz=%d).\n",
6120                         p_end_y, l_cp->ty0 + l_cp->th * l_cp->tdy);
6121                 p_j2k->m_specific_param.m_decoder.m_start_tile_y = l_cp->th; // FIXME (-1) ???
6122         }
6123         else
6124                 p_j2k->m_specific_param.m_decoder.m_end_tile_y = int_ceildiv((p_end_y - l_cp->ty0), l_cp->tdy);
6125         /* ----- */
6126
6127         p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
6128
6129         return OPJ_TRUE;
6130 }
6131
6132
6133 /* ----------------------------------------------------------------------- */
6134 /* J2K / JPT decoder interface                                             */
6135 /* ----------------------------------------------------------------------- */
6136 /**
6137  * Creates a J2K decompression structure.
6138  *
6139  * @return a handle to a J2K decompressor if successful, NULL otherwise.
6140 */
6141 opj_j2k_v2_t* j2k_create_decompress_v2()
6142 {
6143         opj_j2k_v2_t *l_j2k = (opj_j2k_v2_t*) opj_malloc(sizeof(opj_j2k_v2_t));
6144         if (!l_j2k) {
6145                 return 00;
6146         }
6147         memset(l_j2k,0,sizeof(opj_j2k_v2_t));
6148
6149         l_j2k->m_is_decoder = 1;
6150         l_j2k->m_cp.m_is_decoder = 1;
6151
6152         l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_v2_t*) opj_malloc(sizeof(opj_tcp_v2_t));
6153         if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
6154                 j2k_destroy(l_j2k);
6155                 return 00;
6156         }
6157         memset(l_j2k->m_specific_param.m_decoder.m_default_tcp,0,sizeof(opj_tcp_v2_t));
6158
6159         l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_malloc(J2K_DEFAULT_HEADER_SIZE);
6160         if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
6161                 j2k_destroy(l_j2k);
6162                 return 00;
6163         }
6164
6165         l_j2k->m_specific_param.m_decoder.m_header_data_size = J2K_DEFAULT_HEADER_SIZE;
6166
6167         /* codestream index creation */
6168         l_j2k->cstr_index = j2k_create_cstr_index();
6169
6170                         /*(opj_codestream_index_t*) opj_malloc(sizeof(opj_codestream_index_t));
6171         if (!l_j2k->cstr_index){
6172                 j2k_destroy(l_j2k);
6173                 return NULL;
6174         }
6175
6176         l_j2k->cstr_index->marker = (opj_marker_info_t*) opj_malloc(100 * sizeof(opj_marker_info_t));
6177 */
6178
6179         /* validation list creation */
6180         l_j2k->m_validation_list = opj_procedure_list_create();
6181         if (! l_j2k->m_validation_list) {
6182                 j2k_destroy(l_j2k);
6183                 return 00;
6184         }
6185
6186         /* execution list creation */
6187         l_j2k->m_procedure_list = opj_procedure_list_create();
6188         if (! l_j2k->m_procedure_list) {
6189                 j2k_destroy(l_j2k);
6190                 return 00;
6191         }
6192
6193         return l_j2k;
6194 }
6195
6196
6197 opj_codestream_index_t* j2k_create_cstr_index(void)
6198 {
6199         opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
6200                         opj_calloc(1,sizeof(opj_codestream_index_t));
6201         if (!cstr_index)
6202                 return NULL;
6203
6204         cstr_index->maxmarknum = 100;
6205         cstr_index->marknum = 0;
6206         cstr_index->marker = (opj_marker_info_t*)
6207                         opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
6208         if (!cstr_index-> marker)
6209                 return NULL;
6210
6211         cstr_index->tile_index = NULL;
6212
6213         return cstr_index;
6214 }
6215
6216 /**
6217  * Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
6218  * @param       p_header_data   the data contained in the COM box.
6219  * @param       p_j2k                   the jpeg2000 codec.
6220  * @param       p_header_size   the size of the data contained in the COM marker.
6221  * @param       p_manager               the user event manager.
6222 */
6223 opj_bool j2k_read_SPCod_SPCoc(
6224                                                     opj_j2k_v2_t *p_j2k,
6225                                                         OPJ_UINT32 compno,
6226                                                         OPJ_BYTE * p_header_data,
6227                                                         OPJ_UINT32 * p_header_size,
6228                                                         struct opj_event_mgr * p_manager
6229                                                         )
6230 {
6231         OPJ_UINT32 i, l_tmp;
6232         opj_cp_v2_t *l_cp = NULL;
6233         opj_tcp_v2_t *l_tcp = NULL;
6234         opj_tccp_t *l_tccp = NULL;
6235         OPJ_BYTE * l_current_ptr = NULL;
6236
6237         /* preconditions */
6238         assert(p_j2k != 00);
6239         assert(p_manager != 00);
6240         assert(p_header_data != 00);
6241
6242         l_cp = &(p_j2k->m_cp);
6243         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
6244                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
6245                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
6246
6247         /* precondition again */
6248         assert(compno < p_j2k->m_image->numcomps);
6249
6250         l_tccp = &l_tcp->tccps[compno];
6251         l_current_ptr = p_header_data;
6252
6253         /* make sure room is sufficient */
6254         if (*p_header_size < 5) {
6255                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
6256                 return OPJ_FALSE;
6257         }
6258
6259         opj_read_bytes(l_current_ptr, &l_tccp->numresolutions ,1);              /* SPcox (D) */
6260         ++l_tccp->numresolutions;                                                                               /* tccp->numresolutions = read() + 1 */
6261         ++l_current_ptr;
6262
6263         /* If user wants to remove more resolutions than the codestream contains, return error */
6264         if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
6265                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
6266                                         "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
6267                 p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;// FIXME J2K_DEC_STATE_ERR;
6268                 return OPJ_FALSE;
6269         }
6270
6271         opj_read_bytes(l_current_ptr,&l_tccp->cblkw ,1);                /* SPcoc (E) */
6272         ++l_current_ptr;
6273         l_tccp->cblkw += 2;
6274
6275         opj_read_bytes(l_current_ptr,&l_tccp->cblkh ,1);                /* SPcoc (F) */
6276         ++l_current_ptr;
6277         l_tccp->cblkh += 2;
6278
6279         opj_read_bytes(l_current_ptr,&l_tccp->cblksty ,1);              /* SPcoc (G) */
6280         ++l_current_ptr;
6281
6282         opj_read_bytes(l_current_ptr,&l_tccp->qmfbid ,1);               /* SPcoc (H) */
6283         ++l_current_ptr;
6284
6285         *p_header_size = *p_header_size - 5;
6286
6287         /* use custom precinct size ? */
6288         if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
6289                 if (*p_header_size < l_tccp->numresolutions) {
6290                         opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
6291                         return OPJ_FALSE;
6292                 }
6293
6294                 for     (i = 0; i < l_tccp->numresolutions; ++i) {
6295                         opj_read_bytes(l_current_ptr,&l_tmp ,1);                /* SPcoc (I_i) */
6296                         ++l_current_ptr;
6297                         l_tccp->prcw[i] = l_tmp & 0xf;
6298                         l_tccp->prch[i] = l_tmp >> 4;
6299                 }
6300
6301                 *p_header_size = *p_header_size - l_tccp->numresolutions;
6302         }
6303         else {
6304                 /* set default size for the precinct width and height */
6305                 for     (i = 0; i < l_tccp->numresolutions; ++i) {
6306                         l_tccp->prcw[i] = 15;
6307                         l_tccp->prch[i] = 15;
6308                 }
6309         }
6310
6311 #ifdef WIP_REMOVE_MSD
6312         /* INDEX >> */
6313         if (p_j2k->cstr_info && compno == 0) {
6314                 OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
6315
6316                 p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh;
6317                 p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw;
6318                 p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions;
6319                 p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty;
6320                 p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid;
6321
6322
6323                 memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx,l_tccp->prcw, l_data_size);
6324                 memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy,l_tccp->prch, l_data_size);
6325         }
6326         /* << INDEX */
6327 #endif
6328
6329         return OPJ_TRUE;
6330 }
6331
6332 /**
6333  * Copies the tile component parameters of all the component from the first tile component.
6334  *
6335  * @param               p_j2k           the J2k codec.
6336  */
6337 void j2k_copy_tile_component_parameters( opj_j2k_v2_t *p_j2k )
6338 {
6339         // loop
6340         OPJ_UINT32 i;
6341         opj_cp_v2_t *l_cp = NULL;
6342         opj_tcp_v2_t *l_tcp = NULL;
6343         opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
6344         OPJ_UINT32 l_prc_size;
6345
6346         /* preconditions */
6347         assert(p_j2k != 00);
6348
6349         l_cp = &(p_j2k->m_cp);
6350         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? /* FIXME J2K_DEC_STATE_TPH*/
6351                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
6352                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
6353
6354         l_ref_tccp = &l_tcp->tccps[0];
6355         l_copied_tccp = l_ref_tccp + 1;
6356         l_prc_size = l_ref_tccp->numresolutions * sizeof(OPJ_UINT32);
6357
6358         for     (i=1; i<p_j2k->m_image->numcomps; ++i) {
6359                 l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
6360                 l_copied_tccp->cblkw = l_ref_tccp->cblkw;
6361                 l_copied_tccp->cblkh = l_ref_tccp->cblkh;
6362                 l_copied_tccp->cblksty = l_ref_tccp->cblksty;
6363                 l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
6364                 memcpy(l_copied_tccp->prcw,l_ref_tccp->prcw,l_prc_size);
6365                 memcpy(l_copied_tccp->prch,l_ref_tccp->prch,l_prc_size);
6366                 ++l_copied_tccp;
6367         }
6368 }
6369
6370 /**
6371  * Reads a SQcd or SQcc element, i.e. the quantization values of a band.
6372  *
6373  * @param       p_comp_no               the component being targeted.
6374  * @param       p_header_data   the data contained in the COM box.
6375  * @param       p_j2k                   the jpeg2000 codec.
6376  * @param       p_header_size   the size of the data contained in the COM marker.
6377  * @param       p_manager               the user event manager.
6378 */
6379 opj_bool j2k_read_SQcd_SQcc(
6380                                                         opj_j2k_v2_t *p_j2k,
6381                                                         OPJ_UINT32 p_comp_no,
6382                                                         OPJ_BYTE* p_header_data,
6383                                                         OPJ_UINT32 * p_header_size,
6384                                                         struct opj_event_mgr * p_manager
6385                                                         )
6386 {
6387         // loop
6388         OPJ_UINT32 l_band_no;
6389         opj_cp_v2_t *l_cp = 00;
6390         opj_tcp_v2_t *l_tcp = 00;
6391         opj_tccp_t *l_tccp = 00;
6392         OPJ_BYTE * l_current_ptr = 00;
6393         OPJ_UINT32 l_tmp, l_num_band;
6394
6395         // preconditions
6396         assert(p_j2k != 00);
6397         assert(p_manager != 00);
6398         assert(p_header_data != 00);
6399
6400         l_cp = &(p_j2k->m_cp);
6401         // come from tile part header or main header ?
6402         l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? /*FIXME J2K_DEC_STATE_TPH*/
6403                                 &l_cp->tcps[p_j2k->m_current_tile_number] :
6404                                 p_j2k->m_specific_param.m_decoder.m_default_tcp;
6405
6406         // precondition again
6407         assert(p_comp_no <  p_j2k->m_image->numcomps);
6408
6409         l_tccp = &l_tcp->tccps[p_comp_no];
6410         l_current_ptr = p_header_data;
6411
6412         if (*p_header_size < 1) {
6413                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
6414                 return OPJ_FALSE;
6415         }
6416         *p_header_size -= 1;
6417
6418         opj_read_bytes(l_current_ptr, &l_tmp ,1);                       /* Sqcx */
6419         ++l_current_ptr;
6420
6421         l_tccp->qntsty = l_tmp & 0x1f;
6422         l_tccp->numgbits = l_tmp >> 5;
6423         if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
6424         l_num_band = 1;
6425         }
6426         else {
6427                 l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
6428                         (*p_header_size) :
6429                         (*p_header_size) / 2;
6430
6431                 if( l_num_band > J2K_MAXBANDS ) {
6432                         opj_event_msg_v2(p_manager, EVT_WARNING, "While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
6433                                 "number of subbands (%d) is greater to J2K_MAXBANDS (%d). So we limiting the number of elements stored to "
6434                                 "J2K_MAXBANDS (%d) and skip the other. \n", l_num_band, J2K_MAXBANDS, J2K_MAXBANDS);
6435                         //return OPJ_FALSE;
6436                 }
6437         }
6438
6439 #ifdef USE_JPWL
6440         if (l_cp->correct) {
6441
6442                 /* if JPWL is on, we check whether there are too many subbands */
6443                 if ((l_num_band < 0) || (l_num_band >= J2K_MAXBANDS)) {
6444                         opj_event_msg_v2(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
6445                                 "JPWL: bad number of subbands in Sqcx (%d)\n",
6446                                 l_num_band);
6447                         if (!JPWL_ASSUME) {
6448                                 opj_event_msg_v2(p_manager, EVT_ERROR, "JPWL: giving up\n");
6449                                 return OPJ_FALSE;
6450                         }
6451                         /* we try to correct */
6452                         l_num_band = 1;
6453                         opj_event_msg_v2(p_manager, EVT_WARNING, "- trying to adjust them\n"
6454                                 "- setting number of bands to %d => HYPOTHESIS!!!\n",
6455                                 l_num_band);
6456                 };
6457
6458         };
6459 #endif /* USE_JPWL */
6460
6461         if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
6462                 for     (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
6463                         opj_read_bytes(l_current_ptr, &l_tmp ,1);                       /* SPqcx_i */
6464                         ++l_current_ptr;
6465                         if (l_band_no < J2K_MAXBANDS){
6466                                 l_tccp->stepsizes[l_band_no].expn = l_tmp>>3;
6467                                 l_tccp->stepsizes[l_band_no].mant = 0;
6468                         }
6469                 }
6470                 *p_header_size = *p_header_size - l_num_band;
6471         }
6472         else {
6473                 for     (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
6474                         opj_read_bytes(l_current_ptr, &l_tmp ,2);                       /* SPqcx_i */
6475                         l_current_ptr+=2;
6476                         if (l_band_no < J2K_MAXBANDS){
6477                                 l_tccp->stepsizes[l_band_no].expn = l_tmp >> 11;
6478                                 l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
6479                         }
6480                 }
6481                 *p_header_size = *p_header_size - 2*l_num_band;
6482         }
6483
6484         /* Add Antonin : if scalar_derived -> compute other stepsizes */
6485         if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
6486                 for (l_band_no = 1; l_band_no < J2K_MAXBANDS; l_band_no++) {
6487                         l_tccp->stepsizes[l_band_no].expn =
6488                                 ((l_tccp->stepsizes[0].expn) - ((l_band_no - 1) / 3) > 0) ?
6489                                         (l_tccp->stepsizes[0].expn) - ((l_band_no - 1) / 3) : 0;
6490                         l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
6491                 }
6492         }
6493
6494         return OPJ_TRUE;
6495 }
6496
6497 /**
6498  * Copies the tile component parameters of all the component from the first tile component.
6499  *
6500  * @param               p_j2k           the J2k codec.
6501  */
6502 void j2k_copy_tile_quantization_parameters( opj_j2k_v2_t *p_j2k )
6503 {
6504         OPJ_UINT32 i;
6505         opj_cp_v2_t *l_cp = NULL;
6506         opj_tcp_v2_t *l_tcp = NULL;
6507         opj_tccp_t *l_ref_tccp = NULL;
6508         opj_tccp_t *l_copied_tccp = NULL;
6509         OPJ_UINT32 l_size;
6510
6511         /* preconditions */
6512         assert(p_j2k != 00);
6513
6514         l_cp = &(p_j2k->m_cp);
6515         l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
6516                         &l_cp->tcps[p_j2k->m_current_tile_number] :
6517                         p_j2k->m_specific_param.m_decoder.m_default_tcp;
6518
6519         l_ref_tccp = &l_tcp->tccps[0];
6520         l_copied_tccp = l_ref_tccp + 1;
6521         l_size = J2K_MAXBANDS * sizeof(opj_stepsize_t);
6522
6523         for     (i=1;i<p_j2k->m_image->numcomps;++i) {
6524                 l_copied_tccp->qntsty = l_ref_tccp->qntsty;
6525                 l_copied_tccp->numgbits = l_ref_tccp->numgbits;
6526                 memcpy(l_copied_tccp->stepsizes,l_ref_tccp->stepsizes,l_size);
6527                 ++l_copied_tccp;
6528         }
6529 }
6530
6531 /**
6532  * Dump some elements from the J2K decompression structure .
6533  *
6534  *@param p_j2k                          the jpeg2000 codec.
6535  *@param flag                           flag to describe what elments are dump.
6536  *@param out_stream                     output stream where dump the elements.
6537  *
6538 */
6539 void j2k_dump (opj_j2k_v2_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
6540 {
6541         /* Check if the flag is compatible with j2k file*/
6542         if ( (flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)){
6543                 fprintf(out_stream, "Wrong flag\n");
6544                 return;
6545         }
6546
6547         /* Dump the image_header */
6548         if (flag & OPJ_IMG_INFO){
6549                 if (p_j2k->m_image)
6550                         j2k_dump_image_header(p_j2k->m_image, 0, out_stream);
6551         }
6552
6553         /* Dump the codestream info from main header */
6554         if (flag & OPJ_J2K_MH_INFO){
6555                 j2k_dump_MH_info(p_j2k, out_stream);
6556         }
6557
6558
6559         /* Dump the codestream info of the current tile */
6560         if (flag & OPJ_J2K_TH_INFO){
6561
6562         }
6563
6564         /* Dump the codestream index from main header */
6565         if (flag & OPJ_J2K_MH_IND){
6566                 j2k_dump_MH_index(p_j2k, out_stream);
6567         }
6568
6569         /* Dump the codestream index of the current tile */
6570         if (flag & OPJ_J2K_TH_IND){
6571
6572         }
6573
6574 }
6575
6576 /**
6577  * Dump index elements of the codestream extract from the main header.
6578  *
6579  *@param p_j2k                          the jpeg2000 codec.
6580  *@param out_stream                     output stream where dump the elements.
6581  *
6582 */
6583 void j2k_dump_MH_index(opj_j2k_v2_t* p_j2k, FILE* out_stream)
6584 {
6585         opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
6586         OPJ_UINT32 it_marker;
6587
6588         fprintf(out_stream, "Codestream index from main header: {\n");
6589
6590         fprintf(out_stream, "\t Main header start position=%d\n\t Main header end position=%d\n",
6591                         cstr_index->main_head_start, cstr_index->main_head_end);
6592
6593         fprintf(out_stream, "\t Marker list: {\n");
6594
6595         for (it_marker=0; it_marker < cstr_index->marknum ; it_marker++){
6596                 fprintf(out_stream, "\t\t type=%#x, pos=%d, len=%d\n",
6597                                 cstr_index->marker[it_marker].type,
6598                                 cstr_index->marker[it_marker].pos,
6599                                 cstr_index->marker[it_marker].len );
6600         }
6601
6602         fprintf(out_stream, "\t }\n}\n");
6603
6604 }
6605
6606 /**
6607  * Dump info elements of the codestream extract from the main header.
6608  *
6609  *@param p_j2k                          the jpeg2000 codec.
6610  *@param out_stream                     output stream where dump the elements.
6611  *
6612 */
6613 void j2k_dump_MH_info(opj_j2k_v2_t* p_j2k, FILE* out_stream)
6614 {
6615         opj_tcp_v2_t * l_default_tile=NULL;
6616
6617         fprintf(out_stream, "Codestream info from main header: {\n");
6618
6619         fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
6620         fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
6621         fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
6622
6623         l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
6624         if (l_default_tile)
6625         {
6626                 OPJ_INT32 compno;
6627                 OPJ_INT32 numcomps = p_j2k->m_image->numcomps;
6628
6629                 fprintf(out_stream, "\t default tile {\n");
6630                 fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
6631                 fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
6632                 fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
6633                 fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
6634
6635                 for (compno = 0; compno < numcomps; compno++) {
6636                         opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
6637                         OPJ_INT32 resno, bandno, numbands;
6638
6639                         /* coding style*/
6640                         fprintf(out_stream, "\t\t comp %d {\n", compno);
6641                         fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
6642                         fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
6643                         fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
6644                         fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
6645                         fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
6646                         fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
6647
6648                         fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
6649                         for (resno = 0; resno < l_tccp->numresolutions; resno++) {
6650                                 fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
6651                         }
6652                         fprintf(out_stream, "\n");
6653
6654                         /* quantization style*/
6655                         fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
6656                         fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
6657                         fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
6658                         numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : l_tccp->numresolutions * 3 - 2;
6659                         for (bandno = 0; bandno < numbands; bandno++) {
6660                                 fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
6661                                         l_tccp->stepsizes[bandno].expn);
6662                         }
6663                         fprintf(out_stream, "\n");
6664
6665                         /* RGN value*/
6666                         fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
6667
6668                         fprintf(out_stream, "\t\t }\n");
6669                 } /*end of component of default tile*/
6670                 fprintf(out_stream, "\t }\n"); /*end of default tile*/
6671
6672         }
6673
6674         fprintf(out_stream, "}\n");
6675
6676 }
6677
6678 /**
6679  * Dump an image header structure.
6680  *
6681  *@param img_header                     the image header to dump.
6682  *@param dev_dump_flag          flag to describe if we are in the case of this function is use outside j2k_dump function
6683  *@param out_stream                     output stream where dump the elements.
6684  */
6685 void j2k_dump_image_header(opj_image_t* img_header, opj_bool dev_dump_flag, FILE* out_stream)
6686 {
6687         char tab[2];
6688
6689         if (dev_dump_flag){
6690                 fprintf(stdout, "[DEV] Dump a image_header struct {\n");
6691                 tab[0] = '\0';
6692         }
6693         else {
6694                 fprintf(out_stream, "Image info {\n");
6695                 tab[0] = '\t';tab[1] = '\0';
6696         }
6697
6698         fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
6699         fprintf(out_stream,     "%s x1=%d, y1=%d\n", tab, img_header->x1, img_header->y1);
6700         fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
6701
6702         if (img_header->comps){
6703                 int compno;
6704                 for (compno = 0; compno < img_header->numcomps; compno++) {
6705                         fprintf(out_stream, "%s\t component %d {\n", tab, compno);
6706                         j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag, out_stream);
6707                         fprintf(out_stream,"%s}\n",tab);
6708                 }
6709         }
6710
6711         fprintf(out_stream, "}\n");
6712 }
6713
6714 /**
6715  * Dump a component image header structure.
6716  *
6717  *@param comp_header            the component image header to dump.
6718  *@param dev_dump_flag          flag to describe if we are in the case of this function is use outside j2k_dump function
6719  *@param out_stream                     output stream where dump the elements.
6720  */
6721 void j2k_dump_image_comp_header(opj_image_comp_t* comp_header, opj_bool dev_dump_flag, FILE* out_stream)
6722 {
6723         char tab[3];
6724
6725         if (dev_dump_flag){
6726                 fprintf(stdout, "[DEV] Dump a image_comp_header struct {\n");
6727                 tab[0] = '\0';
6728         }       else {
6729                 tab[0] = '\t';tab[1] = '\t';tab[2] = '\0';
6730         }
6731
6732         fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
6733         fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
6734         fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
6735
6736         if (dev_dump_flag)
6737                 fprintf(out_stream, "}\n");
6738 }
6739
6740
6741 /**
6742  * Get the codestream info from a JPEG2000 codec.
6743  *
6744  *@param        p_j2k                           the component image header to dump.
6745  *
6746  *@return       the codestream information extract from the jpg2000 codec
6747  */
6748 opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_v2_t* p_j2k)
6749 {
6750         OPJ_UINT16 compno;
6751         OPJ_UINT16 numcomps = p_j2k->m_image->numcomps;
6752         opj_tcp_v2_t *l_default_tile;
6753         opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,sizeof(opj_codestream_info_v2_t));
6754
6755         cstr_info->nbcomps = p_j2k->m_image->numcomps;
6756
6757         cstr_info->tx0 = p_j2k->m_cp.tx0;
6758         cstr_info->ty0 = p_j2k->m_cp.ty0;
6759         cstr_info->tdx = p_j2k->m_cp.tdx;
6760         cstr_info->tdy = p_j2k->m_cp.tdy;
6761         cstr_info->tw = p_j2k->m_cp.tw;
6762         cstr_info->th = p_j2k->m_cp.th;
6763
6764         l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
6765
6766         cstr_info->m_default_tile_info.csty = l_default_tile->csty;
6767         cstr_info->m_default_tile_info.prg = l_default_tile->prg;
6768         cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
6769         cstr_info->m_default_tile_info.mct = l_default_tile->mct;
6770
6771         cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(cstr_info->nbcomps, sizeof(opj_tccp_info_t));
6772
6773         for (compno = 0; compno < numcomps; compno++) {
6774                 opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
6775                 opj_tccp_info_t *l_tccp_info = &(cstr_info->m_default_tile_info.tccp_info[compno]);
6776                 OPJ_INT32 bandno, numbands;
6777
6778                 /* coding style*/
6779                 l_tccp_info->csty = l_tccp->csty;
6780                 l_tccp_info->numresolutions = l_tccp->numresolutions;
6781                 l_tccp_info->cblkw = l_tccp->cblkw;
6782                 l_tccp_info->cblkh = l_tccp->cblkh;
6783                 l_tccp_info->cblksty = l_tccp->cblksty;
6784                 l_tccp_info->qmfbid = l_tccp->qmfbid;
6785                 if (l_tccp->numresolutions < J2K_MAXRLVLS)
6786                 {
6787                         memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions - 1);
6788                         memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions - 1);
6789                 }
6790
6791                 /* quantization style*/
6792                 l_tccp_info->qntsty = l_tccp->qntsty;
6793                 l_tccp_info->numgbits = l_tccp->numgbits;
6794
6795                 numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : l_tccp->numresolutions * 3 - 2;
6796                 if (numbands < J2K_MAXBANDS) {
6797                         for (bandno = 0; bandno < numbands; bandno++) {
6798                                 l_tccp_info->stepsizes_mant[bandno] = l_tccp->stepsizes[bandno].mant;
6799                                 l_tccp_info->stepsizes_expn[bandno] = l_tccp->stepsizes[bandno].expn;
6800                         }
6801                 }
6802
6803                 /* RGN value*/
6804                 l_tccp_info->roishift = l_tccp->roishift;
6805         }
6806
6807
6808         return cstr_info;
6809 }
6810
6811 /**
6812  * Get the codestream index from a JPEG2000 codec.
6813  *
6814  *@param        p_j2k                           the component image header to dump.
6815  *
6816  *@return       the codestream index extract from the jpg2000 codec
6817  */
6818 opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_v2_t* p_j2k)
6819 {
6820         opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
6821                         opj_calloc(1,sizeof(opj_codestream_index_t));
6822         if (!l_cstr_index)
6823                 return NULL;
6824
6825         l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
6826         l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
6827         l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
6828
6829         l_cstr_index->maxmarknum = p_j2k->cstr_index->maxmarknum;
6830         l_cstr_index->marknum = p_j2k->cstr_index->marknum;
6831         l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum*sizeof(opj_marker_info_t));
6832         if (!l_cstr_index->marker)
6833                 return NULL;
6834
6835         memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker, l_cstr_index->marknum * sizeof(opj_marker_info_t) );
6836
6837
6838         return l_cstr_index;
6839 }
6840
6841
6842
6843 /**
6844  * Reads the tiles.
6845  */
6846 opj_bool j2k_decode_tiles (     opj_j2k_v2_t *p_j2k,
6847                                                         opj_stream_private_t *p_stream,
6848                                                         opj_event_mgr_t * p_manager)
6849 {
6850         opj_bool l_go_on = OPJ_TRUE;
6851         OPJ_UINT32 l_current_tile_no;
6852         OPJ_UINT32 l_data_size,l_max_data_size;
6853         OPJ_INT32 l_tile_x0,l_tile_y0,l_tile_x1,l_tile_y1;
6854         OPJ_UINT32 l_nb_comps;
6855         OPJ_BYTE * l_current_data;
6856
6857         l_current_data = (OPJ_BYTE*)opj_malloc(1000);
6858         if (! l_current_data) {
6859                 return OPJ_FALSE;
6860         }
6861         l_max_data_size = 1000;
6862
6863         while (OPJ_TRUE) {
6864                 if (! j2k_read_tile_header(     p_j2k,
6865                                                                         &l_current_tile_no,
6866                                                                         &l_data_size,
6867                                                                         &l_tile_x0, &l_tile_y0,
6868                                                                         &l_tile_x1, &l_tile_y1,
6869                                                                         &l_nb_comps,
6870                                                                         &l_go_on,
6871                                                                         p_stream,
6872                                                                         p_manager)) {
6873                         return OPJ_FALSE;
6874                 }
6875
6876                 if (! l_go_on) {
6877                         break;
6878                 }
6879
6880                 if (l_data_size > l_max_data_size) {
6881                         l_current_data = (OPJ_BYTE*)opj_realloc(l_current_data,l_data_size);
6882                         if (! l_current_data) {
6883                                 return OPJ_FALSE;
6884                         }
6885
6886                         l_max_data_size = l_data_size;
6887                 }
6888
6889                 if (! j2k_decode_tile(p_j2k,l_current_tile_no,l_current_data,l_data_size,p_stream,p_manager)) {
6890                         opj_free(l_current_data);
6891                         return OPJ_FALSE;
6892                 }
6893                 opj_event_msg_v2(p_manager, EVT_INFO, "Tile %d/%d has been decode.\n", l_current_tile_no +1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
6894
6895                 if (! j2k_update_image_data(p_j2k->m_tcd,l_current_data)) {
6896                         opj_free(l_current_data);
6897                         return OPJ_FALSE;
6898                 }
6899                 opj_event_msg_v2(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
6900
6901         }
6902
6903         opj_free(l_current_data);
6904         return OPJ_TRUE;
6905 }
6906
6907
6908 /**
6909  * Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
6910  */
6911 void j2k_setup_decoding (opj_j2k_v2_t *p_j2k)
6912 {
6913         // preconditions
6914         assert(p_j2k != 00);
6915
6916         opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(void*)j2k_decode_tiles);
6917         /* DEVELOPER CORNER, add your custom procedures */
6918
6919 }
6920
6921
6922 /**
6923  * Decodes the tiles of the stream.
6924  */
6925 opj_bool j2k_decode_v2( opj_j2k_v2_t * p_j2k,
6926                                                 opj_stream_private_t * p_stream,
6927                                                 opj_image_t * p_image,
6928                                                 opj_event_mgr_t * p_manager)
6929 {
6930         OPJ_UINT32 compno;
6931
6932         /* customization of the decoding */
6933         j2k_setup_decoding(p_j2k);
6934
6935         /* write header */
6936         if (! j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
6937                 opj_image_destroy(p_j2k->m_image);
6938                 p_j2k->m_image = NULL;
6939                 return OPJ_FALSE;
6940         }
6941
6942         for (compno = 0; compno < p_image->numcomps; compno++) {
6943                 p_image->comps[compno].data = p_j2k->m_image->comps[compno].data;
6944                 p_j2k->m_image->comps[compno].data = NULL;
6945         }
6946
6947         return OPJ_TRUE /*p_j2k->m_image*/;
6948 }