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