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