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.
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.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
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.
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.
49 #include "windirent.h"
56 #define strcasecmp _stricmp
57 #define strncasecmp _strnicmp
61 #include <sys/resource.h>
62 #include <sys/times.h>
65 #include "opj_apps_config.h"
67 #include "opj_getopt.h"
71 #include "format_defs.h"
72 #include "opj_string.h"
74 typedef struct dircnt {
75 /** Buffer for holding images read from Directory*/
77 /** Pointer to the buffer*/
81 typedef struct img_folder {
82 /** The directory path of the folder containing input images*/
88 /** Enable Cod Format for output*/
92 static void encode_help_display(void)
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());
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");
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");
122 fprintf(stdout, " * No JPWL protection\n");
123 #endif /* USE_JPWL */
125 fprintf(stdout, "\n");
127 fprintf(stdout, "Note:\n");
128 fprintf(stdout, "-----\n");
129 fprintf(stdout, "\n");
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");
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");
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");
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");
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");
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");
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");
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");
191 " Code-block size. The dimension must respect the constraint \n");
193 " defined in the JPEG-2000 standard (no dimension smaller than 4 \n");
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");
199 "-c [<prec width>,<prec height>],[<prec width>,<prec height>],...\n");
200 fprintf(stdout, " Precinct size. Values specified must be power of 2. \n");
202 " Multiple records may be supplied, in which case the first record refers\n");
204 " to the highest resolution level and subsequent records to lower \n");
206 " resolution levels. The last specified record is halved successively for each \n");
207 fprintf(stdout, " remaining lower resolution levels.\n");
208 fprintf(stdout, " Default: 2^15x2^15 at each resolution.\n");
209 fprintf(stdout, "-t <tile width>,<tile height>\n");
210 fprintf(stdout, " Tile size.\n");
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");
221 "-POC <progression order change>/<progression order change>/...\n");
222 fprintf(stdout, " Progression order change.\n");
224 " The syntax of a progression order change is the following:\n");
226 " T<tile>=<resStart>,<compStart>,<layerEnd>,<resEnd>,<compEnd>,<progOrder>\n");
227 fprintf(stdout, " Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\n");
228 fprintf(stdout, "-SOP\n");
229 fprintf(stdout, " Write SOP marker before each packet.\n");
230 fprintf(stdout, "-EPH\n");
231 fprintf(stdout, " Write EPH marker after each header packet.\n");
232 fprintf(stdout, "-PLT\n");
233 fprintf(stdout, " Write PLT marker in tile-part header.\n");
234 fprintf(stdout, "-M <key value>\n");
235 fprintf(stdout, " Mode switch.\n");
236 fprintf(stdout, " [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
237 fprintf(stdout, " 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
238 fprintf(stdout, " Indicate multiple modes by adding their values.\n");
240 " Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");
241 fprintf(stdout, "-TP <R|L|C>\n");
242 fprintf(stdout, " Divide packets of every tile into tile-parts.\n");
244 " Division is made by grouping Resolutions (R), Layers (L)\n");
245 fprintf(stdout, " or Components (C).\n");
247 fprintf(stdout, "-x <index file>\n");
248 fprintf(stdout, " Create an index file.\n");
249 #endif /*FIXME_INDEX*/
250 fprintf(stdout, "-ROI c=<component index>,U=<upshifting value>\n");
251 fprintf(stdout, " Quantization indices upshifted for a component. \n");
253 " Warning: This option does not implement the usual ROI (Region of Interest).\n");
255 " It should be understood as a 'Component of Interest'. It offers the \n");
257 " possibility to upshift the value of a component during quantization step.\n");
259 " The value after c= is the component number [0, 1, 2, ...] and the value \n");
261 " after U= is the value of upshifting. U must be in the range [0, 37].\n");
262 fprintf(stdout, "-d <image offset X,image offset Y>\n");
263 fprintf(stdout, " Offset of the origin of the image.\n");
264 fprintf(stdout, "-T <tile offset X,tile offset Y>\n");
265 fprintf(stdout, " Offset of the origin of the tiles.\n");
266 fprintf(stdout, "-I\n");
267 fprintf(stdout, " Use the irreversible DWT 9-7.\n");
268 fprintf(stdout, "-mct <0|1|2>\n");
270 " Explicitly specifies if a Multiple Component Transform has to be used.\n");
271 fprintf(stdout, " 0: no MCT ; 1: RGB->YCC conversion ; 2: custom MCT.\n");
273 " If custom MCT, \"-m\" option has to be used (see hereunder).\n");
275 " By default, RGB->YCC conversion is used if there are 3 components or more,\n");
276 fprintf(stdout, " no conversion otherwise.\n");
277 fprintf(stdout, "-m <file>\n");
279 " Use array-based MCT, values are coma separated, line by line\n");
281 " No specific separators between lines, no space allowed between values.\n");
283 " If this option is used, it automatically sets \"-mct\" option to 2.\n");
284 fprintf(stdout, "-cinema2K <24|48>\n");
285 fprintf(stdout, " Digital Cinema 2K profile compliant codestream.\n");
287 " Need to specify the frames per second for a 2K resolution.\n");
288 fprintf(stdout, " Only 24 or 48 fps are currently allowed.\n");
289 fprintf(stdout, "-cinema4K\n");
290 fprintf(stdout, " Digital Cinema 4K profile compliant codestream.\n");
291 fprintf(stdout, " Frames per second not required. Default value is 24fps.\n");
292 fprintf(stdout, "-IMF <PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS]\n");
293 fprintf(stdout, " Interoperable Master Format compliant codestream.\n");
294 fprintf(stdout, " <PROFILE>=2K, 4K, 8K, 2K_R, 4K_R or 8K_R.\n");
295 fprintf(stdout, " X >= 0 and X <= 11.\n");
296 fprintf(stdout, " Y >= 0 and Y <= 9.\n");
298 " framerate > 0 may be specified to enhance checks and set maximum bit rate when Y > 0.\n");
299 fprintf(stdout, "-jpip\n");
300 fprintf(stdout, " Write jpip codestream index box in JP2 output file.\n");
301 fprintf(stdout, " Currently supports only RPCL order.\n");
302 fprintf(stdout, "-C <comment>\n");
303 fprintf(stdout, " Add <comment> in the comment marker segment.\n");
306 fprintf(stdout, "-W <params>\n");
307 fprintf(stdout, " Adoption of JPWL (Part 11) capabilities (-W params)\n");
309 " The <params> field can be written and repeated in any order:\n");
310 fprintf(stdout, " [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
311 fprintf(stdout, " ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
313 " h selects the header error protection (EPB): 'type' can be\n");
315 " [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
317 " if 'tilepart' is absent, it is for main and tile headers\n");
318 fprintf(stdout, " if 'tilepart' is present, it applies from that tile\n");
320 " onwards, up to the next h<> spec, or to the last tilepart\n");
321 fprintf(stdout, " in the codestream (max. %d specs)\n",
322 JPWL_MAX_NO_TILESPECS);
324 " p selects the packet error protection (EEP/UEP with EPBs)\n");
325 fprintf(stdout, " to be applied to raw data: 'type' can be\n");
327 " [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
329 " if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
331 " if 'tilepart:pack' is present, it applies from that tile\n");
333 " and that packet onwards, up to the next packet spec\n");
335 " or to the last packet in the last tilepart in the stream\n");
336 fprintf(stdout, " (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
338 " s enables sensitivity data insertion (ESD): 'method' can be\n");
340 " [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
341 fprintf(stdout, " 4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
342 fprintf(stdout, " if 'tilepart' is absent, it is for main header only\n");
343 fprintf(stdout, " if 'tilepart' is present, it applies from that tile\n");
345 " onwards, up to the next s<> spec, or to the last tilepart\n");
346 fprintf(stdout, " in the codestream (max. %d specs)\n",
347 JPWL_MAX_NO_TILESPECS);
348 fprintf(stdout, " g determines the addressing mode: <range> can be\n");
349 fprintf(stdout, " [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
351 " a determines the size of data addressing: <addr> can be\n");
353 " 2/4 bytes (small/large codestreams). If not set, auto-mode\n");
355 " z determines the size of sensitivity values: <size> can be\n");
357 " 1/2 bytes, for the transformed pseudo-floating point value\n");
358 fprintf(stdout, " ex.:\n");
360 " h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
361 fprintf(stdout, " s0=6,s3=-1,a=0,g=1,z=1\n");
362 fprintf(stdout, " means\n");
364 " predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
366 " CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
367 fprintf(stdout, " UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
369 " UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
370 fprintf(stdout, " UEP rs default for packets of tilepart 1,\n");
371 fprintf(stdout, " no UEP for packets 0 to 19 of tilepart 3,\n");
373 " UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
374 fprintf(stdout, " relative sensitivity ESD for MH,\n");
376 " TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
378 " size of addresses and 1 byte for each sensitivity value\n");
379 fprintf(stdout, " ex.:\n");
380 fprintf(stdout, " h,s,p\n");
381 fprintf(stdout, " means\n");
383 " default protection to headers (MH and TPHs) as well as\n");
384 fprintf(stdout, " data packets, one ESD in MH\n");
386 " N.B.: use the following recommendations when specifying\n");
387 fprintf(stdout, " the JPWL parameters list\n");
389 " - when you use UEP, always pair the 'p' option with 'h'\n");
390 #endif /* USE_JPWL */
392 fprintf(stdout, "\n");
394 fprintf(stdout, "Index structure:\n");
395 fprintf(stdout, "----------------\n");
396 fprintf(stdout, "\n");
397 fprintf(stdout, "Image_height Image_width\n");
398 fprintf(stdout, "progression order\n");
399 fprintf(stdout, "Tiles_size_X Tiles_size_Y\n");
400 fprintf(stdout, "Tiles_nb_X Tiles_nb_Y\n");
401 fprintf(stdout, "Components_nb\n");
402 fprintf(stdout, "Layers_nb\n");
403 fprintf(stdout, "decomposition_levels\n");
404 fprintf(stdout, "[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
405 fprintf(stdout, " [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
406 fprintf(stdout, "Main_header_start_position\n");
407 fprintf(stdout, "Main_header_end_position\n");
408 fprintf(stdout, "Codestream_size\n");
409 fprintf(stdout, "\n");
410 fprintf(stdout, "INFO ON TILES\n");
412 "tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");
414 "Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");
416 "Tile_1 '' '' '' '' '' '' ''\n");
417 fprintf(stdout, "...\n");
419 "Tile_Nt '' '' '' '' '' '' ''\n");
420 fprintf(stdout, "...\n");
421 fprintf(stdout, "TILE 0 DETAILS\n");
422 fprintf(stdout, "part_nb tileno num_packs start_pos end_tph_pos end_pos\n");
423 fprintf(stdout, "...\n");
424 fprintf(stdout, "Progression_string\n");
426 "pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");
428 "Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
429 fprintf(stdout, "...\n");
431 "Tpacket_Np '' '' '' '' '' '' '' ''\n");
432 fprintf(stdout, "MaxDisto\n");
433 fprintf(stdout, "TotalDisto\n\n");
434 #endif /*FIXME_INDEX*/
437 static OPJ_PROG_ORDER give_progression(const char progression[4])
439 if (strncmp(progression, "LRCP", 4) == 0) {
442 if (strncmp(progression, "RLCP", 4) == 0) {
445 if (strncmp(progression, "RPCL", 4) == 0) {
448 if (strncmp(progression, "PCRL", 4) == 0) {
451 if (strncmp(progression, "CPRL", 4) == 0) {
455 return OPJ_PROG_UNKNOWN;
458 static unsigned int get_num_images(char *imgdirpath)
461 struct dirent* content;
462 unsigned int num_images = 0;
464 /*Reading the input images from given input directory*/
466 dir = opendir(imgdirpath);
468 fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
473 while ((content = readdir(dir)) != NULL) {
474 if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
483 static int load_images(dircnt_t *dirptr, char *imgdirpath)
486 struct dirent* content;
489 /*Reading the input images from given input directory*/
491 dir = opendir(imgdirpath);
493 fprintf(stderr, "Could not open Folder %s\n", imgdirpath);
496 fprintf(stderr, "Folder opened successfully\n");
499 while ((content = readdir(dir)) != NULL) {
500 if (strcmp(".", content->d_name) == 0 || strcmp("..", content->d_name) == 0) {
504 strcpy(dirptr->filename[i], content->d_name);
511 static int get_file_format(char *filename)
514 static const char *extension[] = {
515 "pgx", "pnm", "pgm", "ppm", "pbm", "pam", "bmp", "tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "j2c", "jpc"
517 static const int format[] = {
518 PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT
520 char * ext = strrchr(filename, '.');
525 for (i = 0; i < sizeof(format) / sizeof(*format); i++) {
526 if (strcasecmp(ext, extension[i]) == 0) {
533 static char * get_file_name(char *name)
535 char *fname = strtok(name, ".");
539 static char get_next_file(int imageno, dircnt_t *dirptr, img_fol_t *img_fol,
540 opj_cparameters_t *parameters)
542 char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],
543 outfilename[OPJ_PATH_LEN], temp_ofname[OPJ_PATH_LEN];
544 char *temp_p, temp1[OPJ_PATH_LEN] = "";
546 strcpy(image_filename, dirptr->filename[imageno]);
547 fprintf(stderr, "File Number %d \"%s\"\n", imageno, image_filename);
548 parameters->decod_format = get_file_format(image_filename);
549 if (parameters->decod_format == -1) {
552 sprintf(infilename, "%s/%s", img_fol->imgdirpath, image_filename);
553 if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile),
559 strcpy(temp_ofname, get_file_name(image_filename));
560 while ((temp_p = strtok(NULL, ".")) != NULL) {
561 strcat(temp_ofname, temp1);
562 sprintf(temp1, ".%s", temp_p);
564 if (img_fol->set_out_format == 1) {
565 sprintf(outfilename, "%s/%s.%s", img_fol->imgdirpath, temp_ofname,
566 img_fol->out_format);
567 if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
575 /* ------------------------------------------------------------------------------------ */
577 static int parse_cmdline_encoder(int argc, char **argv,
578 opj_cparameters_t *parameters,
579 img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename,
580 size_t indexfilename_size,
586 opj_option_t long_option[] = {
587 {"cinema2K", REQ_ARG, NULL, 'w'},
588 {"cinema4K", NO_ARG, NULL, 'y'},
589 {"ImgDir", REQ_ARG, NULL, 'z'},
590 {"TP", REQ_ARG, NULL, 'u'},
591 {"SOP", NO_ARG, NULL, 'S'},
592 {"EPH", NO_ARG, NULL, 'E'},
593 {"OutFor", REQ_ARG, NULL, 'O'},
594 {"POC", REQ_ARG, NULL, 'P'},
595 {"ROI", REQ_ARG, NULL, 'R'},
596 {"jpip", NO_ARG, NULL, 'J'},
597 {"mct", REQ_ARG, NULL, 'Y'},
598 {"IMF", REQ_ARG, NULL, 'Z'},
599 {"PLT", NO_ARG, NULL, 'A'}
602 /* parse the command line */
603 const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
606 #endif /* USE_JPWL */
609 totlen = sizeof(long_option);
610 img_fol->set_out_format = 0;
611 raw_cp->rawWidth = 0;
614 c = opj_getopt_long(argc, argv, optlist, long_option, totlen);
619 case 'i': { /* input file */
620 char *infile = opj_optarg;
621 parameters->decod_format = get_file_format(infile);
622 switch (parameters->decod_format) {
634 "[ERROR] Unknown input file format: %s \n"
635 " Known file formats are *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga\n",
639 if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infile) != 0) {
645 /* ----------------------------------------------------- */
647 case 'o': { /* output file */
648 char *outfile = opj_optarg;
649 parameters->cod_format = get_file_format(outfile);
650 switch (parameters->cod_format) {
656 "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
659 if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile),
666 /* ----------------------------------------------------- */
667 case 'O': { /* output format */
669 char *of = opj_optarg;
670 sprintf(outformat, ".%s", of);
671 img_fol->set_out_format = 1;
672 parameters->cod_format = get_file_format(outformat);
673 switch (parameters->cod_format) {
676 img_fol->out_format = opj_optarg;
679 fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");
686 /* ----------------------------------------------------- */
689 case 'r': { /* rates rates/distorsion */
690 char *s = opj_optarg;
691 parameters->tcp_numlayers = 0;
692 while (sscanf(s, "%f", ¶meters->tcp_rates[parameters->tcp_numlayers]) ==
694 parameters->tcp_numlayers++;
695 while (*s && *s != ',') {
703 parameters->cp_disto_alloc = 1;
707 /* ----------------------------------------------------- */
710 case 'F': { /* Raw image format parameters */
711 OPJ_BOOL wrong = OPJ_FALSE;
716 int width, height, bitdepth, ncomp;
718 OPJ_BOOL raw_signed = OPJ_FALSE;
719 substr2 = strchr(opj_optarg, '@');
720 if (substr2 == NULL) {
721 len = (OPJ_UINT32) strlen(opj_optarg);
723 len = (OPJ_UINT32)(substr2 - opj_optarg);
724 substr2++; /* skip '@' character */
726 substr1 = (char*) malloc((len + 1) * sizeof(char));
727 if (substr1 == NULL) {
730 memcpy(substr1, opj_optarg, len);
732 if (sscanf(substr1, "%d,%d,%d,%d,%c", &width, &height, &ncomp, &bitdepth,
735 raw_signed = OPJ_TRUE;
736 } else if (signo == 'u') {
737 raw_signed = OPJ_FALSE;
748 raw_cp->rawWidth = width;
749 raw_cp->rawHeight = height;
750 raw_cp->rawComp = ncomp;
751 raw_cp->rawBitDepth = bitdepth;
752 raw_cp->rawSigned = raw_signed;
753 raw_cp->rawComps = (raw_comp_cparameters_t*) malloc(((OPJ_UINT32)(
754 ncomp)) * sizeof(raw_comp_cparameters_t));
755 if (raw_cp->rawComps == NULL) {
759 for (compno = 0; compno < ncomp && !wrong; compno++) {
760 if (substr2 == NULL) {
761 raw_cp->rawComps[compno].dx = lastdx;
762 raw_cp->rawComps[compno].dy = lastdy;
765 sep = strchr(substr2, ':');
767 if (sscanf(substr2, "%dx%d", &dx, &dy) == 2) {
770 raw_cp->rawComps[compno].dx = dx;
771 raw_cp->rawComps[compno].dy = dy;
777 if (sscanf(substr2, "%dx%d:%s", &dx, &dy, substr2) == 3) {
778 raw_cp->rawComps[compno].dx = dx;
779 raw_cp->rawComps[compno].dy = dy;
789 fprintf(stderr, "\nError: invalid raw image parameters\n");
790 fprintf(stderr, "Please use the Format option -F:\n");
792 "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
794 "If subsampling is omitted, 1x1 is assumed for all components\n");
796 "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
797 fprintf(stderr, " for raw 512x512 image with 4:2:0 subsampling\n");
798 fprintf(stderr, "Aborting.\n");
804 /* ----------------------------------------------------- */
806 case 'q': { /* add fixed_quality */
807 char *s = opj_optarg;
808 while (sscanf(s, "%f", ¶meters->tcp_distoratio[parameters->tcp_numlayers])
810 parameters->tcp_numlayers++;
811 while (*s && *s != ',') {
819 parameters->cp_fixed_quality = 1;
824 /* ----------------------------------------------------- */
826 case 'f': { /* mod fixed_quality (before : -q) */
827 int *row = NULL, *col = NULL;
828 OPJ_UINT32 numlayers = 0, numresolution = 0, matrix_width = 0;
830 char *s = opj_optarg;
831 sscanf(s, "%u", &numlayers);
837 parameters->tcp_numlayers = (int)numlayers;
838 numresolution = (OPJ_UINT32)parameters->numresolution;
839 matrix_width = numresolution * 3;
840 parameters->cp_matrice = (int *) malloc(sizeof(int) * numlayers * matrix_width);
841 if (parameters->cp_matrice == NULL) {
846 for (i = 0; i < numlayers; i++) {
847 row = ¶meters->cp_matrice[i * matrix_width];
849 parameters->tcp_rates[i] = 1;
850 sscanf(s, "%d,", &col[0]);
857 for (j = 1; j < numresolution; j++) {
859 sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
871 if (i < numlayers - 1) {
875 parameters->cp_fixed_alloc = 1;
879 /* ----------------------------------------------------- */
881 case 't': { /* tiles */
882 sscanf(opj_optarg, "%d,%d", ¶meters->cp_tdx, ¶meters->cp_tdy);
883 parameters->tile_size_on = OPJ_TRUE;
887 /* ----------------------------------------------------- */
889 case 'n': { /* resolution */
890 sscanf(opj_optarg, "%d", ¶meters->numresolution);
894 /* ----------------------------------------------------- */
895 case 'c': { /* precinct dimension */
899 char *s = opj_optarg;
903 ret = sscanf(s, "[%d,%d]%c", ¶meters->prcw_init[res_spec],
904 ¶meters->prch_init[res_spec], &sep);
905 if (!(ret == 2 && sep == 0) && !(ret == 3 && sep == ',')) {
906 fprintf(stderr, "\nError: could not parse precinct dimension: '%s' %x\n", s,
908 fprintf(stderr, "Example: -i lena.raw -o lena.j2k -c [128,128],[128,128]\n");
911 parameters->csty |= 0x01;
913 s = strpbrk(s, "]") + 2;
914 } while (sep == ',');
915 parameters->res_spec = res_spec;
919 /* ----------------------------------------------------- */
921 case 'b': { /* code-block dimension */
922 int cblockw_init = 0, cblockh_init = 0;
923 sscanf(opj_optarg, "%d,%d", &cblockw_init, &cblockh_init);
924 if (cblockw_init > 1024 || cblockw_init < 4 ||
925 cblockh_init > 1024 || cblockh_init < 4 ||
926 cblockw_init * cblockh_init > 4096) {
928 "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
929 " * width*height<=4096\n * 4<=width,height<= 1024\n\n");
932 parameters->cblockw_init = cblockw_init;
933 parameters->cblockh_init = cblockh_init;
937 /* ----------------------------------------------------- */
939 case 'x': { /* creation of index file */
940 if (opj_strcpy_s(indexfilename, indexfilename_size, opj_optarg) != 0) {
943 /* FIXME ADE INDEX >> */
945 "[WARNING] Index file generation is currently broken.\n"
946 " '-x' option ignored.\n");
947 /* << FIXME ADE INDEX */
951 /* ----------------------------------------------------- */
953 case 'p': { /* progression order */
956 strncpy(progression, opj_optarg, 4);
957 parameters->prog_order = give_progression(progression);
958 if (parameters->prog_order == -1) {
959 fprintf(stderr, "Unrecognized progression order "
960 "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
966 /* ----------------------------------------------------- */
968 case 's': { /* subsampling factor */
969 if (sscanf(opj_optarg, "%d,%d", ¶meters->subsampling_dx,
970 ¶meters->subsampling_dy) != 2) {
971 fprintf(stderr, "'-s' sub-sampling argument error ! [-s dx,dy]\n");
977 /* ----------------------------------------------------- */
979 case 'd': { /* coordonnate of the reference grid */
980 if (sscanf(opj_optarg, "%d,%d", ¶meters->image_offset_x0,
981 ¶meters->image_offset_y0) != 2) {
982 fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
983 "error !! [-d x0,y0]\n");
989 /* ----------------------------------------------------- */
991 case 'h': /* display an help description */
992 encode_help_display();
995 /* ----------------------------------------------------- */
997 case 'P': { /* POC */
998 int numpocs = 0; /* number of progression order change (POC) default 0 */
999 opj_poc_t *POC = NULL; /* POC : used in case of Progression order change */
1001 char *s = opj_optarg;
1002 POC = parameters->POC;
1004 while (sscanf(s, "T%u=%u,%u,%u,%u,%u,%4s", &POC[numpocs].tile,
1005 &POC[numpocs].resno0, &POC[numpocs].compno0,
1006 &POC[numpocs].layno1, &POC[numpocs].resno1,
1007 &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
1008 POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
1010 while (*s && *s != '/') {
1018 parameters->numpocs = (OPJ_UINT32)numpocs;
1022 /* ------------------------------------------------------ */
1024 case 'S': { /* SOP marker */
1025 parameters->csty |= 0x02;
1029 /* ------------------------------------------------------ */
1031 case 'E': { /* EPH marker */
1032 parameters->csty |= 0x04;
1036 /* ------------------------------------------------------ */
1038 case 'M': { /* Mode switch pas tous au point !! */
1040 if (sscanf(opj_optarg, "%d", &value) == 1) {
1041 for (i = 0; i <= 5; i++) {
1042 int cache = value & (1 << i);
1044 parameters->mode |= (1 << i);
1051 /* ------------------------------------------------------ */
1053 case 'R': { /* ROI */
1054 if (sscanf(opj_optarg, "c=%d,U=%d", ¶meters->roi_compno,
1055 ¶meters->roi_shift) != 2) {
1056 fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
1062 /* ------------------------------------------------------ */
1064 case 'T': { /* Tile offset */
1065 if (sscanf(opj_optarg, "%d,%d", ¶meters->cp_tx0,
1066 ¶meters->cp_ty0) != 2) {
1067 fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
1073 /* ------------------------------------------------------ */
1075 case 'C': { /* add a comment */
1076 parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
1077 if (parameters->cp_comment) {
1078 strcpy(parameters->cp_comment, opj_optarg);
1084 /* ------------------------------------------------------ */
1086 case 'I': { /* reversible or not */
1087 parameters->irreversible = 1;
1091 /* ------------------------------------------------------ */
1093 case 'u': { /* Tile part generation*/
1094 parameters->tp_flag = opj_optarg[0];
1095 parameters->tp_on = 1;
1099 /* ------------------------------------------------------ */
1101 case 'z': { /* Image Directory path */
1102 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
1103 if (img_fol->imgdirpath == NULL) {
1106 strcpy(img_fol->imgdirpath, opj_optarg);
1107 img_fol->set_imgdir = 1;
1111 /* ------------------------------------------------------ */
1113 case 'w': { /* Digital Cinema 2K profile compliance*/
1115 sscanf(opj_optarg, "%d", &fps);
1117 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1118 parameters->max_comp_size = OPJ_CINEMA_24_COMP;
1119 parameters->max_cs_size = OPJ_CINEMA_24_CS;
1120 } else if (fps == 48) {
1121 parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
1122 parameters->max_comp_size = OPJ_CINEMA_48_COMP;
1123 parameters->max_cs_size = OPJ_CINEMA_48_CS;
1125 fprintf(stderr, "Incorrect value!! must be 24 or 48\n");
1128 fprintf(stdout, "CINEMA 2K profile activated\n"
1129 "Other options specified could be overridden\n");
1134 /* ------------------------------------------------------ */
1136 case 'y': { /* Digital Cinema 4K profile compliance*/
1137 parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
1138 fprintf(stdout, "CINEMA 4K profile activated\n"
1139 "Other options specified could be overridden\n");
1143 /* ------------------------------------------------------ */
1145 case 'Z': { /* IMF profile*/
1151 "Wrong value for -IMF. Should be "
1152 "<PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS] where <PROFILE> is one "
1153 "of 2K/4K/8K/2K_R/4K_R/8K_R.\n";
1156 comma = strstr(opj_optarg, ",mainlevel=");
1157 if (comma && sscanf(comma + 1, "mainlevel=%d", &mainlevel) != 1) {
1158 fprintf(stderr, "%s", msg);
1162 comma = strstr(opj_optarg, ",sublevel=");
1163 if (comma && sscanf(comma + 1, "sublevel=%d", &sublevel) != 1) {
1164 fprintf(stderr, "%s", msg);
1168 comma = strstr(opj_optarg, ",framerate=");
1169 if (comma && sscanf(comma + 1, "framerate=%d", &framerate) != 1) {
1170 fprintf(stderr, "%s", msg);
1174 comma = strchr(opj_optarg, ',');
1175 if (comma != NULL) {
1179 if (strcmp(opj_optarg, "2K") == 0) {
1180 profile = OPJ_PROFILE_IMF_2K;
1181 } else if (strcmp(opj_optarg, "4K") == 0) {
1182 profile = OPJ_PROFILE_IMF_4K;
1183 } else if (strcmp(opj_optarg, "8K") == 0) {
1184 profile = OPJ_PROFILE_IMF_8K;
1185 } else if (strcmp(opj_optarg, "2K_R") == 0) {
1186 profile = OPJ_PROFILE_IMF_2K_R;
1187 } else if (strcmp(opj_optarg, "4K_R") == 0) {
1188 profile = OPJ_PROFILE_IMF_4K_R;
1189 } else if (strcmp(opj_optarg, "8K_R") == 0) {
1190 profile = OPJ_PROFILE_IMF_8K_R;
1192 fprintf(stderr, "%s", msg);
1196 if (!(mainlevel >= 0 && mainlevel <= 15)) {
1197 /* Voluntarily rough validation. More fine grained done in library */
1198 fprintf(stderr, "Invalid mainlevel value.\n");
1201 if (!(sublevel >= 0 && sublevel <= 15)) {
1202 /* Voluntarily rough validation. More fine grained done in library */
1203 fprintf(stderr, "Invalid sublevel value.\n");
1206 parameters->rsiz = (OPJ_UINT16)(profile | (sublevel << 4) | mainlevel);
1208 fprintf(stdout, "IMF profile activated\n"
1209 "Other options specified could be overridden\n");
1211 if (pOutFramerate) {
1212 *pOutFramerate = framerate;
1214 if (framerate > 0 && sublevel > 0 && sublevel <= 9) {
1215 const int limitMBitsSec[] = {
1217 OPJ_IMF_SUBLEVEL_1_MBITSSEC,
1218 OPJ_IMF_SUBLEVEL_2_MBITSSEC,
1219 OPJ_IMF_SUBLEVEL_3_MBITSSEC,
1220 OPJ_IMF_SUBLEVEL_4_MBITSSEC,
1221 OPJ_IMF_SUBLEVEL_5_MBITSSEC,
1222 OPJ_IMF_SUBLEVEL_6_MBITSSEC,
1223 OPJ_IMF_SUBLEVEL_7_MBITSSEC,
1224 OPJ_IMF_SUBLEVEL_8_MBITSSEC,
1225 OPJ_IMF_SUBLEVEL_9_MBITSSEC
1227 parameters->max_cs_size = limitMBitsSec[sublevel] * (1000 * 1000 / 8) /
1229 fprintf(stdout, "Setting max codestream size to %d bytes.\n",
1230 parameters->max_cs_size);
1235 /* ------------------------------------------------------ */
1237 case 'Y': { /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
1239 sscanf(opj_optarg, "%d", &mct_mode);
1240 if (mct_mode < 0 || mct_mode > 2) {
1242 "MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
1245 parameters->tcp_mct = (char) mct_mode;
1249 /* ------------------------------------------------------ */
1252 case 'm': { /* mct input file */
1253 char *lFilename = opj_optarg;
1256 float *lCurrentDoublePtr;
1259 int lNbComp = 0, lTotalComp, lMctComp, i2;
1260 size_t lStrLen, lStrFread;
1263 FILE * lFile = fopen(lFilename, "r");
1264 if (lFile == NULL) {
1268 /* Set size of file and read its content*/
1269 fseek(lFile, 0, SEEK_END);
1270 lStrLen = (size_t)ftell(lFile);
1271 fseek(lFile, 0, SEEK_SET);
1272 lMatrix = (char *) malloc(lStrLen + 1);
1273 if (lMatrix == NULL) {
1277 lStrFread = fread(lMatrix, 1, lStrLen, lFile);
1279 if (lStrLen != lStrFread) {
1284 lMatrix[lStrLen] = 0;
1285 lCurrentPtr = lMatrix;
1287 /* replace ',' by 0 */
1288 while (*lCurrentPtr != 0) {
1289 if (*lCurrentPtr == ' ') {
1296 lCurrentPtr = lMatrix;
1298 lNbComp = (int)(sqrt(4 * lNbComp + 1) / 2. - 0.5);
1299 lMctComp = lNbComp * lNbComp;
1300 lTotalComp = lMctComp + lNbComp;
1301 lSpace = (float *) malloc((size_t)lTotalComp * sizeof(float));
1302 if (lSpace == NULL) {
1306 lCurrentDoublePtr = lSpace;
1307 for (i2 = 0; i2 < lMctComp; ++i2) {
1308 lStrLen = strlen(lCurrentPtr) + 1;
1309 *lCurrentDoublePtr++ = (float) atof(lCurrentPtr);
1310 lCurrentPtr += lStrLen;
1313 l_int_ptr = (int*) lCurrentDoublePtr;
1314 for (i2 = 0; i2 < lNbComp; ++i2) {
1315 lStrLen = strlen(lCurrentPtr) + 1;
1316 *l_int_ptr++ = atoi(lCurrentPtr);
1317 lCurrentPtr += lStrLen;
1320 /* TODO should not be here ! */
1321 opj_set_MCT(parameters, lSpace, (int *)(lSpace + lMctComp),
1322 (OPJ_UINT32)lNbComp);
1331 /* ------------------------------------------------------ */
1335 /* ------------------------------------------------------ */
1337 case 'W': { /* JPWL capabilities switched on */
1339 int hprot, pprot, sens, addr, size, range;
1341 /* we need to enable indexing */
1342 if (!indexfilename || !*indexfilename) {
1343 if (opj_strcpy_s(indexfilename, indexfilename_size,
1344 JPWL_PRIVATEINDEX_NAME) != 0) {
1349 /* search for different protection methods */
1351 /* break the option in comma points and parse the result */
1352 token = strtok(opj_optarg, ",");
1353 while (token != NULL) {
1355 /* search header error protection method */
1356 if (*token == 'h') {
1358 static int tile = 0, tilespec = 0, lasttileno = 0;
1360 hprot = 1; /* predefined method */
1362 if (sscanf(token, "h=%d", &hprot) == 1) {
1363 /* Main header, specified */
1364 if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1365 ((hprot >= 37) && (hprot <= 128)))) {
1366 fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n",
1370 parameters->jpwl_hprot_MH = hprot;
1372 } else if (sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
1373 /* Tile part header, specified */
1374 if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1375 ((hprot >= 37) && (hprot <= 128)))) {
1376 fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n",
1382 "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1385 if (tilespec < JPWL_MAX_NO_TILESPECS) {
1386 parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1387 parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1390 } else if (sscanf(token, "h%d", &tile) == 1) {
1391 /* Tile part header, unspecified */
1394 "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1397 if (tilespec < JPWL_MAX_NO_TILESPECS) {
1398 parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1399 parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1403 } else if (!strcmp(token, "h")) {
1404 /* Main header, unspecified */
1405 parameters->jpwl_hprot_MH = hprot;
1408 fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1414 /* search packet error protection method */
1415 if (*token == 'p') {
1417 static int pack = 0, tile = 0, packspec = 0;
1419 pprot = 1; /* predefined method */
1421 if (sscanf(token, "p=%d", &pprot) == 1) {
1422 /* Method for all tiles and all packets */
1423 if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1424 ((pprot >= 37) && (pprot <= 128)))) {
1425 fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n",
1429 parameters->jpwl_pprot_tileno[0] = 0;
1430 parameters->jpwl_pprot_packno[0] = 0;
1431 parameters->jpwl_pprot[0] = pprot;
1433 } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
1434 /* method specified from that tile on */
1435 if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1436 ((pprot >= 37) && (pprot <= 128)))) {
1437 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1442 "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1445 if (packspec < JPWL_MAX_NO_PACKSPECS) {
1446 parameters->jpwl_pprot_tileno[packspec] = tile;
1447 parameters->jpwl_pprot_packno[packspec] = 0;
1448 parameters->jpwl_pprot[packspec++] = pprot;
1451 } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
1452 /* method fully specified from that tile and that packet on */
1453 if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1454 ((pprot >= 37) && (pprot <= 128)))) {
1455 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1460 "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1464 fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1468 if (packspec < JPWL_MAX_NO_PACKSPECS) {
1469 parameters->jpwl_pprot_tileno[packspec] = tile;
1470 parameters->jpwl_pprot_packno[packspec] = pack;
1471 parameters->jpwl_pprot[packspec++] = pprot;
1474 } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
1475 /* default method from that tile and that packet on */
1476 if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1477 ((pprot >= 37) && (pprot <= 128)))) {
1478 fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1483 "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1487 fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1491 if (packspec < JPWL_MAX_NO_PACKSPECS) {
1492 parameters->jpwl_pprot_tileno[packspec] = tile;
1493 parameters->jpwl_pprot_packno[packspec] = pack;
1494 parameters->jpwl_pprot[packspec++] = pprot;
1497 } else if (sscanf(token, "p%d", &tile) == 1) {
1498 /* default from a tile on */
1501 "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1504 if (packspec < JPWL_MAX_NO_PACKSPECS) {
1505 parameters->jpwl_pprot_tileno[packspec] = tile;
1506 parameters->jpwl_pprot_packno[packspec] = 0;
1507 parameters->jpwl_pprot[packspec++] = pprot;
1511 } else if (!strcmp(token, "p")) {
1513 parameters->jpwl_pprot_tileno[0] = 0;
1514 parameters->jpwl_pprot_packno[0] = 0;
1515 parameters->jpwl_pprot[0] = pprot;
1518 fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1524 /* search sensitivity method */
1525 if (*token == 's') {
1527 static int tile = 0, tilespec = 0, lasttileno = 0;
1529 sens = 0; /* predefined: relative error */
1531 if (sscanf(token, "s=%d", &sens) == 1) {
1532 /* Main header, specified */
1533 if ((sens < -1) || (sens > 7)) {
1534 fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n",
1538 parameters->jpwl_sens_MH = sens;
1540 } else if (sscanf(token, "s%d=%d", &tile, &sens) == 2) {
1541 /* Tile part header, specified */
1542 if ((sens < -1) || (sens > 7)) {
1543 fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n",
1549 "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1552 if (tilespec < JPWL_MAX_NO_TILESPECS) {
1553 parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1554 parameters->jpwl_sens_TPH[tilespec++] = sens;
1557 } else if (sscanf(token, "s%d", &tile) == 1) {
1558 /* Tile part header, unspecified */
1561 "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1564 if (tilespec < JPWL_MAX_NO_TILESPECS) {
1565 parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1566 parameters->jpwl_sens_TPH[tilespec++] = hprot;
1569 } else if (!strcmp(token, "s")) {
1570 /* Main header, unspecified */
1571 parameters->jpwl_sens_MH = sens;
1574 fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
1578 parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
1581 /* search addressing size */
1582 if (*token == 'a') {
1585 addr = 0; /* predefined: auto */
1587 if (sscanf(token, "a=%d", &addr) == 1) {
1589 if ((addr != 0) && (addr != 2) && (addr != 4)) {
1590 fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
1593 parameters->jpwl_sens_addr = addr;
1595 } else if (!strcmp(token, "a")) {
1597 parameters->jpwl_sens_addr = addr; /* auto for default size */
1600 fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
1606 /* search sensitivity size */
1607 if (*token == 'z') {
1610 size = 1; /* predefined: 1 byte */
1612 if (sscanf(token, "z=%d", &size) == 1) {
1614 if ((size != 0) && (size != 1) && (size != 2)) {
1615 fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
1618 parameters->jpwl_sens_size = size;
1620 } else if (!strcmp(token, "a")) {
1622 parameters->jpwl_sens_size = size; /* 1 for default size */
1625 fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
1631 /* search range method */
1632 if (*token == 'g') {
1635 range = 0; /* predefined: 0 (packet) */
1637 if (sscanf(token, "g=%d", &range) == 1) {
1639 if ((range < 0) || (range > 3)) {
1640 fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
1643 parameters->jpwl_sens_range = range;
1645 } else if (!strcmp(token, "g")) {
1647 parameters->jpwl_sens_range = range;
1650 fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
1656 /* next token or bust */
1657 token = strtok(NULL, ",");
1662 fprintf(stdout, "Info: JPWL capabilities enabled\n");
1663 parameters->jpwl_epc_on = OPJ_TRUE;
1667 #endif /* USE_JPWL */
1669 /* ------------------------------------------------------ */
1671 case 'J': { /* jpip on */
1672 parameters->jpip_on = OPJ_TRUE;
1675 /* ------------------------------------------------------ */
1677 case 'A': { /* PLT markers */
1678 *pOutPLT = OPJ_TRUE;
1682 /* ------------------------------------------------------ */
1686 fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
1691 if (img_fol->set_imgdir == 1) {
1692 if (!(parameters->infile[0] == 0)) {
1693 fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together !!\n");
1696 if (img_fol->set_out_format == 0) {
1698 "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
1699 fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
1702 if (!((parameters->outfile[0] == 0))) {
1703 fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together !!\n");
1704 fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
1708 if ((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
1709 fprintf(stderr, "[ERROR] Required parameters are missing\n"
1710 "Example: %s -i image.pgm -o image.j2k\n", argv[0]);
1711 fprintf(stderr, " Help: %s -h\n", argv[0]);
1716 if ((parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0)
1717 || (parameters->decod_format == RAWL_DFMT && raw_cp->rawWidth == 0)) {
1718 fprintf(stderr, "[ERROR] invalid raw image parameters\n");
1719 fprintf(stderr, "Please use the Format option -F:\n");
1721 "-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1722 fprintf(stderr, "Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1723 fprintf(stderr, "Aborting\n");
1727 if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc ||
1728 parameters->cp_fixed_quality)
1729 && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^
1730 parameters->cp_fixed_quality))) {
1731 fprintf(stderr, "[ERROR] options -r -q and -f cannot be used together !!\n");
1733 } /* mod fixed_quality */
1736 /* if no rate entered, lossless by default */
1737 /* Note: post v2.2.0, this is no longer necessary, but for released */
1738 /* versions at the time of writing, this is needed to avoid crashes */
1739 if (parameters->tcp_numlayers == 0) {
1740 parameters->tcp_rates[0] = 0;
1741 parameters->tcp_numlayers++;
1742 parameters->cp_disto_alloc = 1;
1745 if ((parameters->cp_tx0 > parameters->image_offset_x0) ||
1746 (parameters->cp_ty0 > parameters->image_offset_y0)) {
1748 "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
1749 parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0,
1750 parameters->image_offset_y0);
1754 for (i = 0; i < parameters->numpocs; i++) {
1755 if (parameters->POC[i].prg == -1) {
1757 "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
1762 /* If subsampled image is provided, automatically disable MCT */
1763 if (((parameters->decod_format == RAW_DFMT) ||
1764 (parameters->decod_format == RAWL_DFMT))
1765 && (((raw_cp->rawComp > 1) && ((raw_cp->rawComps[1].dx > 1) ||
1766 (raw_cp->rawComps[1].dy > 1)))
1767 || ((raw_cp->rawComp > 2) && ((raw_cp->rawComps[2].dx > 1) ||
1768 (raw_cp->rawComps[2].dy > 1)))
1770 parameters->tcp_mct = 0;
1777 /* -------------------------------------------------------------------------- */
1780 sample error debug callback expecting no client object
1782 static void error_callback(const char *msg, void *client_data)
1785 fprintf(stdout, "[ERROR] %s", msg);
1788 sample warning debug callback expecting no client object
1790 static void warning_callback(const char *msg, void *client_data)
1793 fprintf(stdout, "[WARNING] %s", msg);
1796 sample debug callback expecting no client object
1798 static void info_callback(const char *msg, void *client_data)
1801 fprintf(stdout, "[INFO] %s", msg);
1804 OPJ_FLOAT64 opj_clock(void)
1807 /* _WIN32: use QueryPerformance (very accurate) */
1808 LARGE_INTEGER freq, t ;
1809 /* freq is the clock speed of the CPU */
1810 QueryPerformanceFrequency(&freq) ;
1811 /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
1812 /* t is the high resolution performance counter (see MSDN) */
1813 QueryPerformanceCounter(& t) ;
1814 return freq.QuadPart ? ((OPJ_FLOAT64) t.QuadPart / (OPJ_FLOAT64) freq.QuadPart)
1817 /* Unix or Linux: use resource usage */
1819 OPJ_FLOAT64 procTime;
1820 /* (1) Get the rusage data structure at this moment (man getrusage) */
1822 /* (2) What is the elapsed time ? - CPU time = User time + System time */
1823 /* (2a) Get the seconds */
1824 procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
1825 /* (2b) More precisely! Get the microseconds part ! */
1826 return (procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) *
1832 /* -------------------------------------------------------------------------- */
1836 /* -------------------------------------------------------------------------- */
1837 int main(int argc, char **argv)
1840 opj_cparameters_t parameters; /* compression parameters */
1842 opj_stream_t *l_stream = 00;
1843 opj_codec_t* l_codec = 00;
1844 opj_image_t *image = NULL;
1845 raw_cparameters_t raw_cp;
1846 OPJ_SIZE_T num_compressed_files = 0;
1848 char indexfilename[OPJ_PATH_LEN]; /* index file name */
1850 unsigned int i, num_images, imageno;
1852 dircnt_t *dirptr = NULL;
1857 OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
1858 OPJ_UINT32 l_nb_tiles = 4;
1860 OPJ_FLOAT64 t = opj_clock();
1862 OPJ_BOOL PLT = OPJ_FALSE;
1864 /* set encoding parameters to default values */
1865 opj_set_default_encoder_parameters(¶meters);
1867 /* Initialize indexfilename and img_fol */
1869 memset(&img_fol, 0, sizeof(img_fol_t));
1871 /* raw_cp initialization */
1872 raw_cp.rawBitDepth = 0;
1874 raw_cp.rawComps = 0;
1875 raw_cp.rawHeight = 0;
1876 raw_cp.rawSigned = 0;
1877 raw_cp.rawWidth = 0;
1879 /* parse input and get user encoding parameters */
1880 parameters.tcp_mct = (char)
1881 255; /* This will be set later according to the input image or the provided option */
1882 if (parse_cmdline_encoder(argc, argv, ¶meters, &img_fol, &raw_cp,
1883 indexfilename, sizeof(indexfilename), &framerate, &PLT) == 1) {
1888 /* Read directory if necessary */
1889 if (img_fol.set_imgdir == 1) {
1890 num_images = get_num_images(img_fol.imgdirpath);
1891 dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
1893 dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
1894 char)); /* Stores at max 10 image file names*/
1895 dirptr->filename = (char**) malloc(num_images * sizeof(char*));
1896 if (!dirptr->filename_buf) {
1900 for (i = 0; i < num_images; i++) {
1901 dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
1904 if (load_images(dirptr, img_fol.imgdirpath) == 1) {
1908 if (num_images == 0) {
1909 fprintf(stdout, "Folder is empty\n");
1916 /*Encoding image one by one*/
1917 for (imageno = 0; imageno < num_images; imageno++) {
1919 fprintf(stderr, "\n");
1921 if (img_fol.set_imgdir == 1) {
1922 if (get_next_file((int)imageno, dirptr, &img_fol, ¶meters)) {
1923 fprintf(stderr, "skipping file...\n");
1928 switch (parameters.decod_format) {
1945 fprintf(stderr, "skipping file...\n");
1949 /* decode the source image */
1950 /* ----------------------- */
1952 switch (parameters.decod_format) {
1954 image = pgxtoimage(parameters.infile, ¶meters);
1956 fprintf(stderr, "Unable to load pgx file\n");
1963 image = pnmtoimage(parameters.infile, ¶meters);
1965 fprintf(stderr, "Unable to load pnm file\n");
1972 image = bmptoimage(parameters.infile, ¶meters);
1974 fprintf(stderr, "Unable to load bmp file\n");
1980 #ifdef OPJ_HAVE_LIBTIFF
1982 image = tiftoimage(parameters.infile, ¶meters);
1984 fprintf(stderr, "Unable to load tiff file\n");
1989 #endif /* OPJ_HAVE_LIBTIFF */
1992 image = rawtoimage(parameters.infile, ¶meters, &raw_cp);
1994 fprintf(stderr, "Unable to load raw file\n");
2001 image = rawltoimage(parameters.infile, ¶meters, &raw_cp);
2003 fprintf(stderr, "Unable to load raw file\n");
2010 image = tgatoimage(parameters.infile, ¶meters);
2012 fprintf(stderr, "Unable to load tga file\n");
2018 #ifdef OPJ_HAVE_LIBPNG
2020 image = pngtoimage(parameters.infile, ¶meters);
2022 fprintf(stderr, "Unable to load png file\n");
2027 #endif /* OPJ_HAVE_LIBPNG */
2030 /* Can happen if input file is TIFF or PNG
2031 * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
2034 fprintf(stderr, "Unable to load file: got no image\n");
2039 /* Decide if MCT should be used */
2040 if (parameters.tcp_mct == (char)
2041 255) { /* mct mode has not been set in commandline */
2042 parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;
2043 } else { /* mct mode has been set in commandline */
2044 if ((parameters.tcp_mct == 1) && (image->numcomps < 3)) {
2045 fprintf(stderr, "RGB->YCC conversion cannot be used:\n");
2046 fprintf(stderr, "Input image has less than 3 components\n");
2050 if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {
2051 fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
2052 fprintf(stderr, "has been provided. Aborting.\n");
2058 if (OPJ_IS_IMF(parameters.rsiz) && framerate > 0) {
2059 const int mainlevel = OPJ_GET_IMF_MAINLEVEL(parameters.rsiz);
2060 if (mainlevel > 0 && mainlevel <= OPJ_IMF_MAINLEVEL_MAX) {
2061 const int limitMSamplesSec[] = {
2063 OPJ_IMF_MAINLEVEL_1_MSAMPLESEC,
2064 OPJ_IMF_MAINLEVEL_2_MSAMPLESEC,
2065 OPJ_IMF_MAINLEVEL_3_MSAMPLESEC,
2066 OPJ_IMF_MAINLEVEL_4_MSAMPLESEC,
2067 OPJ_IMF_MAINLEVEL_5_MSAMPLESEC,
2068 OPJ_IMF_MAINLEVEL_6_MSAMPLESEC,
2069 OPJ_IMF_MAINLEVEL_7_MSAMPLESEC,
2070 OPJ_IMF_MAINLEVEL_8_MSAMPLESEC,
2071 OPJ_IMF_MAINLEVEL_9_MSAMPLESEC,
2072 OPJ_IMF_MAINLEVEL_10_MSAMPLESEC,
2073 OPJ_IMF_MAINLEVEL_11_MSAMPLESEC
2075 OPJ_UINT32 avgcomponents = image->numcomps;
2076 double msamplespersec;
2077 if (image->numcomps == 3 &&
2078 image->comps[1].dx == 2 &&
2079 image->comps[1].dy == 2) {
2082 msamplespersec = (double)image->x1 * image->y1 * avgcomponents * framerate /
2084 if (msamplespersec > limitMSamplesSec[mainlevel]) {
2086 "Warning: MSamples/sec is %f, whereas limit is %d.\n",
2088 limitMSamplesSec[mainlevel]);
2093 /* encode the destination image */
2094 /* ---------------------------- */
2096 switch (parameters.cod_format) {
2097 case J2K_CFMT: { /* JPEG-2000 codestream */
2098 /* Get a decoder handle */
2099 l_codec = opj_create_compress(OPJ_CODEC_J2K);
2102 case JP2_CFMT: { /* JPEG 2000 compressed image data */
2103 /* Get a decoder handle */
2104 l_codec = opj_create_compress(OPJ_CODEC_JP2);
2108 fprintf(stderr, "skipping file..\n");
2109 opj_stream_destroy(l_stream);
2113 /* catch events using our callbacks and give a local context */
2114 opj_set_info_handler(l_codec, info_callback, 00);
2115 opj_set_warning_handler(l_codec, warning_callback, 00);
2116 opj_set_error_handler(l_codec, error_callback, 00);
2119 parameters.cp_tx0 = 0;
2120 parameters.cp_ty0 = 0;
2121 parameters.tile_size_on = OPJ_TRUE;
2122 parameters.cp_tdx = 512;
2123 parameters.cp_tdy = 512;
2125 if (! opj_setup_encoder(l_codec, ¶meters, image)) {
2126 fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
2127 opj_destroy_codec(l_codec);
2128 opj_image_destroy(image);
2134 const char* const options[] = { "PLT=YES", NULL };
2135 if (!opj_encoder_set_extra_options(l_codec, options)) {
2136 fprintf(stderr, "failed to encode image: opj_encoder_set_extra_options\n");
2137 opj_destroy_codec(l_codec);
2138 opj_image_destroy(image);
2144 /* open a byte stream for writing and allocate memory for all tiles */
2145 l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);
2151 /* encode the image */
2152 bSuccess = opj_start_compress(l_codec, image, l_stream);
2154 fprintf(stderr, "failed to encode image: opj_start_compress\n");
2156 if (bSuccess && bUseTiles) {
2158 OPJ_UINT32 l_data_size = 512 * 512 * 3;
2159 l_data = (OPJ_BYTE*) calloc(1, l_data_size);
2160 if (l_data == NULL) {
2164 for (i = 0; i < l_nb_tiles; ++i) {
2165 if (! opj_write_tile(l_codec, i, l_data, l_data_size, l_stream)) {
2166 fprintf(stderr, "ERROR -> test_tile_encoder: failed to write the tile %d!\n",
2168 opj_stream_destroy(l_stream);
2169 opj_destroy_codec(l_codec);
2170 opj_image_destroy(image);
2177 bSuccess = bSuccess && opj_encode(l_codec, l_stream);
2179 fprintf(stderr, "failed to encode image: opj_encode\n");
2182 bSuccess = bSuccess && opj_end_compress(l_codec, l_stream);
2184 fprintf(stderr, "failed to encode image: opj_end_compress\n");
2188 opj_stream_destroy(l_stream);
2189 opj_destroy_codec(l_codec);
2190 opj_image_destroy(image);
2191 fprintf(stderr, "failed to encode image\n");
2192 remove(parameters.outfile);
2197 num_compressed_files++;
2198 fprintf(stdout, "[INFO] Generated outfile %s\n", parameters.outfile);
2199 /* close and free the byte stream */
2200 opj_stream_destroy(l_stream);
2202 /* free remaining compression structures */
2203 opj_destroy_codec(l_codec);
2205 /* free image data */
2206 opj_image_destroy(image);
2210 t = opj_clock() - t;
2211 if (num_compressed_files) {
2212 fprintf(stdout, "encode time: %d ms \n",
2213 (int)((t * 1000.0) / (OPJ_FLOAT64)num_compressed_files));
2219 if (parameters.cp_comment) {
2220 free(parameters.cp_comment);
2222 if (parameters.cp_matrice) {
2223 free(parameters.cp_matrice);
2225 if (raw_cp.rawComps) {
2226 free(raw_cp.rawComps);
2228 if (img_fol.imgdirpath) {
2229 free(img_fol.imgdirpath);
2232 if (dirptr->filename_buf) {
2233 free(dirptr->filename_buf);
2235 if (dirptr->filename) {
2236 free(dirptr->filename);