Fix various compiler warnings
[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|TIFF|RAW|YUV|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 or yuv 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 or yuv 512x512 size 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, "-PLT\n");
233     fprintf(stdout, "    Write PLT marker in tile-part header.\n");
234     fprintf(stdout, "-M <key value>\n");
235     fprintf(stdout, "    Mode switch.\n");
236     fprintf(stdout, "    [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
237     fprintf(stdout, "    8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
238     fprintf(stdout, "    Indicate multiple modes by adding their values.\n");
239     fprintf(stdout,
240             "      Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");
241     fprintf(stdout, "-TP <R|L|C>\n");
242     fprintf(stdout, "    Divide packets of every tile into tile-parts.\n");
243     fprintf(stdout,
244             "    Division is made by grouping Resolutions (R), Layers (L)\n");
245     fprintf(stdout, "    or Components (C).\n");
246 #ifdef FIXME_INDEX
247     fprintf(stdout, "-x  <index file>\n");
248     fprintf(stdout, "    Create an index file.\n");
249 #endif /*FIXME_INDEX*/
250     fprintf(stdout, "-ROI c=<component index>,U=<upshifting value>\n");
251     fprintf(stdout, "    Quantization indices upshifted for a component. \n");
252     fprintf(stdout,
253             "    Warning: This option does not implement the usual ROI (Region of Interest).\n");
254     fprintf(stdout,
255             "    It should be understood as a 'Component of Interest'. It offers the \n");
256     fprintf(stdout,
257             "    possibility to upshift the value of a component during quantization step.\n");
258     fprintf(stdout,
259             "    The value after c= is the component number [0, 1, 2, ...] and the value \n");
260     fprintf(stdout,
261             "    after U= is the value of upshifting. U must be in the range [0, 37].\n");
262     fprintf(stdout, "-d <image offset X,image offset Y>\n");
263     fprintf(stdout, "    Offset of the origin of the image.\n");
264     fprintf(stdout, "-T <tile offset X,tile offset Y>\n");
265     fprintf(stdout, "    Offset of the origin of the tiles.\n");
266     fprintf(stdout, "-I\n");
267     fprintf(stdout, "    Use the irreversible DWT 9-7.\n");
268     fprintf(stdout, "-mct <0|1|2>\n");
269     fprintf(stdout,
270             "    Explicitly specifies if a Multiple Component Transform has to be used.\n");
271     fprintf(stdout, "    0: no MCT ; 1: RGB->YCC conversion ; 2: custom MCT.\n");
272     fprintf(stdout,
273             "    If custom MCT, \"-m\" option has to be used (see hereunder).\n");
274     fprintf(stdout,
275             "    By default, RGB->YCC conversion is used if there are 3 components or more,\n");
276     fprintf(stdout, "    no conversion otherwise.\n");
277     fprintf(stdout, "-m <file>\n");
278     fprintf(stdout,
279             "    Use array-based MCT, values are coma separated, line by line\n");
280     fprintf(stdout,
281             "    No specific separators between lines, no space allowed between values.\n");
282     fprintf(stdout,
283             "    If this option is used, it automatically sets \"-mct\" option to 2.\n");
284     fprintf(stdout, "-cinema2K <24|48>\n");
285     fprintf(stdout, "    Digital Cinema 2K profile compliant codestream.\n");
286     fprintf(stdout,
287             "   Need to specify the frames per second for a 2K resolution.\n");
288     fprintf(stdout, "    Only 24 or 48 fps are currently allowed.\n");
289     fprintf(stdout, "-cinema4K\n");
290     fprintf(stdout, "    Digital Cinema 4K profile compliant codestream.\n");
291     fprintf(stdout, "   Frames per second not required. Default value is 24fps.\n");
292     fprintf(stdout, "-IMF <PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS]\n");
293     fprintf(stdout, "    Interoperable Master Format compliant codestream.\n");
294     fprintf(stdout, "    <PROFILE>=2K, 4K, 8K, 2K_R, 4K_R or 8K_R.\n");
295     fprintf(stdout, "    X >= 0 and X <= 11.\n");
296     fprintf(stdout, "    Y >= 0 and Y <= 9.\n");
297     fprintf(stdout,
298             "    framerate > 0 may be specified to enhance checks and set maximum bit rate when Y > 0.\n");
299     fprintf(stdout, "-jpip\n");
300     fprintf(stdout, "    Write jpip codestream index box in JP2 output file.\n");
301     fprintf(stdout, "    Currently supports only RPCL order.\n");
302     fprintf(stdout, "-C <comment>\n");
303     fprintf(stdout, "    Add <comment> in the comment marker segment.\n");
304     if (opj_has_thread_support()) {
305         fprintf(stdout, "  -threads <num_threads|ALL_CPUS>\n"
306                 "    Number of threads to use for encoding or ALL_CPUS for all available cores.\n");
307     }
308     /* UniPG>> */
309 #ifdef USE_JPWL
310     fprintf(stdout, "-W <params>\n");
311     fprintf(stdout, "    Adoption of JPWL (Part 11) capabilities (-W params)\n");
312     fprintf(stdout,
313             "    The <params> field can be written and repeated in any order:\n");
314     fprintf(stdout, "    [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
315     fprintf(stdout, "    ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
316     fprintf(stdout,
317             "     h selects the header error protection (EPB): 'type' can be\n");
318     fprintf(stdout,
319             "       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
320     fprintf(stdout,
321             "       if 'tilepart' is absent, it is for main and tile headers\n");
322     fprintf(stdout, "       if 'tilepart' is present, it applies from that tile\n");
323     fprintf(stdout,
324             "         onwards, up to the next h<> spec, or to the last tilepart\n");
325     fprintf(stdout, "         in the codestream (max. %d specs)\n",
326             JPWL_MAX_NO_TILESPECS);
327     fprintf(stdout,
328             "     p selects the packet error protection (EEP/UEP with EPBs)\n");
329     fprintf(stdout, "      to be applied to raw or yuv data: 'type' can be\n");
330     fprintf(stdout,
331             "       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
332     fprintf(stdout,
333             "       if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
334     fprintf(stdout,
335             "       if 'tilepart:pack' is present, it applies from that tile\n");
336     fprintf(stdout,
337             "         and that packet onwards, up to the next packet spec\n");
338     fprintf(stdout,
339             "         or to the last packet in the last tilepart in the stream\n");
340     fprintf(stdout, "         (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
341     fprintf(stdout,
342             "     s enables sensitivity data insertion (ESD): 'method' can be\n");
343     fprintf(stdout,
344             "       [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
345     fprintf(stdout, "        4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
346     fprintf(stdout, "       if 'tilepart' is absent, it is for main header only\n");
347     fprintf(stdout, "       if 'tilepart' is present, it applies from that tile\n");
348     fprintf(stdout,
349             "         onwards, up to the next s<> spec, or to the last tilepart\n");
350     fprintf(stdout, "         in the codestream (max. %d specs)\n",
351             JPWL_MAX_NO_TILESPECS);
352     fprintf(stdout, "     g determines the addressing mode: <range> can be\n");
353     fprintf(stdout, "       [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
354     fprintf(stdout,
355             "     a determines the size of data addressing: <addr> can be\n");
356     fprintf(stdout,
357             "       2/4 bytes (small/large codestreams). If not set, auto-mode\n");
358     fprintf(stdout,
359             "     z determines the size of sensitivity values: <size> can be\n");
360     fprintf(stdout,
361             "       1/2 bytes, for the transformed pseudo-floating point value\n");
362     fprintf(stdout, "     ex.:\n");
363     fprintf(stdout,
364             "       h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
365     fprintf(stdout, "         s0=6,s3=-1,a=0,g=1,z=1\n");
366     fprintf(stdout, "     means\n");
367     fprintf(stdout,
368             "       predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
369     fprintf(stdout,
370             "       CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
371     fprintf(stdout, "       UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
372     fprintf(stdout,
373             "       UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
374     fprintf(stdout, "       UEP rs default for packets of tilepart 1,\n");
375     fprintf(stdout, "       no UEP for packets 0 to 19 of tilepart 3,\n");
376     fprintf(stdout,
377             "       UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
378     fprintf(stdout, "       relative sensitivity ESD for MH,\n");
379     fprintf(stdout,
380             "       TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
381     fprintf(stdout,
382             "       size of addresses and 1 byte for each sensitivity value\n");
383     fprintf(stdout, "     ex.:\n");
384     fprintf(stdout, "           h,s,p\n");
385     fprintf(stdout, "     means\n");
386     fprintf(stdout,
387             "       default protection to headers (MH and TPHs) as well as\n");
388     fprintf(stdout, "       data packets, one ESD in MH\n");
389     fprintf(stdout,
390             "     N.B.: use the following recommendations when specifying\n");
391     fprintf(stdout, "           the JPWL parameters list\n");
392     fprintf(stdout,
393             "       - when you use UEP, always pair the 'p' option with 'h'\n");
394 #endif /* USE_JPWL */
395     /* <<UniPG */
396     fprintf(stdout, "\n");
397 #ifdef FIXME_INDEX
398     fprintf(stdout, "Index structure:\n");
399     fprintf(stdout, "----------------\n");
400     fprintf(stdout, "\n");
401     fprintf(stdout, "Image_height Image_width\n");
402     fprintf(stdout, "progression order\n");
403     fprintf(stdout, "Tiles_size_X Tiles_size_Y\n");
404     fprintf(stdout, "Tiles_nb_X Tiles_nb_Y\n");
405     fprintf(stdout, "Components_nb\n");
406     fprintf(stdout, "Layers_nb\n");
407     fprintf(stdout, "decomposition_levels\n");
408     fprintf(stdout, "[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
409     fprintf(stdout, "   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
410     fprintf(stdout, "Main_header_start_position\n");
411     fprintf(stdout, "Main_header_end_position\n");
412     fprintf(stdout, "Codestream_size\n");
413     fprintf(stdout, "\n");
414     fprintf(stdout, "INFO ON TILES\n");
415     fprintf(stdout,
416             "tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");
417     fprintf(stdout,
418             "Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");
419     fprintf(stdout,
420             "Tile_1   ''           ''        ''        ''       ''    ''      ''\n");
421     fprintf(stdout, "...\n");
422     fprintf(stdout,
423             "Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");
424     fprintf(stdout, "...\n");
425     fprintf(stdout, "TILE 0 DETAILS\n");
426     fprintf(stdout, "part_nb tileno num_packs start_pos end_tph_pos end_pos\n");
427     fprintf(stdout, "...\n");
428     fprintf(stdout, "Progression_string\n");
429     fprintf(stdout,
430             "pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");
431     fprintf(stdout,
432             "Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
433     fprintf(stdout, "...\n");
434     fprintf(stdout,
435             "Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
436     fprintf(stdout, "MaxDisto\n");
437     fprintf(stdout, "TotalDisto\n\n");
438 #endif /*FIXME_INDEX*/
439 }
440
441 static OPJ_PROG_ORDER give_progression(const char progression[4])
442 {
443     if (strncmp(progression, "LRCP", 4) == 0) {
444         return OPJ_LRCP;
445     }
446     if (strncmp(progression, "RLCP", 4) == 0) {
447         return OPJ_RLCP;
448     }
449     if (strncmp(progression, "RPCL", 4) == 0) {
450         return OPJ_RPCL;
451     }
452     if (strncmp(progression, "PCRL", 4) == 0) {
453         return OPJ_PCRL;
454     }
455     if (strncmp(progression, "CPRL", 4) == 0) {
456         return OPJ_CPRL;
457     }
458
459     return OPJ_PROG_UNKNOWN;
460 }
461
462 static unsigned int get_num_images(char *imgdirpath)
463 {
464     DIR *dir;
465     struct dirent* content;
466     unsigned int num_images = 0;
467
468     /*Reading the input images from given input directory*/
469
470     dir = opendir(imgdirpath);
471     if (!dir) {
472         fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
473         return 0;
474     }
475
476     num_images = 0;
477     while ((content = readdir(dir)) != NULL) {
478         if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
479             continue;
480         }
481         num_images++;
482     }
483     closedir(dir);
484     return num_images;
485 }
486
487 static int load_images(dircnt_t *dirptr, char *imgdirpath)
488 {
489     DIR *dir;
490     struct dirent* content;
491     int i = 0;
492
493     /*Reading the input images from given input directory*/
494
495     dir = opendir(imgdirpath);
496     if (!dir) {
497         fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
498         return 1;
499     } else   {
500         fprintf(stderr, "Folder opened successfully\n");
501     }
502
503     while ((content = readdir(dir)) != NULL) {
504         if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
505             continue;
506         }
507
508         strcpy(dirptr->filename[i], content->d_name);
509         i++;
510     }
511     closedir(dir);
512     return 0;
513 }
514
515 static int get_file_format(char *filename)
516 {
517     unsigned int i;
518     static const char *extension[] = {
519         "pgx", "pnm", "pgm", "ppm", "pbm", "pam", "bmp", "tif", "tiff", "raw", "yuv", "rawl", "tga", "png", "j2k", "jp2", "j2c", "jpc"
520     };
521     static const int format[] = {
522         PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, TIF_DFMT, RAW_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT
523     };
524     char * ext = strrchr(filename, '.');
525     if (ext == NULL) {
526         return -1;
527     }
528     ext++;
529     for (i = 0; i < sizeof(format) / sizeof(*format); i++) {
530         if (strcasecmp(ext, extension[i]) == 0) {
531             return format[i];
532         }
533     }
534     return -1;
535 }
536
537 static char * get_file_name(char *name)
538 {
539     char *fname = strtok(name, ".");
540     return fname;
541 }
542
543 static char get_next_file(int imageno, dircnt_t *dirptr, img_fol_t *img_fol,
544                           opj_cparameters_t *parameters)
545 {
546     char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],
547          outfilename[OPJ_PATH_LEN], temp_ofname[OPJ_PATH_LEN];
548     char *temp_p, temp1[OPJ_PATH_LEN] = "";
549
550     strcpy(image_filename, dirptr->filename[imageno]);
551     fprintf(stderr, "File Number %d \"%s\"\n", imageno, image_filename);
552     parameters->decod_format = get_file_format(image_filename);
553     if (parameters->decod_format == -1) {
554         return 1;
555     }
556     if (strlen(img_fol->imgdirpath) + 1 + strlen(image_filename) + 1 > sizeof(
557                 infilename)) {
558         return 1;
559     }
560     strcpy(infilename, img_fol->imgdirpath);
561     strcat(infilename, "/");
562     strcat(infilename, image_filename);
563     if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile),
564                      infilename) != 0) {
565         return 1;
566     }
567
568     /*Set output file*/
569     strcpy(temp_ofname, get_file_name(image_filename));
570     while ((temp_p = strtok(NULL, ".")) != NULL) {
571         strcat(temp_ofname, temp1);
572         sprintf(temp1, ".%s", temp_p);
573     }
574     if (img_fol->set_out_format == 1) {
575         if (strlen(img_fol->imgdirpath) + 1 + strlen(temp_ofname) + 1 + strlen(
576                     img_fol->out_format) + 1 > sizeof(outfilename)) {
577             return 1;
578         }
579         strcpy(outfilename, img_fol->imgdirpath);
580         strcat(outfilename, "/");
581         strcat(outfilename, temp_ofname);
582         strcat(outfilename, ".");
583         strcat(outfilename, img_fol->out_format);
584         if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
585                          outfilename) != 0) {
586             return 1;
587         }
588     }
589     return 0;
590 }
591
592 /* ------------------------------------------------------------------------------------ */
593
594 static int parse_cmdline_encoder(int argc, char **argv,
595                                  opj_cparameters_t *parameters,
596                                  img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename,
597                                  size_t indexfilename_size,
598                                  int* pOutFramerate,
599                                  OPJ_BOOL* pOutPLT,
600                                  int* pOutNumThreads)
601 {
602     OPJ_UINT32 i, j;
603     int totlen, c;
604     opj_option_t long_option[] = {
605         {"cinema2K", REQ_ARG, NULL, 'w'},
606         {"cinema4K", NO_ARG, NULL, 'y'},
607         {"ImgDir", REQ_ARG, NULL, 'z'},
608         {"TP", REQ_ARG, NULL, 'u'},
609         {"SOP", NO_ARG, NULL, 'S'},
610         {"EPH", NO_ARG, NULL, 'E'},
611         {"OutFor", REQ_ARG, NULL, 'O'},
612         {"POC", REQ_ARG, NULL, 'P'},
613         {"ROI", REQ_ARG, NULL, 'R'},
614         {"jpip", NO_ARG, NULL, 'J'},
615         {"mct", REQ_ARG, NULL, 'Y'},
616         {"IMF", REQ_ARG, NULL, 'Z'},
617         {"PLT", NO_ARG, NULL, 'A'},
618         {"threads",   REQ_ARG, NULL, 'B'}
619     };
620
621     /* parse the command line */
622     const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
623 #ifdef USE_JPWL
624                            "W:"
625 #endif /* USE_JPWL */
626                            "h";
627
628     totlen = sizeof(long_option);
629     img_fol->set_out_format = 0;
630     raw_cp->rawWidth = 0;
631
632     do {
633         c = opj_getopt_long(argc, argv, optlist, long_option, totlen);
634         if (c == -1) {
635             break;
636         }
637         switch (c) {
638         case 'i': {         /* input file */
639             char *infile = opj_optarg;
640             parameters->decod_format = get_file_format(infile);
641             switch (parameters->decod_format) {
642             case PGX_DFMT:
643             case PXM_DFMT:
644             case BMP_DFMT:
645             case TIF_DFMT:
646             case RAW_DFMT:
647             case RAWL_DFMT:
648             case TGA_DFMT:
649             case PNG_DFMT:
650                 break;
651             default:
652                 fprintf(stderr,
653                         "[ERROR] Unknown input file format: %s \n"
654                         "        Known file formats are *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif(f), *.raw, *.yuv or *.tga\n",
655                         infile);
656                 return 1;
657             }
658             if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infile) != 0) {
659                 return 1;
660             }
661         }
662         break;
663
664         /* ----------------------------------------------------- */
665
666         case 'o': {         /* output file */
667             char *outfile = opj_optarg;
668             parameters->cod_format = get_file_format(outfile);
669             switch (parameters->cod_format) {
670             case J2K_CFMT:
671             case JP2_CFMT:
672                 break;
673             default:
674                 fprintf(stderr,
675                         "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
676                 return 1;
677             }
678             if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
679                              outfile) != 0) {
680                 return 1;
681             }
682         }
683         break;
684
685         /* ----------------------------------------------------- */
686         case 'O': {         /* output format */
687             char outformat[50];
688             char *of = opj_optarg;
689             sprintf(outformat, ".%s", of);
690             img_fol->set_out_format = 1;
691             parameters->cod_format = get_file_format(outformat);
692             switch (parameters->cod_format) {
693             case J2K_CFMT:
694             case JP2_CFMT:
695                 img_fol->out_format = opj_optarg;
696                 break;
697             default:
698                 fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");
699                 return 1;
700             }
701         }
702         break;
703
704
705         /* ----------------------------------------------------- */
706
707
708         case 'r': {         /* rates rates/distorsion */
709             char *s = opj_optarg;
710             parameters->tcp_numlayers = 0;
711             while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) ==
712                     1) {
713                 parameters->tcp_numlayers++;
714                 while (*s && *s != ',') {
715                     s++;
716                 }
717                 if (!*s) {
718                     break;
719                 }
720                 s++;
721             }
722             parameters->cp_disto_alloc = 1;
723         }
724         break;
725
726         /* ----------------------------------------------------- */
727
728
729         case 'F': {         /* Raw image format parameters */
730             OPJ_BOOL wrong = OPJ_FALSE;
731             char *substr1;
732             char *substr2;
733             char *sep;
734             char signo;
735             int width, height, bitdepth, ncomp;
736             OPJ_UINT32 len;
737             OPJ_BOOL raw_signed = OPJ_FALSE;
738             substr2 = strchr(opj_optarg, '@');
739             if (substr2 == NULL) {
740                 len = (OPJ_UINT32) strlen(opj_optarg);
741             } else {
742                 len = (OPJ_UINT32)(substr2 - opj_optarg);
743                 substr2++; /* skip '@' character */
744             }
745             substr1 = (char*) malloc((len + 1) * sizeof(char));
746             if (substr1 == NULL) {
747                 return 1;
748             }
749             memcpy(substr1, opj_optarg, len);
750             substr1[len] = '\0';
751             if (sscanf(substr1, "%d,%d,%d,%d,%c", &width, &height, &ncomp, &bitdepth,
752                        &signo) == 5) {
753                 if (signo == 's') {
754                     raw_signed = OPJ_TRUE;
755                 } else if (signo == 'u') {
756                     raw_signed = OPJ_FALSE;
757                 } else {
758                     wrong = OPJ_TRUE;
759                 }
760             } else {
761                 wrong = OPJ_TRUE;
762             }
763             if (!wrong) {
764                 int compno;
765                 int lastdx = 1;
766                 int lastdy = 1;
767                 raw_cp->rawWidth = width;
768                 raw_cp->rawHeight = height;
769                 raw_cp->rawComp = ncomp;
770                 raw_cp->rawBitDepth = bitdepth;
771                 raw_cp->rawSigned  = raw_signed;
772                 raw_cp->rawComps = (raw_comp_cparameters_t*) malloc(((OPJ_UINT32)(
773                                        ncomp)) * sizeof(raw_comp_cparameters_t));
774                 if (raw_cp->rawComps == NULL) {
775                     free(substr1);
776                     return 1;
777                 }
778                 for (compno = 0; compno < ncomp && !wrong; compno++) {
779                     if (substr2 == NULL) {
780                         raw_cp->rawComps[compno].dx = lastdx;
781                         raw_cp->rawComps[compno].dy = lastdy;
782                     } else {
783                         int dx, dy;
784                         sep = strchr(substr2, ':');
785                         if (sep == NULL) {
786                             if (sscanf(substr2, "%dx%d", &dx, &dy) == 2) {
787                                 lastdx = dx;
788                                 lastdy = dy;
789                                 raw_cp->rawComps[compno].dx = dx;
790                                 raw_cp->rawComps[compno].dy = dy;
791                                 substr2 = NULL;
792                             } else {
793                                 wrong = OPJ_TRUE;
794                             }
795                         } else {
796                             if (sscanf(substr2, "%dx%d:%s", &dx, &dy, substr2) == 3) {
797                                 raw_cp->rawComps[compno].dx = dx;
798                                 raw_cp->rawComps[compno].dy = dy;
799                             } else {
800                                 wrong = OPJ_TRUE;
801                             }
802                         }
803                     }
804                 }
805             }
806             free(substr1);
807             if (wrong) {
808                 fprintf(stderr, "\nError: invalid raw or yuv image parameters\n");
809                 fprintf(stderr, "Please use the Format option -F:\n");
810                 fprintf(stderr,
811                         "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
812                 fprintf(stderr,
813                         "If subsampling is omitted, 1x1 is assumed for all components\n");
814                 fprintf(stderr,
815                         "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
816                 fprintf(stderr,
817                         "         for raw or yuv 512x512 size with 4:2:0 subsampling\n");
818                 fprintf(stderr, "Aborting.\n");
819                 return 1;
820             }
821         }
822         break;
823
824         /* ----------------------------------------------------- */
825
826         case 'q': {         /* add fixed_quality */
827             char *s = opj_optarg;
828             while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers])
829                     == 1) {
830                 parameters->tcp_numlayers++;
831                 while (*s && *s != ',') {
832                     s++;
833                 }
834                 if (!*s) {
835                     break;
836                 }
837                 s++;
838             }
839             parameters->cp_fixed_quality = 1;
840         }
841         break;
842
843         /* dda */
844         /* ----------------------------------------------------- */
845
846         case 'f': {         /* mod fixed_quality (before : -q) */
847             int *row = NULL, *col = NULL;
848             OPJ_UINT32 numlayers = 0, numresolution = 0, matrix_width = 0;
849
850             char *s = opj_optarg;
851             sscanf(s, "%u", &numlayers);
852             s++;
853             if (numlayers > 9) {
854                 s++;
855             }
856
857             parameters->tcp_numlayers = (int)numlayers;
858             numresolution = (OPJ_UINT32)parameters->numresolution;
859             matrix_width = numresolution * 3;
860             parameters->cp_matrice = (int *) malloc(sizeof(int) * numlayers * matrix_width);
861             if (parameters->cp_matrice == NULL) {
862                 return 1;
863             }
864             s = s + 2;
865
866             for (i = 0; i < numlayers; i++) {
867                 row = &parameters->cp_matrice[i * matrix_width];
868                 col = row;
869                 parameters->tcp_rates[i] = 1;
870                 sscanf(s, "%d,", &col[0]);
871                 s += 2;
872                 if (col[0] > 9) {
873                     s++;
874                 }
875                 col[1] = 0;
876                 col[2] = 0;
877                 for (j = 1; j < numresolution; j++) {
878                     col += 3;
879                     sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
880                     s += 6;
881                     if (col[0] > 9) {
882                         s++;
883                     }
884                     if (col[1] > 9) {
885                         s++;
886                     }
887                     if (col[2] > 9) {
888                         s++;
889                     }
890                 }
891                 if (i < numlayers - 1) {
892                     s++;
893                 }
894             }
895             parameters->cp_fixed_alloc = 1;
896         }
897         break;
898
899         /* ----------------------------------------------------- */
900
901         case 't': {         /* tiles */
902             sscanf(opj_optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
903             parameters->tile_size_on = OPJ_TRUE;
904         }
905         break;
906
907         /* ----------------------------------------------------- */
908
909         case 'n': {         /* resolution */
910             sscanf(opj_optarg, "%d", &parameters->numresolution);
911         }
912         break;
913
914         /* ----------------------------------------------------- */
915         case 'c': {         /* precinct dimension */
916             char sep;
917             int res_spec = 0;
918
919             char *s = opj_optarg;
920             int ret;
921             do {
922                 sep = 0;
923                 ret = sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
924                              &parameters->prch_init[res_spec], &sep);
925                 if (!(ret == 2 && sep == 0) && !(ret == 3 && sep == ',')) {
926                     fprintf(stderr, "\nError: could not parse precinct dimension: '%s' %x\n", s,
927                             sep);
928                     fprintf(stderr, "Example: -i lena.raw -o lena.j2k -c [128,128],[128,128]\n");
929                     return 1;
930                 }
931                 parameters->csty |= 0x01;
932                 res_spec++;
933                 s = strpbrk(s, "]") + 2;
934             } while (sep == ',');
935             parameters->res_spec = res_spec;
936         }
937         break;
938
939         /* ----------------------------------------------------- */
940
941         case 'b': {         /* code-block dimension */
942             int cblockw_init = 0, cblockh_init = 0;
943             sscanf(opj_optarg, "%d,%d", &cblockw_init, &cblockh_init);
944             if (cblockw_init > 1024 || cblockw_init < 4 ||
945                     cblockh_init > 1024 || cblockh_init < 4 ||
946                     cblockw_init * cblockh_init > 4096) {
947                 fprintf(stderr,
948                         "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
949                         "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
950                 return 1;
951             }
952             parameters->cblockw_init = cblockw_init;
953             parameters->cblockh_init = cblockh_init;
954         }
955         break;
956
957         /* ----------------------------------------------------- */
958
959         case 'x': {         /* creation of index file */
960             if (opj_strcpy_s(indexfilename, indexfilename_size, opj_optarg) != 0) {
961                 return 1;
962             }
963             /* FIXME ADE INDEX >> */
964             fprintf(stderr,
965                     "[WARNING] Index file generation is currently broken.\n"
966                     "          '-x' option ignored.\n");
967             /* << FIXME ADE INDEX */
968         }
969         break;
970
971         /* ----------------------------------------------------- */
972
973         case 'p': {         /* progression order */
974             char progression[5];
975
976             strncpy(progression, opj_optarg, 4);
977             progression[4] = 0;
978             parameters->prog_order = give_progression(progression);
979             if (parameters->prog_order == -1) {
980                 fprintf(stderr, "Unrecognized progression order "
981                         "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
982                 return 1;
983             }
984         }
985         break;
986
987         /* ----------------------------------------------------- */
988
989         case 's': {         /* subsampling factor */
990             if (sscanf(opj_optarg, "%d,%d", &parameters->subsampling_dx,
991                        &parameters->subsampling_dy) != 2) {
992                 fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
993                 return 1;
994             }
995         }
996         break;
997
998         /* ----------------------------------------------------- */
999
1000         case 'd': {         /* coordonnate of the reference grid */
1001             if (sscanf(opj_optarg, "%d,%d", &parameters->image_offset_x0,
1002                        &parameters->image_offset_y0) != 2) {
1003                 fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
1004                         "error !! [-d x0,y0]\n");
1005                 return 1;
1006             }
1007         }
1008         break;
1009
1010         /* ----------------------------------------------------- */
1011
1012         case 'h':           /* display an help description */
1013             encode_help_display();
1014             return 1;
1015
1016         /* ----------------------------------------------------- */
1017
1018         case 'P': {         /* POC */
1019             int numpocs = 0;        /* number of progression order change (POC) default 0 */
1020             opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
1021
1022             char *s = opj_optarg;
1023             POC = parameters->POC;
1024
1025             while (sscanf(s, "T%u=%u,%u,%u,%u,%u,%4s", &POC[numpocs].tile,
1026                           &POC[numpocs].resno0, &POC[numpocs].compno0,
1027                           &POC[numpocs].layno1, &POC[numpocs].resno1,
1028                           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
1029                 POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
1030                 numpocs++;
1031                 while (*s && *s != '/') {
1032                     s++;
1033                 }
1034                 if (!*s) {
1035                     break;
1036                 }
1037                 s++;
1038             }
1039             parameters->numpocs = (OPJ_UINT32)numpocs;
1040         }
1041         break;
1042
1043         /* ------------------------------------------------------ */
1044
1045         case 'S': {         /* SOP marker */
1046             parameters->csty |= 0x02;
1047         }
1048         break;
1049
1050         /* ------------------------------------------------------ */
1051
1052         case 'E': {         /* EPH marker */
1053             parameters->csty |= 0x04;
1054         }
1055         break;
1056
1057         /* ------------------------------------------------------ */
1058
1059         case 'M': {         /* Mode switch pas tous au point !! */
1060             int value = 0;
1061             if (sscanf(opj_optarg, "%d", &value) == 1) {
1062                 for (i = 0; i <= 5; i++) {
1063                     int cache = value & (1 << i);
1064                     if (cache) {
1065                         parameters->mode |= (1 << i);
1066                     }
1067                 }
1068             }
1069         }
1070         break;
1071
1072         /* ------------------------------------------------------ */
1073
1074         case 'R': {         /* ROI */
1075             if (sscanf(opj_optarg, "c=%d,U=%d", &parameters->roi_compno,
1076                        &parameters->roi_shift) != 2) {
1077                 fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
1078                 return 1;
1079             }
1080         }
1081         break;
1082
1083         /* ------------------------------------------------------ */
1084
1085         case 'T': {         /* Tile offset */
1086             if (sscanf(opj_optarg, "%d,%d", &parameters->cp_tx0,
1087                        &parameters->cp_ty0) != 2) {
1088                 fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
1089                 return 1;
1090             }
1091         }
1092         break;
1093
1094         /* ------------------------------------------------------ */
1095
1096         case 'C': {         /* add a comment */
1097             parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
1098             if (parameters->cp_comment) {
1099                 strcpy(parameters->cp_comment, opj_optarg);
1100             }
1101         }
1102         break;
1103
1104
1105         /* ------------------------------------------------------ */
1106
1107         case 'I': {         /* reversible or not */
1108             parameters->irreversible = 1;
1109         }
1110         break;
1111
1112         /* ------------------------------------------------------ */
1113
1114         case 'u': {         /* Tile part generation*/
1115             parameters->tp_flag = opj_optarg[0];
1116             parameters->tp_on = 1;
1117         }
1118         break;
1119
1120         /* ------------------------------------------------------ */
1121
1122         case 'z': {         /* Image Directory path */
1123             img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
1124             if (img_fol->imgdirpath == NULL) {
1125                 return 1;
1126             }
1127             strcpy(img_fol->imgdirpath, opj_optarg);
1128             img_fol->set_imgdir = 1;
1129         }
1130         break;
1131
1132         /* ------------------------------------------------------ */
1133
1134         case 'w': {         /* Digital Cinema 2K profile compliance*/
1135             int fps = 0;
1136             sscanf(opj_optarg, "%d", &fps);
1137             if (fps == 24) {
1138                 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1139                 parameters->max_comp_size = OPJ_CINEMA_24_COMP;
1140                 parameters->max_cs_size = OPJ_CINEMA_24_CS;
1141             } else if (fps == 48) {
1142                 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1143                 parameters->max_comp_size = OPJ_CINEMA_48_COMP;
1144                 parameters->max_cs_size = OPJ_CINEMA_48_CS;
1145             } else {
1146                 fprintf(stderr, "Incorrect value!! must be 24 or 48\n");
1147                 return 1;
1148             }
1149             fprintf(stdout, "CINEMA 2K profile activated\n"
1150                     "Other options specified could be overridden\n");
1151
1152         }
1153         break;
1154
1155         /* ------------------------------------------------------ */
1156
1157         case 'y': {         /* Digital Cinema 4K profile compliance*/
1158             parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
1159             fprintf(stdout, "CINEMA 4K profile activated\n"
1160                     "Other options specified could be overridden\n");
1161         }
1162         break;
1163
1164         /* ------------------------------------------------------ */
1165
1166         case 'Z': {         /* IMF profile*/
1167             int mainlevel = 0;
1168             int sublevel = 0;
1169             int profile = 0;
1170             int framerate = 0;
1171             const char* msg =
1172                 "Wrong value for -IMF. Should be "
1173                 "<PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS] where <PROFILE> is one "
1174                 "of 2K/4K/8K/2K_R/4K_R/8K_R.\n";
1175             char* comma;
1176
1177             comma = strstr(opj_optarg, ",mainlevel=");
1178             if (comma && sscanf(comma + 1, "mainlevel=%d", &mainlevel) != 1) {
1179                 fprintf(stderr, "%s", msg);
1180                 return 1;
1181             }
1182
1183             comma = strstr(opj_optarg, ",sublevel=");
1184             if (comma && sscanf(comma + 1, "sublevel=%d", &sublevel) != 1) {
1185                 fprintf(stderr, "%s", msg);
1186                 return 1;
1187             }
1188
1189             comma = strstr(opj_optarg, ",framerate=");
1190             if (comma && sscanf(comma + 1, "framerate=%d", &framerate) != 1) {
1191                 fprintf(stderr, "%s", msg);
1192                 return 1;
1193             }
1194
1195             comma = strchr(opj_optarg, ',');
1196             if (comma != NULL) {
1197                 *comma = 0;
1198             }
1199
1200             if (strcmp(opj_optarg, "2K") == 0) {
1201                 profile = OPJ_PROFILE_IMF_2K;
1202             } else if (strcmp(opj_optarg, "4K") == 0) {
1203                 profile = OPJ_PROFILE_IMF_4K;
1204             } else if (strcmp(opj_optarg, "8K") == 0) {
1205                 profile = OPJ_PROFILE_IMF_8K;
1206             } else if (strcmp(opj_optarg, "2K_R") == 0) {
1207                 profile = OPJ_PROFILE_IMF_2K_R;
1208             } else if (strcmp(opj_optarg, "4K_R") == 0) {
1209                 profile = OPJ_PROFILE_IMF_4K_R;
1210             } else if (strcmp(opj_optarg, "8K_R") == 0) {
1211                 profile = OPJ_PROFILE_IMF_8K_R;
1212             } else {
1213                 fprintf(stderr, "%s", msg);
1214                 return 1;
1215             }
1216
1217             if (!(mainlevel >= 0 && mainlevel <= 15)) {
1218                 /* Voluntarily rough validation. More fine grained done in library */
1219                 fprintf(stderr, "Invalid mainlevel value.\n");
1220                 return 1;
1221             }
1222             if (!(sublevel >= 0 && sublevel <= 15)) {
1223                 /* Voluntarily rough validation. More fine grained done in library */
1224                 fprintf(stderr, "Invalid sublevel value.\n");
1225                 return 1;
1226             }
1227             parameters->rsiz = (OPJ_UINT16)(profile | (sublevel << 4) | mainlevel);
1228
1229             fprintf(stdout, "IMF profile activated\n"
1230                     "Other options specified could be overridden\n");
1231
1232             if (pOutFramerate) {
1233                 *pOutFramerate = framerate;
1234             }
1235             if (framerate > 0 && sublevel > 0 && sublevel <= 9) {
1236                 const int limitMBitsSec[] = {
1237                     0,
1238                     OPJ_IMF_SUBLEVEL_1_MBITSSEC,
1239                     OPJ_IMF_SUBLEVEL_2_MBITSSEC,
1240                     OPJ_IMF_SUBLEVEL_3_MBITSSEC,
1241                     OPJ_IMF_SUBLEVEL_4_MBITSSEC,
1242                     OPJ_IMF_SUBLEVEL_5_MBITSSEC,
1243                     OPJ_IMF_SUBLEVEL_6_MBITSSEC,
1244                     OPJ_IMF_SUBLEVEL_7_MBITSSEC,
1245                     OPJ_IMF_SUBLEVEL_8_MBITSSEC,
1246                     OPJ_IMF_SUBLEVEL_9_MBITSSEC
1247                 };
1248                 parameters->max_cs_size = limitMBitsSec[sublevel] * (1000 * 1000 / 8) /
1249                                           framerate;
1250                 fprintf(stdout, "Setting max codestream size to %d bytes.\n",
1251                         parameters->max_cs_size);
1252             }
1253         }
1254         break;
1255
1256         /* ------------------------------------------------------ */
1257
1258         case 'Y': {         /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
1259             int mct_mode = 0;
1260             sscanf(opj_optarg, "%d", &mct_mode);
1261             if (mct_mode < 0 || mct_mode > 2) {
1262                 fprintf(stderr,
1263                         "MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
1264                 return 1;
1265             }
1266             parameters->tcp_mct = (char) mct_mode;
1267         }
1268         break;
1269
1270         /* ------------------------------------------------------ */
1271
1272
1273         case 'm': {         /* mct input file */
1274             char *lFilename = opj_optarg;
1275             char *lMatrix;
1276             char *lCurrentPtr ;
1277             float *lCurrentDoublePtr;
1278             float *lSpace;
1279             int *l_int_ptr;
1280             int lNbComp = 0, lTotalComp, lMctComp, i2;
1281             size_t lStrLen, lStrFread;
1282
1283             /* Open file */
1284             FILE * lFile = fopen(lFilename, "r");
1285             if (lFile == NULL) {
1286                 return 1;
1287             }
1288
1289             /* Set size of file and read its content*/
1290             fseek(lFile, 0, SEEK_END);
1291             lStrLen = (size_t)ftell(lFile);
1292             fseek(lFile, 0, SEEK_SET);
1293             lMatrix = (char *) malloc(lStrLen + 1);
1294             if (lMatrix == NULL) {
1295                 fclose(lFile);
1296                 return 1;
1297             }
1298             lStrFread = fread(lMatrix, 1, lStrLen, lFile);
1299             fclose(lFile);
1300             if (lStrLen != lStrFread) {
1301                 free(lMatrix);
1302                 return 1;
1303             }
1304
1305             lMatrix[lStrLen] = 0;
1306             lCurrentPtr = lMatrix;
1307
1308             /* replace ',' by 0 */
1309             while (*lCurrentPtr != 0) {
1310                 if (*lCurrentPtr == ' ') {
1311                     *lCurrentPtr = 0;
1312                     ++lNbComp;
1313                 }
1314                 ++lCurrentPtr;
1315             }
1316             ++lNbComp;
1317             lCurrentPtr = lMatrix;
1318
1319             lNbComp = (int)(sqrt(4 * lNbComp + 1) / 2. - 0.5);
1320             lMctComp = lNbComp * lNbComp;
1321             lTotalComp = lMctComp + lNbComp;
1322             lSpace = (float *) malloc((size_t)lTotalComp * sizeof(float));
1323             if (lSpace == NULL) {
1324                 free(lMatrix);
1325                 return 1;
1326             }
1327             lCurrentDoublePtr = lSpace;
1328             for (i2 = 0; i2 < lMctComp; ++i2) {
1329                 lStrLen = strlen(lCurrentPtr) + 1;
1330                 *lCurrentDoublePtr++ = (float) atof(lCurrentPtr);
1331                 lCurrentPtr += lStrLen;
1332             }
1333
1334             l_int_ptr = (int*) lCurrentDoublePtr;
1335             for (i2 = 0; i2 < lNbComp; ++i2) {
1336                 lStrLen = strlen(lCurrentPtr) + 1;
1337                 *l_int_ptr++ = atoi(lCurrentPtr);
1338                 lCurrentPtr += lStrLen;
1339             }
1340
1341             /* TODO should not be here ! */
1342             opj_set_MCT(parameters, lSpace, (int *)(lSpace + lMctComp),
1343                         (OPJ_UINT32)lNbComp);
1344
1345             /* Free memory*/
1346             free(lSpace);
1347             free(lMatrix);
1348         }
1349         break;
1350
1351
1352             /* ------------------------------------------------------ */
1353
1354             /* UniPG>> */
1355 #ifdef USE_JPWL
1356         /* ------------------------------------------------------ */
1357
1358         case 'W': {         /* JPWL capabilities switched on */
1359             char *token = NULL;
1360             int hprot, pprot, sens, addr, size, range;
1361
1362             /* we need to enable indexing */
1363             if (!indexfilename || !*indexfilename) {
1364                 if (opj_strcpy_s(indexfilename, indexfilename_size,
1365                                  JPWL_PRIVATEINDEX_NAME) != 0) {
1366                     return 1;
1367                 }
1368             }
1369
1370             /* search for different protection methods */
1371
1372             /* break the option in comma points and parse the result */
1373             token = strtok(opj_optarg, ",");
1374             while (token != NULL) {
1375
1376                 /* search header error protection method */
1377                 if (*token == 'h') {
1378
1379                     static int tile = 0, tilespec = 0, lasttileno = 0;
1380
1381                     hprot = 1; /* predefined method */
1382
1383                     if (sscanf(token, "h=%d", &hprot) == 1) {
1384                         /* Main header, specified */
1385                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1386                                 ((hprot >= 37) && (hprot <= 128)))) {
1387                             fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n",
1388                                     hprot);
1389                             return 1;
1390                         }
1391                         parameters->jpwl_hprot_MH = hprot;
1392
1393                     } else if (sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
1394                         /* Tile part header, specified */
1395                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1396                                 ((hprot >= 37) && (hprot <= 128)))) {
1397                             fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n",
1398                                     hprot);
1399                             return 1;
1400                         }
1401                         if (tile < 0) {
1402                             fprintf(stderr,
1403                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1404                             return 1;
1405                         }
1406                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1407                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1408                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1409                         }
1410
1411                     } else if (sscanf(token, "h%d", &tile) == 1) {
1412                         /* Tile part header, unspecified */
1413                         if (tile < 0) {
1414                             fprintf(stderr,
1415                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1416                             return 1;
1417                         }
1418                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1419                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1420                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1421                         }
1422
1423
1424                     } else if (!strcmp(token, "h")) {
1425                         /* Main header, unspecified */
1426                         parameters->jpwl_hprot_MH = hprot;
1427
1428                     } else {
1429                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1430                         return 1;
1431                     };
1432
1433                 }
1434
1435                 /* search packet error protection method */
1436                 if (*token == 'p') {
1437
1438                     static int pack = 0, tile = 0, packspec = 0;
1439
1440                     pprot = 1; /* predefined method */
1441
1442                     if (sscanf(token, "p=%d", &pprot) == 1) {
1443                         /* Method for all tiles and all packets */
1444                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1445                                 ((pprot >= 37) && (pprot <= 128)))) {
1446                             fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n",
1447                                     pprot);
1448                             return 1;
1449                         }
1450                         parameters->jpwl_pprot_tileno[0] = 0;
1451                         parameters->jpwl_pprot_packno[0] = 0;
1452                         parameters->jpwl_pprot[0] = pprot;
1453
1454                     } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
1455                         /* method specified from that tile on */
1456                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1457                                 ((pprot >= 37) && (pprot <= 128)))) {
1458                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1459                             return 1;
1460                         }
1461                         if (tile < 0) {
1462                             fprintf(stderr,
1463                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1464                             return 1;
1465                         }
1466                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1467                             parameters->jpwl_pprot_tileno[packspec] = tile;
1468                             parameters->jpwl_pprot_packno[packspec] = 0;
1469                             parameters->jpwl_pprot[packspec++] = pprot;
1470                         }
1471
1472                     } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
1473                         /* method fully specified from that tile and that packet on */
1474                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1475                                 ((pprot >= 37) && (pprot <= 128)))) {
1476                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1477                             return 1;
1478                         }
1479                         if (tile < 0) {
1480                             fprintf(stderr,
1481                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1482                             return 1;
1483                         }
1484                         if (pack < 0) {
1485                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1486                                     pack);
1487                             return 1;
1488                         }
1489                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1490                             parameters->jpwl_pprot_tileno[packspec] = tile;
1491                             parameters->jpwl_pprot_packno[packspec] = pack;
1492                             parameters->jpwl_pprot[packspec++] = pprot;
1493                         }
1494
1495                     } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
1496                         /* default method from that tile and that packet on */
1497                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1498                                 ((pprot >= 37) && (pprot <= 128)))) {
1499                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1500                             return 1;
1501                         }
1502                         if (tile < 0) {
1503                             fprintf(stderr,
1504                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1505                             return 1;
1506                         }
1507                         if (pack < 0) {
1508                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1509                                     pack);
1510                             return 1;
1511                         }
1512                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1513                             parameters->jpwl_pprot_tileno[packspec] = tile;
1514                             parameters->jpwl_pprot_packno[packspec] = pack;
1515                             parameters->jpwl_pprot[packspec++] = pprot;
1516                         }
1517
1518                     } else if (sscanf(token, "p%d", &tile) == 1) {
1519                         /* default from a tile on */
1520                         if (tile < 0) {
1521                             fprintf(stderr,
1522                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1523                             return 1;
1524                         }
1525                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1526                             parameters->jpwl_pprot_tileno[packspec] = tile;
1527                             parameters->jpwl_pprot_packno[packspec] = 0;
1528                             parameters->jpwl_pprot[packspec++] = pprot;
1529                         }
1530
1531
1532                     } else if (!strcmp(token, "p")) {
1533                         /* all default */
1534                         parameters->jpwl_pprot_tileno[0] = 0;
1535                         parameters->jpwl_pprot_packno[0] = 0;
1536                         parameters->jpwl_pprot[0] = pprot;
1537
1538                     } else {
1539                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1540                         return 1;
1541                     };
1542
1543                 }
1544
1545                 /* search sensitivity method */
1546                 if (*token == 's') {
1547
1548                     static int tile = 0, tilespec = 0, lasttileno = 0;
1549
1550                     sens = 0; /* predefined: relative error */
1551
1552                     if (sscanf(token, "s=%d", &sens) == 1) {
1553                         /* Main header, specified */
1554                         if ((sens < -1) || (sens > 7)) {
1555                             fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n",
1556                                     sens);
1557                             return 1;
1558                         }
1559                         parameters->jpwl_sens_MH = sens;
1560
1561                     } else if (sscanf(token, "s%d=%d", &tile, &sens) == 2) {
1562                         /* Tile part header, specified */
1563                         if ((sens < -1) || (sens > 7)) {
1564                             fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n",
1565                                     sens);
1566                             return 1;
1567                         }
1568                         if (tile < 0) {
1569                             fprintf(stderr,
1570                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1571                             return 1;
1572                         }
1573                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1574                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1575                             parameters->jpwl_sens_TPH[tilespec++] = sens;
1576                         }
1577
1578                     } else if (sscanf(token, "s%d", &tile) == 1) {
1579                         /* Tile part header, unspecified */
1580                         if (tile < 0) {
1581                             fprintf(stderr,
1582                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1583                             return 1;
1584                         }
1585                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1586                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1587                             parameters->jpwl_sens_TPH[tilespec++] = hprot;
1588                         }
1589
1590                     } else if (!strcmp(token, "s")) {
1591                         /* Main header, unspecified */
1592                         parameters->jpwl_sens_MH = sens;
1593
1594                     } else {
1595                         fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
1596                         return 1;
1597                     };
1598
1599                     parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
1600                 }
1601
1602                 /* search addressing size */
1603                 if (*token == 'a') {
1604
1605
1606                     addr = 0; /* predefined: auto */
1607
1608                     if (sscanf(token, "a=%d", &addr) == 1) {
1609                         /* Specified */
1610                         if ((addr != 0) && (addr != 2) && (addr != 4)) {
1611                             fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
1612                             return 1;
1613                         }
1614                         parameters->jpwl_sens_addr = addr;
1615
1616                     } else if (!strcmp(token, "a")) {
1617                         /* default */
1618                         parameters->jpwl_sens_addr = addr; /* auto for default size */
1619
1620                     } else {
1621                         fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
1622                         return 1;
1623                     };
1624
1625                 }
1626
1627                 /* search sensitivity size */
1628                 if (*token == 'z') {
1629
1630
1631                     size = 1; /* predefined: 1 byte */
1632
1633                     if (sscanf(token, "z=%d", &size) == 1) {
1634                         /* Specified */
1635                         if ((size != 0) && (size != 1) && (size != 2)) {
1636                             fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
1637                             return 1;
1638                         }
1639                         parameters->jpwl_sens_size = size;
1640
1641                     } else if (!strcmp(token, "a")) {
1642                         /* default */
1643                         parameters->jpwl_sens_size = size; /* 1 for default size */
1644
1645                     } else {
1646                         fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
1647                         return 1;
1648                     };
1649
1650                 }
1651
1652                 /* search range method */
1653                 if (*token == 'g') {
1654
1655
1656                     range = 0; /* predefined: 0 (packet) */
1657
1658                     if (sscanf(token, "g=%d", &range) == 1) {
1659                         /* Specified */
1660                         if ((range < 0) || (range > 3)) {
1661                             fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
1662                             return 1;
1663                         }
1664                         parameters->jpwl_sens_range = range;
1665
1666                     } else if (!strcmp(token, "g")) {
1667                         /* default */
1668                         parameters->jpwl_sens_range = range;
1669
1670                     } else {
1671                         fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
1672                         return 1;
1673                     };
1674
1675                 }
1676
1677                 /* next token or bust */
1678                 token = strtok(NULL, ",");
1679             };
1680
1681
1682             /* some info */
1683             fprintf(stdout, "Info: JPWL capabilities enabled\n");
1684             parameters->jpwl_epc_on = OPJ_TRUE;
1685
1686         }
1687         break;
1688 #endif /* USE_JPWL */
1689         /* <<UniPG */
1690         /* ------------------------------------------------------ */
1691
1692         case 'J': {         /* jpip on */
1693             parameters->jpip_on = OPJ_TRUE;
1694         }
1695         break;
1696         /* ------------------------------------------------------ */
1697
1698         case 'A': {         /* PLT markers */
1699             *pOutPLT = OPJ_TRUE;
1700         }
1701         break;
1702
1703         /* ----------------------------------------------------- */
1704         case 'B': { /* Number of threads */
1705             if (strcmp(opj_optarg, "ALL_CPUS") == 0) {
1706                 *pOutNumThreads = opj_get_num_cpus();
1707                 if (*pOutNumThreads == 1) {
1708                     *pOutNumThreads = 0;
1709                 }
1710             } else {
1711                 sscanf(opj_optarg, "%d", pOutNumThreads);
1712             }
1713         }
1714         break;
1715
1716         /* ------------------------------------------------------ */
1717
1718
1719         default:
1720             fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
1721             break;
1722         }
1723     } while (c != -1);
1724
1725     if (img_fol->set_imgdir == 1) {
1726         if (!(parameters->infile[0] == 0)) {
1727             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together !!\n");
1728             return 1;
1729         }
1730         if (img_fol->set_out_format == 0) {
1731             fprintf(stderr,
1732                     "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
1733             fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
1734             return 1;
1735         }
1736         if (!((parameters->outfile[0] == 0))) {
1737             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together !!\n");
1738             fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
1739             return 1;
1740         }
1741     } else {
1742         if ((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
1743             fprintf(stderr, "[ERROR] Required parameters are missing\n"
1744                     "Example: %s -i image.pgm -o image.j2k\n", argv[0]);
1745             fprintf(stderr, "   Help: %s -h\n", argv[0]);
1746             return 1;
1747         }
1748     }
1749
1750     if ((parameters->decod_format == RAW_DFMT ||
1751             parameters->decod_format == RAWL_DFMT)
1752             && (raw_cp->rawWidth == 0)) {
1753         fprintf(stderr, "[ERROR] invalid raw or yuv image parameters\n");
1754         fprintf(stderr, "Please use the Format option -F:\n");
1755         fprintf(stderr,
1756                 "-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1757         fprintf(stderr, "Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1758         fprintf(stderr, "Aborting\n");
1759         return 1;
1760     }
1761
1762     if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc ||
1763             parameters->cp_fixed_quality)
1764             && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^
1765                   parameters->cp_fixed_quality))) {
1766         fprintf(stderr, "[ERROR] options -r -q and -f cannot be used together !!\n");
1767         return 1;
1768     }               /* mod fixed_quality */
1769
1770
1771     /* if no rate entered, lossless by default */
1772     /* Note: post v2.2.0, this is no longer necessary, but for released */
1773     /* versions at the time of writing, this is needed to avoid crashes */
1774     if (parameters->tcp_numlayers == 0) {
1775         parameters->tcp_rates[0] = 0;
1776         parameters->tcp_numlayers++;
1777         parameters->cp_disto_alloc = 1;
1778     }
1779
1780     if ((parameters->cp_tx0 > parameters->image_offset_x0) ||
1781             (parameters->cp_ty0 > parameters->image_offset_y0)) {
1782         fprintf(stderr,
1783                 "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
1784                 parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0,
1785                 parameters->image_offset_y0);
1786         return 1;
1787     }
1788
1789     for (i = 0; i < parameters->numpocs; i++) {
1790         if (parameters->POC[i].prg == -1) {
1791             fprintf(stderr,
1792                     "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
1793                     i + 1);
1794         }
1795     }
1796
1797     /* If subsampled image is provided, automatically disable MCT */
1798     if (((parameters->decod_format == RAW_DFMT) ||
1799             (parameters->decod_format == RAWL_DFMT))
1800             && (((raw_cp->rawComp > 1) && ((raw_cp->rawComps[1].dx > 1) ||
1801                                            (raw_cp->rawComps[1].dy > 1)))
1802                 || ((raw_cp->rawComp > 2) && ((raw_cp->rawComps[2].dx > 1) ||
1803                         (raw_cp->rawComps[2].dy > 1)))
1804                )) {
1805         parameters->tcp_mct = 0;
1806     }
1807
1808     return 0;
1809
1810 }
1811
1812 /* -------------------------------------------------------------------------- */
1813
1814 /**
1815 sample error debug callback expecting no client object
1816 */
1817 static void error_callback(const char *msg, void *client_data)
1818 {
1819     (void)client_data;
1820     fprintf(stdout, "[ERROR] %s", msg);
1821 }
1822 /**
1823 sample warning debug callback expecting no client object
1824 */
1825 static void warning_callback(const char *msg, void *client_data)
1826 {
1827     (void)client_data;
1828     fprintf(stdout, "[WARNING] %s", msg);
1829 }
1830 /**
1831 sample debug callback expecting no client object
1832 */
1833 static void info_callback(const char *msg, void *client_data)
1834 {
1835     (void)client_data;
1836     fprintf(stdout, "[INFO] %s", msg);
1837 }
1838
1839 OPJ_FLOAT64 opj_clock(void)
1840 {
1841 #ifdef _WIN32
1842     /* _WIN32: use QueryPerformance (very accurate) */
1843     LARGE_INTEGER freq, t ;
1844     /* freq is the clock speed of the CPU */
1845     QueryPerformanceFrequency(&freq) ;
1846     /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
1847     /* t is the high resolution performance counter (see MSDN) */
1848     QueryPerformanceCounter(& t) ;
1849     return freq.QuadPart ? ((OPJ_FLOAT64) t.QuadPart / (OPJ_FLOAT64) freq.QuadPart)
1850            : 0 ;
1851 #else
1852     /* Unix or Linux: use resource usage */
1853     struct rusage t;
1854     OPJ_FLOAT64 procTime;
1855     /* (1) Get the rusage data structure at this moment (man getrusage) */
1856     getrusage(0, &t);
1857     /* (2) What is the elapsed time ? - CPU time = User time + System time */
1858     /* (2a) Get the seconds */
1859     procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
1860     /* (2b) More precisely! Get the microseconds part ! */
1861     return (procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) *
1862             1e-6) ;
1863 #endif
1864 }
1865
1866
1867 /* -------------------------------------------------------------------------- */
1868 /**
1869  * OPJ_COMPRESS MAIN
1870  */
1871 /* -------------------------------------------------------------------------- */
1872 int main(int argc, char **argv)
1873 {
1874
1875     opj_cparameters_t parameters;   /* compression parameters */
1876
1877     opj_stream_t *l_stream = 00;
1878     opj_codec_t* l_codec = 00;
1879     opj_image_t *image = NULL;
1880     raw_cparameters_t raw_cp;
1881     OPJ_SIZE_T num_compressed_files = 0;
1882
1883     char indexfilename[OPJ_PATH_LEN];   /* index file name */
1884
1885     unsigned int i, num_images, imageno;
1886     img_fol_t img_fol;
1887     dircnt_t *dirptr = NULL;
1888
1889     int ret = 0;
1890
1891     OPJ_BOOL bSuccess;
1892     OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
1893     OPJ_UINT32 l_nb_tiles = 4;
1894     int framerate = 0;
1895     OPJ_FLOAT64 t = opj_clock();
1896
1897     OPJ_BOOL PLT = OPJ_FALSE;
1898     int num_threads = 0;
1899
1900     /* set encoding parameters to default values */
1901     opj_set_default_encoder_parameters(&parameters);
1902
1903     /* Initialize indexfilename and img_fol */
1904     *indexfilename = 0;
1905     memset(&img_fol, 0, sizeof(img_fol_t));
1906
1907     /* raw_cp initialization */
1908     raw_cp.rawBitDepth = 0;
1909     raw_cp.rawComp = 0;
1910     raw_cp.rawComps = 0;
1911     raw_cp.rawHeight = 0;
1912     raw_cp.rawSigned = 0;
1913     raw_cp.rawWidth = 0;
1914
1915     /* parse input and get user encoding parameters */
1916     parameters.tcp_mct = (char)
1917                          255; /* This will be set later according to the input image or the provided option */
1918     if (parse_cmdline_encoder(argc, argv, &parameters, &img_fol, &raw_cp,
1919                               indexfilename, sizeof(indexfilename), &framerate, &PLT, &num_threads) == 1) {
1920         ret = 1;
1921         goto fin;
1922     }
1923
1924     /* Read directory if necessary */
1925     if (img_fol.set_imgdir == 1) {
1926         num_images = get_num_images(img_fol.imgdirpath);
1927         dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
1928         if (dirptr) {
1929             dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
1930                     char)); /* Stores at max 10 image file names*/
1931             dirptr->filename = (char**) malloc(num_images * sizeof(char*));
1932             if (!dirptr->filename_buf) {
1933                 ret = 0;
1934                 goto fin;
1935             }
1936             for (i = 0; i < num_images; i++) {
1937                 dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
1938             }
1939         }
1940         if (load_images(dirptr, img_fol.imgdirpath) == 1) {
1941             ret = 0;
1942             goto fin;
1943         }
1944         if (num_images == 0) {
1945             fprintf(stdout, "Folder is empty\n");
1946             ret = 0;
1947             goto fin;
1948         }
1949     } else {
1950         num_images = 1;
1951     }
1952     /*Encoding image one by one*/
1953     for (imageno = 0; imageno < num_images; imageno++) {
1954         image = NULL;
1955         fprintf(stderr, "\n");
1956
1957         if (img_fol.set_imgdir == 1) {
1958             if (get_next_file((int)imageno, dirptr, &img_fol, &parameters)) {
1959                 fprintf(stderr, "skipping file...\n");
1960                 continue;
1961             }
1962         }
1963
1964         switch (parameters.decod_format) {
1965         case PGX_DFMT:
1966         case PXM_DFMT:
1967         case BMP_DFMT:
1968         case TIF_DFMT:
1969         case RAW_DFMT:
1970         case RAWL_DFMT:
1971         case TGA_DFMT:
1972         case PNG_DFMT:
1973             break;
1974         default:
1975             fprintf(stderr, "skipping file...\n");
1976             continue;
1977         }
1978
1979         /* decode the source image */
1980         /* ----------------------- */
1981
1982         switch (parameters.decod_format) {
1983         case PGX_DFMT:
1984             image = pgxtoimage(parameters.infile, &parameters);
1985             if (!image) {
1986                 fprintf(stderr, "Unable to load pgx file\n");
1987                 ret = 1;
1988                 goto fin;
1989             }
1990             break;
1991
1992         case PXM_DFMT:
1993             image = pnmtoimage(parameters.infile, &parameters);
1994             if (!image) {
1995                 fprintf(stderr, "Unable to load pnm file\n");
1996                 ret = 1;
1997                 goto fin;
1998             }
1999             break;
2000
2001         case BMP_DFMT:
2002             image = bmptoimage(parameters.infile, &parameters);
2003             if (!image) {
2004                 fprintf(stderr, "Unable to load bmp file\n");
2005                 ret = 1;
2006                 goto fin;
2007             }
2008             break;
2009
2010 #ifdef OPJ_HAVE_LIBTIFF
2011         case TIF_DFMT:
2012             image = tiftoimage(parameters.infile, &parameters);
2013             if (!image) {
2014                 fprintf(stderr, "Unable to load tif(f) file\n");
2015                 ret = 1;
2016                 goto fin;
2017             }
2018             break;
2019 #endif /* OPJ_HAVE_LIBTIFF */
2020
2021         case RAW_DFMT:
2022             image = rawtoimage(parameters.infile, &parameters, &raw_cp);
2023             if (!image) {
2024                 fprintf(stderr, "Unable to load raw or yuv file\n");
2025                 ret = 1;
2026                 goto fin;
2027             }
2028             break;
2029
2030         case RAWL_DFMT:
2031             image = rawltoimage(parameters.infile, &parameters, &raw_cp);
2032             if (!image) {
2033                 fprintf(stderr, "Unable to load raw file\n");
2034                 ret = 1;
2035                 goto fin;
2036             }
2037             break;
2038
2039         case TGA_DFMT:
2040             image = tgatoimage(parameters.infile, &parameters);
2041             if (!image) {
2042                 fprintf(stderr, "Unable to load tga file\n");
2043                 ret = 1;
2044                 goto fin;
2045             }
2046             break;
2047
2048 #ifdef OPJ_HAVE_LIBPNG
2049         case PNG_DFMT:
2050             image = pngtoimage(parameters.infile, &parameters);
2051             if (!image) {
2052                 fprintf(stderr, "Unable to load png file\n");
2053                 ret = 1;
2054                 goto fin;
2055             }
2056             break;
2057 #endif /* OPJ_HAVE_LIBPNG */
2058         }
2059
2060         /* Can happen if input file is TIF(F) or PNG
2061         * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
2062         */
2063         if (!image) {
2064             fprintf(stderr, "Unable to load file: got no image\n");
2065             ret = 1;
2066             goto fin;
2067         }
2068
2069         /* Decide if MCT should be used */
2070         if (parameters.tcp_mct == (char)
2071                 255) { /* mct mode has not been set in commandline */
2072             parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;
2073         } else {            /* mct mode has been set in commandline */
2074             if ((parameters.tcp_mct == 1) && (image->numcomps < 3)) {
2075                 fprintf(stderr, "RGB->YCC conversion cannot be used:\n");
2076                 fprintf(stderr, "Input image has less than 3 components\n");
2077                 ret = 1;
2078                 goto fin;
2079             }
2080             if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {
2081                 fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
2082                 fprintf(stderr, "has been provided. Aborting.\n");
2083                 ret = 1;
2084                 goto fin;
2085             }
2086         }
2087
2088         if (OPJ_IS_IMF(parameters.rsiz) && framerate > 0) {
2089             const int mainlevel = OPJ_GET_IMF_MAINLEVEL(parameters.rsiz);
2090             if (mainlevel > 0 && mainlevel <= OPJ_IMF_MAINLEVEL_MAX) {
2091                 const int limitMSamplesSec[] = {
2092                     0,
2093                     OPJ_IMF_MAINLEVEL_1_MSAMPLESEC,
2094                     OPJ_IMF_MAINLEVEL_2_MSAMPLESEC,
2095                     OPJ_IMF_MAINLEVEL_3_MSAMPLESEC,
2096                     OPJ_IMF_MAINLEVEL_4_MSAMPLESEC,
2097                     OPJ_IMF_MAINLEVEL_5_MSAMPLESEC,
2098                     OPJ_IMF_MAINLEVEL_6_MSAMPLESEC,
2099                     OPJ_IMF_MAINLEVEL_7_MSAMPLESEC,
2100                     OPJ_IMF_MAINLEVEL_8_MSAMPLESEC,
2101                     OPJ_IMF_MAINLEVEL_9_MSAMPLESEC,
2102                     OPJ_IMF_MAINLEVEL_10_MSAMPLESEC,
2103                     OPJ_IMF_MAINLEVEL_11_MSAMPLESEC
2104                 };
2105                 OPJ_UINT32 avgcomponents = image->numcomps;
2106                 double msamplespersec;
2107                 if (image->numcomps == 3 &&
2108                         image->comps[1].dx == 2 &&
2109                         image->comps[1].dy == 2) {
2110                     avgcomponents = 2;
2111                 }
2112                 msamplespersec = (double)image->x1 * image->y1 * avgcomponents * framerate /
2113                                  1e6;
2114                 if (msamplespersec > limitMSamplesSec[mainlevel]) {
2115                     fprintf(stderr,
2116                             "Warning: MSamples/sec is %f, whereas limit is %d.\n",
2117                             msamplespersec,
2118                             limitMSamplesSec[mainlevel]);
2119                 }
2120             }
2121         }
2122
2123         /* encode the destination image */
2124         /* ---------------------------- */
2125
2126         switch (parameters.cod_format) {
2127         case J2K_CFMT: { /* JPEG-2000 codestream */
2128             /* Get a decoder handle */
2129             l_codec = opj_create_compress(OPJ_CODEC_J2K);
2130             break;
2131         }
2132         case JP2_CFMT: { /* JPEG 2000 compressed image data */
2133             /* Get a decoder handle */
2134             l_codec = opj_create_compress(OPJ_CODEC_JP2);
2135             break;
2136         }
2137         default:
2138             fprintf(stderr, "skipping file..\n");
2139             opj_stream_destroy(l_stream);
2140             continue;
2141         }
2142
2143         /* catch events using our callbacks and give a local context */
2144         opj_set_info_handler(l_codec, info_callback, 00);
2145         opj_set_warning_handler(l_codec, warning_callback, 00);
2146         opj_set_error_handler(l_codec, error_callback, 00);
2147
2148         if (bUseTiles) {
2149             parameters.cp_tx0 = 0;
2150             parameters.cp_ty0 = 0;
2151             parameters.tile_size_on = OPJ_TRUE;
2152             parameters.cp_tdx = 512;
2153             parameters.cp_tdy = 512;
2154         }
2155         if (! opj_setup_encoder(l_codec, &parameters, image)) {
2156             fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
2157             opj_destroy_codec(l_codec);
2158             opj_image_destroy(image);
2159             ret = 1;
2160             goto fin;
2161         }
2162
2163         if (PLT) {
2164             const char* const options[] = { "PLT=YES", NULL };
2165             if (!opj_encoder_set_extra_options(l_codec, options)) {
2166                 fprintf(stderr, "failed to encode image: opj_encoder_set_extra_options\n");
2167                 opj_destroy_codec(l_codec);
2168                 opj_image_destroy(image);
2169                 ret = 1;
2170                 goto fin;
2171             }
2172         }
2173
2174         if (num_threads >= 1 &&
2175                 !opj_codec_set_threads(l_codec, num_threads)) {
2176             fprintf(stderr, "failed to set number of threads\n");
2177             opj_destroy_codec(l_codec);
2178             opj_image_destroy(image);
2179             ret = 1;
2180             goto fin;
2181         }
2182
2183         /* open a byte stream for writing and allocate memory for all tiles */
2184         l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);
2185         if (! l_stream) {
2186             ret = 1;
2187             goto fin;
2188         }
2189
2190         /* encode the image */
2191         bSuccess = opj_start_compress(l_codec, image, l_stream);
2192         if (!bSuccess)  {
2193             fprintf(stderr, "failed to encode image: opj_start_compress\n");
2194         }
2195         if (bSuccess && bUseTiles) {
2196             OPJ_BYTE *l_data;
2197             OPJ_UINT32 l_data_size = 512 * 512 * 3;
2198             l_data = (OPJ_BYTE*) calloc(1, l_data_size);
2199             if (l_data == NULL) {
2200                 ret = 1;
2201                 goto fin;
2202             }
2203             for (i = 0; i < l_nb_tiles; ++i) {
2204                 if (! opj_write_tile(l_codec, i, l_data, l_data_size, l_stream)) {
2205                     fprintf(stderr, "ERROR -> test_tile_encoder: failed to write the tile %d!\n",
2206                             i);
2207                     opj_stream_destroy(l_stream);
2208                     opj_destroy_codec(l_codec);
2209                     opj_image_destroy(image);
2210                     ret = 1;
2211                     goto fin;
2212                 }
2213             }
2214             free(l_data);
2215         } else {
2216             bSuccess = bSuccess && opj_encode(l_codec, l_stream);
2217             if (!bSuccess)  {
2218                 fprintf(stderr, "failed to encode image: opj_encode\n");
2219             }
2220         }
2221         bSuccess = bSuccess && opj_end_compress(l_codec, l_stream);
2222         if (!bSuccess)  {
2223             fprintf(stderr, "failed to encode image: opj_end_compress\n");
2224         }
2225
2226         if (!bSuccess)  {
2227             opj_stream_destroy(l_stream);
2228             opj_destroy_codec(l_codec);
2229             opj_image_destroy(image);
2230             fprintf(stderr, "failed to encode image\n");
2231             remove(parameters.outfile);
2232             ret = 1;
2233             goto fin;
2234         }
2235
2236         num_compressed_files++;
2237         fprintf(stdout, "[INFO] Generated outfile %s\n", parameters.outfile);
2238         /* close and free the byte stream */
2239         opj_stream_destroy(l_stream);
2240
2241         /* free remaining compression structures */
2242         opj_destroy_codec(l_codec);
2243
2244         /* free image data */
2245         opj_image_destroy(image);
2246
2247     }
2248
2249     t = opj_clock() - t;
2250     if (num_compressed_files) {
2251         fprintf(stdout, "encode time: %d ms \n",
2252                 (int)((t * 1000.0) / (OPJ_FLOAT64)num_compressed_files));
2253     }
2254
2255     ret = 0;
2256
2257 fin:
2258     if (parameters.cp_comment) {
2259         free(parameters.cp_comment);
2260     }
2261     if (parameters.cp_matrice) {
2262         free(parameters.cp_matrice);
2263     }
2264     if (raw_cp.rawComps) {
2265         free(raw_cp.rawComps);
2266     }
2267     if (img_fol.imgdirpath) {
2268         free(img_fol.imgdirpath);
2269     }
2270     if (dirptr) {
2271         if (dirptr->filename_buf) {
2272             free(dirptr->filename_buf);
2273         }
2274         if (dirptr->filename) {
2275             free(dirptr->filename);
2276         }
2277         free(dirptr);
2278     }
2279     return ret;
2280 }