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