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