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