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