* Inserted tool for memory leaks fixing in debug mode
[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) 2002-2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 //MEMORY LEAK
30 #ifdef _DEBUG
31 #define _CRTDBG_MAP_ALLOC
32 #include <stdlib.h>  // Must be included first
33 #include <crtdbg.h>
34 #endif
35 //MEM
36
37 #include <openjpeg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <math.h>
41 #include <string.h>
42 #ifndef DONT_HAVE_GETOPT
43 #include <getopt.h>
44 #else
45 #include "compat/getopt.h"
46 #endif
47 #include "convert.h"
48
49 void help_display()
50 {
51   printf("HELP\n----\n\n");
52   printf("- the option -help displays the readme.txt file on screen\n\n");
53
54
55   printf("List of parameters for the coder JPEG 2000 :\n");
56   printf("\n");
57   printf
58     ("- The markers COD and QCD are writed both of two in the main_header and never appear in the tile_header.  The markers in the main header are : SOC SIZ COD QCD COM.\n");
59   printf("\n");
60   printf
61     ("- This coder can encode mega image, a test was made on a 24000x24000 pixels color image.  You need enough disk space memory (twice the original) to encode the image. (i.e. for a 1.5 Gb image you need a minimum of 3Gb of disk memory)\n");
62   printf("\n");
63   printf("REMARKS :\n");
64   printf("---------\n");
65   printf("\n");
66   printf
67     ("* the value of rate enter in the code line is the compression factor !\n");
68   printf("exemple :\n");
69   printf("\n");
70   printf
71     ("-r 20,10,1 means quality 1 : compress 20x, quality 2 : compress 10x and quality 3 : compress 1x = lossless\n");
72   printf("\n");
73   printf("By default :\n");
74   printf("------------\n");
75   printf("\n");
76   printf(" * lossless\n");
77   printf(" * 1 tile\n");
78   printf(" * size of precinct 2^15 x 2^15 (means 1 precinct)\n");
79   printf(" * size of code-block 64 x 64\n");
80   printf(" * Number of resolution : 6\n");
81   printf(" * No SOP marker in the codestream\n");
82   printf(" * No EPH marker in the codestream\n");
83   printf(" * No sub-sampling in x and y direction\n");
84   printf(" * No mode switch activated\n");
85   printf(" * progression order : LRCP\n");
86   printf(" * No index file\n");
87   printf(" * No ROI upshifted\n");
88   printf(" * No offset of the origin of the image\n");
89   printf(" * No offset of the origin of the tiles\n");
90   printf(" * Reversible DWT 5-3\n");
91   printf("\n");
92   printf("Parameters :\n");
93   printf("------------\n");
94   printf("\n");
95   printf
96     ("-i             : source file  (-i source.pnm also *.pgm, *.ppm) required\n");
97   printf("\n");
98   printf
99     ("-o             : destination file (-o dest.j2k or .jp2) required\n");
100   printf("\n");
101   printf("-help          : Display the help information optional\n ");
102   printf("\n");
103   printf("-r             : different compression ratios for successive layers (-r 20,10,5) optional\n ");
104   printf("                 (options -r and -q cannot be used together)\n ");
105   printf("\n");
106   printf("-q             : different psnr for successive layers (-q 30,40,50) optional\n ");
107   printf("                 (options -r and -q cannot be used together)\n ");
108   printf("\n");
109   printf("-n             : Number of resolution (-n 3) optional\n");
110   printf("\n");
111   printf("-b             : size of code block (-b 32,32) optional\n");
112   printf("\n");
113   printf("-c             : size of precinct (-c 128,128) optional\n");
114   printf("\n");
115   printf("-t             : size of tile (-t 512,512) optional\n");
116   printf("\n");
117   printf
118     ("-p             : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] optional\n");
119   printf("\n");
120   printf
121     ("-s             : subsampling factor (-s 2,2) [-s X,Y] optional\n");
122   printf("\n");
123   printf
124     ("-SOP           : write SOP marker before each packet optional\n");
125   printf("\n");
126   printf
127     ("-EPH           : write EPH marker after each header packet optional\n");
128   printf("\n");
129   printf
130     ("-M             : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL) 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] optional\n");
131   printf
132     ("                    for several mode switch you have to add the value of each mode you want\n");
133   printf
134     ("                    ex : RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
135   printf("\n");
136   printf
137     ("-x             : Create an index file *.Idx (-x index_name.Idx) optional\n");
138   printf("\n");
139   printf
140     ("-ROI:c=%%d,U=%%d : quantization indices upshifted for component c=%%d [%%d = 0,1,2]\n");
141   printf
142     ("                 with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) optional\n");
143   printf("\n");
144   printf
145     ("-d             : offset of the origin of the image (-d 150,300) optional\n");
146   printf("\n");
147   printf
148     ("-T             : offset of the origin of the tiles (-T 100,75) optional\n");
149   printf("\n");
150   printf("-I             : Use the irreversible DWT 9-7 (-I) optional\n");
151   printf("\n");
152   printf("IMPORTANT :\n");
153   printf("-----------\n");
154   printf("\n");
155   printf("* subsampling bigger than 2 can produce error\n");
156   printf("\n");
157   printf("The index file respect the structure below :\n");
158   printf("---------------------------------------------\n");
159   printf("\n");
160   printf("Image_height Image_width\n");
161   printf("progression order\n");
162   printf("Tiles_size_X Tiles_size_Y\n");
163   printf("Components_nb\n");
164   printf("Layers_nb\n");
165   printf("decomposition_levels\n");
166   printf("[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...[Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
167   printf("Main_header_end_position\n");
168   printf("Codestream_size\n");
169   printf("Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
170   printf("Tile_1   ''           ''        ''        ''       ''    ''\n");
171   printf("...\n");
172   printf("Tile_Nt   ''           ''        ''        ''       ''    ''\n");
173   printf("Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
174   printf("...\n");
175   printf("Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
176   printf("MaxDisto\n");
177   printf("TotalDisto\n");
178 }
179
180 int give_progression(char progression[4])
181 {
182   if (progression[0] == 'L' && progression[1] == 'R'
183       && progression[2] == 'C' && progression[3] == 'P') {
184     return 0;
185   } else {
186     if (progression[0] == 'R' && progression[1] == 'L'
187         && progression[2] == 'C' && progression[3] == 'P') {
188       return 1;
189     } else {
190       if (progression[0] == 'R' && progression[1] == 'P'
191           && progression[2] == 'C' && progression[3] == 'L') {
192         return 2;
193       } else {
194         if (progression[0] == 'P' && progression[1] == 'C'
195             && progression[2] == 'R' && progression[3] == 'L') {
196           return 3;
197         } else {
198           if (progression[0] == 'C' && progression[1] == 'P'
199               && progression[2] == 'R' && progression[3] == 'L') {
200             return 4;
201           } else {
202             return -1;
203           }
204         }
205       }
206     }
207   }
208 }
209
210 double dwt_norms_97[4][10] = {
211   {1.000, 1.965, 4.177, 8.403, 16.90, 33.84, 67.69, 135.3, 270.6, 540.9},
212   {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
213   {2.022, 3.989, 8.355, 17.04, 34.27, 68.63, 137.3, 274.6, 549.0},
214   {2.080, 3.865, 8.307, 17.18, 34.71, 69.59, 139.3, 278.6, 557.2}
215 };
216
217 int floorlog2(int a)
218 {
219   int l;
220   for (l = 0; a > 1; l++) {
221     a >>= 1;
222   }
223   return l;
224 }
225
226 void encode_stepsize(int stepsize, int numbps, int *expn, int *mant)
227 {
228   int p, n;
229   p = floorlog2(stepsize) - 13;
230   n = 11 - floorlog2(stepsize);
231   *mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
232   *expn = numbps - p;
233 }
234
235 void calc_explicit_stepsizes(j2k_tccp_t * tccp, int prec)
236 {
237   int numbands, bandno;
238   numbands = 3 * tccp->numresolutions - 2;
239   for (bandno = 0; bandno < numbands; bandno++) {
240     double stepsize;
241
242     int resno, level, orient, gain;
243     resno = bandno == 0 ? 0 : (bandno - 1) / 3 + 1;
244     orient = bandno == 0 ? 0 : (bandno - 1) % 3 + 1;
245     level = tccp->numresolutions - 1 - resno;
246     gain =
247       tccp->qmfbid == 0 ? 0 : (orient ==
248                                0 ? 0 : (orient == 1
249                                         || orient == 2 ? 1 : 2));
250     if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
251       stepsize = 1.0;
252     } else {
253       double norm = dwt_norms_97[orient][level];
254       stepsize = (1 << (gain + 1)) / norm;
255     }
256     encode_stepsize((int) floor(stepsize * 8192.0), prec + gain,
257                     &tccp->stepsizes[bandno].expn,
258                     &tccp->stepsizes[bandno].mant);
259   }
260 }
261
262 int main(int argc, char **argv)
263 {
264   int len;
265   int NumResolution, numD_min;  /*   NumResolution : number of resolution                     */
266   int Tile_arg;                 /*   Tile_arg = 0 (not in argument) ou = 1 (in argument)      */
267   int CSty;                     /*   CSty : coding style                                      */
268   int Prog_order;               /*   progression order (default LRCP)                         */
269   char progression[4];
270   int numpocs, numpocs_tile;    /*   Number of progression order change (POC) default 0       */
271   int prcw_init[J2K_MAXRLVLS];  /*   Initialisation Precinct width                            */
272   int prch_init[J2K_MAXRLVLS];  /*   Initialisation Precinct height                           */
273   //int prcw_init, prch_init;                     /*   Initialisation precincts' size                           */
274   int cblockw_init, cblockh_init;       /*   Initialisation codeblocks' size                          */
275   int mode, value;              /*   Mode switch (cblk_style)                                 */
276   int subsampling_dx, subsampling_dy;   /* subsampling value for dx and dy                    */
277   int ROI_compno, ROI_shift;    /*   region of interrest                                      */
278   int Dim[2];                   /*   portion of the image coded                               */
279   int TX0, TY0;                 /*   tile off-set                                             */
280   j2k_image_t img;
281   j2k_cp_t cp, cp_init;         /*   cp_init is used to initialise in multiple tiles          */
282   j2k_tcp_t *tcp, *tcp_init;    /*   tcp_init is used to initialise in multiple tile          */
283   j2k_poc_t POC[32];            /*   POC : used in case of Progression order change           */
284   j2k_poc_t *tcp_poc;
285   j2k_tccp_t *tccp;
286   int i, tileno, j;
287   char *infile = 0;
288   char *outfile = 0;
289   char *index = 0;
290   char *s, S1, S2, S3;
291   int ir = 0;
292   int res_spec = 0;             /*   For various precinct sizes specification                 */
293   char sep;
294   char *outbuf;
295   FILE *f;
296
297
298   /* default value */
299   /* ------------- */
300   NumResolution = 6;
301   CSty = 0;
302   cblockw_init = 64;
303   cblockh_init = 64;
304   cp.tw = 1;
305   cp.th = 1;
306   cp.index_on = 0;
307   Prog_order = 0;
308   numpocs = 0;
309   mode = 0;
310   subsampling_dx = 1;
311   subsampling_dy = 1;
312   ROI_compno = -1;              /* no ROI */
313   ROI_shift = 0;
314   Dim[0] = 0;
315   Dim[1] = 0;
316   TX0 = 0;
317   TY0 = 0;
318   cp.comment = "Created by OpenJPEG version 0.9";
319   cp.disto_alloc = 0;
320   cp.fixed_alloc = 0;
321   cp.fixed_quality = 0;         //add fixed_quality
322   /* img.PPT=0; */
323
324   Tile_arg = 0;
325   cp_init.tcps = (j2k_tcp_t *) malloc(sizeof(j2k_tcp_t));       /* initialisation if only one tile */
326   tcp_init = &cp_init.tcps[0];
327   tcp_init->numlayers = 0;
328
329   cp.intermed_file = 1;
330
331   while (1) {
332     int c = getopt(argc, argv,
333                    "i:o:r:q:f:t:n:c:b:x:p:s:d:h:P:S:E:M:R:T:C:I");
334     if (c == -1)
335       break;
336     switch (c) {
337     case 'i':                   /* IN fill */
338       infile = optarg;
339       s = optarg;
340       while (*s) {
341         s++;
342       }
343       s--;
344       S3 = *s;
345       s--;
346       S2 = *s;
347       s--;
348       S1 = *s;
349
350       if ((S1 == 'p' && S2 == 'g' && S3 == 'x')
351           || (S1 == 'P' && S2 == 'G' && S3 == 'X')) {
352         cp.image_type = 0;
353         break;
354       }
355
356       if ((S1 == 'p' && S2 == 'n' && S3 == 'm')
357           || (S1 == 'P' && S2 == 'N' && S3 == 'M')
358           || (S1 == 'p' && S2 == 'g' && S3 == 'm') || (S1 == 'P'
359                                                        && S2 == 'G'
360                                                        && S3 == 'M')
361           || (S1 == 'P' && S2 == 'P' && S3 == 'M') || (S1 == 'p'
362                                                        && S2 == 'p'
363                                                        && S3 == 'm')) {
364         cp.image_type = 1;
365         break;
366       }
367
368       if ((S1 == 'b' && S2 == 'm' && S3 == 'p')
369           || (S1 == 'B' && S2 == 'M' && S3 == 'P')) {
370         cp.image_type = 2;
371         break;
372       }
373       fprintf(stderr,
374               "!! Unrecognized format for infile : %c%c%c [accept only *.pnm, *.pgm, *.ppm, *.pgx or *.bmp] !!\n\n",
375               S1, S2, S3);
376       return 1;
377       break;
378       /* ----------------------------------------------------- */
379     case 'o':                   /* OUT fill */
380       outfile = optarg;
381       while (*outfile) {
382         outfile++;
383       }
384       outfile--;
385       S3 = *outfile;
386       outfile--;
387       S2 = *outfile;
388       outfile--;
389       S1 = *outfile;
390
391       outfile = optarg;
392
393       if ((S1 == 'j' && S2 == '2' && S3 == 'k')
394           || (S1 == 'J' && S2 == '2' && S3 == 'K'))
395         cp.JPEG2000_format = 0;
396       else if ((S1 == 'j' && S2 == 'p' && S3 == '2')
397                || (S1 == 'J' && S2 == 'P' && S3 == '2'))
398         cp.JPEG2000_format = 1;
399       else {
400         fprintf(stderr,
401                 "Unknown output format image *.%c%c%c [only *.j2k, *.jp2]!! \n",
402                 S1, S2, S3);
403         return 1;
404       }
405
406
407
408       break;
409       /* ----------------------------------------------------- */
410     case 'r':                   /* rates rates/distorsion */
411       s = optarg;
412       while (sscanf(s, "%d", &tcp_init->rates[tcp_init->numlayers]) == 1) {
413         tcp_init->numlayers++;
414         while (*s && *s != ',') {
415           s++;
416         }
417         if (!*s)
418           break;
419         s++;
420       }
421       cp.disto_alloc = 1;
422       cp.matrice = NULL;
423       break;
424       /* ----------------------------------------------------- */
425     case 'q':                   /* add fixed_quality */
426       s = optarg;
427       while (sscanf(s, "%f", &tcp_init->distoratio[tcp_init->numlayers])
428              == 1) {
429         tcp_init->numlayers++;
430         while (*s && *s != ',') {
431           s++;
432         }
433         if (!*s)
434           break;
435         s++;
436       }
437       cp.fixed_quality = 1;
438       cp.matrice = NULL;
439       break;
440       /* dda */
441       /* ----------------------------------------------------- */
442     case 'f':                   /* mod fixed_quality (before : -q) */
443       s = optarg;
444       sscanf(s, "%d", &tcp_init->numlayers);
445       s++;
446       if (tcp_init->numlayers > 9)
447         s++;
448       cp.matrice =
449         (int *) malloc(tcp_init->numlayers * NumResolution * 3 *
450                        sizeof(int));
451       s = s + 2;
452       for (i = 0; i < tcp_init->numlayers; i++) {
453         tcp_init->rates[i] = 1;
454         sscanf(s, "%d,", &cp.matrice[i * NumResolution * 3]);
455         s += 2;
456         if (cp.matrice[i * NumResolution * 3] > 9)
457           s++;
458         cp.matrice[i * NumResolution * 3 + 1] = 0;
459         cp.matrice[i * NumResolution * 3 + 2] = 0;
460         for (j = 1; j < NumResolution; j++) {
461           sscanf(s, "%d,%d,%d",
462                  &cp.matrice[i * NumResolution * 3 + j * 3 + 0],
463                  &cp.matrice[i * NumResolution * 3 + j * 3 + 1],
464                  &cp.matrice[i * NumResolution * 3 + j * 3 + 2]);
465           s += 6;
466           if (cp.matrice[i * NumResolution * 3 + j * 3] > 9)
467             s++;
468           if (cp.matrice[i * NumResolution * 3 + j * 3 + 1] > 9)
469             s++;
470           if (cp.matrice[i * NumResolution * 3 + j * 3 + 2] > 9)
471             s++;
472         }
473         if (i < tcp_init->numlayers - 1)
474           s++;
475       }
476       cp.fixed_alloc = 1;
477       break;
478       /* ----------------------------------------------------- */
479     case 't':                   /* tiles */
480       sscanf(optarg, "%d,%d", &cp.tdx, &cp.tdy);
481       Tile_arg = 1;
482       break;
483       /* ----------------------------------------------------- */
484     case 'n':                   /* resolution */
485       sscanf(optarg, "%d", &NumResolution);
486       break;
487       /* ----------------------------------------------------- */
488     case 'c':                   /* precinct dimension */
489       s = optarg;
490       do {
491         sep = 0;
492         sscanf(s, "[%d,%d]%c", &prcw_init[res_spec],
493                &prch_init[res_spec], &sep);
494         CSty |= 0x01;
495         res_spec++;
496         s = strpbrk(s, "]") + 2;
497       }
498       while (sep == ',');
499       break;
500       /* ----------------------------------------------------- */
501     case 'b':                   /* code-block dimension */
502       sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
503       if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
504           || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
505         fprintf(stderr,
506                 "!! Size of code_block error (option -b) !!\n\nRestriction :\n    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
507         return 1;
508       }
509       break;
510       /* ----------------------------------------------------- */
511     case 'x':                   /* creation of index file */
512       index = optarg;
513       cp.index_on = 1;
514       break;
515       /* ----------------------------------------------------- */
516     case 'p':                   /* progression order */
517       s = optarg;
518       for (i = 0; i < 4; i++) {
519         progression[i] = *s;
520         s++;
521       }
522       Prog_order = give_progression(progression);
523
524       if (Prog_order == -1) {
525         fprintf(stderr,
526                 "Unrecognized progression order [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
527         return 1;
528       }
529       break;
530       /* ----------------------------------------------------- */
531     case 's':                   /* subsampling factor */
532       if (sscanf(optarg, "%d,%d", &subsampling_dx, &subsampling_dy) != 2) {
533         fprintf(stderr,
534                 "'-s' sub-sampling argument error !  [-s dx,dy]\n");
535         return 1;
536       }
537       break;
538       /* ----------------------------------------------------- */
539     case 'd':                   /* coordonnate of the reference grid */
540       if (sscanf(optarg, "%d,%d", &Dim[0], &Dim[1]) != 2) {
541         fprintf(stderr,
542                 "-d 'coordonnate of the reference grid' argument error !! [-d x0,y0]\n");
543         return 1;
544       }
545       break;
546       /* ----------------------------------------------------- */
547     case 'h':                   /* Display an help description */
548       help_display();
549       return 0;
550       break;
551       /* ----------------------------------------------------- */
552     case 'P':                   /* POC */
553       fprintf(stderr, "/----------------------------------\\\n");
554       fprintf(stderr, "|  POC option not fully tested !!  |\n");
555       fprintf(stderr, "\\----------------------------------/\n");
556
557       s = optarg;
558       while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%s", &POC[numpocs].tile,
559                     &POC[numpocs].resno0, &POC[numpocs].compno0,
560                     &POC[numpocs].layno1, &POC[numpocs].resno1,
561                     &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
562         POC[numpocs].prg = give_progression(POC[numpocs].progorder);
563         /* POC[numpocs].tile; */
564         numpocs++;
565         while (*s && *s != '/') {
566           s++;
567         }
568         if (!*s)
569           break;
570         s++;
571       }
572       break;
573       /* ------------------------------------------------------ */
574     case 'S':                   /* SOP marker */
575       CSty |= 0x02;
576       break;
577       /* ------------------------------------------------------ */
578     case 'E':                   /* EPH marker */
579       CSty |= 0x04;
580       break;
581       /* ------------------------------------------------------ */
582     case 'M':                   /* Mode switch pas tous au point !! */
583       if (sscanf(optarg, "%d", &value) == 1) {
584         for (i = 0; i <= 5; i++) {
585           int cache = value & (1 << i);
586           if (cache)
587             mode |= (1 << i);
588         }
589       }
590       break;
591       /* ------------------------------------------------------ */
592     case 'R':                   /* ROI */
593       if (sscanf(optarg, "OI:c=%d,U=%d", &ROI_compno, &ROI_shift) != 2) {
594         fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
595         return 1;
596       }
597       break;
598       /* ------------------------------------------------------ */
599     case 'T':                   /* Tile offset */
600       if (sscanf(optarg, "%d,%d", &TX0, &TY0) != 2) {
601         fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
602         return 1;
603       }
604       break;
605       /* ------------------------------------------------------ */
606     case 'C':                   /* Add a comment */
607       cp.comment = optarg;
608       break;
609       /* ------------------------------------------------------ */
610     case 'I':                   /* reversible or not */
611       ir = 1;
612       break;
613       /* ------------------------------------------------------ */
614     default:
615       return 1;
616     }
617   }
618
619   cp.tx0 = TX0;
620   cp.ty0 = TY0;
621
622   /* Error messages */
623   /* -------------- */
624   if (!infile || !outfile) {
625     fprintf(stderr,
626             "usage: image_to_j2k -i image-file -o j2k/jp2-file (+ options)\n");
627     return 1;
628   }
629
630   if ((cp.disto_alloc || cp.fixed_alloc || cp.fixed_quality)
631       && (!(cp.disto_alloc ^ cp.fixed_alloc ^ cp.fixed_quality))) {
632     fprintf(stderr,
633             "Error: options -r -q and -f can not be used together !!\n");
634     return 1;
635   }                             // mod fixed_quality
636
637   /* if no rate entered, lossless by default */
638   if (tcp_init->numlayers == 0) {
639     tcp_init->rates[tcp_init->numlayers] = 0;   //MOD antonin : losslessbug
640     tcp_init->numlayers++;
641     cp.disto_alloc = 1;
642   }
643
644   if (TX0 > Dim[0] || TY0 > Dim[1]) {
645     fprintf(stderr,
646             "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
647             TX0, Dim[0], TY0, Dim[1]);
648     return 1;
649   }
650
651   for (i = 0; i < numpocs; i++) {
652     if (POC[i].prg == -1) {
653       fprintf(stderr,
654               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
655               i + 1);
656     }
657   }
658
659   switch (cp.image_type) {
660   case 0:
661     if (Tile_arg) {
662       if (!pgxtoimage
663           (infile, &img, cp.tdy, subsampling_dx, subsampling_dy, Dim, cp))
664       {
665         fprintf(stderr, "not a pgx file\n");
666         return 1;
667       }
668     } else {
669       if (!pgxtoimage
670           (infile, &img, -1, subsampling_dx, subsampling_dy, Dim, cp)) {
671         fprintf(stderr, " not a pgx file\n");
672         return 1;
673       }
674     }
675     break;
676
677   case 1:
678     if (!pnmtoimage(infile, &img, subsampling_dx, subsampling_dy, Dim)) {
679       fprintf(stderr, " not a pnm file\n");
680       return 1;
681     }
682     break;
683
684   case 2:
685     if (!bmptoimage(infile, &img, subsampling_dx, subsampling_dy, Dim)) {
686       fprintf(stderr, " not a bmp file\n");
687       return 1;
688     }
689     break;
690   }
691   /* to respect profile - 0 */
692   /* ---------------------- */
693   numD_min = 0;
694   /*   while (int_ceildiv(img.x1,(1<<numD_min))-int_ceildiv(img.x0,(1<<numD_min))>120 || int_ceildiv(img.y1,(1<<numD_min))-int_ceildiv(img.y0,(1<<numD_min))>160) numD_min++;
695      if ((numD_min+1)>NumResolution)
696      {
697      fprintf(stderr,"\n********************************************************************************\n\n");
698      fprintf(stderr,  "In view to respect Profile-0, the number of resolution used is %d in place of %d\n\n",numD_min+1,NumResolution);
699      fprintf(stderr,  "********************************************************************************\n\n");
700      NumResolution=numD_min+1;
701      } */
702
703   if (Tile_arg == 1) {
704     cp.tw = int_ceildiv(img.x1 - cp.tx0, cp.tdx);
705     cp.th = int_ceildiv(img.y1 - cp.ty0, cp.tdy);
706   } else {
707     cp.tdx = img.x1 - cp.tx0;
708     cp.tdy = img.y1 - cp.ty0;
709   }
710
711   /* Initialization for PPM marker */
712   cp.ppm = 0;
713   cp.ppm_data = NULL;
714   cp.ppm_previous = 0;
715   cp.ppm_store = 0;
716
717   /* Init the mutiple tiles */
718   /* ---------------------- */
719   cp.tcps = (j2k_tcp_t *) malloc(cp.tw * cp.th * sizeof(j2k_tcp_t));
720
721   for (tileno = 0; tileno < cp.tw * cp.th; tileno++) {
722     tcp = &cp.tcps[tileno];
723     tcp->numlayers = tcp_init->numlayers;
724     for (j = 0; j < tcp->numlayers; j++) {
725       if (cp.fixed_quality)     // add fixed_quality
726         tcp->distoratio[j] = tcp_init->distoratio[j];
727       else
728         tcp->rates[j] = tcp_init->rates[j];
729     }
730     tcp->csty = CSty;
731     tcp->prg = Prog_order;
732     tcp->mct = img.numcomps == 3 ? 1 : 0;
733     tcp->ppt = 0;
734     tcp->ppt_data = NULL;
735     tcp->ppt_store = 0;
736
737     numpocs_tile = 0;
738     tcp->POC = 0;
739     if (numpocs) {
740       /* intialisation of POC */
741       tcp->POC = 1;
742       for (i = 0; i < numpocs; i++) {
743         if (tileno == POC[i].tile - 1 || POC[i].tile == -1) {
744           tcp_poc = &tcp->pocs[numpocs_tile];
745           tcp_poc->resno0 = POC[numpocs_tile].resno0;
746           tcp_poc->compno0 = POC[numpocs_tile].compno0;
747           tcp_poc->layno1 = POC[numpocs_tile].layno1;
748           tcp_poc->resno1 = POC[numpocs_tile].resno1;
749           tcp_poc->compno1 = POC[numpocs_tile].compno1;
750           tcp_poc->prg = POC[numpocs_tile].prg;
751           tcp_poc->tile = POC[numpocs_tile].tile;
752           numpocs_tile++;
753         }
754       }
755     }
756     tcp->numpocs = numpocs_tile;
757     tcp->tccps = (j2k_tccp_t *) malloc(img.numcomps * sizeof(j2k_tccp_t));
758
759     for (i = 0; i < img.numcomps; i++) {
760       tccp = &tcp->tccps[i];
761       tccp->csty = CSty & 0x01; /* 0 => one precinct || 1 => custom precinct  */
762       tccp->numresolutions = NumResolution;
763       tccp->cblkw = int_floorlog2(cblockw_init);
764       tccp->cblkh = int_floorlog2(cblockh_init);
765       tccp->cblksty = mode;
766       tccp->qmfbid = ir ? 0 : 1;
767       tccp->qntsty = ir ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
768       tccp->numgbits = 2;
769       if (i == ROI_compno)
770         tccp->roishift = ROI_shift;
771       else
772         tccp->roishift = 0;
773       if (CSty & J2K_CCP_CSTY_PRT) {
774         int p = 0;
775         for (j = tccp->numresolutions - 1; j >= 0; j--) {
776           if (p < res_spec) {
777             if (prcw_init[p] < 1)
778               tccp->prcw[j] = 1;
779             else
780               tccp->prcw[j] = int_floorlog2(prcw_init[p]);
781
782             if (prch_init[p] < 1)
783               tccp->prch[j] = 1;
784             else
785               tccp->prch[j] = int_floorlog2(prch_init[p]);
786           } else {
787             int size_prcw, size_prch;
788             size_prcw = prcw_init[res_spec - 1] >> (p - (res_spec - 1));
789             size_prch = prch_init[res_spec - 1] >> (p - (res_spec - 1));
790             if (size_prcw < 1)
791               tccp->prcw[j] = 1;
792             else
793               tccp->prcw[j] = int_floorlog2(size_prcw);
794             if (size_prch < 1)
795               tccp->prch[j] = 1;
796             else
797               tccp->prch[j] = int_floorlog2(size_prch);
798           }
799           p++;
800           /*printf("\nsize precinct pour level %d : %d,%d\n", j,
801              tccp->prcw[j], tccp->prch[j]); */
802         }
803       } else {
804         for (j = 0; j < tccp->numresolutions; j++) {
805           tccp->prcw[j] = 15;
806           tccp->prch[j] = 15;
807         }
808       }
809       calc_explicit_stepsizes(tccp, img.comps[i].prec);
810     }
811   }
812
813
814
815   if (cp.JPEG2000_format == 0) {        /* J2K format output */
816     if (cp.intermed_file == 1) {        /* After the encoding of each tile, j2k_encode 
817                                            stores the data in the file */
818       len = j2k_encode(&img, &cp, outfile, cp.tdx * cp.tdy * 2, index);
819       if (len == 0) {
820         fprintf(stderr, "failed to encode image\n");
821         return 1;
822       }
823     } else {
824       outbuf = (char *) malloc(cp.tdx * cp.tdy * cp.tw * cp.th * 2);    /* Allocate memory for all tiles */
825       cio_init(outbuf, cp.tdx * cp.tdy * cp.tw * cp.th * 2);
826       len =
827         j2k_encode(&img, &cp, outbuf,
828                    cp.tdx * cp.tdy * cp.tw * cp.th * 2, index);
829       if (len == 0) {
830         fprintf(stderr, "failed to encode image\n");
831         return 1;
832       }
833       f = fopen(outfile, "wb");
834       if (!f) {
835         fprintf(stderr, "failed to open %s for writing\n", outfile);
836         return 1;
837       }
838       fwrite(outbuf, 1, len, f);
839       free(outbuf);
840       fclose(f);
841     }
842   } else {                      /* JP2 format output */
843
844     jp2_struct_t *jp2_struct;
845     jp2_struct = (jp2_struct_t *) malloc(sizeof(jp2_struct_t));
846     jp2_struct->image = &img;
847
848     /* Initialising the standard JP2 box content */
849     /* If you wish to modify those boxes, you have to modify the jp2_struct content */
850     if (jp2_init_stdjp2(jp2_struct, &img)) {
851       fprintf(stderr, "Error with jp2 initialization");
852       return 1;
853     };
854
855     if (cp.intermed_file == 1) {
856       /*For the moment, JP2 format does not use intermediary files for each tile */
857       cp.intermed_file = 0;
858     }
859     outbuf = (char *) malloc(cp.tdx * cp.tdy * cp.tw * cp.th * 2);
860     cio_init(outbuf, cp.tdx * cp.tdy * cp.tw * cp.th * 2);
861     len = jp2_encode(jp2_struct, &cp, outbuf, index);
862     if (len == 0) {
863       fprintf(stderr, "failed to encode image\n");
864       return 1;
865     }
866     f = fopen(outfile, "wb");
867     if (!f) {
868       fprintf(stderr, "failed to open %s for writing\n", outfile);
869       return 1;
870     }
871     fwrite(outbuf, 1, len, f);
872     free(outbuf);
873     fclose(f);
874   }
875
876   /* Remove the temporary files */
877   /* -------------------------- */
878   if (cp.image_type) {          /* PNM PGM PPM */
879     for (i = 0; i < img.numcomps; i++) {
880       char tmp;
881       sprintf(&tmp, "Compo%d", i);
882       if (remove(&tmp) == -1) {
883         fprintf(stderr, "failed to kill %s file !\n", &tmp);
884       }
885     }
886   } else {                      /* PGX */
887     for (i = 0; i < cp.th; i++) {
888       char tmp;
889       sprintf(&tmp, "bandtile%d", i + 1);
890
891       if (remove(&tmp) == -1) {
892         fprintf(stderr, "failed to kill %s file !\n", &tmp);
893       }
894     }
895   }
896
897   /* Free memory */
898   free(img.comps);
899   free(cp_init.tcps);
900   if (tcp_init->numlayers > 9)
901     free(cp.matrice);
902   for (tileno = 0; tileno < cp.tw * cp.th; tileno++)
903     free(cp.tcps[tileno].tccps);
904   free(cp.tcps);
905
906
907   //MEMORY LEAK
908   #ifdef _DEBUG
909     _CrtDumpMemoryLeaks();
910   #endif
911   //MEM
912
913   return 0;
914 }