[trunk] WIP: fix bug with windows platform and j2k_to_image
[openjpeg.git] / applications / codec / j2k_dump.c
1 /*
2  * Copyright (c) 2010, Mathieu Malaterre, GDCM
3  * Copyright (c) 2011, Mickael Savinaud, Communications & Systemes <mickael.savinaud@c-s.fr>
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 #include "opj_config.h"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <math.h>
33
34 #ifdef _WIN32
35 #include "windirent.h"
36 #else
37 #include <dirent.h>
38 #endif /* _WIN32 */
39
40 #ifdef _WIN32
41 #include <windows.h>
42 #else
43 #include <strings.h>
44 #define _stricmp strcasecmp
45 #define _strnicmp strncasecmp
46 #endif /* _WIN32 */
47
48 #include "openjpeg.h"
49 #include "opj_getopt.h"
50 #include "convert.h"
51 #include "index.h"
52
53 #include "format_defs.h"
54
55 typedef struct dircnt{
56         /** Buffer for holding images read from Directory*/
57         char *filename_buf;
58         /** Pointer to the buffer*/
59         char **filename;
60 }dircnt_t;
61
62
63 typedef struct img_folder{
64         /** The directory path of the folder containing input images*/
65         char *imgdirpath;
66         /** Output format*/
67         const char *out_format;
68         /** Enable option*/
69         char set_imgdir;
70         /** Enable Cod Format for output*/
71         char set_out_format;
72
73 }img_fol_t;
74
75 /* -------------------------------------------------------------------------- */
76 /* Declarations                                                               */
77 int get_num_images(char *imgdirpath);
78 int load_images(dircnt_t *dirptr, char *imgdirpath);
79 int get_file_format(const char *filename);
80 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters);
81 static int infile_format(const char *fname);
82
83 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol);
84 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
85
86 /* -------------------------------------------------------------------------- */
87 void decode_help_display(void) {
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,"  -o <output file>\n");
107         fprintf(stdout,"    OPTIONAL\n");
108         fprintf(stdout,"    Output file where file info will be dump.\n");
109         fprintf(stdout,"    By default it will be in the stdout.\n");
110         fprintf(stdout,"  -v "); /* FIXME WIP_MSD */
111         fprintf(stdout,"    OPTIONAL\n");
112         fprintf(stdout,"    Activate or not the verbose mode (display info and warning message)\n");
113         fprintf(stdout,"    By default verbose mode is off.\n");
114         fprintf(stdout,"\n");
115 }
116
117 /* -------------------------------------------------------------------------- */
118 int get_num_images(char *imgdirpath){
119         DIR *dir;
120         struct dirent* content; 
121         int num_images = 0;
122
123         /*Reading the input images from given input directory*/
124
125         dir= opendir(imgdirpath);
126         if(!dir){
127                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
128                 return 0;
129         }
130         
131         while((content=readdir(dir))!=NULL){
132                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
133                         continue;
134                 num_images++;
135         }
136         return num_images;
137 }
138
139 /* -------------------------------------------------------------------------- */
140 int load_images(dircnt_t *dirptr, char *imgdirpath){
141         DIR *dir;
142         struct dirent* content; 
143         int i = 0;
144
145         /*Reading the input images from given input directory*/
146
147         dir= opendir(imgdirpath);
148         if(!dir){
149                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
150                 return 1;
151         }else   {
152                 fprintf(stderr,"Folder opened successfully\n");
153         }
154         
155         while((content=readdir(dir))!=NULL){
156                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
157                         continue;
158
159                 strcpy(dirptr->filename[i],content->d_name);
160                 i++;
161         }
162         return 0;       
163 }
164
165 /* -------------------------------------------------------------------------- */
166 int get_file_format(const char *filename) {
167         unsigned int i;
168         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
169         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 };
170         char * ext = strrchr(filename, '.');
171         if (ext == NULL)
172                 return -1;
173         ext++;
174         if(ext) {
175                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
176                         if(_strnicmp(ext, extension[i], 3) == 0) {
177                                 return format[i];
178                         }
179                 }
180         }
181
182         return -1;
183 }
184
185 /* -------------------------------------------------------------------------- */
186 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
187         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
188         char *temp_p, temp1[OPJ_PATH_LEN]="";
189
190         strcpy(image_filename,dirptr->filename[imageno]);
191         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
192         parameters->decod_format = get_file_format(image_filename);
193         if (parameters->decod_format == -1)
194                 return 1;
195         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
196         strncpy(parameters->infile, infilename, sizeof(infilename));
197
198         /* Set output file */
199         strcpy(temp_ofname,strtok(image_filename,"."));
200         while((temp_p = strtok(NULL,".")) != NULL){
201                 strcat(temp_ofname,temp1);
202                 sprintf(temp1,".%s",temp_p);
203         }
204         if(img_fol->set_out_format==1){
205                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
206                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
207         }
208         return 0;
209 }
210
211 /* -------------------------------------------------------------------------- */
212 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
213 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
214 /* position 45: "\xff\x52" */
215 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
216
217 static int infile_format(const char *fname)
218 {
219         FILE *reader;
220         const char *s, *magic_s;
221         int ext_format, magic_format;
222         unsigned char buf[12];
223
224         reader = fopen(fname, "rb");
225
226         if (reader == NULL)
227                 return -1;
228
229         memset(buf, 0, 12);
230         unsigned int l_nb_read = fread(buf, 1, 12, reader);
231         fclose(reader);
232         if (l_nb_read != 12)
233                 return -1;
234
235
236
237         ext_format = get_file_format(fname);
238
239         if (ext_format == JPT_CFMT)
240                 return JPT_CFMT;
241
242         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
243                 magic_format = JP2_CFMT;
244                 magic_s = ".jp2";
245         }
246         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
247                 magic_format = J2K_CFMT;
248                 magic_s = ".j2k or .jpc or .j2c";
249         }
250         else
251                 return -1;
252
253         if (magic_format == ext_format)
254                 return ext_format;
255
256         s = fname + strlen(fname) - 4;
257
258         fputs("\n===========================================\n", stderr);
259         fprintf(stderr, "The extension of this file is incorrect.\n"
260                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
261         fputs("===========================================\n", stderr);
262
263         return magic_format;
264 }
265 /* -------------------------------------------------------------------------- */
266 /**
267  * Parse the command line
268  */
269 /* -------------------------------------------------------------------------- */
270 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {
271         int totlen, c;
272         opj_option_t long_option[]={
273                 {"ImgDir",REQ_ARG, NULL ,'y'},
274         };
275         const char optlist[] = "i:o:hv";
276
277         totlen=sizeof(long_option);
278         img_fol->set_out_format = 0;
279         do {
280                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
281                 if (c == -1)
282                         break;
283                 switch (c) {
284                         case 'i':                       /* input file */
285                         {
286                                 char *infile = opj_optarg;
287                                 parameters->decod_format = infile_format(infile);
288                                 switch(parameters->decod_format) {
289                                         case J2K_CFMT:
290                                                 break;
291                                         case JP2_CFMT:
292                                                 break;
293                                         case JPT_CFMT:
294                                                 break;
295                                         default:
296                                                 fprintf(stderr, 
297                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
298                                                         infile);
299                                                 return 1;
300                                 }
301                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
302                         }
303                         break;
304
305                                 /* ------------------------------------------------------ */
306
307                         case 'o':     /* output file */
308                         {
309                           char *outfile = opj_optarg;
310                           strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
311                         }
312                         break;
313                                 
314                                 /* ----------------------------------------------------- */
315
316                         case 'h':                       /* display an help description */
317                                 decode_help_display();
318                                 return 1;                               
319
320                                 /* ------------------------------------------------------ */
321
322                         case 'y':                       /* Image Directory path */
323                         {
324                                 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
325                                 strcpy(img_fol->imgdirpath,opj_optarg);
326                                 img_fol->set_imgdir=1;
327                         }
328                         break;
329
330                         /* ----------------------------------------------------- */
331
332                         case 'v':               /* Verbose mode */
333                         {
334                                 parameters->m_verbose = 1;
335                         }
336                         break;
337                         
338                                 /* ----------------------------------------------------- */
339                         default:
340                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, opj_optarg);
341                                 break;
342                 }
343         }while(c != -1);
344
345         /* check for possible errors */
346         if(img_fol->set_imgdir==1){
347                 if(!(parameters->infile[0]==0)){
348                         fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
349                         return 1;
350                 }
351                 if(img_fol->set_out_format == 0){
352                         fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
353                         fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
354                         return 1;
355                 }
356                 if(!((parameters->outfile[0] == 0))){
357                         fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
358                         return 1;
359                 }
360         }else{
361                 if((parameters->infile[0] == 0) ) {
362                         fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
363                         fprintf(stderr, "    Try: %s -h\n",argv[0]);
364                         return 1;
365                 }
366         }
367
368         return 0;
369 }
370
371 /* -------------------------------------------------------------------------- */
372 /**
373  * J2K_DUMP MAIN
374  */
375 /* -------------------------------------------------------------------------- */
376 int main(int argc, char *argv[])
377 {
378         FILE *fsrc = NULL, *fout = NULL;
379
380         opj_dparameters_t parameters;                   /* Decompression parameters */
381         opj_event_mgr_t event_mgr;                              /* Event manager */
382         opj_image_t* image = NULL;                                      /* Image structure */
383         opj_codec_t* dinfo = NULL;                              /* Handle to a decompressor */
384         opj_stream_t *cio = NULL;                               /* Stream */
385         opj_codestream_info_v2_t* cstr_info = NULL;
386         opj_codestream_index_t* cstr_index = NULL;
387
388         OPJ_INT32 num_images, imageno;
389         img_fol_t img_fol;
390         dircnt_t *dirptr = NULL;
391
392 #ifdef MSD
393         opj_bool l_go_on = OPJ_TRUE;
394         OPJ_UINT32 l_max_data_size = 1000;
395         OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
396 #endif
397
398         /* Set decoding parameters to default values */
399         opj_set_default_decoder_parameters(&parameters);
400
401         /* Initialize img_fol */
402         memset(&img_fol,0,sizeof(img_fol_t));
403
404         /* Parse input and get user encoding parameters */
405         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
406                 return EXIT_FAILURE;
407         }
408
409         /* Set default event mgr */
410         opj_initialize_default_event_handler(&event_mgr, parameters.m_verbose);
411
412         /* Initialize reading of directory */
413         if(img_fol.set_imgdir==1){      
414                 int it_image;
415                 num_images=get_num_images(img_fol.imgdirpath);
416
417                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
418                 if(dirptr){
419                         dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names */
420                         dirptr->filename = (char**) malloc(num_images*sizeof(char*));
421
422                         if(!dirptr->filename_buf){
423                                 return EXIT_FAILURE;
424                         }
425
426                         for(it_image=0;it_image<num_images;it_image++){
427                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
428                         }
429                 }
430                 if(load_images(dirptr,img_fol.imgdirpath)==1){
431                         return EXIT_FAILURE;
432                 }
433
434                 if (num_images==0){
435                         fprintf(stdout,"Folder is empty\n");
436                         return EXIT_FAILURE;
437                 }
438         }else{
439                 num_images=1;
440         }
441
442         /* Try to open for writing the output file if necessary */
443         if (parameters.outfile[0] != 0){
444                 fout = fopen(parameters.outfile,"w");
445                 if (!fout){
446                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", parameters.outfile);
447                         return EXIT_FAILURE;
448                 }
449         }
450         else
451                 fout = stdout;
452
453         /* Read the header of each image one by one */
454         for(imageno = 0; imageno < num_images ; imageno++){
455
456                 fprintf(stderr,"\n");
457
458                 if(img_fol.set_imgdir==1){
459                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
460                                 fprintf(stderr,"skipping file...\n");
461                                 continue;
462                         }
463                 }
464
465                 /* Read the input file and put it in memory */
466                 /* ---------------------------------------- */
467                 fsrc = fopen(parameters.infile, "rb");
468                 if (!fsrc) {
469                         fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
470                         return EXIT_FAILURE;
471                 }
472
473                 cio = opj_stream_create_default_file_stream(fsrc,1);
474                 if (!cio){
475                         fclose(fsrc);
476                         fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
477                         return EXIT_FAILURE;
478                 }
479
480                 /* Read the JPEG2000 stream */
481                 /* ------------------------ */
482
483                 switch(parameters.decod_format) {
484                         case J2K_CFMT:  /* JPEG-2000 codestream */
485                         {
486                                 /* Get a decoder handle */
487                                 dinfo = opj_create_decompress_v2(CODEC_J2K);
488                                 break;
489                         }
490                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
491                         {
492                                 /* Get a decoder handle */
493                                 dinfo = opj_create_decompress_v2(CODEC_JP2);
494                                 break;
495                         }
496                         case JPT_CFMT:  /* JPEG 2000, JPIP */
497                         {
498                                 /* Get a decoder handle */
499                                 dinfo = opj_create_decompress_v2(CODEC_JPT);
500                                 break;
501                         }
502                         default:
503                                 fprintf(stderr, "skipping file..\n");
504                                 opj_stream_destroy(cio);
505                                 continue;
506                 }
507
508                 /* Setup the decoder decoding parameters using user parameters */
509                 if ( !opj_setup_decoder_v2(dinfo, &parameters, &event_mgr) ){
510                         fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
511                         opj_stream_destroy(cio);
512                         fclose(fsrc);
513                         opj_destroy_codec(dinfo);
514                         fclose(fout);
515                         return EXIT_FAILURE;
516                 }
517
518                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
519                 if(! opj_read_header(cio, dinfo, &image)){
520                         fprintf(stderr, "ERROR -> j2k_dump: failed to read the header\n");
521                         opj_stream_destroy(cio);
522                         fclose(fsrc);
523                         opj_destroy_codec(dinfo);
524                         opj_image_destroy(image);
525                         fclose(fout);
526                         return EXIT_FAILURE;
527                 }
528
529                 opj_dump_codec(dinfo, OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND, fout );
530
531                 cstr_info = opj_get_cstr_info(dinfo);
532
533                 cstr_index = opj_get_cstr_index(dinfo);
534
535                 /* close the byte stream */
536                 opj_stream_destroy(cio);
537                 fclose(fsrc);
538
539                 /* free remaining structures */
540                 if (dinfo) {
541                         opj_destroy_codec(dinfo);
542                 }
543
544                 /* destroy the image header */
545                 opj_image_destroy(image);
546
547                 /* destroy the codestream index */
548                 opj_destroy_cstr_index(&cstr_index);
549
550                 /* destroy the codestream info */
551                 opj_destroy_cstr_info_v2(&cstr_info);
552
553         }
554
555         /* Close the output file */
556         fclose(fout);
557
558   return EXIT_SUCCESS;
559 }