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