David Fries suggestions. In image_to_j2k and j2k_to_image, strncpy() functions: inste...
[openjpeg.git] / codec / j2k_to_image.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34
35 #include "openjpeg.h"
36 #include "compat/getopt.h"
37 #include "convert.h"
38
39 #ifndef WIN32
40 #define stricmp strcasecmp
41 #define strnicmp strncasecmp
42 #endif
43
44 /* ----------------------------------------------------------------------- */
45
46 #define J2K_CFMT 0
47 #define JP2_CFMT 1
48 #define JPT_CFMT 2
49 #define MJ2_CFMT 3
50 #define PXM_DFMT 0
51 #define PGX_DFMT 1
52 #define BMP_DFMT 2
53 #define YUV_DFMT 3
54
55 /* ----------------------------------------------------------------------- */
56
57 void decode_help_display() {
58         fprintf(stdout,"HELP\n----\n\n");
59         fprintf(stdout,"- the -h option displays this help information on screen\n\n");
60
61 /* UniPG>> */
62         fprintf(stdout,"List of parameters for the JPEG 2000 "
63 #ifdef USE_JPWL
64                 "+ JPWL "
65 #endif /* USE_JPWL */
66                 "decoder:\n");
67 /* <<UniPG */
68         fprintf(stdout,"\n");
69         fprintf(stdout,"  -i <compressed file>\n");
70         fprintf(stdout,"    REQUIRED\n");
71         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
72         fprintf(stdout,"    is identified based on its suffix.\n");
73         fprintf(stdout,"  -o <decompressed file>\n");
74         fprintf(stdout,"    REQUIRED\n");
75         fprintf(stdout,"    Currently accepts PGM-files, PPM-files, PNM-files, PGX-files and\n");
76         fprintf(stdout,"    BMP-files. Binary data is written to the file (not ascii). If a PGX\n");
77         fprintf(stdout,"    filename is given, there will be as many output files as there are\n");
78         fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");
79         fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");
80         fprintf(stdout,"    is given and there are more than one component, only the first component\n");
81         fprintf(stdout,"    will be written to the file.\n");
82         fprintf(stdout,"  -r <reduce factor>\n");
83         fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");
84         fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");
85         fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");
86         fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");
87         fprintf(stdout,"  -l <number of quality layers to decode>\n");
88         fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");
89         fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");
90         fprintf(stdout,"    are decoded.\n");
91 /* UniPG>> */
92 #ifdef USE_JPWL
93         fprintf(stdout,"  -W <options>\n");
94         fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");
95         fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");
96         fprintf(stdout,"    c, c=numcomps\n");
97         fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");
98         fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
99 #endif /* USE_JPWL */
100 /* <<UniPG */
101         fprintf(stdout,"\n");
102 }
103
104 /* -------------------------------------------------------------------------- */
105
106 int get_file_format(char *filename) {
107         unsigned int i;
108         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp", "j2k", "jp2", "jpt" };
109         static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT };
110         char * ext = strrchr(filename, '.') + 1;
111         if(ext) {
112                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
113                         if(strnicmp(ext, extension[i], 3) == 0) {
114                                 return format[i];
115                         }
116                 }
117         }
118
119         return -1;
120 }
121
122 /* -------------------------------------------------------------------------- */
123
124 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters) {
125         /* parse the command line */
126
127 /* UniPG>> */
128         const char optlist[] = "i:o:r:l:h"
129
130 #ifdef USE_JPWL
131                                         "W:"
132 #endif /* USE_JPWL */
133                                         ;
134 /* <<UniPG */
135
136         while (1) {
137                 int c = getopt(argc, argv, optlist); /* >>JPWL<< */
138                 if (c == -1)
139                         break;
140                 switch (c) {
141                         case 'i':                       /* input file */
142                         {
143                                 char *infile = optarg;
144                                 parameters->decod_format = get_file_format(infile);
145                                 switch(parameters->decod_format) {
146                                         case J2K_CFMT:
147                                         case JP2_CFMT:
148                                         case JPT_CFMT:
149                                                 break;
150                                         default:
151                                                 fprintf(stderr, 
152                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
153                                                         infile);
154                                                 return 1;
155                                 }
156                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
157                         }
158                         break;
159                                 
160                                 /* ----------------------------------------------------- */
161
162                         case 'o':                       /* output file */
163                         {
164                                 char *outfile = optarg;
165                                 parameters->cod_format = get_file_format(outfile);
166                                 switch(parameters->cod_format) {
167                                         case PGX_DFMT:
168                                         case PXM_DFMT:
169                                         case BMP_DFMT:
170                                                 break;
171                                         default:
172                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx or *.bmp]!! \n", outfile);
173                                                 return 1;
174                                 }
175                                 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
176                         }
177                         break;
178                         
179                                 /* ----------------------------------------------------- */
180                         
181     
182                         case 'r':               /* reduce option */
183                         {
184                                 sscanf(optarg, "%d", &parameters->cp_reduce);
185                         }
186                         break;
187                         
188                                 /* ----------------------------------------------------- */
189       
190
191                         case 'l':               /* layering option */
192                         {
193                                 sscanf(optarg, "%d", &parameters->cp_layer);
194                         }
195                         break;
196                         
197                                 /* ----------------------------------------------------- */
198                         
199                         case 'h':                       /* display an help description */
200                                 decode_help_display();
201                                 return 1;                               
202             
203 /* UniPG>> */
204 #ifdef USE_JPWL
205                                 /* ----------------------------------------------------- */     
206                         
207                         case 'W':                       /* activate JPWL correction */
208                         {
209                                 char *token = NULL;
210
211                                 token = strtok(optarg, ",");
212                                 while(token != NULL) {
213
214                                         /* search expected number of components */
215                                         if (*token == 'c') {
216
217                                                 static int compno;
218
219                                                 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
220
221                                                 if(sscanf(token, "c=%d", &compno) == 1) {
222                                                         /* Specified */
223                                                         if ((compno < 1) || (compno > 256)) {
224                                                                 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
225                                                                 return 1;
226                                                         }
227                                                         parameters->jpwl_exp_comps = compno;
228
229                                                 } else if (!strcmp(token, "c")) {
230                                                         /* default */
231                                                         parameters->jpwl_exp_comps = compno; /* auto for default size */
232
233                                                 } else {
234                                                         fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
235                                                         return 1;
236                                                 };
237                                         }
238
239                                         /* search maximum number of tiles */
240                                         if (*token == 't') {
241
242                                                 static int tileno;
243
244                                                 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
245
246                                                 if(sscanf(token, "t=%d", &tileno) == 1) {
247                                                         /* Specified */
248                                                         if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
249                                                                 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
250                                                                 return 1;
251                                                         }
252                                                         parameters->jpwl_max_tiles = tileno;
253
254                                                 } else if (!strcmp(token, "t")) {
255                                                         /* default */
256                                                         parameters->jpwl_max_tiles = tileno; /* auto for default size */
257
258                                                 } else {
259                                                         fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
260                                                         return 1;
261                                                 };
262                                         }
263
264                                         /* next token or bust */
265                                         token = strtok(NULL, ",");
266                                 };
267                                 parameters->jpwl_correct = true;
268                                 fprintf(stdout, "JPWL correction capability activated\n");
269                                 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
270                         }
271                         break;  
272 #endif /* USE_JPWL */
273 /* <<UniPG */            
274
275                                 /* ----------------------------------------------------- */
276                         
277                         default:
278                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
279                                 break;
280                 }
281         }
282
283         /* check for possible errors */
284
285         if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
286                 fprintf(stderr,"ERROR -> At least one required argument is missing\nCheck j2k_to_image -h for usage information\n");
287                 return 1;
288         }
289
290         return 0;
291 }
292
293 /* -------------------------------------------------------------------------- */
294
295 /**
296 sample error callback expecting a FILE* client object
297 */
298 void error_callback(const char *msg, void *client_data) {
299         FILE *stream = (FILE*)client_data;
300         fprintf(stream, "[ERROR] %s", msg);
301 }
302 /**
303 sample warning callback expecting a FILE* client object
304 */
305 void warning_callback(const char *msg, void *client_data) {
306         FILE *stream = (FILE*)client_data;
307         fprintf(stream, "[WARNING] %s", msg);
308 }
309 /**
310 sample debug callback expecting no client object
311 */
312 void info_callback(const char *msg, void *client_data) {
313         (void)client_data;
314         fprintf(stdout, "[INFO] %s", msg);
315 }
316
317 /* -------------------------------------------------------------------------- */
318
319 int main(int argc, char **argv) {
320         opj_dparameters_t parameters;   /* decompression parameters */
321         opj_event_mgr_t event_mgr;              /* event manager */
322         opj_image_t *image = NULL;
323         FILE *fsrc = NULL;
324         unsigned char *src = NULL;
325         int file_length;
326
327         opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
328         opj_cio_t *cio = NULL;
329
330         /* configure the event callbacks (not required) */
331         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
332         event_mgr.error_handler = error_callback;
333         event_mgr.warning_handler = warning_callback;
334         event_mgr.info_handler = info_callback;
335
336         /* set decoding parameters to default values */
337         opj_set_default_decoder_parameters(&parameters);
338
339         /* parse input and get user decoding parameters */
340         if(parse_cmdline_decoder(argc, argv, &parameters) == 1) {
341                 return 0;
342         }
343
344         /* read the input file and put it in memory */
345         /* ---------------------------------------- */
346         fsrc = fopen(parameters.infile, "rb");
347         if (!fsrc) {
348                 fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
349                 return 1;
350         }
351         fseek(fsrc, 0, SEEK_END);
352         file_length = ftell(fsrc);
353         fseek(fsrc, 0, SEEK_SET);
354         src = (unsigned char *) malloc(file_length);
355         fread(src, 1, file_length, fsrc);
356         fclose(fsrc);
357
358         /* decode the code-stream */
359         /* ---------------------- */
360
361     switch(parameters.decod_format) {
362                 case J2K_CFMT:
363                 {
364                         /* JPEG-2000 codestream */
365
366                         /* get a decoder handle */
367                         dinfo = opj_create_decompress(CODEC_J2K);
368
369                         /* catch events using our callbacks and give a local context */
370                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
371
372                         /* setup the decoder decoding parameters using user parameters */
373                         opj_setup_decoder(dinfo, &parameters);
374
375                         /* open a byte stream */
376                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
377
378                         /* decode the stream and fill the image structure */
379                         image = opj_decode(dinfo, cio);
380                         if(!image) {
381                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
382                                 opj_destroy_decompress(dinfo);
383                                 opj_cio_close(cio);
384                                 return 1;
385                         }
386
387                         /* close the byte stream */
388                         opj_cio_close(cio);
389                 }
390                 break;
391
392                 case JP2_CFMT:
393                 {
394                         /* JPEG 2000 compressed image data */
395
396                         /* get a decoder handle */
397                         dinfo = opj_create_decompress(CODEC_JP2);
398
399                         /* catch events using our callbacks and give a local context */
400                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
401
402                         /* setup the decoder decoding parameters using the current image and user parameters */
403                         opj_setup_decoder(dinfo, &parameters);
404
405                         /* open a byte stream */
406                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
407
408                         /* decode the stream and fill the image structure */
409                         image = opj_decode(dinfo, cio);
410                         if(!image) {
411                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
412                                 opj_destroy_decompress(dinfo);
413                                 opj_cio_close(cio);
414                                 return 1;
415                         }
416
417                         /* close the byte stream */
418                         opj_cio_close(cio);
419
420                 }
421                 break;
422
423                 case JPT_CFMT:
424                 {
425                         /* JPEG 2000, JPIP */
426
427                         /* get a decoder handle */
428                         dinfo = opj_create_decompress(CODEC_JPT);
429
430                         /* catch events using our callbacks and give a local context */
431                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
432
433                         /* setup the decoder decoding parameters using user parameters */
434                         opj_setup_decoder(dinfo, &parameters);
435
436                         /* open a byte stream */
437                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
438
439                         /* decode the stream and fill the image structure */
440                         image = opj_decode(dinfo, cio);
441                         if(!image) {
442                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
443                                 opj_destroy_decompress(dinfo);
444                                 opj_cio_close(cio);
445                                 return 1;
446                         }
447
448                         /* close the byte stream */
449                         opj_cio_close(cio);
450                 }
451                 break;
452
453                 default:
454                         fprintf(stderr, "ERROR -> j2k_to_image : Unknown input image format\n");
455                         return 1;
456         }
457
458         /* free the memory containing the code-stream */
459         free(src);
460         src = NULL;
461
462         /* create output image */
463         /* ------------------- */
464
465         switch (parameters.cod_format) {
466                 case PXM_DFMT:                  /* PNM PGM PPM */
467                         imagetopnm(image, parameters.outfile);
468                         break;
469
470                 case PGX_DFMT:                  /* PGX */
471                         imagetopgx(image, parameters.outfile);
472                         break;
473
474                 case BMP_DFMT:                  /* BMP */
475                         imagetobmp(image, parameters.outfile);
476                         break;
477         }
478
479         /* free remaining structures */
480         if(dinfo) {
481                 opj_destroy_decompress(dinfo);
482         }
483
484         /* free image data structure */
485         opj_image_destroy(image);
486
487         return 0;
488 }
489