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