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