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