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