cppcheck fix for openjp2 (#740)
[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 #include "opj_string.h"
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   int flag;
81 }img_fol_t;
82
83 /* -------------------------------------------------------------------------- */
84 /* Declarations                                                               */
85 static int get_num_images(char *imgdirpath);
86 static int load_images(dircnt_t *dirptr, char *imgdirpath);
87 static int get_file_format(const char *filename);
88 static char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters);
89 static int infile_format(const char *fname);
90
91 static int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol);
92
93 /* -------------------------------------------------------------------------- */
94 static void decode_help_display(void) {
95     fprintf(stdout,"\nThis is the opj_dump utility from the OpenJPEG project.\n"
96             "It dumps JPEG 2000 codestream info to stdout or a given file.\n"
97             "It has been compiled against openjp2 library v%s.\n\n",opj_version());
98
99     fprintf(stdout,"Parameters:\n");
100     fprintf(stdout,"-----------\n");
101     fprintf(stdout,"\n");
102     fprintf(stdout,"  -ImgDir <directory>\n");
103         fprintf(stdout,"        Image file Directory path \n");
104         fprintf(stdout,"  -i <compressed file>\n");
105         fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
106         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
107         fprintf(stdout,"    is identified based on its suffix.\n");
108         fprintf(stdout,"  -o <output file>\n");
109         fprintf(stdout,"    OPTIONAL\n");
110         fprintf(stdout,"    Output file where file info will be dump.\n");
111         fprintf(stdout,"    By default it will be in the stdout.\n");
112     fprintf(stdout,"  -v "); /* FIXME WIP_MSD */
113         fprintf(stdout,"    OPTIONAL\n");
114     fprintf(stdout,"    Enable informative messages\n");
115     fprintf(stdout,"    By default verbose mode is off.\n");
116         fprintf(stdout,"\n");
117 }
118
119 /* -------------------------------------------------------------------------- */
120 static int get_num_images(char *imgdirpath){
121         DIR *dir;
122         struct dirent* content; 
123         int num_images = 0;
124
125         /*Reading the input images from given input directory*/
126
127         dir= opendir(imgdirpath);
128         if(!dir){
129                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
130                 return 0;
131         }
132         
133         while((content=readdir(dir))!=NULL){
134                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
135                         continue;
136                 num_images++;
137         }
138         closedir(dir);
139         return num_images;
140 }
141
142 /* -------------------------------------------------------------------------- */
143 static int load_images(dircnt_t *dirptr, char *imgdirpath){
144         DIR *dir;
145         struct dirent* content; 
146         int i = 0;
147
148         /*Reading the input images from given input directory*/
149
150         dir= opendir(imgdirpath);
151         if(!dir){
152                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
153                 return 1;
154         }else   {
155                 fprintf(stderr,"Folder opened successfully\n");
156         }
157         
158         while((content=readdir(dir))!=NULL){
159                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
160                         continue;
161
162                 strcpy(dirptr->filename[i],content->d_name);
163                 i++;
164         }
165         closedir(dir);
166         return 0;       
167 }
168
169 /* -------------------------------------------------------------------------- */
170 static int get_file_format(const char *filename) {
171         unsigned int i;
172         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
173         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 };
174         const char *ext = strrchr(filename, '.');
175         if (ext == NULL)
176                 return -1;
177         ext++;
178         if(ext) {
179                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
180                         if(_strnicmp(ext, extension[i], 3) == 0) {
181                                 return format[i];
182                         }
183                 }
184         }
185
186         return -1;
187 }
188
189 /* -------------------------------------------------------------------------- */
190 static char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
191         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
192         char *temp_p, temp1[OPJ_PATH_LEN]="";
193
194         strcpy(image_filename,dirptr->filename[imageno]);
195         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
196         parameters->decod_format = get_file_format(image_filename);
197         if (parameters->decod_format == -1)
198                 return 1;
199         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
200         if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infilename) != 0) {
201                 return 1;
202         }
203
204         /*Set output file*/
205         strcpy(temp_ofname,strtok(image_filename,"."));
206         while((temp_p = strtok(NULL,".")) != NULL){
207                 strcat(temp_ofname,temp1);
208                 sprintf(temp1,".%s",temp_p);
209         }
210         if(img_fol->set_out_format==1){
211                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
212                 if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile), outfilename) != 0) {
213                         return 1;
214                 }
215         }
216         return 0;
217 }
218
219 /* -------------------------------------------------------------------------- */
220 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
221 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
222 /* position 45: "\xff\x52" */
223 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
224
225 static int infile_format(const char *fname)
226 {
227         FILE *reader;
228         const char *s, *magic_s;
229         int ext_format, magic_format;
230         unsigned char buf[12];
231         size_t l_nb_read; 
232
233         reader = fopen(fname, "rb");
234
235         if (reader == NULL)
236                 return -1;
237
238         memset(buf, 0, 12);
239         l_nb_read = fread(buf, 1, 12, reader);
240         fclose(reader);
241         if (l_nb_read != 12)
242                 return -1;
243
244
245
246         ext_format = get_file_format(fname);
247
248         if (ext_format == JPT_CFMT)
249                 return JPT_CFMT;
250
251         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
252                 magic_format = JP2_CFMT;
253                 magic_s = ".jp2";
254         }
255         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
256                 magic_format = J2K_CFMT;
257                 magic_s = ".j2k or .jpc or .j2c";
258         }
259         else
260                 return -1;
261
262         if (magic_format == ext_format)
263                 return ext_format;
264
265         s = fname + strlen(fname) - 4;
266
267         fputs("\n===========================================\n", stderr);
268         fprintf(stderr, "The extension of this file is incorrect.\n"
269                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
270         fputs("===========================================\n", stderr);
271
272         return magic_format;
273 }
274 /* -------------------------------------------------------------------------- */
275 /**
276  * Parse the command line
277  */
278 /* -------------------------------------------------------------------------- */
279 static int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {
280         int totlen, c;
281         opj_option_t long_option[]={
282         {"ImgDir",REQ_ARG, NULL ,'y'}
283         };
284     const char optlist[] = "i:o:f:hv";
285
286         totlen=sizeof(long_option);
287         img_fol->set_out_format = 0;
288         do {
289                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
290                 if (c == -1)
291                         break;
292                 switch (c) {
293                         case 'i':                       /* input file */
294                         {
295                                 char *infile = opj_optarg;
296                                 parameters->decod_format = infile_format(infile);
297                                 switch(parameters->decod_format) {
298                                         case J2K_CFMT:
299                                                 break;
300                                         case JP2_CFMT:
301                                                 break;
302                                         case JPT_CFMT:
303                     break;
304                 default:
305                     fprintf(stderr,
306                             "[ERROR] Unknown input file format: %s \n"
307                             "        Known file formats are *.j2k, *.jp2, *.jpc or *.jpt\n",
308                             infile);
309                     return 1;
310                                 }
311                                 if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infile) != 0) {
312                                         fprintf(stderr, "[ERROR] Path is too long\n");
313                                         return 1;
314                                 }
315                         }
316                         break;
317
318                                 /* ------------------------------------------------------ */
319
320                         case 'o':     /* output file */
321                         {
322                                 if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile), opj_optarg) != 0) {
323                                         fprintf(stderr, "[ERROR] Path is too long\n");
324                                         return 1;
325                                 }
326                         }
327                         break;
328                                 
329                                 /* ----------------------------------------------------- */
330       case 'f':                         /* flag */
331         img_fol->flag = atoi(opj_optarg);
332         break;
333                                 /* ----------------------------------------------------- */
334
335                         case 'h':                       /* display an help description */
336                                 decode_help_display();
337                                 return 1;                               
338
339                                 /* ------------------------------------------------------ */
340
341                         case 'y':                       /* Image Directory path */
342                         {
343                                 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
344                                 if(img_fol->imgdirpath == NULL){
345                                         return 1;
346                                 }
347                                 strcpy(img_fol->imgdirpath,opj_optarg);
348                                 img_fol->set_imgdir=1;
349                         }
350                         break;
351
352                         /* ----------------------------------------------------- */
353
354             case 'v':                   /* Verbose mode */
355                         {
356                 parameters->m_verbose = 1;
357                         }
358                         break;
359                         
360                                 /* ----------------------------------------------------- */
361         default:
362             fprintf(stderr, "[WARNING] An invalid option has been ignored.\n");
363             break;
364         }
365         }while(c != -1);
366
367         /* check for possible errors */
368         if(img_fol->set_imgdir==1){
369                 if(!(parameters->infile[0]==0)){
370             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together.\n");
371                         return 1;
372                 }
373                 if(img_fol->set_out_format == 0){
374             fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used.\n");
375             fprintf(stderr, "Only one format allowed.\n"
376                             "Valid format are PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA.\n");
377                         return 1;
378                 }
379                 if(!(parameters->outfile[0] == 0)){
380             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together\n");
381                         return 1;
382                 }
383         }else{
384                 if(parameters->infile[0] == 0) {
385             fprintf(stderr, "[ERROR] Required parameter is missing\n");
386                         fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
387             fprintf(stderr, "   Help: %s -h\n",argv[0]);
388                         return 1;
389                 }
390         }
391
392         return 0;
393 }
394
395 /* -------------------------------------------------------------------------- */
396
397 /**
398 sample error debug callback expecting no client object
399 */
400 static void error_callback(const char *msg, void *client_data) {
401         (void)client_data;
402         fprintf(stdout, "[ERROR] %s", msg);
403 }
404 /**
405 sample warning debug callback expecting no client object
406 */
407 static void warning_callback(const char *msg, void *client_data) {
408         (void)client_data;
409         fprintf(stdout, "[WARNING] %s", msg);
410 }
411 /**
412 sample debug callback expecting no client object
413 */
414 static void info_callback(const char *msg, void *client_data) {
415         (void)client_data;
416         fprintf(stdout, "[INFO] %s", msg);
417 }
418
419 /* -------------------------------------------------------------------------- */
420 /**
421  * OPJ_DUMP MAIN
422  */
423 /* -------------------------------------------------------------------------- */
424 int main(int argc, char *argv[])
425 {
426         FILE *fout = NULL;
427
428         opj_dparameters_t parameters;                   /* Decompression parameters */
429         opj_image_t* image = NULL;                                      /* Image structure */
430         opj_codec_t* l_codec = NULL;                            /* Handle to a decompressor */
431         opj_stream_t *l_stream = NULL;                          /* Stream */
432         opj_codestream_info_v2_t* cstr_info = NULL;
433         opj_codestream_index_t* cstr_index = NULL;
434
435         OPJ_INT32 num_images, imageno;
436         img_fol_t img_fol;
437         dircnt_t *dirptr = NULL;
438
439         /* Set decoding parameters to default values */
440         opj_set_default_decoder_parameters(&parameters);
441
442         /* Initialize img_fol */
443         memset(&img_fol,0,sizeof(img_fol_t));
444   img_fol.flag = OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND;
445
446         /* Parse input and get user encoding parameters */
447         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
448                 if(img_fol.imgdirpath) free(img_fol.imgdirpath);
449
450                 return EXIT_FAILURE;
451         }
452
453         /* Initialize reading of directory */
454         if(img_fol.set_imgdir==1){      
455                 int it_image;
456                 num_images=get_num_images(img_fol.imgdirpath);
457
458                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
459                 if(!dirptr){
460                         return EXIT_FAILURE;
461                 }
462                 dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names*/
463                 if(!dirptr->filename_buf){
464                         free(dirptr);
465                         return EXIT_FAILURE;
466                 }
467                 dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));
468
469                 if(!dirptr->filename){
470                         goto fails;
471                 }
472
473                 for(it_image=0;it_image<num_images;it_image++){
474                         dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
475                 }
476                 
477                 if(load_images(dirptr,img_fol.imgdirpath)==1){
478                         goto fails;
479                 }
480
481                 if (num_images==0){
482                         fprintf(stdout,"Folder is empty\n");
483                         goto fails;
484                 }
485         }else{
486                 num_images=1;
487         }
488
489         /* Try to open for writing the output file if necessary */
490         if (parameters.outfile[0] != 0){
491                 fout = fopen(parameters.outfile,"w");
492                 if (!fout){
493                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", parameters.outfile);
494                         goto fails;
495                 }
496         }
497         else
498                 fout = stdout;
499
500         /* Read the header of each image one by one */
501         for(imageno = 0; imageno < num_images ; imageno++){
502
503                 fprintf(stderr,"\n");
504
505                 if(img_fol.set_imgdir==1){
506                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
507                                 fprintf(stderr,"skipping file...\n");
508                                 continue;
509                         }
510                 }
511
512                 /* Read the input file and put it in memory */
513                 /* ---------------------------------------- */
514
515                 l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
516                 if (!l_stream){
517                         fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",parameters.infile);
518                         goto fails;
519                 }
520
521                 /* Read the JPEG2000 stream */
522                 /* ------------------------ */
523
524                 switch(parameters.decod_format) {
525                         case J2K_CFMT:  /* JPEG-2000 codestream */
526                         {
527                                 /* Get a decoder handle */
528                                 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
529                                 break;
530                         }
531                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
532                         {
533                                 /* Get a decoder handle */
534                                 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
535                                 break;
536                         }
537                         case JPT_CFMT:  /* JPEG 2000, JPIP */
538                         {
539                                 /* Get a decoder handle */
540                                 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
541                                 break;
542                         }
543                         default:
544                                 fprintf(stderr, "skipping file..\n");
545                                 opj_stream_destroy(l_stream);
546                                 continue;
547                 }
548
549                 /* catch events using our callbacks and give a local context */         
550                 opj_set_info_handler(l_codec, info_callback,00);
551                 opj_set_warning_handler(l_codec, warning_callback,00);
552                 opj_set_error_handler(l_codec, error_callback,00);
553
554                 /* Setup the decoder decoding parameters using user parameters */
555                 if ( !opj_setup_decoder(l_codec, &parameters) ){
556                         fprintf(stderr, "ERROR -> opj_dump: failed to setup the decoder\n");
557                         opj_stream_destroy(l_stream);
558                         opj_destroy_codec(l_codec);
559                         fclose(fout);
560                         goto fails;
561                 }
562
563                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
564                 if(! opj_read_header(l_stream, l_codec, &image)){
565                         fprintf(stderr, "ERROR -> opj_dump: failed to read the header\n");
566                         opj_stream_destroy(l_stream);
567                         opj_destroy_codec(l_codec);
568                         opj_image_destroy(image);
569                         fclose(fout);
570                         goto fails;
571                 }
572
573                 opj_dump_codec(l_codec, img_fol.flag, fout );
574
575                 cstr_info = opj_get_cstr_info(l_codec);
576
577                 cstr_index = opj_get_cstr_index(l_codec);
578
579                 /* close the byte stream */
580                 opj_stream_destroy(l_stream);
581
582                 /* free remaining structures */
583                 if (l_codec) {
584                         opj_destroy_codec(l_codec);
585                 }
586
587                 /* destroy the image header */
588                 opj_image_destroy(image);
589
590                 /* destroy the codestream index */
591                 opj_destroy_cstr_index(&cstr_index);
592
593                 /* destroy the codestream info */
594                 opj_destroy_cstr_info(&cstr_info);
595
596         }
597
598         /* Close the output file */
599         fclose(fout);
600
601   return EXIT_SUCCESS;
602
603 fails:
604         if(dirptr){
605                 if(dirptr->filename) free(dirptr->filename);
606                 if(dirptr->filename_buf) free(dirptr->filename_buf);
607                 free(dirptr);
608         }
609         return EXIT_FAILURE;
610 }