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