[trunk] move to the new API for function opj_stream_create_default_file_stream. Use...
[openjpeg.git] / src / bin / jp2 / opj_dump.c
1 /*
2  * Copyright (c) 2010, Mathieu Malaterre, GDCM
3  * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France 
4  * Copyright (c) 2012, CS Systemes d'Information, France
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 #include "opj_config.h"
29
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <math.h>
34
35 #ifdef _WIN32
36 #include "windirent.h"
37 #else
38 #include <dirent.h>
39 #endif /* _WIN32 */
40
41 #ifdef _WIN32
42 #include <windows.h>
43 #else
44 #include <strings.h>
45 #define _stricmp strcasecmp
46 #define _strnicmp strncasecmp
47 #endif /* _WIN32 */
48
49 #include "openjpeg.h"
50 #include "opj_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 /* -------------------------------------------------------------------------- */
77 /* Declarations                                                               */
78 int get_num_images(char *imgdirpath);
79 int load_images(dircnt_t *dirptr, char *imgdirpath);
80 int get_file_format(const char *filename);
81 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters);
82 static int infile_format(const char *fname);
83
84 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol);
85 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
86
87 /* -------------------------------------------------------------------------- */
88 static void decode_help_display(void) {
89         fprintf(stdout,"HELP for opj_dump\n----\n\n");
90         fprintf(stdout,"- the -h option displays this help information on screen\n\n");
91
92 /* UniPG>> */
93         fprintf(stdout,"List of parameters for the JPEG 2000 "
94 #ifdef USE_JPWL
95                 "+ JPWL "
96 #endif /* USE_JPWL */
97                 "decoder:\n");
98 /* <<UniPG */
99         fprintf(stdout,"\n");
100         fprintf(stdout,"\n");
101         fprintf(stdout,"  -ImgDir \n");
102         fprintf(stdout,"        Image file Directory path \n");
103         fprintf(stdout,"  -i <compressed file>\n");
104         fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
105         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
106         fprintf(stdout,"    is identified based on its suffix.\n");
107         fprintf(stdout,"  -o <output file>\n");
108         fprintf(stdout,"    OPTIONAL\n");
109         fprintf(stdout,"    Output file where file info will be dump.\n");
110         fprintf(stdout,"    By default it will be in the stdout.\n");
111         fprintf(stdout,"  -v "); /* FIXME WIP_MSD */
112         fprintf(stdout,"    OPTIONAL\n");
113         fprintf(stdout,"    Activate or not the verbose mode (display info and warning message)\n");
114         fprintf(stdout,"    By default verbose mode is off.\n");
115         fprintf(stdout,"\n");
116 }
117
118 /* -------------------------------------------------------------------------- */
119 int get_num_images(char *imgdirpath){
120         DIR *dir;
121         struct dirent* content; 
122         int num_images = 0;
123
124         /*Reading the input images from given input directory*/
125
126         dir= opendir(imgdirpath);
127         if(!dir){
128                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
129                 return 0;
130         }
131         
132         while((content=readdir(dir))!=NULL){
133                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
134                         continue;
135                 num_images++;
136         }
137         return num_images;
138 }
139
140 /* -------------------------------------------------------------------------- */
141 int load_images(dircnt_t *dirptr, char *imgdirpath){
142         DIR *dir;
143         struct dirent* content; 
144         int i = 0;
145
146         /*Reading the input images from given input directory*/
147
148         dir= opendir(imgdirpath);
149         if(!dir){
150                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
151                 return 1;
152         }else   {
153                 fprintf(stderr,"Folder opened successfully\n");
154         }
155         
156         while((content=readdir(dir))!=NULL){
157                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
158                         continue;
159
160                 strcpy(dirptr->filename[i],content->d_name);
161                 i++;
162         }
163         return 0;       
164 }
165
166 /* -------------------------------------------------------------------------- */
167 int get_file_format(const char *filename) {
168         unsigned int i;
169         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
170         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 };
171         char * ext = strrchr(filename, '.');
172         if (ext == NULL)
173                 return -1;
174         ext++;
175         if(ext) {
176                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
177                         if(_strnicmp(ext, extension[i], 3) == 0) {
178                                 return format[i];
179                         }
180                 }
181         }
182
183         return -1;
184 }
185
186 /* -------------------------------------------------------------------------- */
187 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
188         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
189         char *temp_p, temp1[OPJ_PATH_LEN]="";
190
191         strcpy(image_filename,dirptr->filename[imageno]);
192         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
193         parameters->decod_format = get_file_format(image_filename);
194         if (parameters->decod_format == -1)
195                 return 1;
196         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
197         strncpy(parameters->infile, infilename, sizeof(infilename));
198
199         /*Set output file*/
200         strcpy(temp_ofname,strtok(image_filename,"."));
201         while((temp_p = strtok(NULL,".")) != NULL){
202                 strcat(temp_ofname,temp1);
203                 sprintf(temp1,".%s",temp_p);
204         }
205         if(img_fol->set_out_format==1){
206                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
207                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
208         }
209         return 0;
210 }
211
212 /* -------------------------------------------------------------------------- */
213 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
214 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
215 /* position 45: "\xff\x52" */
216 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
217
218 static int infile_format(const char *fname)
219 {
220         FILE *reader;
221         const char *s, *magic_s;
222         int ext_format, magic_format;
223         unsigned char buf[12];
224         unsigned int l_nb_read; 
225
226         reader = fopen(fname, "rb");
227
228         if (reader == NULL)
229                 return -1;
230
231         memset(buf, 0, 12);
232         l_nb_read = fread(buf, 1, 12, reader);
233         fclose(reader);
234         if (l_nb_read != 12)
235                 return -1;
236
237
238
239         ext_format = get_file_format(fname);
240
241         if (ext_format == JPT_CFMT)
242                 return JPT_CFMT;
243
244         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
245                 magic_format = JP2_CFMT;
246                 magic_s = ".jp2";
247         }
248         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
249                 magic_format = J2K_CFMT;
250                 magic_s = ".j2k or .jpc or .j2c";
251         }
252         else
253                 return -1;
254
255         if (magic_format == ext_format)
256                 return ext_format;
257
258         s = fname + strlen(fname) - 4;
259
260         fputs("\n===========================================\n", stderr);
261         fprintf(stderr, "The extension of this file is incorrect.\n"
262                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
263         fputs("===========================================\n", stderr);
264
265         return magic_format;
266 }
267 /* -------------------------------------------------------------------------- */
268 /**
269  * Parse the command line
270  */
271 /* -------------------------------------------------------------------------- */
272 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {
273         int totlen, c;
274         opj_option_t long_option[]={
275                 {"ImgDir",REQ_ARG, NULL ,'y'},
276         };
277         const char optlist[] = "i:o:hv";
278
279         totlen=sizeof(long_option);
280         img_fol->set_out_format = 0;
281         do {
282                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
283                 if (c == -1)
284                         break;
285                 switch (c) {
286                         case 'i':                       /* input file */
287                         {
288                                 char *infile = opj_optarg;
289                                 parameters->decod_format = infile_format(infile);
290                                 switch(parameters->decod_format) {
291                                         case J2K_CFMT:
292                                                 break;
293                                         case JP2_CFMT:
294                                                 break;
295                                         case JPT_CFMT:
296                                                 break;
297                                         default:
298                                                 fprintf(stderr, 
299                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
300                                                         infile);
301                                                 return 1;
302                                 }
303                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
304                         }
305                         break;
306
307                                 /* ------------------------------------------------------ */
308
309                         case 'o':     /* output file */
310                         {
311                           char *outfile = opj_optarg;
312                           strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
313                         }
314                         break;
315                                 
316                                 /* ----------------------------------------------------- */
317
318                         case 'h':                       /* display an help description */
319                                 decode_help_display();
320                                 return 1;                               
321
322                                 /* ------------------------------------------------------ */
323
324                         case 'y':                       /* Image Directory path */
325                         {
326                                 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
327                                 strcpy(img_fol->imgdirpath,opj_optarg);
328                                 img_fol->set_imgdir=1;
329                         }
330                         break;
331
332                         /* ----------------------------------------------------- */
333
334                         case 'v':               /* Verbose mode */
335                         {
336                                 parameters->m_verbose = 1;
337                         }
338                         break;
339                         
340                                 /* ----------------------------------------------------- */
341                         default:
342                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, opj_optarg);
343                                 break;
344                 }
345         }while(c != -1);
346
347         /* check for possible errors */
348         if(img_fol->set_imgdir==1){
349                 if(!(parameters->infile[0]==0)){
350                         fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
351                         return 1;
352                 }
353                 if(img_fol->set_out_format == 0){
354                         fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
355                         fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
356                         return 1;
357                 }
358                 if(!(parameters->outfile[0] == 0)){
359                         fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
360                         return 1;
361                 }
362         }else{
363                 if(parameters->infile[0] == 0) {
364                         fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
365                         fprintf(stderr, "    Try: %s -h\n",argv[0]);
366                         return 1;
367                 }
368         }
369
370         return 0;
371 }
372
373 /* -------------------------------------------------------------------------- */
374
375 /**
376 sample error debug callback expecting no client object
377 */
378 static void error_callback(const char *msg, void *client_data) {
379         (void)client_data;
380         fprintf(stdout, "[ERROR] %s", msg);
381 }
382 /**
383 sample warning debug callback expecting no client object
384 */
385 static void warning_callback(const char *msg, void *client_data) {
386         (void)client_data;
387         fprintf(stdout, "[WARNING] %s", msg);
388 }
389 /**
390 sample debug callback expecting no client object
391 */
392 static void info_callback(const char *msg, void *client_data) {
393         (void)client_data;
394         fprintf(stdout, "[INFO] %s", msg);
395 }
396
397 /* -------------------------------------------------------------------------- */
398 /**
399  * OPJ_DUMP MAIN
400  */
401 /* -------------------------------------------------------------------------- */
402 int main(int argc, char *argv[])
403 {
404         FILE *fout = NULL;
405
406         opj_dparameters_t parameters;                   /* Decompression parameters */
407         opj_image_t* image = NULL;                                      /* Image structure */
408         opj_codec_t* l_codec = NULL;                            /* Handle to a decompressor */
409         opj_stream_t *l_stream = NULL;                          /* Stream */
410         opj_codestream_info_v2_t* cstr_info = NULL;
411         opj_codestream_index_t* cstr_index = NULL;
412
413         OPJ_INT32 num_images, imageno;
414         img_fol_t img_fol;
415         dircnt_t *dirptr = NULL;
416
417 #ifdef MSD
418         OPJ_BOOL l_go_on = OPJ_TRUE;
419         OPJ_UINT32 l_max_data_size = 1000;
420         OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
421 #endif
422
423         /* Set decoding parameters to default values */
424         opj_set_default_decoder_parameters(&parameters);
425
426         /* Initialize img_fol */
427         memset(&img_fol,0,sizeof(img_fol_t));
428
429         /* Parse input and get user encoding parameters */
430         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
431                 return EXIT_FAILURE;
432         }
433
434         /* Initialize reading of directory */
435         if(img_fol.set_imgdir==1){      
436                 int it_image;
437                 num_images=get_num_images(img_fol.imgdirpath);
438
439                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
440                 if(dirptr){
441                         dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names*/
442                         dirptr->filename = (char**) malloc(num_images*sizeof(char*));
443
444                         if(!dirptr->filename_buf){
445                                 return EXIT_FAILURE;
446                         }
447
448                         for(it_image=0;it_image<num_images;it_image++){
449                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
450                         }
451                 }
452                 if(load_images(dirptr,img_fol.imgdirpath)==1){
453                         return EXIT_FAILURE;
454                 }
455
456                 if (num_images==0){
457                         fprintf(stdout,"Folder is empty\n");
458                         return EXIT_FAILURE;
459                 }
460         }else{
461                 num_images=1;
462         }
463
464         /* Try to open for writing the output file if necessary */
465         if (parameters.outfile[0] != 0){
466                 fout = fopen(parameters.outfile,"w");
467                 if (!fout){
468                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", parameters.outfile);
469                         return EXIT_FAILURE;
470                 }
471         }
472         else
473                 fout = stdout;
474
475         /* Read the header of each image one by one */
476         for(imageno = 0; imageno < num_images ; imageno++){
477
478                 fprintf(stderr,"\n");
479
480                 if(img_fol.set_imgdir==1){
481                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
482                                 fprintf(stderr,"skipping file...\n");
483                                 continue;
484                         }
485                 }
486
487                 /* Read the input file and put it in memory */
488                 /* ---------------------------------------- */
489
490                 l_stream = opj_stream_create_default_file_stream_v3(parameters.infile,1);
491                 if (!l_stream){
492                         fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",parameters.infile);
493                         return EXIT_FAILURE;
494                 }
495
496                 /* Read the JPEG2000 stream */
497                 /* ------------------------ */
498
499                 switch(parameters.decod_format) {
500                         case J2K_CFMT:  /* JPEG-2000 codestream */
501                         {
502                                 /* Get a decoder handle */
503                                 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
504                                 break;
505                         }
506                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
507                         {
508                                 /* Get a decoder handle */
509                                 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
510                                 break;
511                         }
512                         case JPT_CFMT:  /* JPEG 2000, JPIP */
513                         {
514                                 /* Get a decoder handle */
515                                 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
516                                 break;
517                         }
518                         default:
519                                 fprintf(stderr, "skipping file..\n");
520                                 opj_stream_destroy_v3(l_stream);
521                                 continue;
522                 }
523
524                 /* catch events using our callbacks and give a local context */         
525                 opj_set_info_handler(l_codec, info_callback,00);
526                 opj_set_warning_handler(l_codec, warning_callback,00);
527                 opj_set_error_handler(l_codec, error_callback,00);
528
529                 /* Setup the decoder decoding parameters using user parameters */
530                 if ( !opj_setup_decoder(l_codec, &parameters) ){
531                         fprintf(stderr, "ERROR -> opj_dump: failed to setup the decoder\n");
532                         opj_stream_destroy_v3(l_stream);
533                         opj_destroy_codec(l_codec);
534                         fclose(fout);
535                         return EXIT_FAILURE;
536                 }
537
538                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
539                 if(! opj_read_header(l_stream, l_codec, &image)){
540                         fprintf(stderr, "ERROR -> opj_dump: failed to read the header\n");
541                         opj_stream_destroy_v3(l_stream);
542                         opj_destroy_codec(l_codec);
543                         opj_image_destroy(image);
544                         fclose(fout);
545                         return EXIT_FAILURE;
546                 }
547
548                 opj_dump_codec(l_codec, OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND, fout );
549
550                 cstr_info = opj_get_cstr_info(l_codec);
551
552                 cstr_index = opj_get_cstr_index(l_codec);
553
554                 /* close the byte stream */
555                 opj_stream_destroy_v3(l_stream);
556
557                 /* free remaining structures */
558                 if (l_codec) {
559                         opj_destroy_codec(l_codec);
560                 }
561
562                 /* destroy the image header */
563                 opj_image_destroy(image);
564
565                 /* destroy the codestream index */
566                 opj_destroy_cstr_index(&cstr_index);
567
568                 /* destroy the codestream info */
569                 opj_destroy_cstr_info(&cstr_info);
570
571         }
572
573         /* Close the output file */
574         fclose(fout);
575
576   return EXIT_SUCCESS;
577 }