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