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