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