openjpeg version 1.0 (previous version still available with tag opj0-97)
[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) 2003-2005, Francois Devaux and Antonin Descampe
5  * Copyright (c) 2005, Herv� Drolon, FreeImage Team
6  * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35
36 #include "openjpeg.h"
37 #include "compat/getopt.h"
38 #include "convert.h"
39
40 #define J2K_CFMT 0
41 #define JP2_CFMT 1
42 #define JPT_CFMT 2
43 #define MJ2_CFMT 3
44 #define PXM_DFMT 0
45 #define PGX_DFMT 1
46 #define BMP_DFMT 2
47 #define YUV_DFMT 3
48
49 /* ----------------------------------------------------------------------- */
50
51 void encode_help_display() {
52   fprintf(stdout,"HELP\n----\n\n");
53   fprintf(stdout,"- the -h option displays this help information on screen\n\n");
54
55
56   fprintf(stdout,"List of parameters for the JPEG 2000 encoder:\n");
57   fprintf(stdout,"\n");
58   fprintf(stdout,"REMARKS:\n");
59   fprintf(stdout,"---------\n");
60   fprintf(stdout,"\n");
61   fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
62   fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
63   fprintf(stdout,"\n");
64   fprintf(stdout,"- This coder can encode a mega image, a test was made on a 24000x24000 pixels \n");
65   fprintf(stdout,"color image.  You need enough disk space memory (twice the original) to encode \n");
66   fprintf(stdout,"the image,i.e. for a 1.5 GB image you need a minimum of 3GB of disk memory)\n");
67   fprintf(stdout,"\n");
68   fprintf(stdout,"By default:\n");
69   fprintf(stdout,"------------\n");
70   fprintf(stdout,"\n");
71   fprintf(stdout," * Lossless\n");
72   fprintf(stdout," * 1 tile\n");
73   fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
74   fprintf(stdout," * Size of code-block : 64 x 64\n");
75   fprintf(stdout," * Number of resolutions: 6\n");
76   fprintf(stdout," * No SOP marker in the codestream\n");
77   fprintf(stdout," * No EPH marker in the codestream\n");
78   fprintf(stdout," * No sub-sampling in x or y direction\n");
79   fprintf(stdout," * No mode switch activated\n");
80   fprintf(stdout," * Progression order: LRCP\n");
81   fprintf(stdout," * No index file\n");
82   fprintf(stdout," * No ROI upshifted\n");
83   fprintf(stdout," * No offset of the origin of the image\n");
84   fprintf(stdout," * No offset of the origin of the tiles\n");
85   fprintf(stdout," * Reversible DWT 5-3\n");
86   fprintf(stdout,"\n");
87   fprintf(stdout,"Parameters:\n");
88   fprintf(stdout,"------------\n");
89   fprintf(stdout,"\n");
90   fprintf(stdout,"Required Parameters (except with -h):\n");
91   fprintf(stdout,"\n");
92   fprintf(stdout,"-i           : source file  (-i source.pnm also *.pgm, *.ppm) \n");
93   fprintf(stdout,"\n");
94   fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");
95   fprintf(stdout,"\n");
96   fprintf(stdout,"Optional Parameters:\n");
97   fprintf(stdout,"\n");
98   fprintf(stdout,"-h           : display the help information \n ");
99   fprintf(stdout,"\n");
100   fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
101   fprintf(stdout,"           - The rate specified for each quality level is the desired \n");
102   fprintf(stdout,"             compression factor.\n");
103   fprintf(stdout,"       Example: -r 20,10,1 means quality 1: compress 20x, \n");
104   fprintf(stdout,"         quality 2: compress 10x and quality 3: compress lossless\n");
105   fprintf(stdout,"\n");
106   fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
107   fprintf(stdout,"\n");
108
109   fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");
110
111   fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
112
113   fprintf(stdout,"\n");
114   fprintf(stdout,"-n           : number of resolutions (-n 3) \n");
115   fprintf(stdout,"\n");
116   fprintf(stdout,"-b           : size of code block (-b 32,32) \n");
117   fprintf(stdout,"\n");
118   fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");
119   fprintf(stdout,"\n");
120   fprintf(stdout,"-t           : size of tile (-t 512,512) \n");
121   fprintf(stdout,"\n");
122   fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
123   fprintf(stdout,"\n");
124   fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");
125   fprintf(stdout,"       Remark: subsampling bigger than 2 can produce error\n");
126   fprintf(stdout,"\n");
127   fprintf(stdout,"-SOP         : write SOP marker before each packet \n");
128   fprintf(stdout,"\n");
129   fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");
130   fprintf(stdout,"\n");
131   fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
132   fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
133   fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");
134   fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
135   fprintf(stdout,"\n");
136   fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");
137   fprintf(stdout,"\n");
138   fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
139   fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");
140   fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
141   fprintf(stdout,"\n");
142   fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");
143   fprintf(stdout,"\n");
144   fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");
145   fprintf(stdout,"\n");
146   fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");
147   fprintf(stdout,"\n");
148   fprintf(stdout,"IMPORTANT:\n");
149   fprintf(stdout,"-----------\n");
150   fprintf(stdout,"\n");
151   fprintf(stdout,"The index file has the structure below:\n");
152   fprintf(stdout,"---------------------------------------\n");
153   fprintf(stdout,"\n");
154   fprintf(stdout,"Image_height Image_width\n");
155   fprintf(stdout,"progression order\n");
156   fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
157   fprintf(stdout,"Components_nb\n");
158   fprintf(stdout,"Layers_nb\n");
159   fprintf(stdout,"decomposition_levels\n");
160   fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
161   fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
162   fprintf(stdout,"Main_header_end_position\n");
163   fprintf(stdout,"Codestream_size\n");
164   fprintf(stdout,"Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
165   fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''\n");
166   fprintf(stdout,"...\n");
167   fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''\n");
168   fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
169   fprintf(stdout,"...\n");
170   fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
171
172   fprintf(stdout,"MaxDisto\n");
173
174   fprintf(stdout,"TotalDisto\n\n");
175 }
176
177 OPJ_PROG_ORDER give_progression(char progression[4]) {
178   if(strncmp(progression, "LRCP", 4) == 0) {
179     return LRCP;
180   }
181   if(strncmp(progression, "RLCP", 4) == 0) {
182     return RLCP;
183   }
184   if(strncmp(progression, "RPCL", 4) == 0) {
185     return RPCL;
186   }
187   if(strncmp(progression, "PCRL", 4) == 0) {
188     return PCRL;
189   }
190   if(strncmp(progression, "CPRL", 4) == 0) {
191     return CPRL;
192   }
193
194   return PROG_UNKNOWN;
195 }
196
197 int get_file_format(char *filename) {
198   int i;
199   static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp", "j2k", "jp2" };
200   static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, J2K_CFMT, JP2_CFMT };
201   char * ext = strrchr(filename, '.') + 1;
202   for(i = 0; i < sizeof(format); i++) {
203     if(strnicmp(ext, extension[i], 3) == 0) {
204       return format[i];
205     }
206   }
207
208   return -1;
209 }
210
211 /* ------------------------------------------------------------------------------------ */
212
213 int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters) {
214   int i, j;
215
216   /* parse the command line */
217
218   while (1) {
219     int c = getopt(argc, argv, "i:o:r:q:f:t:n:c:b:x:p:s:d:h:P:S:E:M:R:T:C:I");
220     if (c == -1)
221       break;
222     switch (c) {
223       case 'i':     /* input file */
224       {
225         char *infile = optarg;
226         parameters->decod_format = get_file_format(infile);
227         switch(parameters->decod_format) {
228           case PGX_DFMT:
229           case PXM_DFMT:
230           case BMP_DFMT:
231             break;
232           default:
233             fprintf(stderr, 
234               "!! Unrecognized format for infile : %s [accept only *.pnm, *.pgm, *.ppm, *.pgx or *.bmp] !!\n\n", 
235               infile);
236             return 1;
237             break;
238         }
239         strncpy(parameters->infile, infile, MAX_PATH);
240       }
241       break;
242         
243         /* ----------------------------------------------------- */
244
245       case 'o':     /* output file */
246       {
247         char *outfile = optarg;
248         parameters->cod_format = get_file_format(outfile);
249         switch(parameters->cod_format) {
250           case J2K_CFMT:
251           case JP2_CFMT:
252             break;
253           default:
254             fprintf(stderr, "Unknown output format image %s [only *.j2k, *.jp2]!! \n", outfile);
255             return 1;
256             break;
257         }
258         strncpy(parameters->outfile, outfile, MAX_PATH);
259       }
260       break;
261
262         /* ----------------------------------------------------- */
263       
264       case 'r':     /* rates rates/distorsion */
265       {
266         char *s = optarg;
267         while (sscanf(s, "%d", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {
268           parameters->tcp_numlayers++;
269           while (*s && *s != ',') {
270             s++;
271           }
272           if (!*s)
273             break;
274           s++;
275         }
276         parameters->cp_disto_alloc = 1;
277       }
278       break;
279         
280         /* ----------------------------------------------------- */
281       
282       case 'q':     /* add fixed_quality */
283       {
284         char *s = optarg;
285         while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {
286           parameters->tcp_numlayers++;
287           while (*s && *s != ',') {
288             s++;
289           }
290           if (!*s)
291             break;
292           s++;
293         }
294         parameters->cp_fixed_quality = 1;
295       }
296       break;
297         
298         /* dda */
299         /* ----------------------------------------------------- */
300
301       case 'f':     /* mod fixed_quality (before : -q) */
302       {
303         int *row = NULL, *col = NULL;
304         int numlayers = 0, numresolution = 0, matrix_width = 0;
305
306         char *s = optarg;
307         sscanf(s, "%d", &numlayers);
308         s++;
309         if (numlayers > 9)
310           s++;
311
312         parameters->tcp_numlayers = numlayers;
313         numresolution = parameters->numresolution;
314         matrix_width = numresolution * 3;
315         parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
316         s = s + 2;
317
318         for (i = 0; i < numlayers; i++) {
319           row = &parameters->cp_matrice[i * matrix_width];
320           col = row;
321           parameters->tcp_rates[i] = 1;
322           sscanf(s, "%d,", &col[0]);
323           s += 2;
324           if (col[0] > 9)
325             s++;
326           col[1] = 0;
327           col[2] = 0;
328           for (j = 1; j < numresolution; j++) {
329             col += 3;
330             sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
331             s += 6;
332             if (col[0] > 9)
333               s++;
334             if (col[1] > 9)
335               s++;
336             if (col[2] > 9)
337               s++;
338           }
339           if (i < numlayers - 1)
340             s++;
341         }
342         parameters->cp_fixed_alloc = 1;
343       }
344       break;
345         
346         /* ----------------------------------------------------- */
347
348       case 't':     /* tiles */
349       {
350         sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
351         parameters->tile_size_on = true;
352       }
353       break;
354         
355         /* ----------------------------------------------------- */
356       
357       case 'n':     /* resolution */
358       {
359         sscanf(optarg, "%d", &parameters->numresolution);
360       }
361       break;
362         
363         /* ----------------------------------------------------- */
364       case 'c':     /* precinct dimension */
365       {
366         char sep;
367         int res_spec = 0;
368
369         char *s = optarg;
370         do {
371           sep = 0;
372           sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec], &parameters->prch_init[res_spec], &sep);
373           parameters->csty |= 0x01;
374           res_spec++;
375           s = strpbrk(s, "]") + 2;
376         }
377         while (sep == ',');
378         parameters->res_spec = res_spec;
379       }
380       break;
381         
382         /* ----------------------------------------------------- */
383       
384       case 'b':     /* code-block dimension */
385       {
386         int cblockw_init = 0, cblockh_init = 0;
387         sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
388         if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
389           || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
390           fprintf(stderr,
391             "!! Size of code_block error (option -b) !!\n\nRestriction :\n    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
392           return 1;
393         }
394         parameters->cblockw_init = cblockw_init;
395         parameters->cblockh_init = cblockh_init;
396       }
397       break;
398         
399         /* ----------------------------------------------------- */
400       
401       case 'x':     /* creation of index file */
402       {
403         char *index = optarg;
404         strncpy(parameters->index, index, MAX_PATH);
405         parameters->index_on = 1;
406       }
407       break;
408         
409         /* ----------------------------------------------------- */
410       
411       case 'p':     /* progression order */
412       {
413         char progression[4];
414
415         strncpy(progression, optarg, 4);
416         parameters->prog_order = give_progression(progression);
417         if (parameters->prog_order == -1) {
418           fprintf(stderr, "Unrecognized progression order [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
419           return 1;
420         }
421       }
422       break;
423         
424         /* ----------------------------------------------------- */
425       
426       case 's':     /* subsampling factor */
427       {
428         if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx, &parameters->subsampling_dy) != 2) {
429           fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
430           return 1;
431         }
432       }
433       break;
434         
435         /* ----------------------------------------------------- */
436       
437       case 'd':     /* coordonnate of the reference grid */
438       {
439         if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0, &parameters->image_offset_y0) != 2) {
440           fprintf(stderr, "-d 'coordonnate of the reference grid' argument error !! [-d x0,y0]\n");
441           return 1;
442         }
443       }
444       break;
445         
446         /* ----------------------------------------------------- */
447       
448       case 'h':     /* display an help description */
449       {
450         encode_help_display();
451         return 1;
452       }
453       break;
454         
455         /* ----------------------------------------------------- */
456
457       case 'P':     /* POC */
458       {
459         int numpocs = 0;    /* number of progression order change (POC) default 0 */
460         opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
461
462         char *s = optarg;
463         POC = parameters->POC;
464
465         fprintf(stderr, "/----------------------------------\\\n");
466         fprintf(stderr, "|  POC option not fully tested !!  |\n");
467         fprintf(stderr, "\\----------------------------------/\n");
468         
469         while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%s", &POC[numpocs].tile,
470           &POC[numpocs].resno0, &POC[numpocs].compno0,
471           &POC[numpocs].layno1, &POC[numpocs].resno1,
472           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
473           POC[numpocs].prg = give_progression(POC[numpocs].progorder);
474           /* POC[numpocs].tile; */
475           numpocs++;
476           while (*s && *s != '/') {
477             s++;
478           }
479           if (!*s) {
480             break;
481           }
482           s++;
483         }
484         parameters->numpocs = numpocs;
485       }
486       break;
487         
488         /* ------------------------------------------------------ */
489         
490       case 'S':     /* SOP marker */
491       {
492         parameters->csty |= 0x02;
493       }
494       break;
495         
496         /* ------------------------------------------------------ */
497       
498       case 'E':     /* EPH marker */
499       {
500         parameters->csty |= 0x04;
501       }
502       break;
503         
504         /* ------------------------------------------------------ */
505       
506       case 'M':     /* Mode switch pas tous au point !! */
507       {
508         int value = 0;
509         if (sscanf(optarg, "%d", &value) == 1) {
510           for (i = 0; i <= 5; i++) {
511             int cache = value & (1 << i);
512             if (cache)
513               parameters->mode |= (1 << i);
514           }
515         }
516       }
517       break;
518         
519         /* ------------------------------------------------------ */
520       
521       case 'R':     /* ROI */
522       {
523         if (sscanf(optarg, "OI:c=%d,U=%d", &parameters->roi_compno, &parameters->roi_shift) != 2) {
524           fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
525           return 1;
526         }
527       }
528       break;
529         
530         /* ------------------------------------------------------ */
531       
532       case 'T':     /* Tile offset */
533       {
534         if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {
535           fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
536           return 1;
537         }
538       }
539       break;
540         
541         /* ------------------------------------------------------ */
542         
543       case 'C':     /* add a comment */
544       {
545         parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
546         if(parameters->cp_comment) {
547           strcpy(parameters->cp_comment, optarg);
548         }
549       }
550       break;
551         
552         /* ------------------------------------------------------ */
553       
554       case 'I':     /* reversible or not */
555       {
556         parameters->irreversible = 1;
557       }
558       break;
559         
560         /* ------------------------------------------------------ */
561       
562       default:
563         fprintf(stderr, "ERROR -> this option is not valid \"-%c %s\"\n", c, optarg);
564         return 1;
565     }
566   }
567
568   /* check for possible errors */
569
570   if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
571     fprintf(stderr, "usage: image_to_j2k -i image-file -o j2k/jp2-file (+ options)\n");
572     return 1;
573   }
574
575   if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
576     && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
577     fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
578     return 1;
579   }       /* mod fixed_quality */
580
581   /* if no rate entered, lossless by default */
582   if (parameters->tcp_numlayers == 0) {
583     parameters->tcp_rates[0] = 0; /* MOD antonin : losslessbug */
584     parameters->tcp_numlayers++;
585     parameters->cp_disto_alloc = 1;
586   }
587
588   if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
589     fprintf(stderr,
590       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
591       parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
592     return 1;
593   }
594
595   for (i = 0; i < parameters->numpocs; i++) {
596     if (parameters->POC[i].prg == -1) {
597       fprintf(stderr,
598         "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
599         i + 1);
600     }
601   }
602
603   return 0;
604 }
605
606 /* -------------------------------------------------------------------------- */
607
608 /**
609 sample error callback expecting a FILE* client object
610 */
611 void error_callback(const char *msg, void *client_data) {
612   FILE *stream = (FILE*)client_data;
613   fprintf(stream, "[ERROR] %s", msg);
614 }
615 /**
616 sample warning callback expecting a FILE* client object
617 */
618 void warning_callback(const char *msg, void *client_data) {
619   FILE *stream = (FILE*)client_data;
620   fprintf(stream, "[WARNING] %s", msg);
621 }
622 /**
623 sample debug callback expecting a FILE* client object
624 */
625 void info_callback(const char *msg, void *client_data) {
626   FILE *stream = (FILE*)client_data;
627   fprintf(stream, "[INFO] %s", msg);
628 }
629
630 /* -------------------------------------------------------------------------- */
631
632 int main(int argc, char **argv) {
633   bool bSuccess;
634   bool delete_comment = true;
635   opj_cparameters_t parameters; /* compression parameters */
636   opj_event_mgr_t event_mgr;    /* event manager */
637   opj_image_t *image = NULL;
638
639   /* 
640   configure the event callbacks (not required)
641   setting of each callback is optionnal 
642   */
643   memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
644   event_mgr.error_handler = error_callback;
645   event_mgr.warning_handler = warning_callback;
646   event_mgr.info_handler = info_callback;
647
648   /* set encoding parameters to default values */
649   opj_set_default_encoder_parameters(&parameters);
650
651   /* parse input and get user encoding parameters */
652   if(parse_cmdline_encoder(argc, argv, &parameters) == 1) {
653     return 0;
654   }
655
656   if(parameters.cp_comment == NULL) {
657     parameters.cp_comment = "Created by OpenJPEG version 0.9";
658     /* no need to delete parameters.cp_comment on exit */
659     delete_comment = false;
660   }
661
662   /* decode the source image */
663   /* ----------------------- */
664
665   switch (parameters.decod_format) {
666     case PGX_DFMT:
667       image = pgxtoimage(parameters.infile, &parameters);
668       if (!image) {
669         fprintf(stderr, " unable to load pgx file\n");
670         return 1;
671       }
672       break;
673     
674     case PXM_DFMT:
675       image = pnmtoimage(parameters.infile, &parameters);
676       if (!image) {
677         fprintf(stderr, " not a pnm file\n");
678         return 1;
679       }
680       break;
681
682     case BMP_DFMT:
683       image = bmptoimage(parameters.infile, &parameters);
684       if (!image) {
685         fprintf(stderr, " not a bmp file\n");
686         return 1;
687       }
688       break;
689   }
690
691   /* encode the destination image */
692   /* ---------------------------- */
693
694   if (parameters.cod_format == J2K_CFMT) {  /* J2K format output */
695     int codestream_length;
696     opj_cio_t *cio = NULL;
697     FILE *f = NULL;
698
699     /* get a J2K compressor handle */
700     opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
701
702     /* catch events using our callbacks and give a local context */
703     opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);     
704
705     /* setup the encoder parameters using the current image and using user parameters */
706     opj_setup_encoder(cinfo, &parameters, image);
707
708     /* open a byte stream for writing */
709     /* allocate memory for all tiles */
710     cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
711
712     /* encode the image */
713     bSuccess = opj_encode(cinfo, cio, image, parameters.index);
714     if (!bSuccess) {
715       opj_cio_close(cio);
716       fprintf(stderr, "failed to encode image\n");
717       return 1;
718     }
719     codestream_length = cio_tell(cio);
720
721     /* write the buffer to disk */
722     f = fopen(parameters.outfile, "wb");
723     if (!f) {
724       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
725       return 1;
726     }
727     fwrite(cio->buffer, 1, codestream_length, f);
728     fclose(f);
729
730     /* close and free the byte stream */
731     opj_cio_close(cio);
732
733     /* free remaining compression structures */
734     opj_destroy_compress(cinfo);
735
736   } else {      /* JP2 format output */
737     int codestream_length;
738     opj_cio_t *cio = NULL;
739     FILE *f = NULL;
740
741     /* get a JP2 compressor handle */
742     opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
743
744     /* catch events using our callbacks and give a local context */
745     opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);     
746
747     /* setup the encoder parameters using the current image and using user parameters */
748     opj_setup_encoder(cinfo, &parameters, image);
749
750     /* open a byte stream for writing */
751     /* allocate memory for all tiles */
752     cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
753
754     /* encode the image */
755     bSuccess = opj_encode(cinfo, cio, image, parameters.index);
756     if (!bSuccess) {
757       opj_cio_close(cio);
758       fprintf(stderr, "failed to encode image\n");
759       return 1;
760     }
761     codestream_length = cio_tell(cio);
762
763     /* write the buffer to disk */
764     f = fopen(parameters.outfile, "wb");
765     if (!f) {
766       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
767       return 1;
768     }
769     fwrite(cio->buffer, 1, codestream_length, f);
770     fclose(f);
771
772     /* close and free the byte stream */
773     opj_cio_close(cio);
774
775     /* free remaining compression structures */
776     opj_destroy_compress(cinfo);
777
778   }
779
780   /* free user parameters structure */
781   if(delete_comment) {
782     if(parameters.cp_comment) free(parameters.cp_comment);
783   }
784   if(parameters.cp_matrice) free(parameters.cp_matrice);
785
786   /* free image data */
787   opj_image_destroy(image);
788
789   return 0;
790 }
791