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