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