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