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