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