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