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