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