First integration of JPWL code
[openjpeg.git] / codec / image_to_j2k.c
1 /*
2  * Copyright (c) 2001-2003, David Janssens
3  * Copyright (c) 2002-2003, Yannick Verschueren
4  * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
5  * Copyright (c) 2005, Herv� Drolon, FreeImage Team
6  * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "openjpeg.h"
35 #include "compat/getopt.h"
36 #include "convert.h"
37
38 #ifndef WIN32
39 #define stricmp strcasecmp
40 #define strnicmp strncasecmp
41 #endif
42
43 /* ----------------------------------------------------------------------- */
44
45 #define J2K_CFMT 0
46 #define JP2_CFMT 1
47 #define JPT_CFMT 2
48 #define MJ2_CFMT 3
49 #define PXM_DFMT 0
50 #define PGX_DFMT 1
51 #define BMP_DFMT 2
52 #define YUV_DFMT 3
53
54 /* ----------------------------------------------------------------------- */
55
56 void encode_help_display() {
57         fprintf(stdout,"HELP\n----\n\n");
58         fprintf(stdout,"- the -h option displays this help information on screen\n\n");
59
60 /* UniPG>> */
61         fprintf(stdout,"List of parameters for the JPEG 2000 "
62 #ifdef USE_JPWL
63                 "+ JPWL "
64 #endif /* USE_JPWL */
65                 "encoder:\n");
66 /* <<UniPG */
67         fprintf(stdout,"\n");
68         fprintf(stdout,"REMARKS:\n");
69         fprintf(stdout,"---------\n");
70         fprintf(stdout,"\n");
71         fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
72         fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
73         fprintf(stdout,"\n");
74         fprintf(stdout,"- This coder can encode a mega image, a test was made on a 24000x24000 pixels \n");
75         fprintf(stdout,"color image.  You need enough disk space memory (twice the original) to encode \n");
76         fprintf(stdout,"the image,i.e. for a 1.5 GB image you need a minimum of 3GB of disk memory)\n");
77         fprintf(stdout,"\n");
78         fprintf(stdout,"By default:\n");
79         fprintf(stdout,"------------\n");
80         fprintf(stdout,"\n");
81         fprintf(stdout," * Lossless\n");
82         fprintf(stdout," * 1 tile\n");
83         fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
84         fprintf(stdout," * Size of code-block : 64 x 64\n");
85         fprintf(stdout," * Number of resolutions: 6\n");
86         fprintf(stdout," * No SOP marker in the codestream\n");
87         fprintf(stdout," * No EPH marker in the codestream\n");
88         fprintf(stdout," * No sub-sampling in x or y direction\n");
89         fprintf(stdout," * No mode switch activated\n");
90         fprintf(stdout," * Progression order: LRCP\n");
91         fprintf(stdout," * No index file\n");
92         fprintf(stdout," * No ROI upshifted\n");
93         fprintf(stdout," * No offset of the origin of the image\n");
94         fprintf(stdout," * No offset of the origin of the tiles\n");
95         fprintf(stdout," * Reversible DWT 5-3\n");
96 /* UniPG>> */
97 #ifdef USE_JPWL
98         fprintf(stdout," * No JPWL protection\n");
99 #endif /* USE_JPWL */
100 /* <<UniPG */
101         fprintf(stdout,"\n");
102         fprintf(stdout,"Parameters:\n");
103         fprintf(stdout,"------------\n");
104         fprintf(stdout,"\n");
105         fprintf(stdout,"Required Parameters (except with -h):\n");
106         fprintf(stdout,"\n");
107         fprintf(stdout,"-i           : source file  (-i source.pnm also *.pgm, *.ppm) \n");
108         fprintf(stdout,"\n");
109         fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");
110         fprintf(stdout,"\n");
111         fprintf(stdout,"Optional Parameters:\n");
112         fprintf(stdout,"\n");
113         fprintf(stdout,"-h           : display the help information \n ");
114         fprintf(stdout,"\n");
115         fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
116         fprintf(stdout,"                 - The rate specified for each quality level is the desired \n");
117         fprintf(stdout,"                   compression factor.\n");
118         fprintf(stdout,"                   Example: -r 20,10,1 means quality 1: compress 20x, \n");
119         fprintf(stdout,"                     quality 2: compress 10x and quality 3: compress lossless\n");
120         fprintf(stdout,"\n");
121         fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
122         fprintf(stdout,"\n");
123
124         fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");
125
126         fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
127
128         fprintf(stdout,"\n");
129         fprintf(stdout,"-n           : number of resolutions (-n 3) \n");
130         fprintf(stdout,"\n");
131         fprintf(stdout,"-b           : size of code block (-b 32,32) \n");
132         fprintf(stdout,"\n");
133         fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");
134         fprintf(stdout,"\n");
135         fprintf(stdout,"-t           : size of tile (-t 512,512) \n");
136         fprintf(stdout,"\n");
137         fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
138         fprintf(stdout,"\n");
139         fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");
140         fprintf(stdout,"             Remark: subsampling bigger than 2 can produce error\n");
141         fprintf(stdout,"\n");
142         fprintf(stdout,"-SOP         : write SOP marker before each packet \n");
143         fprintf(stdout,"\n");
144         fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");
145         fprintf(stdout,"\n");
146         fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
147         fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
148         fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");
149         fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
150         fprintf(stdout,"\n");
151         fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");
152         fprintf(stdout,"\n");
153         fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
154         fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");
155         fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
156         fprintf(stdout,"\n");
157         fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");
158         fprintf(stdout,"\n");
159         fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");
160         fprintf(stdout,"\n");
161         fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");
162         fprintf(stdout,"\n");
163 /* UniPG>> */
164 #ifdef USE_JPWL
165         fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");
166         fprintf(stdout,"               The parameters can be written and repeated in any order:\n");
167         fprintf(stdout,"               [h<tile><=type>,s<tile><=method>,a=<addr>,z=<size>,g=<range>,...\n");
168         fprintf(stdout,"                ...,p<tile:pack><=type>]\n");
169         fprintf(stdout,"\n");
170         fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");
171         fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
172         fprintf(stdout,"                   if 'tile' is absent, it applies to main and tile headers\n");
173         fprintf(stdout,"                   if 'tile' is present, it applies from that tile\n");
174         fprintf(stdout,"                     onwards, up to the next h<tile> spec, or to the last tile\n");
175         fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
176         fprintf(stdout,"\n");
177         fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");
178         fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");
179         fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
180         fprintf(stdout,"                   if 'tile:pack' is absent, it starts from tile 0, packet 0\n");
181         fprintf(stdout,"                   if 'tile:pack' is present, it applies from that tile\n");
182         fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");
183         fprintf(stdout,"                     or to the last packet in the last tile in the codestream\n");
184         fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
185         fprintf(stdout,"\n");
186         fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");
187         fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
188         fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
189         fprintf(stdout,"                   if 'tile' is absent, it applies to main header only\n");
190         fprintf(stdout,"                   if 'tile' is present, it applies from that tile\n");
191         fprintf(stdout,"                     onwards, up to the next s<tile> spec, or to the last tile\n");
192         fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
193         fprintf(stdout,"\n");
194         fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");
195         fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
196         fprintf(stdout,"\n");
197         fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");
198         fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");
199         fprintf(stdout,"\n");
200         fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");
201         fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");
202         fprintf(stdout,"\n");
203         fprintf(stdout,"                 ex.:\n");
204         fprintf(stdout," h,h0=64,h3=16,h5=0,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,s0=6,s3=-1,a=0,g=1,z=1\n");
205         fprintf(stdout,"                 means\n");
206         fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
207         fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, no EPBs in remaining TPHs,\n");
208         fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
209         fprintf(stdout,"                   UEP rs(56,32) for packets 24 to the last of tile 0,\n");
210         fprintf(stdout,"                   UEP rs default for packets of tile 1,\n");
211         fprintf(stdout,"                   no UEP for packets 0 to 19 of tile 3,\n");
212         fprintf(stdout,"                   UEP CRC-32 for packets 20 of tile 3 to last tile,\n");
213         fprintf(stdout,"                   relative sensitivity ESD for MH,\n");
214         fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
215         fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");
216         fprintf(stdout,"\n");
217         fprintf(stdout,"                 ex.:\n");
218         fprintf(stdout,"                       h,s,p\n");
219         fprintf(stdout,"                 means\n");
220         fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");
221         fprintf(stdout,"                   data packets, one ESD in MH\n");
222 #endif /* USE_JPWL */
223 /* <<UniPG */
224         fprintf(stdout,"IMPORTANT:\n");
225         fprintf(stdout,"-----------\n");
226         fprintf(stdout,"\n");
227         fprintf(stdout,"The index file has the structure below:\n");
228         fprintf(stdout,"---------------------------------------\n");
229         fprintf(stdout,"\n");
230         fprintf(stdout,"Image_height Image_width\n");
231         fprintf(stdout,"progression order\n");
232         fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
233 /* UniPG>> */
234         fprintf(stdout,"Tiles_nb_X Tiles_nb_Y\n");
235 /* <<UniPG */
236         fprintf(stdout,"Components_nb\n");
237         fprintf(stdout,"Layers_nb\n");
238         fprintf(stdout,"decomposition_levels\n");
239         fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
240         fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
241         fprintf(stdout,"Main_header_end_position\n");
242         fprintf(stdout,"Codestream_size\n");
243         fprintf(stdout,"Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
244         fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''\n");
245         fprintf(stdout,"...\n");
246         fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''\n");
247         fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
248         fprintf(stdout,"...\n");
249         fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
250
251         fprintf(stdout,"MaxDisto\n");
252
253         fprintf(stdout,"TotalDisto\n\n");
254 }
255
256 OPJ_PROG_ORDER give_progression(char progression[4]) {
257         if(strncmp(progression, "LRCP", 4) == 0) {
258                 return LRCP;
259         }
260         if(strncmp(progression, "RLCP", 4) == 0) {
261                 return RLCP;
262         }
263         if(strncmp(progression, "RPCL", 4) == 0) {
264                 return RPCL;
265         }
266         if(strncmp(progression, "PCRL", 4) == 0) {
267                 return PCRL;
268         }
269         if(strncmp(progression, "CPRL", 4) == 0) {
270                 return CPRL;
271         }
272
273         return PROG_UNKNOWN;
274 }
275
276 int get_file_format(char *filename) {
277         unsigned int i;
278         static const char *extension[] = {
279     "pgx", "pnm", "pgm", "ppm", "bmp", "j2k", "jp2"
280     };
281         static const int format[] = {
282     PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, J2K_CFMT, JP2_CFMT
283     };
284         char * ext = strrchr(filename, '.') + 1;
285         for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
286                 if(strnicmp(ext, extension[i], 3) == 0) {
287                         return format[i];
288                 }
289         }
290
291         return -1;
292 }
293
294 /* -------------------------------------------------------------------------*/
295
296 int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters) {
297         int i, j;
298
299         /* parse the command line */
300 /* UniPG>> */
301         const char optlist[] = "i:o:hr:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:"
302 #ifdef USE_JPWL
303                 "W:"
304 #endif /* USE_JPWL */
305                 ;
306
307         while (1) {
308                 int c = getopt(argc, argv, optlist);
309 /* <<UniPG */
310                 if (c == -1)
311                         break;
312                 switch (c) {
313                         case 'i':                       /* input file */
314                         {
315                                 char *infile = optarg;
316                                 parameters->decod_format = get_file_format(infile);
317                                 switch(parameters->decod_format) {
318                                         case PGX_DFMT:
319                                         case PXM_DFMT:
320                                         case BMP_DFMT:
321                                                 break;
322                                         default:
323                                                 fprintf(stderr,
324                                                         "!! Unrecognized format for infile : %s "
325               "[accept only *.pnm, *.pgm, *.ppm, *.pgx or *.bmp] !!\n\n", 
326                                                         infile);
327                                                 return 1;
328                                 }
329                                 strncpy(parameters->infile, infile, MAX_PATH);
330                         }
331                         break;
332
333                                 /* ----------------------------------------------------- */
334
335                         case 'o':                       /* output file */
336                         {
337                                 char *outfile = optarg;
338                                 parameters->cod_format = get_file_format(outfile);
339                                 switch(parameters->cod_format) {
340                                         case J2K_CFMT:
341                                         case JP2_CFMT:
342                                                 break;
343                                         default:
344                                                 fprintf(stderr, "Unknown output format image %s [only *.j2k, *.jp2]!! \n", outfile);
345                                                 return 1;
346                                 }
347                                 strncpy(parameters->outfile, outfile, MAX_PATH);
348                         }
349                         break;
350
351                                 /* ----------------------------------------------------- */
352
353                         case 'r':                       /* rates rates/distorsion */
354                         {
355                                 char *s = optarg;
356                                 while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {
357                                         parameters->tcp_numlayers++;
358                                         while (*s && *s != ',') {
359                                                 s++;
360                                         }
361                                         if (!*s)
362                                                 break;
363                                         s++;
364                                 }
365                                 parameters->cp_disto_alloc = 1;
366                         }
367                         break;
368
369                                 /* ----------------------------------------------------- */
370
371                         case 'q':                       /* add fixed_quality */
372                         {
373                                 char *s = optarg;
374                                 while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {
375                                         parameters->tcp_numlayers++;
376                                         while (*s && *s != ',') {
377                                                 s++;
378                                         }
379                                         if (!*s)
380                                                 break;
381                                         s++;
382                                 }
383                                 parameters->cp_fixed_quality = 1;
384                         }
385                         break;
386
387                                 /* dda */
388                                 /* ----------------------------------------------------- */
389
390                         case 'f':                       /* mod fixed_quality (before : -q) */
391                         {
392                                 int *row = NULL, *col = NULL;
393                                 int numlayers = 0, numresolution = 0, matrix_width = 0;
394
395                                 char *s = optarg;
396                                 sscanf(s, "%d", &numlayers);
397                                 s++;
398                                 if (numlayers > 9)
399                                         s++;
400
401                                 parameters->tcp_numlayers = numlayers;
402                                 numresolution = parameters->numresolution;
403                                 matrix_width = numresolution * 3;
404                                 parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
405                                 s = s + 2;
406
407                                 for (i = 0; i < numlayers; i++) {
408                                         row = &parameters->cp_matrice[i * matrix_width];
409                                         col = row;
410                                         parameters->tcp_rates[i] = 1;
411                                         sscanf(s, "%d,", &col[0]);
412                                         s += 2;
413                                         if (col[0] > 9)
414                                                 s++;
415                                         col[1] = 0;
416                                         col[2] = 0;
417                                         for (j = 1; j < numresolution; j++) {
418                                                 col += 3;
419                                                 sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
420                                                 s += 6;
421                                                 if (col[0] > 9)
422                                                         s++;
423                                                 if (col[1] > 9)
424                                                         s++;
425                                                 if (col[2] > 9)
426                                                         s++;
427                                         }
428                                         if (i < numlayers - 1)
429                                                 s++;
430                                 }
431                                 parameters->cp_fixed_alloc = 1;
432                         }
433                         break;
434
435                                 /* ----------------------------------------------------- */
436
437                         case 't':                       /* tiles */
438                         {
439                                 sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
440                                 parameters->tile_size_on = true;
441                         }
442                         break;
443
444                                 /* ----------------------------------------------------- */
445
446                         case 'n':                       /* resolution */
447                         {
448                                 sscanf(optarg, "%d", &parameters->numresolution);
449                         }
450                         break;
451
452                                 /* ----------------------------------------------------- */
453                         case 'c':                       /* precinct dimension */
454                         {
455                                 char sep;
456                                 int res_spec = 0;
457
458                                 char *s = optarg;
459                                 do {
460                                         sep = 0;
461                                         sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
462                                  &parameters->prch_init[res_spec], &sep);
463                                         parameters->csty |= 0x01;
464                                         res_spec++;
465                                         s = strpbrk(s, "]") + 2;
466                                 }
467                                 while (sep == ',');
468                                 parameters->res_spec = res_spec;
469                         }
470                         break;
471
472                                 /* ----------------------------------------------------- */
473
474                         case 'b':                       /* code-block dimension */
475                         {
476                                 int cblockw_init = 0, cblockh_init = 0;
477                                 sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
478                                 if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
479                                         || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
480                                         fprintf(stderr,
481                                                 "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
482             "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
483                                         return 1;
484                                 }
485                                 parameters->cblockw_init = cblockw_init;
486                                 parameters->cblockh_init = cblockh_init;
487                         }
488                         break;
489
490                                 /* ----------------------------------------------------- */
491
492                         case 'x':                       /* creation of index file */
493                         {
494                                 char *index = optarg;
495                                 strncpy(parameters->index, index, MAX_PATH);
496                                 parameters->index_on = 1;
497                         }
498                         break;
499
500                                 /* ----------------------------------------------------- */
501
502                         case 'p':                       /* progression order */
503                         {
504                                 char progression[4];
505
506                                 strncpy(progression, optarg, 4);
507                                 parameters->prog_order = give_progression(progression);
508                                 if (parameters->prog_order == -1) {
509                                         fprintf(stderr, "Unrecognized progression order "
510             "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
511                                         return 1;
512                                 }
513                         }
514                         break;
515
516                                 /* ----------------------------------------------------- */
517
518                         case 's':                       /* subsampling factor */
519                         {
520                                 if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx,
521                                     &parameters->subsampling_dy) != 2) {
522                                         fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
523                                         return 1;
524                                 }
525                         }
526                         break;
527
528                                 /* ----------------------------------------------------- */
529
530                         case 'd':                       /* coordonnate of the reference grid */
531                         {
532                                 if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0,
533                                     &parameters->image_offset_y0) != 2) {
534                                         fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
535             "error !! [-d x0,y0]\n");
536                                         return 1;
537                                 }
538                         }
539                         break;
540
541                                 /* ----------------------------------------------------- */
542
543                         case 'h':                       /* display an help description */
544                                 encode_help_display();
545                                 return 1;
546
547                                 /* ----------------------------------------------------- */
548
549                         case 'P':                       /* POC */
550                         {
551                                 int numpocs = 0;                /* number of progression order change (POC) default 0 */
552                                 opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
553
554                                 char *s = optarg;
555                                 POC = parameters->POC;
556
557                                 fprintf(stderr, "/----------------------------------\\\n");
558                                 fprintf(stderr, "|  POC option not fully tested !!  |\n");
559                                 fprintf(stderr, "\\----------------------------------/\n");
560
561                                 while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%s", &POC[numpocs].tile,
562                                         &POC[numpocs].resno0, &POC[numpocs].compno0,
563                                         &POC[numpocs].layno1, &POC[numpocs].resno1,
564                                         &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
565                                         POC[numpocs].prg = give_progression(POC[numpocs].progorder);
566                                         /* POC[numpocs].tile; */
567                                         numpocs++;
568                                         while (*s && *s != '/') {
569                                                 s++;
570                                         }
571                                         if (!*s) {
572                                                 break;
573                                         }
574                                         s++;
575                                 }
576                                 parameters->numpocs = numpocs;
577                         }
578                         break;
579
580                                 /* ------------------------------------------------------ */
581
582                         case 'S':                       /* SOP marker */
583                         {
584                                 parameters->csty |= 0x02;
585                         }
586                         break;
587
588                                 /* ------------------------------------------------------ */
589
590                         case 'E':                       /* EPH marker */
591                         {
592                                 parameters->csty |= 0x04;
593                         }
594                         break;
595
596                                 /* ------------------------------------------------------ */
597
598                         case 'M':                       /* Mode switch pas tous au point !! */
599                         {
600                                 int value = 0;
601                                 if (sscanf(optarg, "%d", &value) == 1) {
602                                         for (i = 0; i <= 5; i++) {
603                                                 int cache = value & (1 << i);
604                                                 if (cache)
605                                                         parameters->mode |= (1 << i);
606                                         }
607                                 }
608                         }
609                         break;
610
611                                 /* ------------------------------------------------------ */
612
613                         case 'R':                       /* ROI */
614                         {
615                                 if (sscanf(optarg, "OI:c=%d,U=%d", &parameters->roi_compno,
616                                            &parameters->roi_shift) != 2) {
617                                         fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
618                                         return 1;
619                                 }
620                         }
621                         break;
622
623                                 /* ------------------------------------------------------ */
624
625                         case 'T':                       /* Tile offset */
626                         {
627                                 if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {
628                                         fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
629                                         return 1;
630                                 }
631                         }
632                         break;
633
634                                 /* ------------------------------------------------------ */
635
636                         case 'C':                       /* add a comment */
637                         {
638                                 parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
639                                 if(parameters->cp_comment) {
640                                         strcpy(parameters->cp_comment, optarg);
641                                 }
642                         }
643                         break;
644
645
646                                 /* ------------------------------------------------------ */
647
648                         case 'I':                       /* reversible or not */
649                         {
650                                 parameters->irreversible = 1;
651                         }
652                         break;
653
654 /* UniPG>> */
655 #ifdef USE_JPWL
656                                 /* ------------------------------------------------------ */
657                         
658                         case 'W':                       /* JPWL capabilities switched on */
659                         {
660                                 char *token = NULL;
661                                 int hprot, pprot, sens, addr, size, range;
662
663                                 /* we need to enable indexing */
664                                 if (!parameters->index_on) {
665                                         strncpy(parameters->index, JPWL_PRIVATEINDEX_NAME, MAX_PATH);
666                                         parameters->index_on = 1;
667                                 }
668
669                                 /* search for different protection methods */
670
671                                 /* break the option in comma points and parse the result */
672                                 token = strtok(optarg, ",");
673                                 while(token != NULL) {
674
675                                         /* search header error protection method */
676                                         if (*token == 'h') {
677
678                                                 static int tile = 0, tilespec = 0, lasttileno = 0;
679
680                                                 hprot = 1; /* predefined method */
681
682                                                 if(sscanf(token, "h=%d", &hprot) == 1) {
683                                                         /* Main header, specified */
684                                                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
685                                                                 ((hprot >= 37) && (hprot <= 128)))) {
686                                                                 fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n", hprot);
687                                                                 return 1;
688                                                         }
689                                                         parameters->jpwl_hprot_MH = hprot;
690
691                                                 } else if(sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
692                                                         /* Tile part header, specified */
693                                                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
694                                                                 ((hprot >= 37) && (hprot <= 128)))) {
695                                                                 fprintf(stderr, "ERROR -> invalid tile header protection method h = %d\n", hprot);
696                                                                 return 1;
697                                                         }
698                                                         if (tile < 0) {
699                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method t = %d\n", tile);
700                                                                 return 1;
701                                                         }
702                                                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
703                                                                 parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
704                                                                 parameters->jpwl_hprot_TPH[tilespec++] = hprot;
705                                                         }
706
707                                                 } else if(sscanf(token, "h%d", &tile) == 1) {
708                                                         /* Tile part header, unspecified */
709                                                         if (tile < 0) {
710                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method t = %d\n", tile);
711                                                                 return 1;
712                                                         }
713                                                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
714                                                                 parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
715                                                                 parameters->jpwl_hprot_TPH[tilespec++] = hprot;
716                                                         }
717
718
719                                                 } else if (!strcmp(token, "h")) {
720                                                         /* Main header, unspecified */
721                                                         parameters->jpwl_hprot_MH = hprot;
722
723                                                 } else {
724                                                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
725                                                         return 1;
726                                                 };
727
728                                         }
729
730                                         /* search packet error protection method */
731                                         if (*token == 'p') {
732
733                                                 static int pack = 0, tile = 0, packspec = 0, lastpackno = 0;
734
735                                                 pprot = 1; /* predefined method */
736
737                                                 if (sscanf(token, "p=%d", &pprot) == 1) {
738                                                         /* Method for all tiles and all packets */
739                                                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
740                                                                 ((pprot >= 37) && (pprot <= 128)))) {
741                                                                 fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n", pprot);
742                                                                 return 1;
743                                                         }
744                                                         parameters->jpwl_pprot_tileno[0] = 0;
745                                                         parameters->jpwl_pprot_packno[0] = 0;
746                                                         parameters->jpwl_pprot[0] = pprot;
747
748                                                 } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
749                                                         /* method specified from that tile on */
750                                                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
751                                                                 ((pprot >= 37) && (pprot <= 128)))) {
752                                                                 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
753                                                                 return 1;
754                                                         }
755                                                         if (tile < 0) {
756                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method p = %d\n", tile);
757                                                                 return 1;
758                                                         }
759                                                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
760                                                                 parameters->jpwl_pprot_tileno[packspec] = tile;
761                                                                 parameters->jpwl_pprot_packno[packspec] = 0;
762                                                                 parameters->jpwl_pprot[packspec++] = pprot;
763                                                         }
764
765                                                 } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
766                                                         /* method fully specified from that tile and that packet on */
767                                                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
768                                                                 ((pprot >= 37) && (pprot <= 128)))) {
769                                                                 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
770                                                                 return 1;
771                                                         }
772                                                         if (tile < 0) {
773                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method p = %d\n", tile);
774                                                                 return 1;
775                                                         }
776                                                         if (pack < 0) {
777                                                                 fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
778                                                                 return 1;
779                                                         }
780                                                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
781                                                                 parameters->jpwl_pprot_tileno[packspec] = tile;
782                                                                 parameters->jpwl_pprot_packno[packspec] = pack;
783                                                                 parameters->jpwl_pprot[packspec++] = pprot;
784                                                         }
785
786                                                 } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
787                                                         /* default method from that tile and that packet on */
788                                                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
789                                                                 ((pprot >= 37) && (pprot <= 128)))) {
790                                                                 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
791                                                                 return 1;
792                                                         }
793                                                         if (tile < 0) {
794                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method p = %d\n", tile);
795                                                                 return 1;
796                                                         }
797                                                         if (pack < 0) {
798                                                                 fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
799                                                                 return 1;
800                                                         }
801                                                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
802                                                                 parameters->jpwl_pprot_tileno[packspec] = tile;
803                                                                 parameters->jpwl_pprot_packno[packspec] = pack;
804                                                                 parameters->jpwl_pprot[packspec++] = pprot;
805                                                         }
806
807                                                 } else if (sscanf(token, "p%d", &tile) == 1) {
808                                                         /* default from a tile on */
809                                                         if (tile < 0) {
810                                                                 fprintf(stderr, "ERROR -> invalid tile number on protection method p = %d\n", tile);
811                                                                 return 1;
812                                                         }
813                                                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
814                                                                 parameters->jpwl_pprot_tileno[packspec] = tile;
815                                                                 parameters->jpwl_pprot_packno[packspec] = 0;
816                                                                 parameters->jpwl_pprot[packspec++] = pprot;
817                                                         }
818
819
820                                                 } else if (!strcmp(token, "p")) {
821                                                         /* all default */
822                                                         parameters->jpwl_pprot_tileno[0] = 0;
823                                                         parameters->jpwl_pprot_packno[0] = 0;
824                                                         parameters->jpwl_pprot[0] = pprot;
825
826                                                 } else {
827                                                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
828                                                         return 1;
829                                                 };
830
831                                         }
832
833                                         /* search sensitivity method */
834                                         if (*token == 's') {
835
836                                                 static int tile = 0, tilespec = 0, lasttileno = 0;
837
838                                                 sens = 0; /* predefined: relative error */
839
840                                                 if(sscanf(token, "s=%d", &sens) == 1) {
841                                                         /* Main header, specified */
842                                                         if ((sens < -1) || (sens > 7)) {
843                                                                 fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n", sens);
844                                                                 return 1;
845                                                         }
846                                                         parameters->jpwl_sens_MH = sens;
847
848                                                 } else if(sscanf(token, "s%d=%d", &tile, &sens) == 2) {
849                                                         /* Tile part header, specified */
850                                                         if ((sens < -1) || (sens > 7)) {
851                                                                 fprintf(stderr, "ERROR -> invalid tile header sensitivity method s = %d\n", sens);
852                                                                 return 1;
853                                                         }
854                                                         if (tile < 0) {
855                                                                 fprintf(stderr, "ERROR -> invalid tile number on sensitivity method t = %d\n", tile);
856                                                                 return 1;
857                                                         }
858                                                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
859                                                                 parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
860                                                                 parameters->jpwl_sens_TPH[tilespec++] = sens;
861                                                         }
862
863                                                 } else if(sscanf(token, "s%d", &tile) == 1) {
864                                                         /* Tile part header, unspecified */
865                                                         if (tile < 0) {
866                                                                 fprintf(stderr, "ERROR -> invalid tile number on sensitivity method t = %d\n", tile);
867                                                                 return 1;
868                                                         }
869                                                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
870                                                                 parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
871                                                                 parameters->jpwl_sens_TPH[tilespec++] = hprot;
872                                                         }
873
874                                                 } else if (!strcmp(token, "s")) {
875                                                         /* Main header, unspecified */
876                                                         parameters->jpwl_sens_MH = sens;
877
878                                                 } else {
879                                                         fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
880                                                         return 1;
881                                                 };
882                                                 
883                                                 parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
884                                         }
885
886                                         /* search addressing size */
887                                         if (*token == 'a') {
888
889                                                 static int tile = 0, tilespec = 0, lasttileno = 0;
890
891                                                 addr = 0; /* predefined: auto */
892
893                                                 if(sscanf(token, "a=%d", &addr) == 1) {
894                                                         /* Specified */
895                                                         if ((addr != 0) && (addr != 2) && (addr != 4)) {
896                                                                 fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
897                                                                 return 1;
898                                                         }
899                                                         parameters->jpwl_sens_addr = addr;
900
901                                                 } else if (!strcmp(token, "a")) {
902                                                         /* default */
903                                                         parameters->jpwl_sens_addr = addr; /* auto for default size */
904
905                                                 } else {
906                                                         fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
907                                                         return 1;
908                                                 };
909                                                 
910                                         }
911
912                                         /* search sensitivity size */
913                                         if (*token == 'z') {
914
915                                                 static int tile = 0, tilespec = 0, lasttileno = 0;
916
917                                                 size = 1; /* predefined: 1 byte */
918
919                                                 if(sscanf(token, "z=%d", &size) == 1) {
920                                                         /* Specified */
921                                                         if ((size != 0) && (size != 1) && (size != 2)) {
922                                                                 fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
923                                                                 return 1;
924                                                         }
925                                                         parameters->jpwl_sens_size = size;
926
927                                                 } else if (!strcmp(token, "a")) {
928                                                         /* default */
929                                                         parameters->jpwl_sens_size = size; /* 1 for default size */
930
931                                                 } else {
932                                                         fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
933                                                         return 1;
934                                                 };
935                                                 
936                                         }
937
938                                         /* search range method */
939                                         if (*token == 'g') {
940
941                                                 static int tile = 0, tilespec = 0, lasttileno = 0;
942
943                                                 range = 0; /* predefined: 0 (packet) */
944
945                                                 if(sscanf(token, "g=%d", &range) == 1) {
946                                                         /* Specified */
947                                                         if ((range < 0) || (range > 3)) {
948                                                                 fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
949                                                                 return 1;
950                                                         }
951                                                         parameters->jpwl_sens_range = range;
952
953                                                 } else if (!strcmp(token, "g")) {
954                                                         /* default */
955                                                         parameters->jpwl_sens_range = range;
956
957                                                 } else {
958                                                         fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
959                                                         return 1;
960                                                 };
961                                                 
962                                         }
963
964                                         /* next token or bust */
965                                         token = strtok(NULL, ",");
966                                 };
967
968
969                                 /* some info */
970                                 fprintf(stdout, "Info: JPWL capabilities enabled\n");
971                                 parameters->jpwl_epc_on = true;
972
973                         }
974                         break;
975 #endif USE_JPWL
976 /* <<UniPG */
977
978                                 /* ------------------------------------------------------ */
979
980                         default:
981                                 fprintf(stderr, "ERROR -> this option is not valid \"-%c %s\"\n", c, optarg);
982                                 return 1;
983                 }
984         }
985
986         /* check for possible errors */
987
988         if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
989                 fprintf(stderr, "usage: image_to_j2k -i image-file -o j2k/jp2-file (+ options)\n");
990                 return 1;
991         }
992
993         if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
994                 && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
995                 fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
996                 return 1;
997         }                               /* mod fixed_quality */
998
999         /* if no rate entered, lossless by default */
1000         if (parameters->tcp_numlayers == 0) {
1001                 parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */
1002                 parameters->tcp_numlayers++;
1003                 parameters->cp_disto_alloc = 1;
1004         }
1005
1006         if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
1007                 fprintf(stderr,
1008                         "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
1009                         parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
1010                 return 1;
1011         }
1012
1013         for (i = 0; i < parameters->numpocs; i++) {
1014                 if (parameters->POC[i].prg == -1) {
1015                         fprintf(stderr,
1016                                 "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
1017                                 i + 1);
1018                 }
1019         }
1020
1021         return 0;
1022 }
1023
1024 /* -------------------------------------------------------------------------- */
1025
1026 /**
1027 sample error callback expecting a FILE* client object
1028 */
1029 void error_callback(const char *msg, void *client_data) {
1030         FILE *stream = (FILE*)client_data;
1031         fprintf(stream, "[ERROR] %s", msg);
1032 }
1033 /**
1034 sample warning callback expecting a FILE* client object
1035 */
1036 void warning_callback(const char *msg, void *client_data) {
1037         FILE *stream = (FILE*)client_data;
1038         fprintf(stream, "[WARNING] %s", msg);
1039 }
1040 /**
1041 sample debug callback expecting a FILE* client object
1042 */
1043 void info_callback(const char *msg, void *client_data) {
1044         FILE *stream = (FILE*)client_data;
1045         fprintf(stream, "[INFO] %s", msg);
1046 }
1047
1048 /* -------------------------------------------------------------------------- */
1049
1050 int main(int argc, char **argv) {
1051         bool bSuccess;
1052         opj_cparameters_t parameters;   /* compression parameters */
1053         opj_event_mgr_t event_mgr;              /* event manager */
1054         opj_image_t *image = NULL;
1055
1056         /*
1057         configure the event callbacks (not required)
1058         setting of each callback is optionnal
1059         */
1060         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
1061         event_mgr.error_handler = error_callback;
1062         event_mgr.warning_handler = warning_callback;
1063         event_mgr.info_handler = info_callback;
1064
1065         /* set encoding parameters to default values */
1066         opj_set_default_encoder_parameters(&parameters);
1067
1068         /* parse input and get user encoding parameters */
1069         if(parse_cmdline_encoder(argc, argv, &parameters) == 1) {
1070                 return 0;
1071         }
1072
1073         if(parameters.cp_comment == NULL) {
1074     const char comment[] = "Created by OpenJPEG version ";
1075                 const size_t clen = strlen(comment);
1076     const char *version = opj_version();
1077 /* UniPG>> */
1078 #ifdef USE_JPWL
1079                 parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);
1080                 sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);
1081 #else
1082                 parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);
1083                 sprintf(parameters.cp_comment,"%s%s", comment, version);
1084 #endif
1085 /* <<UniPG */
1086
1087         }
1088
1089         /* decode the source image */
1090         /* ----------------------- */
1091
1092         switch (parameters.decod_format) {
1093                 case PGX_DFMT:
1094                         image = pgxtoimage(parameters.infile, &parameters);
1095                         if (!image) {
1096                                 fprintf(stderr, " unable to load pgx file\n");
1097                                 return 1;
1098                         }
1099                         break;
1100
1101                 case PXM_DFMT:
1102                         image = pnmtoimage(parameters.infile, &parameters);
1103                         if (!image) {
1104                                 fprintf(stderr, " not a pnm file\n");
1105                                 return 1;
1106                         }
1107                         break;
1108
1109                 case BMP_DFMT:
1110                         image = bmptoimage(parameters.infile, &parameters);
1111                         if (!image) {
1112                                 fprintf(stderr, " not a bmp file\n");
1113                                 return 1;
1114                         }
1115                         break;
1116         }
1117
1118         /* encode the destination image */
1119         /* ---------------------------- */
1120
1121         if (parameters.cod_format == J2K_CFMT) {        /* J2K format output */
1122                 int codestream_length;
1123                 opj_cio_t *cio = NULL;
1124                 FILE *f = NULL;
1125
1126                 /* get a J2K compressor handle */
1127                 opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
1128
1129                 /* catch events using our callbacks and give a local context */
1130                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
1131
1132                 /* setup the encoder parameters using the current image and user parameters */
1133                 opj_setup_encoder(cinfo, &parameters, image);
1134
1135                 /* open a byte stream for writing */
1136                 /* allocate memory for all tiles */
1137                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
1138
1139                 /* encode the image */
1140                 bSuccess = opj_encode(cinfo, cio, image, parameters.index);
1141                 if (!bSuccess) {
1142                         opj_cio_close(cio);
1143                         fprintf(stderr, "failed to encode image\n");
1144                         return 1;
1145                 }
1146                 codestream_length = cio_tell(cio);
1147
1148                 /* write the buffer to disk */
1149                 f = fopen(parameters.outfile, "wb");
1150                 if (!f) {
1151                         fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
1152                         return 1;
1153                 }
1154                 fwrite(cio->buffer, 1, codestream_length, f);
1155                 fclose(f);
1156
1157                 /* close and free the byte stream */
1158                 opj_cio_close(cio);
1159
1160                 /* free remaining compression structures */
1161                 opj_destroy_compress(cinfo);
1162
1163         } else {                        /* JP2 format output */
1164                 int codestream_length;
1165                 opj_cio_t *cio = NULL;
1166                 FILE *f = NULL;
1167
1168                 /* get a JP2 compressor handle */
1169                 opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
1170
1171                 /* catch events using our callbacks and give a local context */
1172                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);                   
1173
1174                 /* setup the encoder parameters using the current image and using user parameters */
1175                 opj_setup_encoder(cinfo, &parameters, image);
1176
1177                 /* open a byte stream for writing */
1178                 /* allocate memory for all tiles */
1179                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
1180
1181                 /* encode the image */
1182                 bSuccess = opj_encode(cinfo, cio, image, parameters.index);
1183                 if (!bSuccess) {
1184                         opj_cio_close(cio);
1185                         fprintf(stderr, "failed to encode image\n");
1186                         return 1;
1187                 }
1188                 codestream_length = cio_tell(cio);
1189
1190                 /* write the buffer to disk */
1191                 f = fopen(parameters.outfile, "wb");
1192                 if (!f) {
1193                         fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
1194                         return 1;
1195                 }
1196                 fwrite(cio->buffer, 1, codestream_length, f);
1197                 fclose(f);
1198
1199                 /* close and free the byte stream */
1200                 opj_cio_close(cio);
1201
1202                 /* free remaining compression structures */
1203                 opj_destroy_compress(cinfo);
1204
1205         }
1206
1207         /* free user parameters structure */
1208   if(parameters.cp_comment) free(parameters.cp_comment);
1209         if(parameters.cp_matrice) free(parameters.cp_matrice);
1210
1211         /* free image data */
1212         opj_image_destroy(image);
1213
1214         return 0;
1215 }
1216