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