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