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