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