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