37a74fd9144d24d6592e7431720cff106ff3e068
[openjpeg.git] / applications / codec / j2k_dump.c
1 /*
2  * Copyright (c) 2010, Mathieu Malaterre, GDCM
3  * Copyright (c) 2011, Mickael Savinaud, Communications & Systemes <mickael.savinaud@c-s.fr>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 #include "opj_config.h"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <math.h>
33
34 #ifdef _WIN32
35 #include "windirent.h"
36 #else
37 #include <dirent.h>
38 #endif /* _WIN32 */
39
40 #ifdef _WIN32
41 #include <windows.h>
42 #else
43 #include <strings.h>
44 #define _stricmp strcasecmp
45 #define _strnicmp strncasecmp
46 #endif /* _WIN32 */
47
48 #include "openjpeg.h"
49 #include "j2k.h"
50 #include "jp2.h"
51 #include "opj_getopt.h"
52 #include "convert.h"
53 #include "index.h"
54
55 #include "format_defs.h"
56
57 typedef struct dircnt{
58         /** Buffer for holding images read from Directory*/
59         char *filename_buf;
60         /** Pointer to the buffer*/
61         char **filename;
62 }dircnt_t;
63
64
65 typedef struct img_folder{
66         /** The directory path of the folder containing input images*/
67         char *imgdirpath;
68         /** Output format*/
69         const char *out_format;
70         /** Enable option*/
71         char set_imgdir;
72         /** Enable Cod Format for output*/
73         char set_out_format;
74
75 }img_fol_t;
76
77 /* -------------------------------------------------------------------------- */
78 /* Declarations                                                               */
79 int get_num_images(char *imgdirpath);
80 int load_images(dircnt_t *dirptr, char *imgdirpath);
81 int get_file_format(char *filename);
82 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters);
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 void decode_help_display(void) {
89         fprintf(stdout,"HELP for j2k_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,"  -d <x0,x1,y0,y1>\n"); /* FIXME WIP_MSD */
112         fprintf(stdout,"    OPTIONAL\n");
113         fprintf(stdout,"    Decoding area\n");
114         fprintf(stdout,"    By default all tiles header are read.\n");
115         fprintf(stdout,"  -v "); /* FIXME WIP_MSD */
116         fprintf(stdout,"    OPTIONAL\n");
117         fprintf(stdout,"    Activate or not the verbose mode (display info and warning message)\n");
118         fprintf(stdout,"    By default verbose mode is off.\n");
119         fprintf(stdout,"\n");
120 }
121
122 /* -------------------------------------------------------------------------- */
123 int get_num_images(char *imgdirpath){
124         DIR *dir;
125         struct dirent* content; 
126         int num_images = 0;
127
128         /*Reading the input images from given input directory*/
129
130         dir= opendir(imgdirpath);
131         if(!dir){
132                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
133                 return 0;
134         }
135         
136         while((content=readdir(dir))!=NULL){
137                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
138                         continue;
139                 num_images++;
140         }
141         return num_images;
142 }
143
144 /* -------------------------------------------------------------------------- */
145 int load_images(dircnt_t *dirptr, char *imgdirpath){
146         DIR *dir;
147         struct dirent* content; 
148         int i = 0;
149
150         /*Reading the input images from given input directory*/
151
152         dir= opendir(imgdirpath);
153         if(!dir){
154                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
155                 return 1;
156         }else   {
157                 fprintf(stderr,"Folder opened successfully\n");
158         }
159         
160         while((content=readdir(dir))!=NULL){
161                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
162                         continue;
163
164                 strcpy(dirptr->filename[i],content->d_name);
165                 i++;
166         }
167         return 0;       
168 }
169
170 /* -------------------------------------------------------------------------- */
171 int get_file_format(char *filename) {
172         unsigned int i;
173         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
174         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 };
175         char * ext = strrchr(filename, '.');
176         if (ext == NULL)
177                 return -1;
178         ext++;
179         if(ext) {
180                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
181                         if(_strnicmp(ext, extension[i], 3) == 0) {
182                                 return format[i];
183                         }
184                 }
185         }
186
187         return -1;
188 }
189
190 /* -------------------------------------------------------------------------- */
191 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
192         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
193         char *temp_p, temp1[OPJ_PATH_LEN]="";
194
195         strcpy(image_filename,dirptr->filename[imageno]);
196         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
197         parameters->decod_format = get_file_format(image_filename);
198         if (parameters->decod_format == -1)
199                 return 1;
200         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
201         strncpy(parameters->infile, infilename, sizeof(infilename));
202
203         /* Set output file */
204         strcpy(temp_ofname,strtok(image_filename,"."));
205         while((temp_p = strtok(NULL,".")) != NULL){
206                 strcat(temp_ofname,temp1);
207                 sprintf(temp1,".%s",temp_p);
208         }
209         if(img_fol->set_out_format==1){
210                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
211                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
212         }
213         return 0;
214 }
215
216 /* -------------------------------------------------------------------------- */
217 /**
218  * Parse the command line
219  */
220 /* -------------------------------------------------------------------------- */
221 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {
222         int totlen, c;
223         opj_option_t long_option[]={
224                 {"ImgDir",REQ_ARG, NULL ,'y'},
225         };
226         const char optlist[] = "i:o:d:hv";
227
228         totlen=sizeof(long_option);
229         img_fol->set_out_format = 0;
230         do {
231                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
232                 if (c == -1)
233                         break;
234                 switch (c) {
235                         case 'i':                       /* input file */
236                         {
237                                 char *infile = opj_optarg;
238                                 parameters->decod_format = get_file_format(infile);
239                                 switch(parameters->decod_format) {
240                                         case J2K_CFMT:
241                                                 break;
242                                         case JP2_CFMT:
243                                                 break;
244                                         case JPT_CFMT:
245                                                 break;
246                                         default:
247                                                 fprintf(stderr, 
248                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
249                                                         infile);
250                                                 return 1;
251                                 }
252                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
253                         }
254                         break;
255
256                                 /* ------------------------------------------------------ */
257
258                         case 'o':     /* output file */
259                         {
260                           char *outfile = opj_optarg;
261                           strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
262                         }
263                         break;
264                                 
265                                 /* ----------------------------------------------------- */
266
267                         case 'h':                       /* display an help description */
268                                 decode_help_display();
269                                 return 1;                               
270
271                                 /* ------------------------------------------------------ */
272
273                         case 'y':                       /* Image Directory path */
274                         {
275                                 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
276                                 strcpy(img_fol->imgdirpath,opj_optarg);
277                                 img_fol->set_imgdir=1;
278                         }
279                         break;
280
281                                 /* ----------------------------------------------------- */
282
283                         case 'd':               /* Input decode ROI */
284                         {
285                                 int size_optarg = (int)strlen(opj_optarg) + 1;
286                                 char *ROI_values = (char*) malloc(size_optarg);
287                                 ROI_values[0] = '\0';
288                                 strncpy(ROI_values, opj_optarg, strlen(opj_optarg));
289                                 ROI_values[strlen(opj_optarg)] = '\0';
290                                 /*printf("ROI_values = %s [%d / %d]\n", ROI_values, strlen(ROI_values), size_optarg ); */
291                                 parse_DA_values( ROI_values, &parameters->DA_x0, &parameters->DA_y0, &parameters->DA_x1, &parameters->DA_y1);
292                         }
293                         break;
294                         /* ----------------------------------------------------- */
295
296                         case 'v':               /* Verbose mode */
297                         {
298                                 parameters->m_verbose = 1;
299                         }
300                         break;
301                         
302                                 /* ----------------------------------------------------- */
303                         default:
304                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, opj_optarg);
305                                 break;
306                 }
307         }while(c != -1);
308
309         /* check for possible errors */
310         if(img_fol->set_imgdir==1){
311                 if(!(parameters->infile[0]==0)){
312                         fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
313                         return 1;
314                 }
315                 if(img_fol->set_out_format == 0){
316                         fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
317                         fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
318                         return 1;
319                 }
320                 if(!((parameters->outfile[0] == 0))){
321                         fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
322                         return 1;
323                 }
324         }else{
325                 if((parameters->infile[0] == 0) ) {
326                         fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
327                         fprintf(stderr, "    Try: %s -h\n",argv[0]);
328                         return 1;
329                 }
330         }
331
332         return 0;
333 }
334
335 /* -------------------------------------------------------------------------- */
336 /**
337  * Parse decoding area input values
338  * separator = ","
339  */
340 /* -------------------------------------------------------------------------- */
341 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1)
342 {
343         int it = 0;
344         int values[4];
345         char delims[] = ",";
346         char *result = NULL;
347         result = strtok( inArg, delims );
348
349         while( (result != NULL) && (it < 4 ) ) {
350                 values[it] = atoi(result);
351                 result = strtok( NULL, delims );
352                 it++;
353         }
354
355         if (it != 4) {
356                 return EXIT_FAILURE;
357         }
358         else{
359                 *DA_x0 = values[0]; *DA_y0 = values[1];
360                 *DA_x1 = values[2]; *DA_y1 = values[3];
361                 return EXIT_SUCCESS;
362         }
363 }
364
365
366 /* -------------------------------------------------------------------------- */
367 /**
368  * J2K_DUMP MAIN
369  */
370 /* -------------------------------------------------------------------------- */
371 int main(int argc, char *argv[])
372 {
373         FILE *fsrc = NULL, *fout = NULL;
374
375         opj_dparameters_t parameters;                   /* Decompression parameters */
376         opj_event_mgr_t event_mgr;                              /* Event manager */
377         opj_image_header_t img_header;                  /* Image info structure */
378         opj_codec_t* dinfo = NULL;                              /* Handle to a decompressor */
379         opj_stream_t *cio = NULL;                               /* Stream */
380         opj_codestream_info_v2_t* cstr_info;
381         opj_codestream_index_t* cstr_index;
382
383         OPJ_INT32 num_images, imageno;
384         img_fol_t img_fol;
385         dircnt_t *dirptr = NULL;
386
387         opj_bool l_go_on = OPJ_TRUE;
388         OPJ_UINT32 l_max_data_size = 1000;
389         OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
390
391         /* Set decoding parameters to default values */
392         opj_set_default_decoder_parameters(&parameters);
393
394         /* Initialize img_fol */
395         memset(&img_fol,0,sizeof(img_fol_t));
396
397         /* Parse input and get user encoding parameters */
398         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {
399                 return EXIT_FAILURE;
400         }
401
402         /* Set default event mgr */
403         opj_set_default_event_handler(&event_mgr, parameters.m_verbose);
404
405         /* Initialize reading of directory */
406         if(img_fol.set_imgdir==1){      
407                 int it_image;
408                 num_images=get_num_images(img_fol.imgdirpath);
409
410                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
411                 if(dirptr){
412                         dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names */
413                         dirptr->filename = (char**) malloc(num_images*sizeof(char*));
414
415                         if(!dirptr->filename_buf){
416                                 return EXIT_FAILURE;
417                         }
418
419                         for(it_image=0;it_image<num_images;it_image++){
420                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
421                         }
422                 }
423                 if(load_images(dirptr,img_fol.imgdirpath)==1){
424                         return EXIT_FAILURE;
425                 }
426
427                 if (num_images==0){
428                         fprintf(stdout,"Folder is empty\n");
429                         return EXIT_FAILURE;
430                 }
431         }else{
432                 num_images=1;
433         }
434
435         /* Try to open for writing the output file if necessary */
436         if (parameters.outfile[0] != 0){
437                 fout = fopen(parameters.outfile,"w");
438                 if (!fout){
439                         fprintf(stderr, "ERROR -> failed to open %s for writing\n", parameters.outfile);
440                         return EXIT_FAILURE;
441                 }
442         }
443         else
444                 fout = stdout;
445
446         /* Read the header of each image one by one */
447         for(imageno = 0; imageno < num_images ; imageno++){
448
449                 fprintf(stderr,"\n");
450
451                 if(img_fol.set_imgdir==1){
452                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
453                                 fprintf(stderr,"skipping file...\n");
454                                 continue;
455                         }
456                 }
457
458                 /* Read the input file and put it in memory */
459                 /* ---------------------------------------- */
460                 fsrc = fopen(parameters.infile, "rb");
461                 if (!fsrc) {
462                         fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
463                         return EXIT_FAILURE;
464                 }
465
466                 cio = opj_stream_create_default_file_stream(fsrc,1);
467                 if (!cio){
468                         fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
469                         return EXIT_FAILURE;
470                 }
471
472                 /* Read the JPEG2000 stream */
473                 /* ------------------------ */
474
475                 switch(parameters.decod_format) {
476                         case J2K_CFMT:  /* JPEG-2000 codestream */
477                         {
478                                 /* Get a decoder handle */
479                                 dinfo = opj_create_decompress_v2(CODEC_J2K);
480                                 break;
481                         }
482                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
483                         {
484                                 /* Get a decoder handle */
485                                 dinfo = opj_create_decompress_v2(CODEC_JP2);
486                                 break;
487                         }
488                         case JPT_CFMT:  /* JPEG 2000, JPIP */
489                         {
490                                 /* Get a decoder handle */
491                                 dinfo = opj_create_decompress_v2(CODEC_JPT);
492                                 break;
493                         }
494                         default:
495                                 fprintf(stderr, "skipping file..\n");
496                                 opj_stream_destroy(cio);
497                                 continue;
498                 }
499
500                 /* Setup the decoder decoding parameters using user parameters */
501                 if ( !opj_setup_decoder_v2(dinfo, &parameters, &event_mgr) ){
502                         fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
503                         opj_stream_destroy(cio);
504                         fclose(fsrc);
505                         opj_destroy_codec(dinfo);
506                         fclose(fout);
507                         return EXIT_FAILURE;
508                 }
509
510                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
511                 if(! opj_read_header(cio, dinfo, &img_header)){
512                         fprintf(stderr, "ERROR -> j2k_dump: failed to read the header\n");
513                         opj_stream_destroy(cio);
514                         fclose(fsrc);
515                         opj_destroy_codec(dinfo);
516                         fclose(fout);
517                         return EXIT_FAILURE;
518                 }
519
520                 opj_dump_codec(dinfo, OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND, stdout );
521
522                 cstr_info = opj_get_cstr_info(dinfo);
523
524                 cstr_index = opj_get_cstr_index(dinfo);
525
526                 fprintf(stdout,"Setting decoding area to %d,%d,%d,%d\n",
527                                 parameters.DA_x0, parameters.DA_y0, parameters.DA_x1, parameters.DA_y1);
528
529 #ifdef MSD
530                 /* FIXME WIP_MSD <*/
531                 if (! opj_set_decode_area(      dinfo,
532                                                                         parameters.DA_x0, parameters.DA_y0,
533                                                                         parameters.DA_x1, parameters.DA_y1)){
534                         fprintf(stderr, "ERROR -> j2k_dump: failed to set the decoded area\n");
535                         opj_stream_destroy(cio);
536                         opj_destroy_codec(dinfo);
537                         fclose(fsrc);
538                         fclose(fout);
539                         return EXIT_FAILURE;
540                 }
541
542                 while (l_go_on) {
543                         OPJ_INT32 l_current_tile_x0,l_current_tile_y0,l_current_tile_x1,l_current_tile_y1;
544                         OPJ_UINT32 l_nb_comps, l_tile_index, l_data_size;
545
546
547                         if (! opj_read_tile_header(     dinfo,
548                                                                                 cio,
549                                                                                 &l_tile_index,
550                                                                                 &l_data_size,
551                                                                                 &l_current_tile_x0,
552                                                                                 &l_current_tile_y0,
553                                                                                 &l_current_tile_x1,
554                                                                                 &l_current_tile_y1,
555                                                                                 &l_nb_comps,
556                                                                                 &l_go_on
557                                                                                 )) {
558                                 fprintf(stderr, "ERROR -> j2k_dump: failed read the tile header\n");
559                                 opj_stream_destroy(cio);
560                                 fclose(fsrc);
561                                 opj_destroy_codec(dinfo);
562                                 return EXIT_FAILURE;
563                         }
564
565                         if (l_go_on) {
566
567                                 if (l_data_size > l_max_data_size) {
568
569                                         l_data = (OPJ_BYTE *) realloc(l_data,l_data_size);
570                                         if (! l_data) {
571                                                 opj_stream_destroy(cio);
572                                                 opj_destroy_codec(dinfo);
573                                                 fclose(fsrc);
574                                                 fclose(fout);
575                                                 return EXIT_FAILURE;
576                                         }
577
578                                         l_max_data_size = l_data_size;
579                                 }
580
581                                 if (! opj_decode_tile_data(dinfo,l_tile_index,l_data,l_data_size,cio))
582                                 {
583                                         free(l_data);
584                                         opj_stream_destroy(cio);
585                                         opj_destroy_codec(dinfo);
586                                         fclose(fsrc);
587                                         fclose(fout);
588                                         return EXIT_FAILURE;
589                                 }
590                                 /** now should inspect image to know the reduction factor and then how to behave with data */
591                         }
592                 }
593                 /* FIXME WIP_MSD >*/
594 #endif
595
596                 /* close the byte stream */
597                 opj_stream_destroy(cio);
598                 fclose(fsrc);
599
600                 /* free remaining structures */
601                 if (dinfo) {
602                         opj_destroy_codec(dinfo);
603                 }
604
605                 /* destroy the image header */
606                 opj_image_header_destroy(&img_header);
607
608         }
609
610         /* Close the output file */
611         fclose(fout);
612
613   return EXIT_SUCCESS;
614 }