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