Fix several memory and resource leaks
[openjpeg.git] / src / bin / jp2 / opj_compress.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) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
16  * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
17  * Copyright (c) 2012, CS Systemes d'Information, France
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
30  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
33  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include <stdio.h>
43 #include <string.h>
44 #include <stdlib.h>
45 #include <math.h>
46 #include <assert.h>
47
48 #ifdef _WIN32
49 #include "windirent.h"
50 #else
51 #include <dirent.h>
52 #endif /* _WIN32 */
53
54 #ifdef _WIN32
55 #include <windows.h>
56 #define strcasecmp _stricmp
57 #define strncasecmp _strnicmp
58 #else
59 #include <strings.h>
60 #include <sys/time.h>
61 #include <sys/resource.h>
62 #include <sys/times.h>
63 #endif /* _WIN32 */
64
65 #include "opj_apps_config.h"
66 #include "openjpeg.h"
67 #include "opj_getopt.h"
68 #include "convert.h"
69 #include "index.h"
70
71 #include "format_defs.h"
72 #include "opj_string.h"
73
74 typedef struct dircnt {
75     /** Buffer for holding images read from Directory*/
76     char *filename_buf;
77     /** Pointer to the buffer*/
78     char **filename;
79 } dircnt_t;
80
81 typedef struct img_folder {
82     /** The directory path of the folder containing input images*/
83     char *imgdirpath;
84     /** Output format*/
85     char *out_format;
86     /** Enable option*/
87     char set_imgdir;
88     /** Enable Cod Format for output*/
89     char set_out_format;
90 } img_fol_t;
91
92 static void encode_help_display(void)
93 {
94     fprintf(stdout,
95             "\nThis is the opj_compress utility from the OpenJPEG project.\n"
96             "It compresses various image formats with the JPEG 2000 algorithm.\n"
97             "It has been compiled against openjp2 library v%s.\n\n", opj_version());
98
99     fprintf(stdout, "Default encoding options:\n");
100     fprintf(stdout, "-------------------------\n");
101     fprintf(stdout, "\n");
102     fprintf(stdout, " * Lossless\n");
103     fprintf(stdout, " * 1 tile\n");
104     fprintf(stdout, " * RGB->YCC conversion if at least 3 components\n");
105     fprintf(stdout, " * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
106     fprintf(stdout, " * Size of code-block : 64 x 64\n");
107     fprintf(stdout, " * Number of resolutions: 6\n");
108     fprintf(stdout, " * No SOP marker in the codestream\n");
109     fprintf(stdout, " * No EPH marker in the codestream\n");
110     fprintf(stdout, " * No sub-sampling in x or y direction\n");
111     fprintf(stdout, " * No mode switch activated\n");
112     fprintf(stdout, " * Progression order: LRCP\n");
113 #ifdef FIXME_INDEX
114     fprintf(stdout, " * No index file\n");
115 #endif /* FIXME_INDEX */
116     fprintf(stdout, " * No ROI upshifted\n");
117     fprintf(stdout, " * No offset of the origin of the image\n");
118     fprintf(stdout, " * No offset of the origin of the tiles\n");
119     fprintf(stdout, " * Reversible DWT 5-3\n");
120     /* UniPG>> */
121 #ifdef USE_JPWL
122     fprintf(stdout, " * No JPWL protection\n");
123 #endif /* USE_JPWL */
124     /* <<UniPG */
125     fprintf(stdout, "\n");
126
127     fprintf(stdout, "Note:\n");
128     fprintf(stdout, "-----\n");
129     fprintf(stdout, "\n");
130     fprintf(stdout,
131             "The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
132     fprintf(stdout, "COD and QCD never appear in the tile_header.\n");
133     fprintf(stdout, "\n");
134
135     fprintf(stdout, "Parameters:\n");
136     fprintf(stdout, "-----------\n");
137     fprintf(stdout, "\n");
138     fprintf(stdout, "Required Parameters (except with -h):\n");
139     fprintf(stdout, "One of the two options -ImgDir or -i must be used\n");
140     fprintf(stdout, "\n");
141     fprintf(stdout, "-i <file>\n");
142     fprintf(stdout, "    Input file\n");
143     fprintf(stdout,
144             "    Known extensions are <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n");
145     fprintf(stdout, "    If used, '-o <file>' must be provided\n");
146     fprintf(stdout, "-o <compressed file>\n");
147     fprintf(stdout, "    Output file (accepted extensions are j2k or jp2).\n");
148     fprintf(stdout, "-ImgDir <dir>\n");
149     fprintf(stdout, "    Image file Directory path (example ../Images) \n");
150     fprintf(stdout, "    When using this option -OutFor must be used\n");
151     fprintf(stdout, "-OutFor <J2K|J2C|JP2>\n");
152     fprintf(stdout, "    Output format for compressed files.\n");
153     fprintf(stdout, "    Required only if -ImgDir is used\n");
154     fprintf(stdout,
155             "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
156     fprintf(stdout, "    Characteristics of the raw input image\n");
157     fprintf(stdout,
158             "    If subsampling is omitted, 1x1 is assumed for all components\n");
159     fprintf(stdout, "      Example: -F 512,512,3,8,u@1x1:2x2:2x2\n");
160     fprintf(stdout,
161             "               for raw 512x512 image with 4:2:0 subsampling\n");
162     fprintf(stdout, "    Required only if RAW or RAWL input file is provided.\n");
163     fprintf(stdout, "\n");
164     fprintf(stdout, "Optional Parameters:\n");
165     fprintf(stdout, "\n");
166     fprintf(stdout, "-h\n");
167     fprintf(stdout, "    Display the help information.\n");
168     fprintf(stdout, "-r <compression ratio>,<compression ratio>,...\n");
169     fprintf(stdout, "    Different compression ratios for successive layers.\n");
170     fprintf(stdout,
171             "    The rate specified for each quality level is the desired\n");
172     fprintf(stdout, "    compression factor (use 1 for lossless)\n");
173     fprintf(stdout, "    Decreasing ratios required.\n");
174     fprintf(stdout, "      Example: -r 20,10,1 means \n");
175     fprintf(stdout, "            quality layer 1: compress 20x, \n");
176     fprintf(stdout, "            quality layer 2: compress 10x \n");
177     fprintf(stdout, "            quality layer 3: compress lossless\n");
178     fprintf(stdout, "    Options -r and -q cannot be used together.\n");
179     fprintf(stdout, "-q <psnr value>,<psnr value>,<psnr value>,...\n");
180     fprintf(stdout, "    Different psnr for successive layers (-q 30,40,50).\n");
181     fprintf(stdout, "    Increasing PSNR values required, except 0 which can\n");
182     fprintf(stdout, "    be used for the last layer to indicate it is lossless.\n");
183     fprintf(stdout, "    Options -r and -q cannot be used together.\n");
184     fprintf(stdout, "-n <number of resolutions>\n");
185     fprintf(stdout, "    Number of resolutions.\n");
186     fprintf(stdout,
187             "    It corresponds to the number of DWT decompositions +1. \n");
188     fprintf(stdout, "    Default: 6.\n");
189     fprintf(stdout, "-b <cblk width>,<cblk height>\n");
190     fprintf(stdout,
191             "    Code-block size. The dimension must respect the constraint \n");
192     fprintf(stdout,
193             "    defined in the JPEG-2000 standard (no dimension smaller than 4 \n");
194     fprintf(stdout,
195             "    or greater than 1024, no code-block with more than 4096 coefficients).\n");
196     fprintf(stdout, "    The maximum value authorized is 64x64. \n");
197     fprintf(stdout, "    Default: 64x64.\n");
198     fprintf(stdout,
199             "-c [<prec width>,<prec height>],[<prec width>,<prec height>],...\n");
200     fprintf(stdout, "    Precinct size. Values specified must be power of 2. \n");
201     fprintf(stdout,
202             "    Multiple records may be supplied, in which case the first record refers\n");
203     fprintf(stdout,
204             "    to the highest resolution level and subsequent records to lower \n");
205     fprintf(stdout,
206             "    resolution levels. The last specified record is halved successively for each \n");
207     fprintf(stdout, "    remaining lower resolution levels.\n");
208     fprintf(stdout, "    Default: 2^15x2^15 at each resolution.\n");
209     fprintf(stdout, "-t <tile width>,<tile height>\n");
210     fprintf(stdout, "    Tile size.\n");
211     fprintf(stdout,
212             "    Default: the dimension of the whole image, thus only one tile.\n");
213     fprintf(stdout, "-p <LRCP|RLCP|RPCL|PCRL|CPRL>\n");
214     fprintf(stdout, "    Progression order.\n");
215     fprintf(stdout, "    Default: LRCP.\n");
216     fprintf(stdout, "-s  <subX,subY>\n");
217     fprintf(stdout, "    Subsampling factor.\n");
218     fprintf(stdout, "    Subsampling bigger than 2 can produce error\n");
219     fprintf(stdout, "    Default: no subsampling.\n");
220     fprintf(stdout,
221             "-POC <progression order change>/<progression order change>/...\n");
222     fprintf(stdout, "    Progression order change.\n");
223     fprintf(stdout,
224             "    The syntax of a progression order change is the following:\n");
225     fprintf(stdout,
226             "    T<tile>=<resStart>,<compStart>,<layerEnd>,<resEnd>,<compEnd>,<progOrder>\n");
227     fprintf(stdout, "      Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\n");
228     fprintf(stdout, "-SOP\n");
229     fprintf(stdout, "    Write SOP marker before each packet.\n");
230     fprintf(stdout, "-EPH\n");
231     fprintf(stdout, "    Write EPH marker after each header packet.\n");
232     fprintf(stdout, "-M <key value>\n");
233     fprintf(stdout, "    Mode switch.\n");
234     fprintf(stdout, "    [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
235     fprintf(stdout, "    8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
236     fprintf(stdout, "    Indicate multiple modes by adding their values.\n");
237     fprintf(stdout,
238             "      Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");
239     fprintf(stdout, "-TP <R|L|C>\n");
240     fprintf(stdout, "    Divide packets of every tile into tile-parts.\n");
241     fprintf(stdout,
242             "    Division is made by grouping Resolutions (R), Layers (L)\n");
243     fprintf(stdout, "    or Components (C).\n");
244 #ifdef FIXME_INDEX
245     fprintf(stdout, "-x  <index file>\n");
246     fprintf(stdout, "    Create an index file.\n");
247 #endif /*FIXME_INDEX*/
248     fprintf(stdout, "-ROI c=<component index>,U=<upshifting value>\n");
249     fprintf(stdout, "    Quantization indices upshifted for a component. \n");
250     fprintf(stdout,
251             "    Warning: This option does not implement the usual ROI (Region of Interest).\n");
252     fprintf(stdout,
253             "    It should be understood as a 'Component of Interest'. It offers the \n");
254     fprintf(stdout,
255             "    possibility to upshift the value of a component during quantization step.\n");
256     fprintf(stdout,
257             "    The value after c= is the component number [0, 1, 2, ...] and the value \n");
258     fprintf(stdout,
259             "    after U= is the value of upshifting. U must be in the range [0, 37].\n");
260     fprintf(stdout, "-d <image offset X,image offset Y>\n");
261     fprintf(stdout, "    Offset of the origin of the image.\n");
262     fprintf(stdout, "-T <tile offset X,tile offset Y>\n");
263     fprintf(stdout, "    Offset of the origin of the tiles.\n");
264     fprintf(stdout, "-I\n");
265     fprintf(stdout, "    Use the irreversible DWT 9-7.\n");
266     fprintf(stdout, "-mct <0|1|2>\n");
267     fprintf(stdout,
268             "    Explicitly specifies if a Multiple Component Transform has to be used.\n");
269     fprintf(stdout, "    0: no MCT ; 1: RGB->YCC conversion ; 2: custom MCT.\n");
270     fprintf(stdout,
271             "    If custom MCT, \"-m\" option has to be used (see hereunder).\n");
272     fprintf(stdout,
273             "    By default, RGB->YCC conversion is used if there are 3 components or more,\n");
274     fprintf(stdout, "    no conversion otherwise.\n");
275     fprintf(stdout, "-m <file>\n");
276     fprintf(stdout,
277             "    Use array-based MCT, values are coma separated, line by line\n");
278     fprintf(stdout,
279             "    No specific separators between lines, no space allowed between values.\n");
280     fprintf(stdout,
281             "    If this option is used, it automatically sets \"-mct\" option to 2.\n");
282     fprintf(stdout, "-cinema2K <24|48>\n");
283     fprintf(stdout, "    Digital Cinema 2K profile compliant codestream.\n");
284     fprintf(stdout,
285             "   Need to specify the frames per second for a 2K resolution.\n");
286     fprintf(stdout, "    Only 24 or 48 fps are currently allowed.\n");
287     fprintf(stdout, "-cinema4K\n");
288     fprintf(stdout, "    Digital Cinema 4K profile compliant codestream.\n");
289     fprintf(stdout, "   Frames per second not required. Default value is 24fps.\n");
290     fprintf(stdout, "-jpip\n");
291     fprintf(stdout, "    Write jpip codestream index box in JP2 output file.\n");
292     fprintf(stdout, "    Currently supports only RPCL order.\n");
293     fprintf(stdout, "-C <comment>\n");
294     fprintf(stdout, "    Add <comment> in the comment marker segment.\n");
295     /* UniPG>> */
296 #ifdef USE_JPWL
297     fprintf(stdout, "-W <params>\n");
298     fprintf(stdout, "    Adoption of JPWL (Part 11) capabilities (-W params)\n");
299     fprintf(stdout,
300             "    The <params> field can be written and repeated in any order:\n");
301     fprintf(stdout, "    [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
302     fprintf(stdout, "    ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
303     fprintf(stdout,
304             "     h selects the header error protection (EPB): 'type' can be\n");
305     fprintf(stdout,
306             "       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
307     fprintf(stdout,
308             "       if 'tilepart' is absent, it is for main and tile headers\n");
309     fprintf(stdout, "       if 'tilepart' is present, it applies from that tile\n");
310     fprintf(stdout,
311             "         onwards, up to the next h<> spec, or to the last tilepart\n");
312     fprintf(stdout, "         in the codestream (max. %d specs)\n",
313             JPWL_MAX_NO_TILESPECS);
314     fprintf(stdout,
315             "     p selects the packet error protection (EEP/UEP with EPBs)\n");
316     fprintf(stdout, "      to be applied to raw data: 'type' can be\n");
317     fprintf(stdout,
318             "       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
319     fprintf(stdout,
320             "       if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
321     fprintf(stdout,
322             "       if 'tilepart:pack' is present, it applies from that tile\n");
323     fprintf(stdout,
324             "         and that packet onwards, up to the next packet spec\n");
325     fprintf(stdout,
326             "         or to the last packet in the last tilepart in the stream\n");
327     fprintf(stdout, "         (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
328     fprintf(stdout,
329             "     s enables sensitivity data insertion (ESD): 'method' can be\n");
330     fprintf(stdout,
331             "       [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
332     fprintf(stdout, "        4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
333     fprintf(stdout, "       if 'tilepart' is absent, it is for main header only\n");
334     fprintf(stdout, "       if 'tilepart' is present, it applies from that tile\n");
335     fprintf(stdout,
336             "         onwards, up to the next s<> spec, or to the last tilepart\n");
337     fprintf(stdout, "         in the codestream (max. %d specs)\n",
338             JPWL_MAX_NO_TILESPECS);
339     fprintf(stdout, "     g determines the addressing mode: <range> can be\n");
340     fprintf(stdout, "       [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
341     fprintf(stdout,
342             "     a determines the size of data addressing: <addr> can be\n");
343     fprintf(stdout,
344             "       2/4 bytes (small/large codestreams). If not set, auto-mode\n");
345     fprintf(stdout,
346             "     z determines the size of sensitivity values: <size> can be\n");
347     fprintf(stdout,
348             "       1/2 bytes, for the transformed pseudo-floating point value\n");
349     fprintf(stdout, "     ex.:\n");
350     fprintf(stdout,
351             "       h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
352     fprintf(stdout, "         s0=6,s3=-1,a=0,g=1,z=1\n");
353     fprintf(stdout, "     means\n");
354     fprintf(stdout,
355             "       predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
356     fprintf(stdout,
357             "       CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
358     fprintf(stdout, "       UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
359     fprintf(stdout,
360             "       UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
361     fprintf(stdout, "       UEP rs default for packets of tilepart 1,\n");
362     fprintf(stdout, "       no UEP for packets 0 to 19 of tilepart 3,\n");
363     fprintf(stdout,
364             "       UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
365     fprintf(stdout, "       relative sensitivity ESD for MH,\n");
366     fprintf(stdout,
367             "       TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
368     fprintf(stdout,
369             "       size of addresses and 1 byte for each sensitivity value\n");
370     fprintf(stdout, "     ex.:\n");
371     fprintf(stdout, "           h,s,p\n");
372     fprintf(stdout, "     means\n");
373     fprintf(stdout,
374             "       default protection to headers (MH and TPHs) as well as\n");
375     fprintf(stdout, "       data packets, one ESD in MH\n");
376     fprintf(stdout,
377             "     N.B.: use the following recommendations when specifying\n");
378     fprintf(stdout, "           the JPWL parameters list\n");
379     fprintf(stdout,
380             "       - when you use UEP, always pair the 'p' option with 'h'\n");
381 #endif /* USE_JPWL */
382     /* <<UniPG */
383     fprintf(stdout, "\n");
384 #ifdef FIXME_INDEX
385     fprintf(stdout, "Index structure:\n");
386     fprintf(stdout, "----------------\n");
387     fprintf(stdout, "\n");
388     fprintf(stdout, "Image_height Image_width\n");
389     fprintf(stdout, "progression order\n");
390     fprintf(stdout, "Tiles_size_X Tiles_size_Y\n");
391     fprintf(stdout, "Tiles_nb_X Tiles_nb_Y\n");
392     fprintf(stdout, "Components_nb\n");
393     fprintf(stdout, "Layers_nb\n");
394     fprintf(stdout, "decomposition_levels\n");
395     fprintf(stdout, "[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
396     fprintf(stdout, "   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
397     fprintf(stdout, "Main_header_start_position\n");
398     fprintf(stdout, "Main_header_end_position\n");
399     fprintf(stdout, "Codestream_size\n");
400     fprintf(stdout, "\n");
401     fprintf(stdout, "INFO ON TILES\n");
402     fprintf(stdout,
403             "tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");
404     fprintf(stdout,
405             "Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");
406     fprintf(stdout,
407             "Tile_1   ''           ''        ''        ''       ''    ''      ''\n");
408     fprintf(stdout, "...\n");
409     fprintf(stdout,
410             "Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");
411     fprintf(stdout, "...\n");
412     fprintf(stdout, "TILE 0 DETAILS\n");
413     fprintf(stdout, "part_nb tileno num_packs start_pos end_tph_pos end_pos\n");
414     fprintf(stdout, "...\n");
415     fprintf(stdout, "Progression_string\n");
416     fprintf(stdout,
417             "pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");
418     fprintf(stdout,
419             "Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
420     fprintf(stdout, "...\n");
421     fprintf(stdout,
422             "Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
423     fprintf(stdout, "MaxDisto\n");
424     fprintf(stdout, "TotalDisto\n\n");
425 #endif /*FIXME_INDEX*/
426 }
427
428 static OPJ_PROG_ORDER give_progression(const char progression[4])
429 {
430     if (strncmp(progression, "LRCP", 4) == 0) {
431         return OPJ_LRCP;
432     }
433     if (strncmp(progression, "RLCP", 4) == 0) {
434         return OPJ_RLCP;
435     }
436     if (strncmp(progression, "RPCL", 4) == 0) {
437         return OPJ_RPCL;
438     }
439     if (strncmp(progression, "PCRL", 4) == 0) {
440         return OPJ_PCRL;
441     }
442     if (strncmp(progression, "CPRL", 4) == 0) {
443         return OPJ_CPRL;
444     }
445
446     return OPJ_PROG_UNKNOWN;
447 }
448
449 static unsigned int get_num_images(char *imgdirpath)
450 {
451     DIR *dir;
452     struct dirent* content;
453     unsigned int num_images = 0;
454
455     /*Reading the input images from given input directory*/
456
457     dir = opendir(imgdirpath);
458     if (!dir) {
459         fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
460         return 0;
461     }
462
463     num_images = 0;
464     while ((content = readdir(dir)) != NULL) {
465         if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
466             continue;
467         }
468         num_images++;
469     }
470     closedir(dir);
471     return num_images;
472 }
473
474 static int load_images(dircnt_t *dirptr, char *imgdirpath)
475 {
476     DIR *dir;
477     struct dirent* content;
478     int i = 0;
479
480     /*Reading the input images from given input directory*/
481
482     dir = opendir(imgdirpath);
483     if (!dir) {
484         fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
485         return 1;
486     } else   {
487         fprintf(stderr, "Folder opened successfully\n");
488     }
489
490     while ((content = readdir(dir)) != NULL) {
491         if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
492             continue;
493         }
494
495         strcpy(dirptr->filename[i], content->d_name);
496         i++;
497     }
498     closedir(dir);
499     return 0;
500 }
501
502 static int get_file_format(char *filename)
503 {
504     unsigned int i;
505     static const char *extension[] = {
506         "pgx", "pnm", "pgm", "ppm", "pbm", "pam", "bmp", "tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "j2c", "jpc"
507     };
508     static const int format[] = {
509         PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT
510     };
511     char * ext = strrchr(filename, '.');
512     if (ext == NULL) {
513         return -1;
514     }
515     ext++;
516     for (i = 0; i < sizeof(format) / sizeof(*format); i++) {
517         if (strcasecmp(ext, extension[i]) == 0) {
518             return format[i];
519         }
520     }
521     return -1;
522 }
523
524 static char * get_file_name(char *name)
525 {
526     char *fname = strtok(name, ".");
527     return fname;
528 }
529
530 static char get_next_file(int imageno, dircnt_t *dirptr, img_fol_t *img_fol,
531                           opj_cparameters_t *parameters)
532 {
533     char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],
534          outfilename[OPJ_PATH_LEN], temp_ofname[OPJ_PATH_LEN];
535     char *temp_p, temp1[OPJ_PATH_LEN] = "";
536
537     strcpy(image_filename, dirptr->filename[imageno]);
538     fprintf(stderr, "File Number %d \"%s\"\n", imageno, image_filename);
539     parameters->decod_format = get_file_format(image_filename);
540     if (parameters->decod_format == -1) {
541         return 1;
542     }
543     sprintf(infilename, "%s/%s", img_fol->imgdirpath, image_filename);
544     if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile),
545                      infilename) != 0) {
546         return 1;
547     }
548
549     /*Set output file*/
550     strcpy(temp_ofname, get_file_name(image_filename));
551     while ((temp_p = strtok(NULL, ".")) != NULL) {
552         strcat(temp_ofname, temp1);
553         sprintf(temp1, ".%s", temp_p);
554     }
555     if (img_fol->set_out_format == 1) {
556         sprintf(outfilename, "%s/%s.%s", img_fol->imgdirpath, temp_ofname,
557                 img_fol->out_format);
558         if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
559                          outfilename) != 0) {
560             return 1;
561         }
562     }
563     return 0;
564 }
565
566 /* ------------------------------------------------------------------------------------ */
567
568 static int parse_cmdline_encoder(int argc, char **argv,
569                                  opj_cparameters_t *parameters,
570                                  img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename,
571                                  size_t indexfilename_size)
572 {
573     OPJ_UINT32 i, j;
574     int totlen, c;
575     opj_option_t long_option[] = {
576         {"cinema2K", REQ_ARG, NULL, 'w'},
577         {"cinema4K", NO_ARG, NULL, 'y'},
578         {"ImgDir", REQ_ARG, NULL, 'z'},
579         {"TP", REQ_ARG, NULL, 'u'},
580         {"SOP", NO_ARG, NULL, 'S'},
581         {"EPH", NO_ARG, NULL, 'E'},
582         {"OutFor", REQ_ARG, NULL, 'O'},
583         {"POC", REQ_ARG, NULL, 'P'},
584         {"ROI", REQ_ARG, NULL, 'R'},
585         {"jpip", NO_ARG, NULL, 'J'},
586         {"mct", REQ_ARG, NULL, 'Y'}
587     };
588
589     /* parse the command line */
590     const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
591 #ifdef USE_JPWL
592                            "W:"
593 #endif /* USE_JPWL */
594                            "h";
595
596     totlen = sizeof(long_option);
597     img_fol->set_out_format = 0;
598     raw_cp->rawWidth = 0;
599
600     do {
601         c = opj_getopt_long(argc, argv, optlist, long_option, totlen);
602         if (c == -1) {
603             break;
604         }
605         switch (c) {
606         case 'i': {         /* input file */
607             char *infile = opj_optarg;
608             parameters->decod_format = get_file_format(infile);
609             switch (parameters->decod_format) {
610             case PGX_DFMT:
611             case PXM_DFMT:
612             case BMP_DFMT:
613             case TIF_DFMT:
614             case RAW_DFMT:
615             case RAWL_DFMT:
616             case TGA_DFMT:
617             case PNG_DFMT:
618                 break;
619             default:
620                 fprintf(stderr,
621                         "[ERROR] Unknown input file format: %s \n"
622                         "        Known file formats are *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga\n",
623                         infile);
624                 return 1;
625             }
626             if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infile) != 0) {
627                 return 1;
628             }
629         }
630         break;
631
632         /* ----------------------------------------------------- */
633
634         case 'o': {         /* output file */
635             char *outfile = opj_optarg;
636             parameters->cod_format = get_file_format(outfile);
637             switch (parameters->cod_format) {
638             case J2K_CFMT:
639             case JP2_CFMT:
640                 break;
641             default:
642                 fprintf(stderr,
643                         "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
644                 return 1;
645             }
646             if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
647                              outfile) != 0) {
648                 return 1;
649             }
650         }
651         break;
652
653         /* ----------------------------------------------------- */
654         case 'O': {         /* output format */
655             char outformat[50];
656             char *of = opj_optarg;
657             sprintf(outformat, ".%s", of);
658             img_fol->set_out_format = 1;
659             parameters->cod_format = get_file_format(outformat);
660             switch (parameters->cod_format) {
661             case J2K_CFMT:
662             case JP2_CFMT:
663                 img_fol->out_format = opj_optarg;
664                 break;
665             default:
666                 fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");
667                 return 1;
668             }
669         }
670         break;
671
672
673         /* ----------------------------------------------------- */
674
675
676         case 'r': {         /* rates rates/distorsion */
677             char *s = opj_optarg;
678             parameters->tcp_numlayers = 0;
679             while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) ==
680                     1) {
681                 parameters->tcp_numlayers++;
682                 while (*s && *s != ',') {
683                     s++;
684                 }
685                 if (!*s) {
686                     break;
687                 }
688                 s++;
689             }
690             parameters->cp_disto_alloc = 1;
691         }
692         break;
693
694         /* ----------------------------------------------------- */
695
696
697         case 'F': {         /* Raw image format parameters */
698             OPJ_BOOL wrong = OPJ_FALSE;
699             char *substr1;
700             char *substr2;
701             char *sep;
702             char signo;
703             int width, height, bitdepth, ncomp;
704             OPJ_UINT32 len;
705             OPJ_BOOL raw_signed = OPJ_FALSE;
706             substr2 = strchr(opj_optarg, '@');
707             if (substr2 == NULL) {
708                 len = (OPJ_UINT32) strlen(opj_optarg);
709             } else {
710                 len = (OPJ_UINT32)(substr2 - opj_optarg);
711                 substr2++; /* skip '@' character */
712             }
713             substr1 = (char*) malloc((len + 1) * sizeof(char));
714             if (substr1 == NULL) {
715                 return 1;
716             }
717             memcpy(substr1, opj_optarg, len);
718             substr1[len] = '\0';
719             if (sscanf(substr1, "%d,%d,%d,%d,%c", &width, &height, &ncomp, &bitdepth,
720                        &signo) == 5) {
721                 if (signo == 's') {
722                     raw_signed = OPJ_TRUE;
723                 } else if (signo == 'u') {
724                     raw_signed = OPJ_FALSE;
725                 } else {
726                     wrong = OPJ_TRUE;
727                 }
728             } else {
729                 wrong = OPJ_TRUE;
730             }
731             if (!wrong) {
732                 int compno;
733                 int lastdx = 1;
734                 int lastdy = 1;
735                 raw_cp->rawWidth = width;
736                 raw_cp->rawHeight = height;
737                 raw_cp->rawComp = ncomp;
738                 raw_cp->rawBitDepth = bitdepth;
739                 raw_cp->rawSigned  = raw_signed;
740                 raw_cp->rawComps = (raw_comp_cparameters_t*) malloc(((OPJ_UINT32)(
741                                        ncomp)) * sizeof(raw_comp_cparameters_t));
742                 if (raw_cp->rawComps == NULL) {
743                     free(substr1);
744                     return 1;
745                 }
746                 for (compno = 0; compno < ncomp && !wrong; compno++) {
747                     if (substr2 == NULL) {
748                         raw_cp->rawComps[compno].dx = lastdx;
749                         raw_cp->rawComps[compno].dy = lastdy;
750                     } else {
751                         int dx, dy;
752                         sep = strchr(substr2, ':');
753                         if (sep == NULL) {
754                             if (sscanf(substr2, "%dx%d", &dx, &dy) == 2) {
755                                 lastdx = dx;
756                                 lastdy = dy;
757                                 raw_cp->rawComps[compno].dx = dx;
758                                 raw_cp->rawComps[compno].dy = dy;
759                                 substr2 = NULL;
760                             } else {
761                                 wrong = OPJ_TRUE;
762                             }
763                         } else {
764                             if (sscanf(substr2, "%dx%d:%s", &dx, &dy, substr2) == 3) {
765                                 raw_cp->rawComps[compno].dx = dx;
766                                 raw_cp->rawComps[compno].dy = dy;
767                             } else {
768                                 wrong = OPJ_TRUE;
769                             }
770                         }
771                     }
772                 }
773             }
774             free(substr1);
775             if (wrong) {
776                 fprintf(stderr, "\nError: invalid raw image parameters\n");
777                 fprintf(stderr, "Please use the Format option -F:\n");
778                 fprintf(stderr,
779                         "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
780                 fprintf(stderr,
781                         "If subsampling is omitted, 1x1 is assumed for all components\n");
782                 fprintf(stderr,
783                         "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
784                 fprintf(stderr, "         for raw 512x512 image with 4:2:0 subsampling\n");
785                 fprintf(stderr, "Aborting.\n");
786                 return 1;
787             }
788         }
789         break;
790
791         /* ----------------------------------------------------- */
792
793         case 'q': {         /* add fixed_quality */
794             char *s = opj_optarg;
795             while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers])
796                     == 1) {
797                 parameters->tcp_numlayers++;
798                 while (*s && *s != ',') {
799                     s++;
800                 }
801                 if (!*s) {
802                     break;
803                 }
804                 s++;
805             }
806             parameters->cp_fixed_quality = 1;
807         }
808         break;
809
810         /* dda */
811         /* ----------------------------------------------------- */
812
813         case 'f': {         /* mod fixed_quality (before : -q) */
814             int *row = NULL, *col = NULL;
815             OPJ_UINT32 numlayers = 0, numresolution = 0, matrix_width = 0;
816
817             char *s = opj_optarg;
818             sscanf(s, "%u", &numlayers);
819             s++;
820             if (numlayers > 9) {
821                 s++;
822             }
823
824             parameters->tcp_numlayers = (int)numlayers;
825             numresolution = (OPJ_UINT32)parameters->numresolution;
826             matrix_width = numresolution * 3;
827             parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
828             if (parameters->cp_matrice == NULL) {
829                 return 1;
830             }
831             s = s + 2;
832
833             for (i = 0; i < numlayers; i++) {
834                 row = &parameters->cp_matrice[i * matrix_width];
835                 col = row;
836                 parameters->tcp_rates[i] = 1;
837                 sscanf(s, "%d,", &col[0]);
838                 s += 2;
839                 if (col[0] > 9) {
840                     s++;
841                 }
842                 col[1] = 0;
843                 col[2] = 0;
844                 for (j = 1; j < numresolution; j++) {
845                     col += 3;
846                     sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
847                     s += 6;
848                     if (col[0] > 9) {
849                         s++;
850                     }
851                     if (col[1] > 9) {
852                         s++;
853                     }
854                     if (col[2] > 9) {
855                         s++;
856                     }
857                 }
858                 if (i < numlayers - 1) {
859                     s++;
860                 }
861             }
862             parameters->cp_fixed_alloc = 1;
863         }
864         break;
865
866         /* ----------------------------------------------------- */
867
868         case 't': {         /* tiles */
869             sscanf(opj_optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
870             parameters->tile_size_on = OPJ_TRUE;
871         }
872         break;
873
874         /* ----------------------------------------------------- */
875
876         case 'n': {         /* resolution */
877             sscanf(opj_optarg, "%d", &parameters->numresolution);
878         }
879         break;
880
881         /* ----------------------------------------------------- */
882         case 'c': {         /* precinct dimension */
883             char sep;
884             int res_spec = 0;
885
886             char *s = opj_optarg;
887             int ret;
888             do {
889                 sep = 0;
890                 ret = sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
891                              &parameters->prch_init[res_spec], &sep);
892                 if (!(ret == 2 && sep == 0) && !(ret == 3 && sep == ',')) {
893                     fprintf(stderr, "\nError: could not parse precinct dimension: '%s' %x\n", s,
894                             sep);
895                     fprintf(stderr, "Example: -i lena.raw -o lena.j2k -c [128,128],[128,128]\n");
896                     return 1;
897                 }
898                 parameters->csty |= 0x01;
899                 res_spec++;
900                 s = strpbrk(s, "]") + 2;
901             } while (sep == ',');
902             parameters->res_spec = res_spec;
903         }
904         break;
905
906         /* ----------------------------------------------------- */
907
908         case 'b': {         /* code-block dimension */
909             int cblockw_init = 0, cblockh_init = 0;
910             sscanf(opj_optarg, "%d,%d", &cblockw_init, &cblockh_init);
911             if (cblockw_init > 1024 || cblockw_init < 4 ||
912                     cblockh_init > 1024 || cblockh_init < 4 ||
913                     cblockw_init * cblockh_init > 4096) {
914                 fprintf(stderr,
915                         "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
916                         "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
917                 return 1;
918             }
919             parameters->cblockw_init = cblockw_init;
920             parameters->cblockh_init = cblockh_init;
921         }
922         break;
923
924         /* ----------------------------------------------------- */
925
926         case 'x': {         /* creation of index file */
927             if (opj_strcpy_s(indexfilename, indexfilename_size, opj_optarg) != 0) {
928                 return 1;
929             }
930             /* FIXME ADE INDEX >> */
931             fprintf(stderr,
932                     "[WARNING] Index file generation is currently broken.\n"
933                     "          '-x' option ignored.\n");
934             /* << FIXME ADE INDEX */
935         }
936         break;
937
938         /* ----------------------------------------------------- */
939
940         case 'p': {         /* progression order */
941             char progression[4];
942
943             strncpy(progression, opj_optarg, 4);
944             parameters->prog_order = give_progression(progression);
945             if (parameters->prog_order == -1) {
946                 fprintf(stderr, "Unrecognized progression order "
947                         "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
948                 return 1;
949             }
950         }
951         break;
952
953         /* ----------------------------------------------------- */
954
955         case 's': {         /* subsampling factor */
956             if (sscanf(opj_optarg, "%d,%d", &parameters->subsampling_dx,
957                        &parameters->subsampling_dy) != 2) {
958                 fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
959                 return 1;
960             }
961         }
962         break;
963
964         /* ----------------------------------------------------- */
965
966         case 'd': {         /* coordonnate of the reference grid */
967             if (sscanf(opj_optarg, "%d,%d", &parameters->image_offset_x0,
968                        &parameters->image_offset_y0) != 2) {
969                 fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
970                         "error !! [-d x0,y0]\n");
971                 return 1;
972             }
973         }
974         break;
975
976         /* ----------------------------------------------------- */
977
978         case 'h':           /* display an help description */
979             encode_help_display();
980             return 1;
981
982         /* ----------------------------------------------------- */
983
984         case 'P': {         /* POC */
985             int numpocs = 0;        /* number of progression order change (POC) default 0 */
986             opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
987
988             char *s = opj_optarg;
989             POC = parameters->POC;
990
991             while (sscanf(s, "T%u=%u,%u,%u,%u,%u,%4s", &POC[numpocs].tile,
992                           &POC[numpocs].resno0, &POC[numpocs].compno0,
993                           &POC[numpocs].layno1, &POC[numpocs].resno1,
994                           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
995                 POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
996                 numpocs++;
997                 while (*s && *s != '/') {
998                     s++;
999                 }
1000                 if (!*s) {
1001                     break;
1002                 }
1003                 s++;
1004             }
1005             parameters->numpocs = (OPJ_UINT32)numpocs;
1006         }
1007         break;
1008
1009         /* ------------------------------------------------------ */
1010
1011         case 'S': {         /* SOP marker */
1012             parameters->csty |= 0x02;
1013         }
1014         break;
1015
1016         /* ------------------------------------------------------ */
1017
1018         case 'E': {         /* EPH marker */
1019             parameters->csty |= 0x04;
1020         }
1021         break;
1022
1023         /* ------------------------------------------------------ */
1024
1025         case 'M': {         /* Mode switch pas tous au point !! */
1026             int value = 0;
1027             if (sscanf(opj_optarg, "%d", &value) == 1) {
1028                 for (i = 0; i <= 5; i++) {
1029                     int cache = value & (1 << i);
1030                     if (cache) {
1031                         parameters->mode |= (1 << i);
1032                     }
1033                 }
1034             }
1035         }
1036         break;
1037
1038         /* ------------------------------------------------------ */
1039
1040         case 'R': {         /* ROI */
1041             if (sscanf(opj_optarg, "c=%d,U=%d", &parameters->roi_compno,
1042                        &parameters->roi_shift) != 2) {
1043                 fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
1044                 return 1;
1045             }
1046         }
1047         break;
1048
1049         /* ------------------------------------------------------ */
1050
1051         case 'T': {         /* Tile offset */
1052             if (sscanf(opj_optarg, "%d,%d", &parameters->cp_tx0,
1053                        &parameters->cp_ty0) != 2) {
1054                 fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
1055                 return 1;
1056             }
1057         }
1058         break;
1059
1060         /* ------------------------------------------------------ */
1061
1062         case 'C': {         /* add a comment */
1063             parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
1064             if (parameters->cp_comment) {
1065                 strcpy(parameters->cp_comment, opj_optarg);
1066             }
1067         }
1068         break;
1069
1070
1071         /* ------------------------------------------------------ */
1072
1073         case 'I': {         /* reversible or not */
1074             parameters->irreversible = 1;
1075         }
1076         break;
1077
1078         /* ------------------------------------------------------ */
1079
1080         case 'u': {         /* Tile part generation*/
1081             parameters->tp_flag = opj_optarg[0];
1082             parameters->tp_on = 1;
1083         }
1084         break;
1085
1086         /* ------------------------------------------------------ */
1087
1088         case 'z': {         /* Image Directory path */
1089             img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
1090             if (img_fol->imgdirpath == NULL) {
1091                 return 1;
1092             }
1093             strcpy(img_fol->imgdirpath, opj_optarg);
1094             img_fol->set_imgdir = 1;
1095         }
1096         break;
1097
1098         /* ------------------------------------------------------ */
1099
1100         case 'w': {         /* Digital Cinema 2K profile compliance*/
1101             int fps = 0;
1102             sscanf(opj_optarg, "%d", &fps);
1103             if (fps == 24) {
1104                 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1105                 parameters->max_comp_size = OPJ_CINEMA_24_COMP;
1106                 parameters->max_cs_size = OPJ_CINEMA_24_CS;
1107             } else if (fps == 48) {
1108                 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1109                 parameters->max_comp_size = OPJ_CINEMA_48_COMP;
1110                 parameters->max_cs_size = OPJ_CINEMA_48_CS;
1111             } else {
1112                 fprintf(stderr, "Incorrect value!! must be 24 or 48\n");
1113                 return 1;
1114             }
1115             fprintf(stdout, "CINEMA 2K profile activated\n"
1116                     "Other options specified could be overridden\n");
1117
1118         }
1119         break;
1120
1121         /* ------------------------------------------------------ */
1122
1123         case 'y': {         /* Digital Cinema 4K profile compliance*/
1124             parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
1125             fprintf(stdout, "CINEMA 4K profile activated\n"
1126                     "Other options specified could be overridden\n");
1127         }
1128         break;
1129
1130         /* ------------------------------------------------------ */
1131
1132         case 'Y': {         /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
1133             int mct_mode = 0;
1134             sscanf(opj_optarg, "%d", &mct_mode);
1135             if (mct_mode < 0 || mct_mode > 2) {
1136                 fprintf(stderr,
1137                         "MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
1138                 return 1;
1139             }
1140             parameters->tcp_mct = (char) mct_mode;
1141         }
1142         break;
1143
1144         /* ------------------------------------------------------ */
1145
1146
1147         case 'm': {         /* mct input file */
1148             char *lFilename = opj_optarg;
1149             char *lMatrix;
1150             char *lCurrentPtr ;
1151             float *lCurrentDoublePtr;
1152             float *lSpace;
1153             int *l_int_ptr;
1154             int lNbComp = 0, lTotalComp, lMctComp, i2;
1155             size_t lStrLen, lStrFread;
1156
1157             /* Open file */
1158             FILE * lFile = fopen(lFilename, "r");
1159             if (lFile == NULL) {
1160                 return 1;
1161             }
1162
1163             /* Set size of file and read its content*/
1164             fseek(lFile, 0, SEEK_END);
1165             lStrLen = (size_t)ftell(lFile);
1166             fseek(lFile, 0, SEEK_SET);
1167             lMatrix = (char *) malloc(lStrLen + 1);
1168             if (lMatrix == NULL) {
1169                 fclose(lFile);
1170                 return 1;
1171             }
1172             lStrFread = fread(lMatrix, 1, lStrLen, lFile);
1173             fclose(lFile);
1174             if (lStrLen != lStrFread) {
1175                 free(lMatrix);
1176                 return 1;
1177             }
1178
1179             lMatrix[lStrLen] = 0;
1180             lCurrentPtr = lMatrix;
1181
1182             /* replace ',' by 0 */
1183             while (*lCurrentPtr != 0) {
1184                 if (*lCurrentPtr == ' ') {
1185                     *lCurrentPtr = 0;
1186                     ++lNbComp;
1187                 }
1188                 ++lCurrentPtr;
1189             }
1190             ++lNbComp;
1191             lCurrentPtr = lMatrix;
1192
1193             lNbComp = (int)(sqrt(4 * lNbComp + 1) / 2. - 0.5);
1194             lMctComp = lNbComp * lNbComp;
1195             lTotalComp = lMctComp + lNbComp;
1196             lSpace = (float *) malloc((size_t)lTotalComp * sizeof(float));
1197             if (lSpace == NULL) {
1198                 free(lMatrix);
1199                 return 1;
1200             }
1201             lCurrentDoublePtr = lSpace;
1202             for (i2 = 0; i2 < lMctComp; ++i2) {
1203                 lStrLen = strlen(lCurrentPtr) + 1;
1204                 *lCurrentDoublePtr++ = (float) atof(lCurrentPtr);
1205                 lCurrentPtr += lStrLen;
1206             }
1207
1208             l_int_ptr = (int*) lCurrentDoublePtr;
1209             for (i2 = 0; i2 < lNbComp; ++i2) {
1210                 lStrLen = strlen(lCurrentPtr) + 1;
1211                 *l_int_ptr++ = atoi(lCurrentPtr);
1212                 lCurrentPtr += lStrLen;
1213             }
1214
1215             /* TODO should not be here ! */
1216             opj_set_MCT(parameters, lSpace, (int *)(lSpace + lMctComp),
1217                         (OPJ_UINT32)lNbComp);
1218
1219             /* Free memory*/
1220             free(lSpace);
1221             free(lMatrix);
1222         }
1223         break;
1224
1225
1226             /* ------------------------------------------------------ */
1227
1228             /* UniPG>> */
1229 #ifdef USE_JPWL
1230         /* ------------------------------------------------------ */
1231
1232         case 'W': {         /* JPWL capabilities switched on */
1233             char *token = NULL;
1234             int hprot, pprot, sens, addr, size, range;
1235
1236             /* we need to enable indexing */
1237             if (!indexfilename || !*indexfilename) {
1238                 if (opj_strcpy_s(indexfilename, indexfilename_size,
1239                                  JPWL_PRIVATEINDEX_NAME) != 0) {
1240                     return 1;
1241                 }
1242             }
1243
1244             /* search for different protection methods */
1245
1246             /* break the option in comma points and parse the result */
1247             token = strtok(opj_optarg, ",");
1248             while (token != NULL) {
1249
1250                 /* search header error protection method */
1251                 if (*token == 'h') {
1252
1253                     static int tile = 0, tilespec = 0, lasttileno = 0;
1254
1255                     hprot = 1; /* predefined method */
1256
1257                     if (sscanf(token, "h=%d", &hprot) == 1) {
1258                         /* Main header, specified */
1259                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1260                                 ((hprot >= 37) && (hprot <= 128)))) {
1261                             fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n",
1262                                     hprot);
1263                             return 1;
1264                         }
1265                         parameters->jpwl_hprot_MH = hprot;
1266
1267                     } else if (sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
1268                         /* Tile part header, specified */
1269                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1270                                 ((hprot >= 37) && (hprot <= 128)))) {
1271                             fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n",
1272                                     hprot);
1273                             return 1;
1274                         }
1275                         if (tile < 0) {
1276                             fprintf(stderr,
1277                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1278                             return 1;
1279                         }
1280                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1281                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1282                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1283                         }
1284
1285                     } else if (sscanf(token, "h%d", &tile) == 1) {
1286                         /* Tile part header, unspecified */
1287                         if (tile < 0) {
1288                             fprintf(stderr,
1289                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1290                             return 1;
1291                         }
1292                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1293                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1294                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1295                         }
1296
1297
1298                     } else if (!strcmp(token, "h")) {
1299                         /* Main header, unspecified */
1300                         parameters->jpwl_hprot_MH = hprot;
1301
1302                     } else {
1303                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1304                         return 1;
1305                     };
1306
1307                 }
1308
1309                 /* search packet error protection method */
1310                 if (*token == 'p') {
1311
1312                     static int pack = 0, tile = 0, packspec = 0;
1313
1314                     pprot = 1; /* predefined method */
1315
1316                     if (sscanf(token, "p=%d", &pprot) == 1) {
1317                         /* Method for all tiles and all packets */
1318                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1319                                 ((pprot >= 37) && (pprot <= 128)))) {
1320                             fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n",
1321                                     pprot);
1322                             return 1;
1323                         }
1324                         parameters->jpwl_pprot_tileno[0] = 0;
1325                         parameters->jpwl_pprot_packno[0] = 0;
1326                         parameters->jpwl_pprot[0] = pprot;
1327
1328                     } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
1329                         /* method specified from that tile on */
1330                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1331                                 ((pprot >= 37) && (pprot <= 128)))) {
1332                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1333                             return 1;
1334                         }
1335                         if (tile < 0) {
1336                             fprintf(stderr,
1337                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1338                             return 1;
1339                         }
1340                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1341                             parameters->jpwl_pprot_tileno[packspec] = tile;
1342                             parameters->jpwl_pprot_packno[packspec] = 0;
1343                             parameters->jpwl_pprot[packspec++] = pprot;
1344                         }
1345
1346                     } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
1347                         /* method fully specified from that tile and that packet on */
1348                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1349                                 ((pprot >= 37) && (pprot <= 128)))) {
1350                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1351                             return 1;
1352                         }
1353                         if (tile < 0) {
1354                             fprintf(stderr,
1355                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1356                             return 1;
1357                         }
1358                         if (pack < 0) {
1359                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1360                                     pack);
1361                             return 1;
1362                         }
1363                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1364                             parameters->jpwl_pprot_tileno[packspec] = tile;
1365                             parameters->jpwl_pprot_packno[packspec] = pack;
1366                             parameters->jpwl_pprot[packspec++] = pprot;
1367                         }
1368
1369                     } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
1370                         /* default method from that tile and that packet on */
1371                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1372                                 ((pprot >= 37) && (pprot <= 128)))) {
1373                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1374                             return 1;
1375                         }
1376                         if (tile < 0) {
1377                             fprintf(stderr,
1378                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1379                             return 1;
1380                         }
1381                         if (pack < 0) {
1382                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1383                                     pack);
1384                             return 1;
1385                         }
1386                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1387                             parameters->jpwl_pprot_tileno[packspec] = tile;
1388                             parameters->jpwl_pprot_packno[packspec] = pack;
1389                             parameters->jpwl_pprot[packspec++] = pprot;
1390                         }
1391
1392                     } else if (sscanf(token, "p%d", &tile) == 1) {
1393                         /* default from a tile on */
1394                         if (tile < 0) {
1395                             fprintf(stderr,
1396                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1397                             return 1;
1398                         }
1399                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1400                             parameters->jpwl_pprot_tileno[packspec] = tile;
1401                             parameters->jpwl_pprot_packno[packspec] = 0;
1402                             parameters->jpwl_pprot[packspec++] = pprot;
1403                         }
1404
1405
1406                     } else if (!strcmp(token, "p")) {
1407                         /* all default */
1408                         parameters->jpwl_pprot_tileno[0] = 0;
1409                         parameters->jpwl_pprot_packno[0] = 0;
1410                         parameters->jpwl_pprot[0] = pprot;
1411
1412                     } else {
1413                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1414                         return 1;
1415                     };
1416
1417                 }
1418
1419                 /* search sensitivity method */
1420                 if (*token == 's') {
1421
1422                     static int tile = 0, tilespec = 0, lasttileno = 0;
1423
1424                     sens = 0; /* predefined: relative error */
1425
1426                     if (sscanf(token, "s=%d", &sens) == 1) {
1427                         /* Main header, specified */
1428                         if ((sens < -1) || (sens > 7)) {
1429                             fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n",
1430                                     sens);
1431                             return 1;
1432                         }
1433                         parameters->jpwl_sens_MH = sens;
1434
1435                     } else if (sscanf(token, "s%d=%d", &tile, &sens) == 2) {
1436                         /* Tile part header, specified */
1437                         if ((sens < -1) || (sens > 7)) {
1438                             fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n",
1439                                     sens);
1440                             return 1;
1441                         }
1442                         if (tile < 0) {
1443                             fprintf(stderr,
1444                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1445                             return 1;
1446                         }
1447                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1448                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1449                             parameters->jpwl_sens_TPH[tilespec++] = sens;
1450                         }
1451
1452                     } else if (sscanf(token, "s%d", &tile) == 1) {
1453                         /* Tile part header, unspecified */
1454                         if (tile < 0) {
1455                             fprintf(stderr,
1456                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1457                             return 1;
1458                         }
1459                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1460                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1461                             parameters->jpwl_sens_TPH[tilespec++] = hprot;
1462                         }
1463
1464                     } else if (!strcmp(token, "s")) {
1465                         /* Main header, unspecified */
1466                         parameters->jpwl_sens_MH = sens;
1467
1468                     } else {
1469                         fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
1470                         return 1;
1471                     };
1472
1473                     parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
1474                 }
1475
1476                 /* search addressing size */
1477                 if (*token == 'a') {
1478
1479
1480                     addr = 0; /* predefined: auto */
1481
1482                     if (sscanf(token, "a=%d", &addr) == 1) {
1483                         /* Specified */
1484                         if ((addr != 0) && (addr != 2) && (addr != 4)) {
1485                             fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
1486                             return 1;
1487                         }
1488                         parameters->jpwl_sens_addr = addr;
1489
1490                     } else if (!strcmp(token, "a")) {
1491                         /* default */
1492                         parameters->jpwl_sens_addr = addr; /* auto for default size */
1493
1494                     } else {
1495                         fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
1496                         return 1;
1497                     };
1498
1499                 }
1500
1501                 /* search sensitivity size */
1502                 if (*token == 'z') {
1503
1504
1505                     size = 1; /* predefined: 1 byte */
1506
1507                     if (sscanf(token, "z=%d", &size) == 1) {
1508                         /* Specified */
1509                         if ((size != 0) && (size != 1) && (size != 2)) {
1510                             fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
1511                             return 1;
1512                         }
1513                         parameters->jpwl_sens_size = size;
1514
1515                     } else if (!strcmp(token, "a")) {
1516                         /* default */
1517                         parameters->jpwl_sens_size = size; /* 1 for default size */
1518
1519                     } else {
1520                         fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
1521                         return 1;
1522                     };
1523
1524                 }
1525
1526                 /* search range method */
1527                 if (*token == 'g') {
1528
1529
1530                     range = 0; /* predefined: 0 (packet) */
1531
1532                     if (sscanf(token, "g=%d", &range) == 1) {
1533                         /* Specified */
1534                         if ((range < 0) || (range > 3)) {
1535                             fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
1536                             return 1;
1537                         }
1538                         parameters->jpwl_sens_range = range;
1539
1540                     } else if (!strcmp(token, "g")) {
1541                         /* default */
1542                         parameters->jpwl_sens_range = range;
1543
1544                     } else {
1545                         fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
1546                         return 1;
1547                     };
1548
1549                 }
1550
1551                 /* next token or bust */
1552                 token = strtok(NULL, ",");
1553             };
1554
1555
1556             /* some info */
1557             fprintf(stdout, "Info: JPWL capabilities enabled\n");
1558             parameters->jpwl_epc_on = OPJ_TRUE;
1559
1560         }
1561         break;
1562 #endif /* USE_JPWL */
1563         /* <<UniPG */
1564         /* ------------------------------------------------------ */
1565
1566         case 'J': {         /* jpip on */
1567             parameters->jpip_on = OPJ_TRUE;
1568         }
1569         break;
1570         /* ------------------------------------------------------ */
1571
1572
1573         default:
1574             fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
1575             break;
1576         }
1577     } while (c != -1);
1578
1579     if (img_fol->set_imgdir == 1) {
1580         if (!(parameters->infile[0] == 0)) {
1581             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together !!\n");
1582             return 1;
1583         }
1584         if (img_fol->set_out_format == 0) {
1585             fprintf(stderr,
1586                     "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
1587             fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
1588             return 1;
1589         }
1590         if (!((parameters->outfile[0] == 0))) {
1591             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together !!\n");
1592             fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
1593             return 1;
1594         }
1595     } else {
1596         if ((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
1597             fprintf(stderr, "[ERROR] Required parameters are missing\n"
1598                     "Example: %s -i image.pgm -o image.j2k\n", argv[0]);
1599             fprintf(stderr, "   Help: %s -h\n", argv[0]);
1600             return 1;
1601         }
1602     }
1603
1604     if ((parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0)
1605             || (parameters->decod_format == RAWL_DFMT && raw_cp->rawWidth == 0)) {
1606         fprintf(stderr, "[ERROR] invalid raw image parameters\n");
1607         fprintf(stderr, "Please use the Format option -F:\n");
1608         fprintf(stderr,
1609                 "-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1610         fprintf(stderr, "Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1611         fprintf(stderr, "Aborting\n");
1612         return 1;
1613     }
1614
1615     if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc ||
1616             parameters->cp_fixed_quality)
1617             && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^
1618                   parameters->cp_fixed_quality))) {
1619         fprintf(stderr, "[ERROR] options -r -q and -f cannot be used together !!\n");
1620         return 1;
1621     }               /* mod fixed_quality */
1622
1623
1624     /* if no rate entered, lossless by default */
1625     /* Note: post v2.2.0, this is no longer necessary, but for released */
1626     /* versions at the time of writing, this is needed to avoid crashes */
1627     if (parameters->tcp_numlayers == 0) {
1628         parameters->tcp_rates[0] = 0;
1629         parameters->tcp_numlayers++;
1630         parameters->cp_disto_alloc = 1;
1631     }
1632
1633     if ((parameters->cp_tx0 > parameters->image_offset_x0) ||
1634             (parameters->cp_ty0 > parameters->image_offset_y0)) {
1635         fprintf(stderr,
1636                 "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
1637                 parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0,
1638                 parameters->image_offset_y0);
1639         return 1;
1640     }
1641
1642     for (i = 0; i < parameters->numpocs; i++) {
1643         if (parameters->POC[i].prg == -1) {
1644             fprintf(stderr,
1645                     "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
1646                     i + 1);
1647         }
1648     }
1649
1650     /* If subsampled image is provided, automatically disable MCT */
1651     if (((parameters->decod_format == RAW_DFMT) ||
1652             (parameters->decod_format == RAWL_DFMT))
1653             && (((raw_cp->rawComp > 1) && ((raw_cp->rawComps[1].dx > 1) ||
1654                                            (raw_cp->rawComps[1].dy > 1)))
1655                 || ((raw_cp->rawComp > 2) && ((raw_cp->rawComps[2].dx > 1) ||
1656                         (raw_cp->rawComps[2].dy > 1)))
1657                )) {
1658         parameters->tcp_mct = 0;
1659     }
1660
1661     return 0;
1662
1663 }
1664
1665 /* -------------------------------------------------------------------------- */
1666
1667 /**
1668 sample error debug callback expecting no client object
1669 */
1670 static void error_callback(const char *msg, void *client_data)
1671 {
1672     (void)client_data;
1673     fprintf(stdout, "[ERROR] %s", msg);
1674 }
1675 /**
1676 sample warning debug callback expecting no client object
1677 */
1678 static void warning_callback(const char *msg, void *client_data)
1679 {
1680     (void)client_data;
1681     fprintf(stdout, "[WARNING] %s", msg);
1682 }
1683 /**
1684 sample debug callback expecting no client object
1685 */
1686 static void info_callback(const char *msg, void *client_data)
1687 {
1688     (void)client_data;
1689     fprintf(stdout, "[INFO] %s", msg);
1690 }
1691
1692 OPJ_FLOAT64 opj_clock(void)
1693 {
1694 #ifdef _WIN32
1695     /* _WIN32: use QueryPerformance (very accurate) */
1696     LARGE_INTEGER freq, t ;
1697     /* freq is the clock speed of the CPU */
1698     QueryPerformanceFrequency(&freq) ;
1699     /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
1700     /* t is the high resolution performance counter (see MSDN) */
1701     QueryPerformanceCounter(& t) ;
1702     return freq.QuadPart ? ((OPJ_FLOAT64) t.QuadPart / (OPJ_FLOAT64) freq.QuadPart)
1703            : 0 ;
1704 #else
1705     /* Unix or Linux: use resource usage */
1706     struct rusage t;
1707     OPJ_FLOAT64 procTime;
1708     /* (1) Get the rusage data structure at this moment (man getrusage) */
1709     getrusage(0, &t);
1710     /* (2) What is the elapsed time ? - CPU time = User time + System time */
1711     /* (2a) Get the seconds */
1712     procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
1713     /* (2b) More precisely! Get the microseconds part ! */
1714     return (procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) *
1715             1e-6) ;
1716 #endif
1717 }
1718
1719
1720 /* -------------------------------------------------------------------------- */
1721 /**
1722  * OPJ_COMPRESS MAIN
1723  */
1724 /* -------------------------------------------------------------------------- */
1725 int main(int argc, char **argv)
1726 {
1727
1728     opj_cparameters_t parameters;   /* compression parameters */
1729
1730     opj_stream_t *l_stream = 00;
1731     opj_codec_t* l_codec = 00;
1732     opj_image_t *image = NULL;
1733     raw_cparameters_t raw_cp;
1734     OPJ_SIZE_T num_compressed_files = 0;
1735
1736     char indexfilename[OPJ_PATH_LEN];   /* index file name */
1737
1738     unsigned int i, num_images, imageno;
1739     img_fol_t img_fol;
1740     dircnt_t *dirptr = NULL;
1741
1742     int ret = 0;
1743
1744     OPJ_BOOL bSuccess;
1745     OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
1746     OPJ_UINT32 l_nb_tiles = 4;
1747     OPJ_FLOAT64 t = opj_clock();
1748
1749     /* set encoding parameters to default values */
1750     opj_set_default_encoder_parameters(&parameters);
1751
1752     /* Initialize indexfilename and img_fol */
1753     *indexfilename = 0;
1754     memset(&img_fol, 0, sizeof(img_fol_t));
1755
1756     /* raw_cp initialization */
1757     raw_cp.rawBitDepth = 0;
1758     raw_cp.rawComp = 0;
1759     raw_cp.rawComps = 0;
1760     raw_cp.rawHeight = 0;
1761     raw_cp.rawSigned = 0;
1762     raw_cp.rawWidth = 0;
1763
1764     /* parse input and get user encoding parameters */
1765     parameters.tcp_mct = (char)
1766                          255; /* This will be set later according to the input image or the provided option */
1767     if (parse_cmdline_encoder(argc, argv, &parameters, &img_fol, &raw_cp,
1768                               indexfilename, sizeof(indexfilename)) == 1) {
1769         ret = 1;
1770         goto fin;
1771     }
1772
1773     /* Read directory if necessary */
1774     if (img_fol.set_imgdir == 1) {
1775         num_images = get_num_images(img_fol.imgdirpath);
1776         dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
1777         if (dirptr) {
1778             dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
1779                     char)); /* Stores at max 10 image file names*/
1780             dirptr->filename = (char**) malloc(num_images * sizeof(char*));
1781             if (!dirptr->filename_buf) {
1782                 ret = 0;
1783                 goto fin;
1784             }
1785             for (i = 0; i < num_images; i++) {
1786                 dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
1787             }
1788         }
1789         if (load_images(dirptr, img_fol.imgdirpath) == 1) {
1790             ret = 0;
1791             goto fin;
1792         }
1793         if (num_images == 0) {
1794             fprintf(stdout, "Folder is empty\n");
1795             ret = 0;
1796             goto fin;
1797         }
1798     } else {
1799         num_images = 1;
1800     }
1801     /*Encoding image one by one*/
1802     for (imageno = 0; imageno < num_images; imageno++) {
1803         image = NULL;
1804         fprintf(stderr, "\n");
1805
1806         if (img_fol.set_imgdir == 1) {
1807             if (get_next_file((int)imageno, dirptr, &img_fol, &parameters)) {
1808                 fprintf(stderr, "skipping file...\n");
1809                 continue;
1810             }
1811         }
1812
1813         switch (parameters.decod_format) {
1814         case PGX_DFMT:
1815             break;
1816         case PXM_DFMT:
1817             break;
1818         case BMP_DFMT:
1819             break;
1820         case TIF_DFMT:
1821             break;
1822         case RAW_DFMT:
1823         case RAWL_DFMT:
1824             break;
1825         case TGA_DFMT:
1826             break;
1827         case PNG_DFMT:
1828             break;
1829         default:
1830             fprintf(stderr, "skipping file...\n");
1831             continue;
1832         }
1833
1834         /* decode the source image */
1835         /* ----------------------- */
1836
1837         switch (parameters.decod_format) {
1838         case PGX_DFMT:
1839             image = pgxtoimage(parameters.infile, &parameters);
1840             if (!image) {
1841                 fprintf(stderr, "Unable to load pgx file\n");
1842                 ret = 1;
1843                 goto fin;
1844             }
1845             break;
1846
1847         case PXM_DFMT:
1848             image = pnmtoimage(parameters.infile, &parameters);
1849             if (!image) {
1850                 fprintf(stderr, "Unable to load pnm file\n");
1851                 ret = 1;
1852                 goto fin;
1853             }
1854             break;
1855
1856         case BMP_DFMT:
1857             image = bmptoimage(parameters.infile, &parameters);
1858             if (!image) {
1859                 fprintf(stderr, "Unable to load bmp file\n");
1860                 ret = 1;
1861                 goto fin;
1862             }
1863             break;
1864
1865 #ifdef OPJ_HAVE_LIBTIFF
1866         case TIF_DFMT:
1867             image = tiftoimage(parameters.infile, &parameters);
1868             if (!image) {
1869                 fprintf(stderr, "Unable to load tiff file\n");
1870                 ret = 1;
1871                 goto fin;
1872             }
1873             break;
1874 #endif /* OPJ_HAVE_LIBTIFF */
1875
1876         case RAW_DFMT:
1877             image = rawtoimage(parameters.infile, &parameters, &raw_cp);
1878             if (!image) {
1879                 fprintf(stderr, "Unable to load raw file\n");
1880                 ret = 1;
1881                 goto fin;
1882             }
1883             break;
1884
1885         case RAWL_DFMT:
1886             image = rawltoimage(parameters.infile, &parameters, &raw_cp);
1887             if (!image) {
1888                 fprintf(stderr, "Unable to load raw file\n");
1889                 ret = 1;
1890                 goto fin;
1891             }
1892             break;
1893
1894         case TGA_DFMT:
1895             image = tgatoimage(parameters.infile, &parameters);
1896             if (!image) {
1897                 fprintf(stderr, "Unable to load tga file\n");
1898                 ret = 1;
1899                 goto fin;
1900             }
1901             break;
1902
1903 #ifdef OPJ_HAVE_LIBPNG
1904         case PNG_DFMT:
1905             image = pngtoimage(parameters.infile, &parameters);
1906             if (!image) {
1907                 fprintf(stderr, "Unable to load png file\n");
1908                 ret = 1;
1909                 goto fin;
1910             }
1911             break;
1912 #endif /* OPJ_HAVE_LIBPNG */
1913         }
1914
1915         /* Can happen if input file is TIFF or PNG
1916         * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
1917         */
1918         if (!image) {
1919             fprintf(stderr, "Unable to load file: got no image\n");
1920             ret = 1;
1921             goto fin;
1922         }
1923
1924         /* Decide if MCT should be used */
1925         if (parameters.tcp_mct == (char)
1926                 255) { /* mct mode has not been set in commandline */
1927             parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;
1928         } else {            /* mct mode has been set in commandline */
1929             if ((parameters.tcp_mct == 1) && (image->numcomps < 3)) {
1930                 fprintf(stderr, "RGB->YCC conversion cannot be used:\n");
1931                 fprintf(stderr, "Input image has less than 3 components\n");
1932                 ret = 1;
1933                 goto fin;
1934             }
1935             if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {
1936                 fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
1937                 fprintf(stderr, "has been provided. Aborting.\n");
1938                 ret = 1;
1939                 goto fin;
1940             }
1941         }
1942
1943         /* encode the destination image */
1944         /* ---------------------------- */
1945
1946         switch (parameters.cod_format) {
1947         case J2K_CFMT: { /* JPEG-2000 codestream */
1948             /* Get a decoder handle */
1949             l_codec = opj_create_compress(OPJ_CODEC_J2K);
1950             break;
1951         }
1952         case JP2_CFMT: { /* JPEG 2000 compressed image data */
1953             /* Get a decoder handle */
1954             l_codec = opj_create_compress(OPJ_CODEC_JP2);
1955             break;
1956         }
1957         default:
1958             fprintf(stderr, "skipping file..\n");
1959             opj_stream_destroy(l_stream);
1960             continue;
1961         }
1962
1963         /* catch events using our callbacks and give a local context */
1964         opj_set_info_handler(l_codec, info_callback, 00);
1965         opj_set_warning_handler(l_codec, warning_callback, 00);
1966         opj_set_error_handler(l_codec, error_callback, 00);
1967
1968         if (bUseTiles) {
1969             parameters.cp_tx0 = 0;
1970             parameters.cp_ty0 = 0;
1971             parameters.tile_size_on = OPJ_TRUE;
1972             parameters.cp_tdx = 512;
1973             parameters.cp_tdy = 512;
1974         }
1975         if (! opj_setup_encoder(l_codec, &parameters, image)) {
1976             fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
1977             opj_destroy_codec(l_codec);
1978             opj_image_destroy(image);
1979             ret = 1;
1980             goto fin;
1981         }
1982
1983         /* open a byte stream for writing and allocate memory for all tiles */
1984         l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);
1985         if (! l_stream) {
1986             ret = 1;
1987             goto fin;
1988         }
1989
1990         /* encode the image */
1991         bSuccess = opj_start_compress(l_codec, image, l_stream);
1992         if (!bSuccess)  {
1993             fprintf(stderr, "failed to encode image: opj_start_compress\n");
1994         }
1995         if (bSuccess && bUseTiles) {
1996             OPJ_BYTE *l_data;
1997             OPJ_UINT32 l_data_size = 512 * 512 * 3;
1998             l_data = (OPJ_BYTE*) calloc(1, l_data_size);
1999             if (l_data == NULL) {
2000                 ret = 1;
2001                 goto fin;
2002             }
2003             for (i = 0; i < l_nb_tiles; ++i) {
2004                 if (! opj_write_tile(l_codec, i, l_data, l_data_size, l_stream)) {
2005                     fprintf(stderr, "ERROR -> test_tile_encoder: failed to write the tile %d!\n",
2006                             i);
2007                     opj_stream_destroy(l_stream);
2008                     opj_destroy_codec(l_codec);
2009                     opj_image_destroy(image);
2010                     ret = 1;
2011                     goto fin;
2012                 }
2013             }
2014             free(l_data);
2015         } else {
2016             bSuccess = bSuccess && opj_encode(l_codec, l_stream);
2017             if (!bSuccess)  {
2018                 fprintf(stderr, "failed to encode image: opj_encode\n");
2019             }
2020         }
2021         bSuccess = bSuccess && opj_end_compress(l_codec, l_stream);
2022         if (!bSuccess)  {
2023             fprintf(stderr, "failed to encode image: opj_end_compress\n");
2024         }
2025
2026         if (!bSuccess)  {
2027             opj_stream_destroy(l_stream);
2028             opj_destroy_codec(l_codec);
2029             opj_image_destroy(image);
2030             fprintf(stderr, "failed to encode image\n");
2031             remove(parameters.outfile);
2032             ret = 1;
2033             goto fin;
2034         }
2035
2036         num_compressed_files++;
2037         fprintf(stdout, "[INFO] Generated outfile %s\n", parameters.outfile);
2038         /* close and free the byte stream */
2039         opj_stream_destroy(l_stream);
2040
2041         /* free remaining compression structures */
2042         opj_destroy_codec(l_codec);
2043
2044         /* free image data */
2045         opj_image_destroy(image);
2046
2047     }
2048
2049     t = opj_clock() - t;
2050     if (num_compressed_files) {
2051         fprintf(stdout, "encode time: %d ms \n",
2052                 (int)((t * 1000.0) / (OPJ_FLOAT64)num_compressed_files));
2053     }
2054
2055     ret = 0;
2056
2057 fin:
2058     if (parameters.cp_comment) {
2059         free(parameters.cp_comment);
2060     }
2061     if (parameters.cp_matrice) {
2062         free(parameters.cp_matrice);
2063     }
2064     if (raw_cp.rawComps) {
2065         free(raw_cp.rawComps);
2066     }
2067     if (img_fol.imgdirpath) {
2068         free(img_fol.imgdirpath);
2069     }
2070     if (dirptr) {
2071         if (dirptr->filename_buf) {
2072             free(dirptr->filename_buf);
2073         }
2074         if (dirptr->filename) {
2075             free(dirptr->filename);
2076         }
2077         free(dirptr);
2078     }
2079     return ret;
2080 }