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