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