ENH: Including the new header file openjpegConfigure.h
[openjpeg.git] / codec / j2k_dump.c
1 /*
2  * Copyright (c) 20010, Mathieu Malaterre, GDCM
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
18  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <math.h>
31
32 #include "openjpegConfigure.h"
33 #include "openjpeg.h"
34 #include "j2k.h"
35 #include "jp2.h"
36 #include "compat/getopt.h"
37 #include "convert.h"
38 #include "dirent.h"
39 #include "index.h"
40
41 #ifndef WIN32
42 #include <strings.h>
43 #define _stricmp strcasecmp
44 #define _strnicmp strncasecmp
45 #endif
46
47 /* ----------------------------------------------------------------------- */
48
49 #define J2K_CFMT 0
50 #define JP2_CFMT 1
51 #define JPT_CFMT 2
52
53 #define PXM_DFMT 10
54 #define PGX_DFMT 11
55 #define BMP_DFMT 12
56 #define YUV_DFMT 13
57 #define TIF_DFMT 14
58 #define RAW_DFMT 15
59 #define TGA_DFMT 16
60 #define PNG_DFMT 17
61 /* ----------------------------------------------------------------------- */
62
63 typedef struct dircnt{
64         /** Buffer for holding images read from Directory*/
65         char *filename_buf;
66         /** Pointer to the buffer*/
67         char **filename;
68 }dircnt_t;
69
70
71 typedef struct img_folder{
72         /** The directory path of the folder containing input images*/
73         char *imgdirpath;
74         /** Output format*/
75         const char *out_format;
76         /** Enable option*/
77         char set_imgdir;
78         /** Enable Cod Format for output*/
79         char set_out_format;
80
81 }img_fol_t;
82
83 void decode_help_display() {
84         fprintf(stdout,"HELP\n----\n\n");
85         fprintf(stdout,"- the -h option displays this help information on screen\n\n");
86
87 /* UniPG>> */
88         fprintf(stdout,"List of parameters for the JPEG 2000 "
89 #ifdef USE_JPWL
90                 "+ JPWL "
91 #endif /* USE_JPWL */
92                 "decoder:\n");
93 /* <<UniPG */
94         fprintf(stdout,"\n");
95         fprintf(stdout,"\n");
96         fprintf(stdout,"  -ImgDir \n");
97         fprintf(stdout,"        Image file Directory path \n");
98         fprintf(stdout,"  -i <compressed file>\n");
99         fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
100         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
101         fprintf(stdout,"    is identified based on its suffix.\n");
102         fprintf(stdout,"\n");
103 }
104
105 /* -------------------------------------------------------------------------- */
106
107 int get_num_images(char *imgdirpath){
108         DIR *dir;
109         struct dirent* content; 
110         int num_images = 0;
111
112         /*Reading the input images from given input directory*/
113
114         dir= opendir(imgdirpath);
115         if(!dir){
116                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
117                 return 0;
118         }
119         
120         while((content=readdir(dir))!=NULL){
121                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
122                         continue;
123                 num_images++;
124         }
125         return num_images;
126 }
127
128 int load_images(dircnt_t *dirptr, char *imgdirpath){
129         DIR *dir;
130         struct dirent* content; 
131         int i = 0;
132
133         /*Reading the input images from given input directory*/
134
135         dir= opendir(imgdirpath);
136         if(!dir){
137                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
138                 return 1;
139         }else   {
140                 fprintf(stderr,"Folder opened successfully\n");
141         }
142         
143         while((content=readdir(dir))!=NULL){
144                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
145                         continue;
146
147                 strcpy(dirptr->filename[i],content->d_name);
148                 i++;
149         }
150         return 0;       
151 }
152
153 int get_file_format(char *filename) {
154         unsigned int i;
155         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
156         static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
157         char * ext = strrchr(filename, '.');
158         if (ext == NULL)
159                 return -1;
160         ext++;
161         if(ext) {
162                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
163                         if(_strnicmp(ext, extension[i], 3) == 0) {
164                                 return format[i];
165                         }
166                 }
167         }
168
169         return -1;
170 }
171
172 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
173         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
174         char *temp_p, temp1[OPJ_PATH_LEN]="";
175
176         strcpy(image_filename,dirptr->filename[imageno]);
177         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
178         parameters->decod_format = get_file_format(image_filename);
179         if (parameters->decod_format == -1)
180                 return 1;
181         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
182         strncpy(parameters->infile, infilename, sizeof(infilename));
183
184         //Set output file
185         strcpy(temp_ofname,strtok(image_filename,"."));
186         while((temp_p = strtok(NULL,".")) != NULL){
187                 strcat(temp_ofname,temp1);
188                 sprintf(temp1,".%s",temp_p);
189         }
190         if(img_fol->set_out_format==1){
191                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
192                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
193         }
194         return 0;
195 }
196
197 /* -------------------------------------------------------------------------- */
198 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
199         /* parse the command line */
200         int totlen;
201         option_t long_option[]={
202                 {"ImgDir",REQ_ARG, NULL ,'y'},
203         };
204
205         const char optlist[] = "i:h";
206         totlen=sizeof(long_option);
207         img_fol->set_out_format = 0;
208         while (1) {
209                 int c = getopt_long(argc, argv,optlist,long_option,totlen);
210                 if (c == -1)
211                         break;
212                 switch (c) {
213                         case 'i':                       /* input file */
214                         {
215                                 char *infile = optarg;
216                                 parameters->decod_format = get_file_format(infile);
217                                 switch(parameters->decod_format) {
218                                         case J2K_CFMT:
219                                         case JP2_CFMT:
220                                         case JPT_CFMT:
221                                                 break;
222                                         default:
223                                                 fprintf(stderr, 
224                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
225                                                         infile);
226                                                 return 1;
227                                 }
228                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
229                         }
230                         break;
231                                 
232                                 /* ----------------------------------------------------- */
233
234                         case 'h':                       /* display an help description */
235                                 decode_help_display();
236                                 return 1;                               
237
238                                 /* ------------------------------------------------------ */
239
240                         case 'y':                       /* Image Directory path */
241                                 {
242                                         img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
243                                         strcpy(img_fol->imgdirpath,optarg);
244                                         img_fol->set_imgdir=1;
245                                 }
246                                 break;
247
248                                 /* ----------------------------------------------------- */
249                         
250                         default:
251                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
252                                 break;
253                 }
254         }
255
256         /* check for possible errors */
257         if(img_fol->set_imgdir==1){
258                 if(!(parameters->infile[0]==0)){
259                         fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
260                         return 1;
261                 }
262                 if(img_fol->set_out_format == 0){
263                         fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
264                         fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
265                         return 1;
266                 }
267                 if(!((parameters->outfile[0] == 0))){
268                         fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
269                         return 1;
270                 }
271         }else{
272                 if((parameters->infile[0] == 0) ) {
273                         fprintf(stderr, "Error: One of the options -i or -ImgDir must be specified\n");
274                         fprintf(stderr, "usage: image_to_j2k -i *.j2k/jp2/j2c (+ options)\n");
275                         return 1;
276                 }
277         }
278
279         return 0;
280 }
281
282 /* -------------------------------------------------------------------------- */
283
284 /**
285 sample error callback expecting a FILE* client object
286 */
287 void error_callback(const char *msg, void *client_data) {
288         FILE *stream = (FILE*)client_data;
289         fprintf(stream, "[ERROR] %s", msg);
290 }
291 /**
292 sample warning callback expecting a FILE* client object
293 */
294 void warning_callback(const char *msg, void *client_data) {
295         FILE *stream = (FILE*)client_data;
296         fprintf(stream, "[WARNING] %s", msg);
297 }
298 /**
299 sample debug callback expecting no client object
300 */
301 void info_callback(const char *msg, void *client_data) {
302         (void)client_data;
303         fprintf(stdout, "[INFO] %s", msg);
304 }
305
306 /* -------------------------------------------------------------------------- */
307
308 int main(int argc, char *argv[])
309 {
310         opj_dparameters_t parameters;   /* decompression parameters */
311         img_fol_t img_fol;
312         opj_event_mgr_t event_mgr;              /* event manager */
313         opj_image_t *image = NULL;
314         FILE *fsrc = NULL;
315         unsigned char *src = NULL;
316         int file_length;
317         int num_images;
318         int i,imageno;
319         dircnt_t *dirptr = NULL;
320         opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
321         opj_cio_t *cio = NULL;
322         opj_codestream_info_t cstr_info;  /* Codestream information structure */
323         char indexfilename[OPJ_PATH_LEN];       /* index file name */
324
325         /* configure the event callbacks (not required) */
326         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
327         event_mgr.error_handler = error_callback;
328         event_mgr.warning_handler = warning_callback;
329         event_mgr.info_handler = info_callback;
330
331         /* set decoding parameters to default values */
332         opj_set_default_decoder_parameters(&parameters);
333
334         /* Initialize indexfilename and img_fol */
335         *indexfilename = 0;
336         memset(&img_fol,0,sizeof(img_fol_t));
337
338         /* parse input and get user encoding parameters */
339         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
340                 return 1;
341         }
342
343         /* Initialize reading of directory */
344         if(img_fol.set_imgdir==1){      
345                 num_images=get_num_images(img_fol.imgdirpath);
346
347                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
348                 if(dirptr){
349                         dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
350                         dirptr->filename = (char**) malloc(num_images*sizeof(char*));
351
352                         if(!dirptr->filename_buf){
353                                 return 1;
354                         }
355                         for(i=0;i<num_images;i++){
356                                 dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
357                         }
358                 }
359                 if(load_images(dirptr,img_fol.imgdirpath)==1){
360                         return 1;
361                 }
362                 if (num_images==0){
363                         fprintf(stdout,"Folder is empty\n");
364                         return 1;
365                 }
366         }else{
367                 num_images=1;
368         }
369
370         /*Encoding image one by one*/
371         for(imageno = 0; imageno < num_images ; imageno++)
372   {
373                 image = NULL;
374                 fprintf(stderr,"\n");
375
376                 if(img_fol.set_imgdir==1){
377                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
378                                 fprintf(stderr,"skipping file...\n");
379                                 continue;
380                         }
381                 }
382
383                 /* read the input file and put it in memory */
384                 /* ---------------------------------------- */
385                 fsrc = fopen(parameters.infile, "rb");
386                 if (!fsrc) {
387                         fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
388                         return 1;
389                 }
390                 fseek(fsrc, 0, SEEK_END);
391                 file_length = ftell(fsrc);
392                 fseek(fsrc, 0, SEEK_SET);
393                 src = (unsigned char *) malloc(file_length);
394                 fread(src, 1, file_length, fsrc);
395                 fclose(fsrc);
396
397                 /* decode the code-stream */
398                 /* ---------------------- */
399
400                 switch(parameters.decod_format) {
401                 case J2K_CFMT:
402                 {
403                         /* JPEG-2000 codestream */
404
405                         /* get a decoder handle */
406                         dinfo = opj_create_decompress(CODEC_J2K);
407
408                         /* catch events using our callbacks and give a local context */
409                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
410
411                         /* setup the decoder decoding parameters using user parameters */
412                         opj_setup_decoder(dinfo, &parameters);
413
414                         /* open a byte stream */
415                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
416
417                         /* decode the stream and fill the image structure */
418                         if (*indexfilename)                             // If need to extract codestream information
419                                 image = opj_decode_with_info(dinfo, cio, &cstr_info);
420                         else
421                                 image = opj_decode(dinfo, cio);
422                         if(!image) {
423                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
424                                 opj_destroy_decompress(dinfo);
425                                 opj_cio_close(cio);
426                                 return 1;
427                         }
428                         /* dump image */
429       j2k_dump_image(stdout, image);
430
431                         /* dump cp */
432       j2k_dump_cp(stdout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp);
433
434                         /* close the byte stream */
435                         opj_cio_close(cio);
436
437                         /* Write the index to disk */
438                         if (*indexfilename) {
439                                 char bSuccess;
440                                 bSuccess = write_index_file(&cstr_info, indexfilename);
441                                 if (bSuccess) {
442                                         fprintf(stderr, "Failed to output index file\n");
443                                 }
444                         }
445                 }
446                 break;
447
448                 case JP2_CFMT:
449                 {
450                         /* JPEG 2000 compressed image data */
451
452                         /* get a decoder handle */
453                         dinfo = opj_create_decompress(CODEC_JP2);
454
455                         /* catch events using our callbacks and give a local context */
456                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
457
458                         /* setup the decoder decoding parameters using the current image and user parameters */
459                         opj_setup_decoder(dinfo, &parameters);
460
461                         /* open a byte stream */
462                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
463
464                         /* decode the stream and fill the image structure */
465                         if (*indexfilename)                             // If need to extract codestream information
466                                 image = opj_decode_with_info(dinfo, cio, &cstr_info);
467                         else
468                                 image = opj_decode(dinfo, cio);                 
469                         if(!image) {
470                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
471                                 opj_destroy_decompress(dinfo);
472                                 opj_cio_close(cio);
473                                 return 1;
474                         }
475                         /* dump image */
476       j2k_dump_image(stdout, image);
477
478                         /* dump cp */
479       j2k_dump_cp(stdout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp);
480
481                         /* close the byte stream */
482                         opj_cio_close(cio);
483
484                         /* Write the index to disk */
485                         if (*indexfilename) {
486                                 char bSuccess;
487                                 bSuccess = write_index_file(&cstr_info, indexfilename);
488                                 if (bSuccess) {
489                                         fprintf(stderr, "Failed to output index file\n");
490                                 }
491                         }
492                 }
493                 break;
494
495                 case JPT_CFMT:
496                 {
497                         /* JPEG 2000, JPIP */
498
499                         /* get a decoder handle */
500                         dinfo = opj_create_decompress(CODEC_JPT);
501
502                         /* catch events using our callbacks and give a local context */
503                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
504
505                         /* setup the decoder decoding parameters using user parameters */
506                         opj_setup_decoder(dinfo, &parameters);
507
508                         /* open a byte stream */
509                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
510
511                         /* decode the stream and fill the image structure */
512                         if (*indexfilename)                             // If need to extract codestream information
513                                 image = opj_decode_with_info(dinfo, cio, &cstr_info);
514                         else
515                                 image = opj_decode(dinfo, cio);
516                         if(!image) {
517                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
518                                 opj_destroy_decompress(dinfo);
519                                 opj_cio_close(cio);
520                                 return 1;
521                         }
522
523                         /* close the byte stream */
524                         opj_cio_close(cio);
525
526                         /* Write the index to disk */
527                         if (*indexfilename) {
528                                 char bSuccess;
529                                 bSuccess = write_index_file(&cstr_info, indexfilename);
530                                 if (bSuccess) {
531                                         fprintf(stderr, "Failed to output index file\n");
532                                 }
533                         }
534                 }
535                 break;
536
537                 default:
538                         fprintf(stderr, "skipping file..\n");
539                         continue;
540         }
541
542                 /* free the memory containing the code-stream */
543                 free(src);
544                 src = NULL;
545
546                 /* free remaining structures */
547                 if(dinfo) {
548                         opj_destroy_decompress(dinfo);
549                 }
550                 /* free codestream information structure */
551                 if (*indexfilename)     
552                         opj_destroy_cstr_info(&cstr_info);
553                 /* free image data structure */
554                 opj_image_destroy(image);
555
556         }
557
558   return EXIT_SUCCESS;
559 }