Merge pull request #919 from rouault/reformat
[openjpeg.git] / src / lib / openjp2 / t2.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses
3  * BSD License, included below. This software may be subject to other third
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
15  * Copyright (c) 2012, CS Systemes d'Information, France
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
28  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39
40 #include "opj_includes.h"
41
42 /** @defgroup T2 T2 - Implementation of a tier-2 coding */
43 /*@{*/
44
45 /** @name Local static functions */
46 /*@{*/
47
48 static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n);
49
50 static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio);
51 /**
52 Variable length code for signalling delta Zil (truncation point)
53 @param bio  Bit Input/Output component
54 @param n    delta Zil
55 */
56 static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n);
57 static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio);
58
59 /**
60 Encode a packet of a tile to a destination buffer
61 @param tileno Number of the tile encoded
62 @param tile Tile for which to write the packets
63 @param tcp Tile coding parameters
64 @param pi Packet identity
65 @param dest Destination buffer
66 @param p_data_written   FIXME DOC
67 @param len Length of the destination buffer
68 @param cstr_info Codestream information structure
69 @return
70 */
71 static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
72                                      opj_tcd_tile_t *tile,
73                                      opj_tcp_t *tcp,
74                                      opj_pi_iterator_t *pi,
75                                      OPJ_BYTE *dest,
76                                      OPJ_UINT32 * p_data_written,
77                                      OPJ_UINT32 len,
78                                      opj_codestream_info_t *cstr_info);
79
80 /**
81 Decode a packet of a tile from a source buffer
82 @param t2 T2 handle
83 @param tile Tile for which to write the packets
84 @param tcp Tile coding parameters
85 @param pi Packet identity
86 @param src Source buffer
87 @param data_read   FIXME DOC
88 @param max_length  FIXME DOC
89 @param pack_info Packet information
90
91 @return  FIXME DOC
92 */
93 static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* t2,
94                                      opj_tcd_tile_t *tile,
95                                      opj_tcp_t *tcp,
96                                      opj_pi_iterator_t *pi,
97                                      OPJ_BYTE *src,
98                                      OPJ_UINT32 * data_read,
99                                      OPJ_UINT32 max_length,
100                                      opj_packet_info_t *pack_info,
101                                      opj_event_mgr_t *p_manager);
102
103 static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
104                                    opj_tcd_tile_t *p_tile,
105                                    opj_tcp_t *p_tcp,
106                                    opj_pi_iterator_t *p_pi,
107                                    OPJ_BYTE *p_src,
108                                    OPJ_UINT32 * p_data_read,
109                                    OPJ_UINT32 p_max_length,
110                                    opj_packet_info_t *p_pack_info,
111                                    opj_event_mgr_t *p_manager);
112
113 static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
114         opj_tcd_tile_t *p_tile,
115         opj_tcp_t *p_tcp,
116         opj_pi_iterator_t *p_pi,
117         OPJ_BOOL * p_is_data_present,
118         OPJ_BYTE *p_src_data,
119         OPJ_UINT32 * p_data_read,
120         OPJ_UINT32 p_max_length,
121         opj_packet_info_t *p_pack_info,
122         opj_event_mgr_t *p_manager);
123
124 static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
125                                         opj_tcd_tile_t *p_tile,
126                                         opj_pi_iterator_t *p_pi,
127                                         OPJ_BYTE *p_src_data,
128                                         OPJ_UINT32 * p_data_read,
129                                         OPJ_UINT32 p_max_length,
130                                         opj_packet_info_t *pack_info,
131                                         opj_event_mgr_t *p_manager);
132
133 static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
134                                         opj_tcd_tile_t *p_tile,
135                                         opj_pi_iterator_t *p_pi,
136                                         OPJ_UINT32 * p_data_read,
137                                         OPJ_UINT32 p_max_length,
138                                         opj_packet_info_t *pack_info,
139                                         opj_event_mgr_t *p_manager);
140
141 /**
142 @param cblk
143 @param index
144 @param cblksty
145 @param first
146 */
147 static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
148                                 OPJ_UINT32 index,
149                                 OPJ_UINT32 cblksty,
150                                 OPJ_UINT32 first);
151
152 /*@}*/
153
154 /*@}*/
155
156 /* ----------------------------------------------------------------------- */
157
158 /* #define RESTART 0x04 */
159 static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n)
160 {
161     while (--n >= 0) {
162         opj_bio_write(bio, 1, 1);
163     }
164     opj_bio_write(bio, 0, 1);
165 }
166
167 static OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio)
168 {
169     OPJ_UINT32 n = 0;
170     while (opj_bio_read(bio, 1)) {
171         ++n;
172     }
173     return n;
174 }
175
176 static void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n)
177 {
178     if (n == 1) {
179         opj_bio_write(bio, 0, 1);
180     } else if (n == 2) {
181         opj_bio_write(bio, 2, 2);
182     } else if (n <= 5) {
183         opj_bio_write(bio, 0xc | (n - 3), 4);
184     } else if (n <= 36) {
185         opj_bio_write(bio, 0x1e0 | (n - 6), 9);
186     } else if (n <= 164) {
187         opj_bio_write(bio, 0xff80 | (n - 37), 16);
188     }
189 }
190
191 static OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio)
192 {
193     OPJ_UINT32 n;
194     if (!opj_bio_read(bio, 1)) {
195         return 1;
196     }
197     if (!opj_bio_read(bio, 1)) {
198         return 2;
199     }
200     if ((n = opj_bio_read(bio, 2)) != 3) {
201         return (3 + n);
202     }
203     if ((n = opj_bio_read(bio, 5)) != 31) {
204         return (6 + n);
205     }
206     return (37 + opj_bio_read(bio, 7));
207 }
208
209 /* ----------------------------------------------------------------------- */
210
211 OPJ_BOOL opj_t2_encode_packets(opj_t2_t* p_t2,
212                                OPJ_UINT32 p_tile_no,
213                                opj_tcd_tile_t *p_tile,
214                                OPJ_UINT32 p_maxlayers,
215                                OPJ_BYTE *p_dest,
216                                OPJ_UINT32 * p_data_written,
217                                OPJ_UINT32 p_max_len,
218                                opj_codestream_info_t *cstr_info,
219                                OPJ_UINT32 p_tp_num,
220                                OPJ_INT32 p_tp_pos,
221                                OPJ_UINT32 p_pino,
222                                J2K_T2_MODE p_t2_mode)
223 {
224     OPJ_BYTE *l_current_data = p_dest;
225     OPJ_UINT32 l_nb_bytes = 0;
226     OPJ_UINT32 compno;
227     OPJ_UINT32 poc;
228     opj_pi_iterator_t *l_pi = 00;
229     opj_pi_iterator_t *l_current_pi = 00;
230     opj_image_t *l_image = p_t2->image;
231     opj_cp_t *l_cp = p_t2->cp;
232     opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
233     OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K) ? 2 : 1;
234     OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ?
235                             l_image->numcomps : 1;
236     OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
237
238     l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
239     if (!l_pi) {
240         return OPJ_FALSE;
241     }
242
243     * p_data_written = 0;
244
245     if (p_t2_mode == THRESH_CALC) { /* Calculating threshold */
246         l_current_pi = l_pi;
247
248         for (compno = 0; compno < l_max_comp; ++compno) {
249             OPJ_UINT32 l_comp_len = 0;
250             l_current_pi = l_pi;
251
252             for (poc = 0; poc < pocno ; ++poc) {
253                 OPJ_UINT32 l_tp_num = compno;
254
255                 /* TODO MSD : check why this function cannot fail (cf. v1) */
256                 opj_pi_create_encode(l_pi, l_cp, p_tile_no, poc, l_tp_num, p_tp_pos, p_t2_mode);
257
258                 if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
259                     /* TODO ADE : add an error */
260                     opj_pi_destroy(l_pi, l_nb_pocs);
261                     return OPJ_FALSE;
262                 }
263                 while (opj_pi_next(l_current_pi)) {
264                     if (l_current_pi->layno < p_maxlayers) {
265                         l_nb_bytes = 0;
266
267                         if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
268                                                    l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
269                             opj_pi_destroy(l_pi, l_nb_pocs);
270                             return OPJ_FALSE;
271                         }
272
273                         l_comp_len += l_nb_bytes;
274                         l_current_data += l_nb_bytes;
275                         p_max_len -= l_nb_bytes;
276
277                         * p_data_written += l_nb_bytes;
278                     }
279                 }
280
281                 if (l_cp->m_specific_param.m_enc.m_max_comp_size) {
282                     if (l_comp_len > l_cp->m_specific_param.m_enc.m_max_comp_size) {
283                         opj_pi_destroy(l_pi, l_nb_pocs);
284                         return OPJ_FALSE;
285                     }
286                 }
287
288                 ++l_current_pi;
289             }
290         }
291     } else { /* t2_mode == FINAL_PASS  */
292         opj_pi_create_encode(l_pi, l_cp, p_tile_no, p_pino, p_tp_num, p_tp_pos,
293                              p_t2_mode);
294
295         l_current_pi = &l_pi[p_pino];
296         if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
297             /* TODO ADE : add an error */
298             opj_pi_destroy(l_pi, l_nb_pocs);
299             return OPJ_FALSE;
300         }
301         while (opj_pi_next(l_current_pi)) {
302             if (l_current_pi->layno < p_maxlayers) {
303                 l_nb_bytes = 0;
304
305                 if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
306                                            l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
307                     opj_pi_destroy(l_pi, l_nb_pocs);
308                     return OPJ_FALSE;
309                 }
310
311                 l_current_data += l_nb_bytes;
312                 p_max_len -= l_nb_bytes;
313
314                 * p_data_written += l_nb_bytes;
315
316                 /* INDEX >> */
317                 if (cstr_info) {
318                     if (cstr_info->index_write) {
319                         opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
320                         opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
321                         if (!cstr_info->packno) {
322                             info_PK->start_pos = info_TL->end_header + 1;
323                         } else {
324                             info_PK->start_pos = ((l_cp->m_specific_param.m_enc.m_tp_on | l_tcp->POC) &&
325                                                   info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno -
326                                                                             1].end_pos + 1;
327                         }
328                         info_PK->end_pos = info_PK->start_pos + l_nb_bytes - 1;
329                         info_PK->end_ph_pos += info_PK->start_pos -
330                                                1;  /* End of packet header which now only represents the distance
331                                                                                                                                                                                                                                                    to start of packet is incremented by value of start of packet*/
332                     }
333
334                     cstr_info->packno++;
335                 }
336                 /* << INDEX */
337                 ++p_tile->packno;
338             }
339         }
340     }
341
342     opj_pi_destroy(l_pi, l_nb_pocs);
343
344     return OPJ_TRUE;
345 }
346
347 /* see issue 80 */
348 #if 0
349 #define JAS_FPRINTF fprintf
350 #else
351 /* issue 290 */
352 static void opj_null_jas_fprintf(FILE* file, const char * format, ...)
353 {
354     (void)file;
355     (void)format;
356 }
357 #define JAS_FPRINTF opj_null_jas_fprintf
358 #endif
359
360 OPJ_BOOL opj_t2_decode_packets(opj_t2_t *p_t2,
361                                OPJ_UINT32 p_tile_no,
362                                opj_tcd_tile_t *p_tile,
363                                OPJ_BYTE *p_src,
364                                OPJ_UINT32 * p_data_read,
365                                OPJ_UINT32 p_max_len,
366                                opj_codestream_index_t *p_cstr_index,
367                                opj_event_mgr_t *p_manager)
368 {
369     OPJ_BYTE *l_current_data = p_src;
370     opj_pi_iterator_t *l_pi = 00;
371     OPJ_UINT32 pino;
372     opj_image_t *l_image = p_t2->image;
373     opj_cp_t *l_cp = p_t2->cp;
374     opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
375     OPJ_UINT32 l_nb_bytes_read;
376     OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
377     opj_pi_iterator_t *l_current_pi = 00;
378 #ifdef TODO_MSD
379     OPJ_UINT32 curtp = 0;
380     OPJ_UINT32 tp_start_packno;
381 #endif
382     opj_packet_info_t *l_pack_info = 00;
383     opj_image_comp_t* l_img_comp = 00;
384
385     OPJ_ARG_NOT_USED(p_cstr_index);
386
387 #ifdef TODO_MSD
388     if (p_cstr_index) {
389         l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
390     }
391 #endif
392
393     /* create a packet iterator */
394     l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
395     if (!l_pi) {
396         return OPJ_FALSE;
397     }
398
399
400     l_current_pi = l_pi;
401
402     for (pino = 0; pino <= l_tcp->numpocs; ++pino) {
403
404         /* if the resolution needed is too low, one dim of the tilec could be equal to zero
405          * and no packets are used to decode this resolution and
406          * l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
407          * and no l_img_comp->resno_decoded are computed
408          */
409         OPJ_BOOL* first_pass_failed = NULL;
410
411         if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
412             /* TODO ADE : add an error */
413             opj_pi_destroy(l_pi, l_nb_pocs);
414             return OPJ_FALSE;
415         }
416
417         first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));
418         if (!first_pass_failed) {
419             opj_pi_destroy(l_pi, l_nb_pocs);
420             return OPJ_FALSE;
421         }
422         memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));
423
424         while (opj_pi_next(l_current_pi)) {
425             JAS_FPRINTF(stderr,
426                         "packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\n\n",
427                         l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno,
428                         l_current_pi->precno, l_current_pi->layno);
429
430             if (l_tcp->num_layers_to_decode > l_current_pi->layno
431                     && l_current_pi->resno <
432                     p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
433                 l_nb_bytes_read = 0;
434
435                 first_pass_failed[l_current_pi->compno] = OPJ_FALSE;
436
437                 if (! opj_t2_decode_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
438                                            &l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
439                     opj_pi_destroy(l_pi, l_nb_pocs);
440                     opj_free(first_pass_failed);
441                     return OPJ_FALSE;
442                 }
443
444                 l_img_comp = &(l_image->comps[l_current_pi->compno]);
445                 l_img_comp->resno_decoded = opj_uint_max(l_current_pi->resno,
446                                             l_img_comp->resno_decoded);
447             } else {
448                 l_nb_bytes_read = 0;
449                 if (! opj_t2_skip_packet(p_t2, p_tile, l_tcp, l_current_pi, l_current_data,
450                                          &l_nb_bytes_read, p_max_len, l_pack_info, p_manager)) {
451                     opj_pi_destroy(l_pi, l_nb_pocs);
452                     opj_free(first_pass_failed);
453                     return OPJ_FALSE;
454                 }
455             }
456
457             if (first_pass_failed[l_current_pi->compno]) {
458                 l_img_comp = &(l_image->comps[l_current_pi->compno]);
459                 if (l_img_comp->resno_decoded == 0) {
460                     l_img_comp->resno_decoded =
461                         p_tile->comps[l_current_pi->compno].minimum_num_resolutions - 1;
462                 }
463             }
464
465             l_current_data += l_nb_bytes_read;
466             p_max_len -= l_nb_bytes_read;
467
468             /* INDEX >> */
469 #ifdef TODO_MSD
470             if (p_cstr_info) {
471                 opj_tile_info_v2_t *info_TL = &p_cstr_info->tile[p_tile_no];
472                 opj_packet_info_t *info_PK = &info_TL->packet[p_cstr_info->packno];
473                 tp_start_packno = 0;
474                 if (!p_cstr_info->packno) {
475                     info_PK->start_pos = info_TL->end_header + 1;
476                 } else if (info_TL->packet[p_cstr_info->packno - 1].end_pos >=
477                            (OPJ_INT32)
478                            p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_pos) { /* New tile part */
479                     info_TL->tp[curtp].tp_numpacks = p_cstr_info->packno -
480                                                      tp_start_packno; /* Number of packets in previous tile-part */
481                     tp_start_packno = p_cstr_info->packno;
482                     curtp++;
483                     info_PK->start_pos = p_cstr_info->tile[p_tile_no].tp[curtp].tp_end_header + 1;
484                 } else {
485                     info_PK->start_pos = (l_cp->m_specific_param.m_enc.m_tp_on &&
486                                           info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[p_cstr_info->packno -
487                                                                       1].end_pos + 1;
488                 }
489                 info_PK->end_pos = info_PK->start_pos + l_nb_bytes_read - 1;
490                 info_PK->end_ph_pos += info_PK->start_pos -
491                                        1;  /* End of packet header which now only represents the distance */
492                 ++p_cstr_info->packno;
493             }
494 #endif
495             /* << INDEX */
496         }
497         ++l_current_pi;
498
499         opj_free(first_pass_failed);
500     }
501     /* INDEX >> */
502 #ifdef TODO_MSD
503     if
504     (p_cstr_info) {
505         p_cstr_info->tile[p_tile_no].tp[curtp].tp_numpacks = p_cstr_info->packno -
506                 tp_start_packno; /* Number of packets in last tile-part */
507     }
508 #endif
509     /* << INDEX */
510
511     /* don't forget to release pi */
512     opj_pi_destroy(l_pi, l_nb_pocs);
513     *p_data_read = (OPJ_UINT32)(l_current_data - p_src);
514     return OPJ_TRUE;
515 }
516
517 /* ----------------------------------------------------------------------- */
518
519 /**
520  * Creates a Tier 2 handle
521  *
522  * @param       p_image         Source or destination image
523  * @param       p_cp            Image coding parameters.
524  * @return              a new T2 handle if successful, NULL otherwise.
525 */
526 opj_t2_t* opj_t2_create(opj_image_t *p_image, opj_cp_t *p_cp)
527 {
528     /* create the t2 structure */
529     opj_t2_t *l_t2 = (opj_t2_t*)opj_calloc(1, sizeof(opj_t2_t));
530     if (!l_t2) {
531         return NULL;
532     }
533
534     l_t2->image = p_image;
535     l_t2->cp = p_cp;
536
537     return l_t2;
538 }
539
540 void opj_t2_destroy(opj_t2_t *t2)
541 {
542     if (t2) {
543         opj_free(t2);
544     }
545 }
546
547 static OPJ_BOOL opj_t2_decode_packet(opj_t2_t* p_t2,
548                                      opj_tcd_tile_t *p_tile,
549                                      opj_tcp_t *p_tcp,
550                                      opj_pi_iterator_t *p_pi,
551                                      OPJ_BYTE *p_src,
552                                      OPJ_UINT32 * p_data_read,
553                                      OPJ_UINT32 p_max_length,
554                                      opj_packet_info_t *p_pack_info,
555                                      opj_event_mgr_t *p_manager)
556 {
557     OPJ_BOOL l_read_data;
558     OPJ_UINT32 l_nb_bytes_read = 0;
559     OPJ_UINT32 l_nb_total_bytes_read = 0;
560
561     *p_data_read = 0;
562
563     if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
564                                     &l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
565         return OPJ_FALSE;
566     }
567
568     p_src += l_nb_bytes_read;
569     l_nb_total_bytes_read += l_nb_bytes_read;
570     p_max_length -= l_nb_bytes_read;
571
572     /* we should read data for the packet */
573     if (l_read_data) {
574         l_nb_bytes_read = 0;
575
576         if (! opj_t2_read_packet_data(p_t2, p_tile, p_pi, p_src, &l_nb_bytes_read,
577                                       p_max_length, p_pack_info, p_manager)) {
578             return OPJ_FALSE;
579         }
580
581         l_nb_total_bytes_read += l_nb_bytes_read;
582     }
583
584     *p_data_read = l_nb_total_bytes_read;
585
586     return OPJ_TRUE;
587 }
588
589 static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
590                                      opj_tcd_tile_t * tile,
591                                      opj_tcp_t * tcp,
592                                      opj_pi_iterator_t *pi,
593                                      OPJ_BYTE *dest,
594                                      OPJ_UINT32 * p_data_written,
595                                      OPJ_UINT32 length,
596                                      opj_codestream_info_t *cstr_info)
597 {
598     OPJ_UINT32 bandno, cblkno;
599     OPJ_BYTE* c = dest;
600     OPJ_UINT32 l_nb_bytes;
601     OPJ_UINT32 compno = pi->compno;     /* component value */
602     OPJ_UINT32 resno  = pi->resno;      /* resolution level value */
603     OPJ_UINT32 precno = pi->precno;     /* precinct value */
604     OPJ_UINT32 layno  = pi->layno;      /* quality layer value */
605     OPJ_UINT32 l_nb_blocks;
606     opj_tcd_band_t *band = 00;
607     opj_tcd_cblk_enc_t* cblk = 00;
608     opj_tcd_pass_t *pass = 00;
609
610     opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
611     opj_tcd_resolution_t *res = &tilec->resolutions[resno];
612
613     opj_bio_t *bio = 00;    /* BIO component */
614
615     /* <SOP 0xff91> */
616     if (tcp->csty & J2K_CP_CSTY_SOP) {
617         c[0] = 255;
618         c[1] = 145;
619         c[2] = 0;
620         c[3] = 4;
621 #if 0
622         c[4] = (tile->packno % 65536) / 256;
623         c[5] = (tile->packno % 65536) % 256;
624 #else
625         c[4] = (tile->packno >> 8) & 0xff; /* packno is uint32_t */
626         c[5] = tile->packno & 0xff;
627 #endif
628         c += 6;
629         length -= 6;
630     }
631     /* </SOP> */
632
633     if (!layno) {
634         band = res->bands;
635
636         for (bandno = 0; bandno < res->numbands; ++bandno) {
637             opj_tcd_precinct_t *prc = &band->precincts[precno];
638
639             opj_tgt_reset(prc->incltree);
640             opj_tgt_reset(prc->imsbtree);
641
642             l_nb_blocks = prc->cw * prc->ch;
643             for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
644                 cblk = &prc->cblks.enc[cblkno];
645
646                 cblk->numpasses = 0;
647                 opj_tgt_setvalue(prc->imsbtree, cblkno, band->numbps - (OPJ_INT32)cblk->numbps);
648             }
649             ++band;
650         }
651     }
652
653     bio = opj_bio_create();
654     if (!bio) {
655         /* FIXME event manager error callback */
656         return OPJ_FALSE;
657     }
658     opj_bio_init_enc(bio, c, length);
659     opj_bio_write(bio, 1, 1);           /* Empty header bit */
660
661     /* Writing Packet header */
662     band = res->bands;
663     for (bandno = 0; bandno < res->numbands; ++bandno)      {
664         opj_tcd_precinct_t *prc = &band->precincts[precno];
665
666         l_nb_blocks = prc->cw * prc->ch;
667         cblk = prc->cblks.enc;
668
669         for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
670             opj_tcd_layer_t *layer = &cblk->layers[layno];
671
672             if (!cblk->numpasses && layer->numpasses) {
673                 opj_tgt_setvalue(prc->incltree, cblkno, (OPJ_INT32)layno);
674             }
675
676             ++cblk;
677         }
678
679         cblk = prc->cblks.enc;
680         for (cblkno = 0; cblkno < l_nb_blocks; cblkno++) {
681             opj_tcd_layer_t *layer = &cblk->layers[layno];
682             OPJ_UINT32 increment = 0;
683             OPJ_UINT32 nump = 0;
684             OPJ_UINT32 len = 0, passno;
685             OPJ_UINT32 l_nb_passes;
686
687             /* cblk inclusion bits */
688             if (!cblk->numpasses) {
689                 opj_tgt_encode(bio, prc->incltree, cblkno, (OPJ_INT32)(layno + 1));
690             } else {
691                 opj_bio_write(bio, layer->numpasses != 0, 1);
692             }
693
694             /* if cblk not included, go to the next cblk  */
695             if (!layer->numpasses) {
696                 ++cblk;
697                 continue;
698             }
699
700             /* if first instance of cblk --> zero bit-planes information */
701             if (!cblk->numpasses) {
702                 cblk->numlenbits = 3;
703                 opj_tgt_encode(bio, prc->imsbtree, cblkno, 999);
704             }
705
706             /* number of coding passes included */
707             opj_t2_putnumpasses(bio, layer->numpasses);
708             l_nb_passes = cblk->numpasses + layer->numpasses;
709             pass = cblk->passes +  cblk->numpasses;
710
711             /* computation of the increase of the length indicator and insertion in the header     */
712             for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
713                 ++nump;
714                 len += pass->len;
715
716                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
717                     increment = (OPJ_UINT32)opj_int_max((OPJ_INT32)increment,
718                                                         opj_int_floorlog2((OPJ_INT32)len) + 1
719                                                         - ((OPJ_INT32)cblk->numlenbits + opj_int_floorlog2((OPJ_INT32)nump)));
720                     len = 0;
721                     nump = 0;
722                 }
723
724                 ++pass;
725             }
726             opj_t2_putcommacode(bio, (OPJ_INT32)increment);
727
728             /* computation of the new Length indicator */
729             cblk->numlenbits += increment;
730
731             pass = cblk->passes +  cblk->numpasses;
732             /* insertion of the codeword segment length */
733             for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
734                 nump++;
735                 len += pass->len;
736
737                 if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
738                     opj_bio_write(bio, (OPJ_UINT32)len,
739                                   cblk->numlenbits + (OPJ_UINT32)opj_int_floorlog2((OPJ_INT32)nump));
740                     len = 0;
741                     nump = 0;
742                 }
743                 ++pass;
744             }
745
746             ++cblk;
747         }
748
749         ++band;
750     }
751
752     if (!opj_bio_flush(bio)) {
753         opj_bio_destroy(bio);
754         return OPJ_FALSE;               /* modified to eliminate longjmp !! */
755     }
756
757     l_nb_bytes = (OPJ_UINT32)opj_bio_numbytes(bio);
758     c += l_nb_bytes;
759     length -= l_nb_bytes;
760
761     opj_bio_destroy(bio);
762
763     /* <EPH 0xff92> */
764     if (tcp->csty & J2K_CP_CSTY_EPH) {
765         c[0] = 255;
766         c[1] = 146;
767         c += 2;
768         length -= 2;
769     }
770     /* </EPH> */
771
772     /* << INDEX */
773     /* End of packet header position. Currently only represents the distance to start of packet
774        Will be updated later by incrementing with packet start value*/
775     if (cstr_info && cstr_info->index_write) {
776         opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
777         info_PK->end_ph_pos = (OPJ_INT32)(c - dest);
778     }
779     /* INDEX >> */
780
781     /* Writing the packet body */
782     band = res->bands;
783     for (bandno = 0; bandno < res->numbands; bandno++) {
784         opj_tcd_precinct_t *prc = &band->precincts[precno];
785
786         l_nb_blocks = prc->cw * prc->ch;
787         cblk = prc->cblks.enc;
788
789         for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
790             opj_tcd_layer_t *layer = &cblk->layers[layno];
791
792             if (!layer->numpasses) {
793                 ++cblk;
794                 continue;
795             }
796
797             if (layer->len > length) {
798                 return OPJ_FALSE;
799             }
800
801             memcpy(c, layer->data, layer->len);
802             cblk->numpasses += layer->numpasses;
803             c += layer->len;
804             length -= layer->len;
805
806             /* << INDEX */
807             if (cstr_info && cstr_info->index_write) {
808                 opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
809                 info_PK->disto += layer->disto;
810                 if (cstr_info->D_max < info_PK->disto) {
811                     cstr_info->D_max = info_PK->disto;
812                 }
813             }
814
815             ++cblk;
816             /* INDEX >> */
817         }
818         ++band;
819     }
820
821     assert(c >= dest);
822     * p_data_written += (OPJ_UINT32)(c - dest);
823
824     return OPJ_TRUE;
825 }
826
827 static OPJ_BOOL opj_t2_skip_packet(opj_t2_t* p_t2,
828                                    opj_tcd_tile_t *p_tile,
829                                    opj_tcp_t *p_tcp,
830                                    opj_pi_iterator_t *p_pi,
831                                    OPJ_BYTE *p_src,
832                                    OPJ_UINT32 * p_data_read,
833                                    OPJ_UINT32 p_max_length,
834                                    opj_packet_info_t *p_pack_info,
835                                    opj_event_mgr_t *p_manager)
836 {
837     OPJ_BOOL l_read_data;
838     OPJ_UINT32 l_nb_bytes_read = 0;
839     OPJ_UINT32 l_nb_total_bytes_read = 0;
840
841     *p_data_read = 0;
842
843     if (! opj_t2_read_packet_header(p_t2, p_tile, p_tcp, p_pi, &l_read_data, p_src,
844                                     &l_nb_bytes_read, p_max_length, p_pack_info, p_manager)) {
845         return OPJ_FALSE;
846     }
847
848     p_src += l_nb_bytes_read;
849     l_nb_total_bytes_read += l_nb_bytes_read;
850     p_max_length -= l_nb_bytes_read;
851
852     /* we should read data for the packet */
853     if (l_read_data) {
854         l_nb_bytes_read = 0;
855
856         if (! opj_t2_skip_packet_data(p_t2, p_tile, p_pi, &l_nb_bytes_read,
857                                       p_max_length, p_pack_info, p_manager)) {
858             return OPJ_FALSE;
859         }
860
861         l_nb_total_bytes_read += l_nb_bytes_read;
862     }
863     *p_data_read = l_nb_total_bytes_read;
864
865     return OPJ_TRUE;
866 }
867
868
869 static OPJ_BOOL opj_t2_read_packet_header(opj_t2_t* p_t2,
870         opj_tcd_tile_t *p_tile,
871         opj_tcp_t *p_tcp,
872         opj_pi_iterator_t *p_pi,
873         OPJ_BOOL * p_is_data_present,
874         OPJ_BYTE *p_src_data,
875         OPJ_UINT32 * p_data_read,
876         OPJ_UINT32 p_max_length,
877         opj_packet_info_t *p_pack_info,
878         opj_event_mgr_t *p_manager)
879
880 {
881     /* loop */
882     OPJ_UINT32 bandno, cblkno;
883     OPJ_UINT32 l_nb_code_blocks;
884     OPJ_UINT32 l_remaining_length;
885     OPJ_UINT32 l_header_length;
886     OPJ_UINT32 * l_modified_length_ptr = 00;
887     OPJ_BYTE *l_current_data = p_src_data;
888     opj_cp_t *l_cp = p_t2->cp;
889     opj_bio_t *l_bio = 00;  /* BIO component */
890     opj_tcd_band_t *l_band = 00;
891     opj_tcd_cblk_dec_t* l_cblk = 00;
892     opj_tcd_resolution_t* l_res =
893         &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
894
895     OPJ_BYTE *l_header_data = 00;
896     OPJ_BYTE **l_header_data_start = 00;
897
898     OPJ_UINT32 l_present;
899
900     if (p_pi->layno == 0) {
901         l_band = l_res->bands;
902
903         /* reset tagtrees */
904         for (bandno = 0; bandno < l_res->numbands; ++bandno) {
905             if (!((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0))) {
906                 opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
907                 if (!(p_pi->precno < (l_band->precincts_data_size / sizeof(
908                                           opj_tcd_precinct_t)))) {
909                     opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct\n");
910                     return OPJ_FALSE;
911                 }
912
913
914                 opj_tgt_reset(l_prc->incltree);
915                 opj_tgt_reset(l_prc->imsbtree);
916                 l_cblk = l_prc->cblks.dec;
917
918                 l_nb_code_blocks = l_prc->cw * l_prc->ch;
919                 for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
920                     l_cblk->numsegs = 0;
921                     l_cblk->real_num_segs = 0;
922                     ++l_cblk;
923                 }
924             }
925
926             ++l_band;
927         }
928     }
929
930     /* SOP markers */
931
932     if (p_tcp->csty & J2K_CP_CSTY_SOP) {
933         if (p_max_length < 6) {
934             opj_event_msg(p_manager, EVT_WARNING,
935                           "Not enough space for expected SOP marker\n");
936         } else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) {
937             opj_event_msg(p_manager, EVT_WARNING, "Expected SOP marker\n");
938         } else {
939             l_current_data += 6;
940         }
941
942         /** TODO : check the Nsop value */
943     }
944
945     /*
946     When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
947     This part deal with this caracteristic
948     step 1: Read packet header in the saved structure
949     step 2: Return to codestream for decoding
950     */
951
952     l_bio = opj_bio_create();
953     if (! l_bio) {
954         return OPJ_FALSE;
955     }
956
957     if (l_cp->ppm == 1) { /* PPM */
958         l_header_data_start = &l_cp->ppm_data;
959         l_header_data = *l_header_data_start;
960         l_modified_length_ptr = &(l_cp->ppm_len);
961
962     } else if (p_tcp->ppt == 1) { /* PPT */
963         l_header_data_start = &(p_tcp->ppt_data);
964         l_header_data = *l_header_data_start;
965         l_modified_length_ptr = &(p_tcp->ppt_len);
966     } else { /* Normal Case */
967         l_header_data_start = &(l_current_data);
968         l_header_data = *l_header_data_start;
969         l_remaining_length = (OPJ_UINT32)(p_src_data + p_max_length - l_header_data);
970         l_modified_length_ptr = &(l_remaining_length);
971     }
972
973     opj_bio_init_dec(l_bio, l_header_data, *l_modified_length_ptr);
974
975     l_present = opj_bio_read(l_bio, 1);
976     JAS_FPRINTF(stderr, "present=%d \n", l_present);
977     if (!l_present) {
978         /* TODO MSD: no test to control the output of this function*/
979         opj_bio_inalign(l_bio);
980         l_header_data += opj_bio_numbytes(l_bio);
981         opj_bio_destroy(l_bio);
982
983         /* EPH markers */
984         if (p_tcp->csty & J2K_CP_CSTY_EPH) {
985             if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
986                     *l_header_data_start)) < 2U) {
987                 opj_event_msg(p_manager, EVT_WARNING,
988                               "Not enough space for expected EPH marker\n");
989             } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
990                 opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
991             } else {
992                 l_header_data += 2;
993             }
994         }
995
996         l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
997         *l_modified_length_ptr -= l_header_length;
998         *l_header_data_start += l_header_length;
999
1000         /* << INDEX */
1001         /* End of packet header position. Currently only represents the distance to start of packet
1002            Will be updated later by incrementing with packet start value */
1003         if (p_pack_info) {
1004             p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1005         }
1006         /* INDEX >> */
1007
1008         * p_is_data_present = OPJ_FALSE;
1009         *p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
1010         return OPJ_TRUE;
1011     }
1012
1013     l_band = l_res->bands;
1014     for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1015         opj_tcd_precinct_t *l_prc = &(l_band->precincts[p_pi->precno]);
1016
1017         if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
1018             ++l_band;
1019             continue;
1020         }
1021
1022         l_nb_code_blocks = l_prc->cw * l_prc->ch;
1023         l_cblk = l_prc->cblks.dec;
1024         for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) {
1025             OPJ_UINT32 l_included, l_increment, l_segno;
1026             OPJ_INT32 n;
1027
1028             /* if cblk not yet included before --> inclusion tagtree */
1029             if (!l_cblk->numsegs) {
1030                 l_included = opj_tgt_decode(l_bio, l_prc->incltree, cblkno,
1031                                             (OPJ_INT32)(p_pi->layno + 1));
1032                 /* else one bit */
1033             } else {
1034                 l_included = opj_bio_read(l_bio, 1);
1035             }
1036
1037             /* if cblk not included */
1038             if (!l_included) {
1039                 l_cblk->numnewpasses = 0;
1040                 ++l_cblk;
1041                 JAS_FPRINTF(stderr, "included=%d \n", l_included);
1042                 continue;
1043             }
1044
1045             /* if cblk not yet included --> zero-bitplane tagtree */
1046             if (!l_cblk->numsegs) {
1047                 OPJ_UINT32 i = 0;
1048
1049                 while (!opj_tgt_decode(l_bio, l_prc->imsbtree, cblkno, (OPJ_INT32)i)) {
1050                     ++i;
1051                 }
1052
1053                 l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i;
1054                 l_cblk->numlenbits = 3;
1055             }
1056
1057             /* number of coding passes */
1058             l_cblk->numnewpasses = opj_t2_getnumpasses(l_bio);
1059             l_increment = opj_t2_getcommacode(l_bio);
1060
1061             /* length indicator increment */
1062             l_cblk->numlenbits += l_increment;
1063             l_segno = 0;
1064
1065             if (!l_cblk->numsegs) {
1066                 if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 1)) {
1067                     opj_bio_destroy(l_bio);
1068                     return OPJ_FALSE;
1069                 }
1070             } else {
1071                 l_segno = l_cblk->numsegs - 1;
1072                 if (l_cblk->segs[l_segno].numpasses == l_cblk->segs[l_segno].maxpasses) {
1073                     ++l_segno;
1074                     if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1075                         opj_bio_destroy(l_bio);
1076                         return OPJ_FALSE;
1077                     }
1078                 }
1079             }
1080             n = (OPJ_INT32)l_cblk->numnewpasses;
1081
1082             do {
1083                 l_cblk->segs[l_segno].numnewpasses = (OPJ_UINT32)opj_int_min((OPJ_INT32)(
1084                         l_cblk->segs[l_segno].maxpasses - l_cblk->segs[l_segno].numpasses), n);
1085                 l_cblk->segs[l_segno].newlen = opj_bio_read(l_bio,
1086                                                l_cblk->numlenbits + opj_uint_floorlog2(l_cblk->segs[l_segno].numnewpasses));
1087                 JAS_FPRINTF(stderr, "included=%d numnewpasses=%d increment=%d len=%d \n",
1088                             l_included, l_cblk->segs[l_segno].numnewpasses, l_increment,
1089                             l_cblk->segs[l_segno].newlen);
1090
1091                 n -= (OPJ_INT32)l_cblk->segs[l_segno].numnewpasses;
1092                 if (n > 0) {
1093                     ++l_segno;
1094
1095                     if (! opj_t2_init_seg(l_cblk, l_segno, p_tcp->tccps[p_pi->compno].cblksty, 0)) {
1096                         opj_bio_destroy(l_bio);
1097                         return OPJ_FALSE;
1098                     }
1099                 }
1100             } while (n > 0);
1101
1102             ++l_cblk;
1103         }
1104
1105         ++l_band;
1106     }
1107
1108     if (!opj_bio_inalign(l_bio)) {
1109         opj_bio_destroy(l_bio);
1110         return OPJ_FALSE;
1111     }
1112
1113     l_header_data += opj_bio_numbytes(l_bio);
1114     opj_bio_destroy(l_bio);
1115
1116     /* EPH markers */
1117     if (p_tcp->csty & J2K_CP_CSTY_EPH) {
1118         if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data -
1119                 *l_header_data_start)) < 2U) {
1120             opj_event_msg(p_manager, EVT_WARNING,
1121                           "Not enough space for expected EPH marker\n");
1122         } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) {
1123             opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n");
1124         } else {
1125             l_header_data += 2;
1126         }
1127     }
1128
1129     l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
1130     JAS_FPRINTF(stderr, "hdrlen=%d \n", l_header_length);
1131     JAS_FPRINTF(stderr, "packet body\n");
1132     *l_modified_length_ptr -= l_header_length;
1133     *l_header_data_start += l_header_length;
1134
1135     /* << INDEX */
1136     /* End of packet header position. Currently only represents the distance to start of packet
1137      Will be updated later by incrementing with packet start value */
1138     if (p_pack_info) {
1139         p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data);
1140     }
1141     /* INDEX >> */
1142
1143     *p_is_data_present = OPJ_TRUE;
1144     *p_data_read = (OPJ_UINT32)(l_current_data - p_src_data);
1145
1146     return OPJ_TRUE;
1147 }
1148
1149 static OPJ_BOOL opj_t2_read_packet_data(opj_t2_t* p_t2,
1150                                         opj_tcd_tile_t *p_tile,
1151                                         opj_pi_iterator_t *p_pi,
1152                                         OPJ_BYTE *p_src_data,
1153                                         OPJ_UINT32 * p_data_read,
1154                                         OPJ_UINT32 p_max_length,
1155                                         opj_packet_info_t *pack_info,
1156                                         opj_event_mgr_t* p_manager)
1157 {
1158     OPJ_UINT32 bandno, cblkno;
1159     OPJ_UINT32 l_nb_code_blocks;
1160     OPJ_BYTE *l_current_data = p_src_data;
1161     opj_tcd_band_t *l_band = 00;
1162     opj_tcd_cblk_dec_t* l_cblk = 00;
1163     opj_tcd_resolution_t* l_res =
1164         &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1165
1166     OPJ_ARG_NOT_USED(p_t2);
1167     OPJ_ARG_NOT_USED(pack_info);
1168
1169     l_band = l_res->bands;
1170     for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1171         opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
1172
1173         if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
1174             ++l_band;
1175             continue;
1176         }
1177
1178         l_nb_code_blocks = l_prc->cw * l_prc->ch;
1179         l_cblk = l_prc->cblks.dec;
1180
1181         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1182             opj_tcd_seg_t *l_seg = 00;
1183
1184             if (!l_cblk->numnewpasses) {
1185                 /* nothing to do */
1186                 ++l_cblk;
1187                 continue;
1188             }
1189
1190             if (!l_cblk->numsegs) {
1191                 l_seg = l_cblk->segs;
1192                 ++l_cblk->numsegs;
1193                 l_cblk->data_current_size = 0;
1194             } else {
1195                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1196
1197                 if (l_seg->numpasses == l_seg->maxpasses) {
1198                     ++l_seg;
1199                     ++l_cblk->numsegs;
1200                 }
1201             }
1202
1203             do {
1204                 /* Check possible overflow (on l_current_data only, assumes input args already checked) then size */
1205                 if ((((OPJ_SIZE_T)l_current_data + (OPJ_SIZE_T)l_seg->newlen) <
1206                         (OPJ_SIZE_T)l_current_data) ||
1207                         (l_current_data + l_seg->newlen > p_src_data + p_max_length)) {
1208                     opj_event_msg(p_manager, EVT_ERROR,
1209                                   "read: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1210                                   l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
1211                                   p_pi->compno);
1212                     return OPJ_FALSE;
1213                 }
1214
1215 #ifdef USE_JPWL
1216                 /* we need here a j2k handle to verify if making a check to
1217                 the validity of cblocks parameters is selected from user (-W) */
1218
1219                 /* let's check that we are not exceeding */
1220                 if ((l_cblk->len + l_seg->newlen) > 8192) {
1221                     opj_event_msg(p_manager, EVT_WARNING,
1222                                   "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1223                                   l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
1224                     if (!JPWL_ASSUME) {
1225                         opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
1226                         return OPJ_FALSE;
1227                     }
1228                     l_seg->newlen = 8192 - l_cblk->len;
1229                     opj_event_msg(p_manager, EVT_WARNING, "      - truncating segment to %d\n",
1230                                   l_seg->newlen);
1231                     break;
1232                 };
1233
1234 #endif /* USE_JPWL */
1235                 /* Check possible overflow on size */
1236                 if ((l_cblk->data_current_size + l_seg->newlen) < l_cblk->data_current_size) {
1237                     opj_event_msg(p_manager, EVT_ERROR,
1238                                   "read: segment too long (%d) with current size (%d > %d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1239                                   l_seg->newlen, l_cblk->data_current_size, 0xFFFFFFFF - l_seg->newlen, cblkno,
1240                                   p_pi->precno, bandno, p_pi->resno, p_pi->compno);
1241                     return OPJ_FALSE;
1242                 }
1243                 /* Check if the cblk->data have allocated enough memory */
1244                 if ((l_cblk->data_current_size + l_seg->newlen) > l_cblk->data_max_size) {
1245                     OPJ_BYTE* new_cblk_data = (OPJ_BYTE*) opj_realloc(l_cblk->data,
1246                                               l_cblk->data_current_size + l_seg->newlen);
1247                     if (! new_cblk_data) {
1248                         opj_free(l_cblk->data);
1249                         l_cblk->data = NULL;
1250                         l_cblk->data_max_size = 0;
1251                         /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to realloc code block cata!\n"); */
1252                         return OPJ_FALSE;
1253                     }
1254                     l_cblk->data_max_size = l_cblk->data_current_size + l_seg->newlen;
1255                     l_cblk->data = new_cblk_data;
1256                 }
1257
1258                 memcpy(l_cblk->data + l_cblk->data_current_size, l_current_data, l_seg->newlen);
1259
1260                 if (l_seg->numpasses == 0) {
1261                     l_seg->data = &l_cblk->data;
1262                     l_seg->dataindex = l_cblk->data_current_size;
1263                 }
1264
1265                 l_current_data += l_seg->newlen;
1266                 l_seg->numpasses += l_seg->numnewpasses;
1267                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1268
1269                 l_seg->real_num_passes = l_seg->numpasses;
1270                 l_cblk->data_current_size += l_seg->newlen;
1271                 l_seg->len += l_seg->newlen;
1272
1273                 if (l_cblk->numnewpasses > 0) {
1274                     ++l_seg;
1275                     ++l_cblk->numsegs;
1276                 }
1277             } while (l_cblk->numnewpasses > 0);
1278
1279             l_cblk->real_num_segs = l_cblk->numsegs;
1280             ++l_cblk;
1281         } /* next code_block */
1282
1283         ++l_band;
1284     }
1285
1286     *(p_data_read) = (OPJ_UINT32)(l_current_data - p_src_data);
1287
1288
1289     return OPJ_TRUE;
1290 }
1291
1292 static OPJ_BOOL opj_t2_skip_packet_data(opj_t2_t* p_t2,
1293                                         opj_tcd_tile_t *p_tile,
1294                                         opj_pi_iterator_t *p_pi,
1295                                         OPJ_UINT32 * p_data_read,
1296                                         OPJ_UINT32 p_max_length,
1297                                         opj_packet_info_t *pack_info,
1298                                         opj_event_mgr_t *p_manager)
1299 {
1300     OPJ_UINT32 bandno, cblkno;
1301     OPJ_UINT32 l_nb_code_blocks;
1302     opj_tcd_band_t *l_band = 00;
1303     opj_tcd_cblk_dec_t* l_cblk = 00;
1304     opj_tcd_resolution_t* l_res =
1305         &p_tile->comps[p_pi->compno].resolutions[p_pi->resno];
1306
1307     OPJ_ARG_NOT_USED(p_t2);
1308     OPJ_ARG_NOT_USED(pack_info);
1309
1310     *p_data_read = 0;
1311     l_band = l_res->bands;
1312
1313     for (bandno = 0; bandno < l_res->numbands; ++bandno) {
1314         opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno];
1315
1316         if ((l_band->x1 - l_band->x0 == 0) || (l_band->y1 - l_band->y0 == 0)) {
1317             ++l_band;
1318             continue;
1319         }
1320
1321         l_nb_code_blocks = l_prc->cw * l_prc->ch;
1322         l_cblk = l_prc->cblks.dec;
1323
1324         for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
1325             opj_tcd_seg_t *l_seg = 00;
1326
1327             if (!l_cblk->numnewpasses) {
1328                 /* nothing to do */
1329                 ++l_cblk;
1330                 continue;
1331             }
1332
1333             if (!l_cblk->numsegs) {
1334                 l_seg = l_cblk->segs;
1335                 ++l_cblk->numsegs;
1336                 l_cblk->data_current_size = 0;
1337             } else {
1338                 l_seg = &l_cblk->segs[l_cblk->numsegs - 1];
1339
1340                 if (l_seg->numpasses == l_seg->maxpasses) {
1341                     ++l_seg;
1342                     ++l_cblk->numsegs;
1343                 }
1344             }
1345
1346             do {
1347                 /* Check possible overflow then size */
1348                 if (((*p_data_read + l_seg->newlen) < (*p_data_read)) ||
1349                         ((*p_data_read + l_seg->newlen) > p_max_length)) {
1350                     opj_event_msg(p_manager, EVT_ERROR,
1351                                   "skip: segment too long (%d) with max (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1352                                   l_seg->newlen, p_max_length, cblkno, p_pi->precno, bandno, p_pi->resno,
1353                                   p_pi->compno);
1354                     return OPJ_FALSE;
1355                 }
1356
1357 #ifdef USE_JPWL
1358                 /* we need here a j2k handle to verify if making a check to
1359                 the validity of cblocks parameters is selected from user (-W) */
1360
1361                 /* let's check that we are not exceeding */
1362                 if ((l_cblk->len + l_seg->newlen) > 8192) {
1363                     opj_event_msg(p_manager, EVT_WARNING,
1364                                   "JPWL: segment too long (%d) for codeblock %d (p=%d, b=%d, r=%d, c=%d)\n",
1365                                   l_seg->newlen, cblkno, p_pi->precno, bandno, p_pi->resno, p_pi->compno);
1366                     if (!JPWL_ASSUME) {
1367                         opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
1368                         return -999;
1369                     }
1370                     l_seg->newlen = 8192 - l_cblk->len;
1371                     opj_event_msg(p_manager, EVT_WARNING, "      - truncating segment to %d\n",
1372                                   l_seg->newlen);
1373                     break;
1374                 };
1375
1376 #endif /* USE_JPWL */
1377                 JAS_FPRINTF(stderr, "p_data_read (%d) newlen (%d) \n", *p_data_read,
1378                             l_seg->newlen);
1379                 *(p_data_read) += l_seg->newlen;
1380
1381                 l_seg->numpasses += l_seg->numnewpasses;
1382                 l_cblk->numnewpasses -= l_seg->numnewpasses;
1383                 if (l_cblk->numnewpasses > 0) {
1384                     ++l_seg;
1385                     ++l_cblk->numsegs;
1386                 }
1387             } while (l_cblk->numnewpasses > 0);
1388
1389             ++l_cblk;
1390         }
1391
1392         ++l_band;
1393     }
1394
1395     return OPJ_TRUE;
1396 }
1397
1398
1399 static OPJ_BOOL opj_t2_init_seg(opj_tcd_cblk_dec_t* cblk,
1400                                 OPJ_UINT32 index,
1401                                 OPJ_UINT32 cblksty,
1402                                 OPJ_UINT32 first)
1403 {
1404     opj_tcd_seg_t* seg = 00;
1405     OPJ_UINT32 l_nb_segs = index + 1;
1406
1407     if (l_nb_segs > cblk->m_current_max_segs) {
1408         opj_tcd_seg_t* new_segs;
1409         cblk->m_current_max_segs += OPJ_J2K_DEFAULT_NB_SEGS;
1410
1411         new_segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs,
1412                                                 cblk->m_current_max_segs * sizeof(opj_tcd_seg_t));
1413         if (! new_segs) {
1414             opj_free(cblk->segs);
1415             cblk->segs = NULL;
1416             cblk->m_current_max_segs = 0;
1417             /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to initialize segment %d\n", l_nb_segs); */
1418             return OPJ_FALSE;
1419         }
1420         cblk->segs = new_segs;
1421     }
1422
1423     seg = &cblk->segs[index];
1424     memset(seg, 0, sizeof(opj_tcd_seg_t));
1425
1426     if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
1427         seg->maxpasses = 1;
1428     } else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
1429         if (first) {
1430             seg->maxpasses = 10;
1431         } else {
1432             seg->maxpasses = (((seg - 1)->maxpasses == 1) ||
1433                               ((seg - 1)->maxpasses == 10)) ? 2 : 1;
1434         }
1435     } else {
1436         seg->maxpasses = 109;
1437     }
1438
1439     return OPJ_TRUE;
1440 }