Reformat whole codebase with astyle.options (#128)
[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 * cblockh_init > 4096 || cblockw_init > 1024
956                     || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
957                 fprintf(stderr,
958                         "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
959                         "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
960                 return 1;
961             }
962             parameters->cblockw_init = cblockw_init;
963             parameters->cblockh_init = cblockh_init;
964         }
965         break;
966
967         /* ----------------------------------------------------- */
968
969         case 'x': {         /* creation of index file */
970             char *index = opj_optarg;
971             strncpy(indexfilename, index, OPJ_PATH_LEN);
972         }
973         break;
974
975         /* ----------------------------------------------------- */
976
977         case 'p': {         /* progression order */
978             char progression[4];
979
980             strncpy(progression, opj_optarg, 4);
981             parameters->prog_order = give_progression(progression);
982             if (parameters->prog_order == -1) {
983                 fprintf(stderr, "Unrecognized progression order "
984                         "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
985                 return 1;
986             }
987         }
988         break;
989
990         /* ----------------------------------------------------- */
991
992         case 's': {         /* subsampling factor */
993             if (sscanf(opj_optarg, "%d,%d", &parameters->subsampling_dx,
994                        &parameters->subsampling_dy) != 2) {
995                 fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
996                 return 1;
997             }
998         }
999         break;
1000
1001         /* ----------------------------------------------------- */
1002
1003         case 'd': {         /* coordonnate of the reference grid */
1004             if (sscanf(opj_optarg, "%d,%d", &parameters->image_offset_x0,
1005                        &parameters->image_offset_y0) != 2) {
1006                 fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
1007                         "error !! [-d x0,y0]\n");
1008                 return 1;
1009             }
1010         }
1011         break;
1012
1013         /* ----------------------------------------------------- */
1014
1015         case 'h':           /* display an help description */
1016             encode_help_display();
1017             return 1;
1018
1019         /* ----------------------------------------------------- */
1020
1021         case 'P': {         /* POC */
1022             int numpocs = 0;        /* number of progression order change (POC) default 0 */
1023             opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
1024
1025             char *s = opj_optarg;
1026             POC = parameters->POC;
1027
1028             while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
1029                           &POC[numpocs].resno0, &POC[numpocs].compno0,
1030                           &POC[numpocs].layno1, &POC[numpocs].resno1,
1031                           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
1032                 POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
1033                 numpocs++;
1034                 while (*s && *s != '/') {
1035                     s++;
1036                 }
1037                 if (!*s) {
1038                     break;
1039                 }
1040                 s++;
1041             }
1042             parameters->numpocs = numpocs;
1043         }
1044         break;
1045
1046         /* ------------------------------------------------------ */
1047
1048         case 'S': {         /* SOP marker */
1049             parameters->csty |= 0x02;
1050         }
1051         break;
1052
1053         /* ------------------------------------------------------ */
1054
1055         case 'E': {         /* EPH marker */
1056             parameters->csty |= 0x04;
1057         }
1058         break;
1059
1060         /* ------------------------------------------------------ */
1061
1062         case 'M': {         /* Mode switch pas tous au point !! */
1063             int value = 0;
1064             if (sscanf(opj_optarg, "%d", &value) == 1) {
1065                 for (i = 0; i <= 5; i++) {
1066                     int cache = value & (1 << i);
1067                     if (cache) {
1068                         parameters->mode |= (1 << i);
1069                     }
1070                 }
1071             }
1072         }
1073         break;
1074
1075         /* ------------------------------------------------------ */
1076
1077         case 'R': {         /* ROI */
1078             if (sscanf(opj_optarg, "c=%d,U=%d", &parameters->roi_compno,
1079                        &parameters->roi_shift) != 2) {
1080                 fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
1081                 return 1;
1082             }
1083         }
1084         break;
1085
1086         /* ------------------------------------------------------ */
1087
1088         case 'T': {         /* Tile offset */
1089             if (sscanf(opj_optarg, "%d,%d", &parameters->cp_tx0,
1090                        &parameters->cp_ty0) != 2) {
1091                 fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
1092                 return 1;
1093             }
1094         }
1095         break;
1096
1097         /* ------------------------------------------------------ */
1098
1099         case 'C': {         /* add a comment */
1100             parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
1101             if (parameters->cp_comment) {
1102                 strcpy(parameters->cp_comment, opj_optarg);
1103             }
1104         }
1105         break;
1106
1107
1108         /* ------------------------------------------------------ */
1109
1110         case 'I': {         /* reversible or not */
1111             parameters->irreversible = 1;
1112         }
1113         break;
1114
1115         /* ------------------------------------------------------ */
1116
1117         case 'u': {         /* Tile part generation*/
1118             parameters->tp_flag = opj_optarg[0];
1119             parameters->tp_on = 1;
1120         }
1121         break;
1122
1123         /* ------------------------------------------------------ */
1124
1125         case 'z': {         /* Image Directory path */
1126             img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
1127             strcpy(img_fol->imgdirpath, opj_optarg);
1128             img_fol->set_imgdir = 1;
1129         }
1130         break;
1131
1132         /* ------------------------------------------------------ */
1133
1134         case 'w': {         /* Digital Cinema 2K profile compliance*/
1135             int fps = 0;
1136             sscanf(opj_optarg, "%d", &fps);
1137             if (fps == 24) {
1138                 parameters->cp_cinema = CINEMA2K_24;
1139             } else if (fps == 48) {
1140                 parameters->cp_cinema = CINEMA2K_48;
1141             } else {
1142                 fprintf(stderr, "Incorrect value!! must be 24 or 48\n");
1143                 return 1;
1144             }
1145             fprintf(stdout, "CINEMA 2K compliant codestream\n");
1146             parameters->cp_rsiz = CINEMA2K;
1147
1148         }
1149         break;
1150
1151         /* ------------------------------------------------------ */
1152
1153         case 'y': {         /* Digital Cinema 4K profile compliance*/
1154             parameters->cp_cinema = CINEMA4K_24;
1155             fprintf(stdout, "CINEMA 4K compliant codestream\n");
1156             parameters->cp_rsiz = CINEMA4K;
1157         }
1158         break;
1159
1160             /* ------------------------------------------------------ */
1161
1162             /* UniPG>> */
1163 #ifdef USE_JPWL
1164         /* ------------------------------------------------------ */
1165
1166         case 'W': {         /* JPWL capabilities switched on */
1167             char *token = NULL;
1168             int hprot, pprot, sens, addr, size, range;
1169
1170             /* we need to enable indexing */
1171             if (!indexfilename || !*indexfilename) {
1172                 strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);
1173             }
1174
1175             /* search for different protection methods */
1176
1177             /* break the option in comma points and parse the result */
1178             token = strtok(opj_optarg, ",");
1179             while (token != NULL) {
1180
1181                 /* search header error protection method */
1182                 if (*token == 'h') {
1183
1184                     static int tile = 0, tilespec = 0, lasttileno = 0;
1185
1186                     hprot = 1; /* predefined method */
1187
1188                     if (sscanf(token, "h=%d", &hprot) == 1) {
1189                         /* Main header, specified */
1190                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1191                                 ((hprot >= 37) && (hprot <= 128)))) {
1192                             fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n",
1193                                     hprot);
1194                             return 1;
1195                         }
1196                         parameters->jpwl_hprot_MH = hprot;
1197
1198                     } else if (sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
1199                         /* Tile part header, specified */
1200                         if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
1201                                 ((hprot >= 37) && (hprot <= 128)))) {
1202                             fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n",
1203                                     hprot);
1204                             return 1;
1205                         }
1206                         if (tile < 0) {
1207                             fprintf(stderr,
1208                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1209                             return 1;
1210                         }
1211                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1212                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1213                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1214                         }
1215
1216                     } else if (sscanf(token, "h%d", &tile) == 1) {
1217                         /* Tile part header, unspecified */
1218                         if (tile < 0) {
1219                             fprintf(stderr,
1220                                     "ERROR -> invalid tile part number on protection method t = %d\n", tile);
1221                             return 1;
1222                         }
1223                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1224                             parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
1225                             parameters->jpwl_hprot_TPH[tilespec++] = hprot;
1226                         }
1227
1228
1229                     } else if (!strcmp(token, "h")) {
1230                         /* Main header, unspecified */
1231                         parameters->jpwl_hprot_MH = hprot;
1232
1233                     } else {
1234                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1235                         return 1;
1236                     };
1237
1238                 }
1239
1240                 /* search packet error protection method */
1241                 if (*token == 'p') {
1242
1243                     static int pack = 0, tile = 0, packspec = 0;
1244
1245                     pprot = 1; /* predefined method */
1246
1247                     if (sscanf(token, "p=%d", &pprot) == 1) {
1248                         /* Method for all tiles and all packets */
1249                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1250                                 ((pprot >= 37) && (pprot <= 128)))) {
1251                             fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n",
1252                                     pprot);
1253                             return 1;
1254                         }
1255                         parameters->jpwl_pprot_tileno[0] = 0;
1256                         parameters->jpwl_pprot_packno[0] = 0;
1257                         parameters->jpwl_pprot[0] = pprot;
1258
1259                     } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
1260                         /* method specified from that tile on */
1261                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1262                                 ((pprot >= 37) && (pprot <= 128)))) {
1263                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1264                             return 1;
1265                         }
1266                         if (tile < 0) {
1267                             fprintf(stderr,
1268                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1269                             return 1;
1270                         }
1271                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1272                             parameters->jpwl_pprot_tileno[packspec] = tile;
1273                             parameters->jpwl_pprot_packno[packspec] = 0;
1274                             parameters->jpwl_pprot[packspec++] = pprot;
1275                         }
1276
1277                     } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
1278                         /* method fully specified from that tile and that packet on */
1279                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1280                                 ((pprot >= 37) && (pprot <= 128)))) {
1281                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1282                             return 1;
1283                         }
1284                         if (tile < 0) {
1285                             fprintf(stderr,
1286                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1287                             return 1;
1288                         }
1289                         if (pack < 0) {
1290                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1291                                     pack);
1292                             return 1;
1293                         }
1294                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1295                             parameters->jpwl_pprot_tileno[packspec] = tile;
1296                             parameters->jpwl_pprot_packno[packspec] = pack;
1297                             parameters->jpwl_pprot[packspec++] = pprot;
1298                         }
1299
1300                     } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
1301                         /* default method from that tile and that packet on */
1302                         if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
1303                                 ((pprot >= 37) && (pprot <= 128)))) {
1304                             fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
1305                             return 1;
1306                         }
1307                         if (tile < 0) {
1308                             fprintf(stderr,
1309                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1310                             return 1;
1311                         }
1312                         if (pack < 0) {
1313                             fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n",
1314                                     pack);
1315                             return 1;
1316                         }
1317                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1318                             parameters->jpwl_pprot_tileno[packspec] = tile;
1319                             parameters->jpwl_pprot_packno[packspec] = pack;
1320                             parameters->jpwl_pprot[packspec++] = pprot;
1321                         }
1322
1323                     } else if (sscanf(token, "p%d", &tile) == 1) {
1324                         /* default from a tile on */
1325                         if (tile < 0) {
1326                             fprintf(stderr,
1327                                     "ERROR -> invalid tile part number on protection method p = %d\n", tile);
1328                             return 1;
1329                         }
1330                         if (packspec < JPWL_MAX_NO_PACKSPECS) {
1331                             parameters->jpwl_pprot_tileno[packspec] = tile;
1332                             parameters->jpwl_pprot_packno[packspec] = 0;
1333                             parameters->jpwl_pprot[packspec++] = pprot;
1334                         }
1335
1336
1337                     } else if (!strcmp(token, "p")) {
1338                         /* all default */
1339                         parameters->jpwl_pprot_tileno[0] = 0;
1340                         parameters->jpwl_pprot_packno[0] = 0;
1341                         parameters->jpwl_pprot[0] = pprot;
1342
1343                     } else {
1344                         fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
1345                         return 1;
1346                     };
1347
1348                 }
1349
1350                 /* search sensitivity method */
1351                 if (*token == 's') {
1352
1353                     static int tile = 0, tilespec = 0, lasttileno = 0;
1354
1355                     sens = 0; /* predefined: relative error */
1356
1357                     if (sscanf(token, "s=%d", &sens) == 1) {
1358                         /* Main header, specified */
1359                         if ((sens < -1) || (sens > 7)) {
1360                             fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n",
1361                                     sens);
1362                             return 1;
1363                         }
1364                         parameters->jpwl_sens_MH = sens;
1365
1366                     } else if (sscanf(token, "s%d=%d", &tile, &sens) == 2) {
1367                         /* Tile part header, specified */
1368                         if ((sens < -1) || (sens > 7)) {
1369                             fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n",
1370                                     sens);
1371                             return 1;
1372                         }
1373                         if (tile < 0) {
1374                             fprintf(stderr,
1375                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1376                             return 1;
1377                         }
1378                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1379                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1380                             parameters->jpwl_sens_TPH[tilespec++] = sens;
1381                         }
1382
1383                     } else if (sscanf(token, "s%d", &tile) == 1) {
1384                         /* Tile part header, unspecified */
1385                         if (tile < 0) {
1386                             fprintf(stderr,
1387                                     "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
1388                             return 1;
1389                         }
1390                         if (tilespec < JPWL_MAX_NO_TILESPECS) {
1391                             parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
1392                             parameters->jpwl_sens_TPH[tilespec++] = hprot;
1393                         }
1394
1395                     } else if (!strcmp(token, "s")) {
1396                         /* Main header, unspecified */
1397                         parameters->jpwl_sens_MH = sens;
1398
1399                     } else {
1400                         fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
1401                         return 1;
1402                     };
1403
1404                     parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
1405                 }
1406
1407                 /* search addressing size */
1408                 if (*token == 'a') {
1409
1410
1411                     addr = 0; /* predefined: auto */
1412
1413                     if (sscanf(token, "a=%d", &addr) == 1) {
1414                         /* Specified */
1415                         if ((addr != 0) && (addr != 2) && (addr != 4)) {
1416                             fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
1417                             return 1;
1418                         }
1419                         parameters->jpwl_sens_addr = addr;
1420
1421                     } else if (!strcmp(token, "a")) {
1422                         /* default */
1423                         parameters->jpwl_sens_addr = addr; /* auto for default size */
1424
1425                     } else {
1426                         fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
1427                         return 1;
1428                     };
1429
1430                 }
1431
1432                 /* search sensitivity size */
1433                 if (*token == 'z') {
1434
1435
1436                     size = 1; /* predefined: 1 byte */
1437
1438                     if (sscanf(token, "z=%d", &size) == 1) {
1439                         /* Specified */
1440                         if ((size != 0) && (size != 1) && (size != 2)) {
1441                             fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
1442                             return 1;
1443                         }
1444                         parameters->jpwl_sens_size = size;
1445
1446                     } else if (!strcmp(token, "a")) {
1447                         /* default */
1448                         parameters->jpwl_sens_size = size; /* 1 for default size */
1449
1450                     } else {
1451                         fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
1452                         return 1;
1453                     };
1454
1455                 }
1456
1457                 /* search range method */
1458                 if (*token == 'g') {
1459
1460
1461                     range = 0; /* predefined: 0 (packet) */
1462
1463                     if (sscanf(token, "g=%d", &range) == 1) {
1464                         /* Specified */
1465                         if ((range < 0) || (range > 3)) {
1466                             fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
1467                             return 1;
1468                         }
1469                         parameters->jpwl_sens_range = range;
1470
1471                     } else if (!strcmp(token, "g")) {
1472                         /* default */
1473                         parameters->jpwl_sens_range = range;
1474
1475                     } else {
1476                         fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
1477                         return 1;
1478                     };
1479
1480                 }
1481
1482                 /* next token or bust */
1483                 token = strtok(NULL, ",");
1484             };
1485
1486
1487             /* some info */
1488             fprintf(stdout, "Info: JPWL capabilities enabled\n");
1489             parameters->jpwl_epc_on = OPJ_TRUE;
1490
1491         }
1492         break;
1493 #endif /* USE_JPWL */
1494         /* <<UniPG */
1495         /* ------------------------------------------------------ */
1496
1497         case 'J': {         /* jpip on */
1498             /*parameters->jpip_on = OPJ_TRUE;*/
1499         }
1500         break;
1501         /* ------------------------------------------------------ */
1502
1503
1504         default:
1505             fprintf(stderr, "ERROR -> Command line not valid\n");
1506             return 1;
1507         }
1508     } while (c != -1);
1509
1510     /* check for possible errors */
1511     if (parameters->cp_cinema) {
1512         if (parameters->tcp_numlayers > 1) {
1513             parameters->cp_rsiz = STD_RSIZ;
1514             fprintf(stdout,
1515                     "Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile\n");
1516         }
1517     }
1518     if (img_fol->set_imgdir == 1) {
1519         if (!(parameters->infile[0] == 0)) {
1520             fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
1521             return 1;
1522         }
1523         if (img_fol->set_out_format == 0) {
1524             fprintf(stderr,
1525                     "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
1526             fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
1527             return 1;
1528         }
1529         if (!((parameters->outfile[0] == 0))) {
1530             fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
1531             fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
1532             return 1;
1533         }
1534     } else {
1535         if ((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
1536             fprintf(stderr, "Example: %s -i image.ppm  -o image.j2k\n", argv[0]);
1537             fprintf(stderr, "    Try: %s -h\n", argv[0]);
1538             return 1;
1539         }
1540     }
1541
1542     if (parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0) {
1543         fprintf(stderr, "\nError: invalid raw image parameters\n");
1544         fprintf(stderr, "Please use the Format option -F:\n");
1545         fprintf(stderr,
1546                 "-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
1547         fprintf(stderr, "Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
1548         fprintf(stderr, "Aborting\n");
1549         return 1;
1550     }
1551
1552     if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc ||
1553             parameters->cp_fixed_quality)
1554             && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^
1555                   parameters->cp_fixed_quality))) {
1556         fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
1557         return 1;
1558     }               /* mod fixed_quality */
1559
1560     /* if no rate entered, lossless by default */
1561     if (parameters->tcp_numlayers == 0) {
1562         parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */
1563         parameters->tcp_numlayers++;
1564         parameters->cp_disto_alloc = 1;
1565     }
1566
1567     if ((parameters->cp_tx0 > parameters->image_offset_x0) ||
1568             (parameters->cp_ty0 > parameters->image_offset_y0)) {
1569         fprintf(stderr,
1570                 "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
1571                 parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0,
1572                 parameters->image_offset_y0);
1573         return 1;
1574     }
1575
1576     for (i = 0; i < parameters->numpocs; i++) {
1577         if (parameters->POC[i].prg == -1) {
1578             fprintf(stderr,
1579                     "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
1580                     i + 1);
1581         }
1582     }
1583
1584     return 0;
1585 }
1586
1587 /* -------------------------------------------------------------------------- */
1588
1589 /**
1590 sample error callback expecting a FILE* client object
1591 */
1592 static void error_callback(const char *msg, void *client_data)
1593 {
1594     FILE *stream = (FILE*)client_data;
1595     fprintf(stream, "[ERROR] %s", msg);
1596 }
1597 /**
1598 sample warning callback expecting a FILE* client object
1599 */
1600 static void warning_callback(const char *msg, void *client_data)
1601 {
1602     FILE *stream = (FILE*)client_data;
1603     fprintf(stream, "[WARNING] %s", msg);
1604 }
1605 /**
1606 sample debug callback expecting a FILE* client object
1607 */
1608 static void info_callback(const char *msg, void *client_data)
1609 {
1610     FILE *stream = (FILE*)client_data;
1611     fprintf(stream, "[INFO] %s", msg);
1612 }
1613
1614 /* -------------------------------------------------------------------------- */
1615
1616 int main(int argc, char **argv)
1617 {
1618     opj_bool bSuccess;
1619     opj_cparameters_t parameters;   /* compression parameters */
1620     img_fol_t img_fol;
1621     opj_event_mgr_t event_mgr;      /* event manager */
1622     opj_image_t *image = NULL;
1623     int i, num_images;
1624     int imageno;
1625     dircnt_t *dirptr = NULL;
1626     raw_cparameters_t raw_cp;
1627     opj_codestream_info_t cstr_info;        /* Codestream information structure */
1628     char indexfilename[OPJ_PATH_LEN];   /* index file name */
1629
1630     /*
1631     configure the event callbacks (not required)
1632     setting of each callback is optionnal
1633     */
1634     memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
1635     event_mgr.error_handler = error_callback;
1636     event_mgr.warning_handler = warning_callback;
1637     event_mgr.info_handler = info_callback;
1638
1639     /* set encoding parameters to default values */
1640     opj_set_default_encoder_parameters(&parameters);
1641
1642     /* Initialize indexfilename and img_fol */
1643     *indexfilename = 0;
1644     memset(&img_fol, 0, sizeof(img_fol_t));
1645
1646     /* parse input and get user encoding parameters */
1647     if (parse_cmdline_encoder(argc, argv, &parameters, &img_fol, &raw_cp,
1648                               indexfilename) == 1) {
1649         return 1;
1650     }
1651
1652     if (parameters.cp_cinema) {
1653         img_fol.rates = (float*)malloc(parameters.tcp_numlayers * sizeof(float));
1654         for (i = 0; i < parameters.tcp_numlayers; i++) {
1655             img_fol.rates[i] = parameters.tcp_rates[i];
1656         }
1657         cinema_parameters(&parameters);
1658     }
1659
1660     /* Create comment for codestream */
1661     if (parameters.cp_comment == NULL) {
1662         const char comment[] = "Created by OpenJPEG version ";
1663         const size_t clen = strlen(comment);
1664         const char *version = opj_version();
1665         /* UniPG>> */
1666 #ifdef USE_JPWL
1667         parameters.cp_comment = (char*)malloc(clen + strlen(version) + 11);
1668         sprintf(parameters.cp_comment, "%s%s with JPWL", comment, version);
1669 #else
1670         parameters.cp_comment = (char*)malloc(clen + strlen(version) + 1);
1671         sprintf(parameters.cp_comment, "%s%s", comment, version);
1672 #endif
1673         /* <<UniPG */
1674     }
1675
1676     /* Read directory if necessary */
1677     if (img_fol.set_imgdir == 1) {
1678         num_images = get_num_images(img_fol.imgdirpath);
1679         dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
1680         if (dirptr) {
1681             dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
1682                     char)); /* Stores at max 10 image file names*/
1683             dirptr->filename = (char**) malloc(num_images * sizeof(char*));
1684             if (!dirptr->filename_buf) {
1685                 return 0;
1686             }
1687             for (i = 0; i < num_images; i++) {
1688                 dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
1689             }
1690         }
1691         if (load_images(dirptr, img_fol.imgdirpath) == 1) {
1692             return 0;
1693         }
1694         if (num_images == 0) {
1695             fprintf(stdout, "Folder is empty\n");
1696             return 0;
1697         }
1698     } else {
1699         num_images = 1;
1700     }
1701     /*Encoding image one by one*/
1702     for (imageno = 0; imageno < num_images; imageno++) {
1703         image = NULL;
1704         fprintf(stderr, "\n");
1705
1706         if (img_fol.set_imgdir == 1) {
1707             if (get_next_file(imageno, dirptr, &img_fol, &parameters)) {
1708                 fprintf(stderr, "skipping file...\n");
1709                 continue;
1710             }
1711         }
1712         switch (parameters.decod_format) {
1713         case PGX_DFMT:
1714             break;
1715         case PXM_DFMT:
1716             break;
1717         case BMP_DFMT:
1718             break;
1719         case TIF_DFMT:
1720             break;
1721         case RAW_DFMT:
1722             break;
1723         case TGA_DFMT:
1724             break;
1725         case PNG_DFMT:
1726             break;
1727         default:
1728             fprintf(stderr, "skipping file...\n");
1729             continue;
1730         }
1731
1732         /* decode the source image */
1733         /* ----------------------- */
1734
1735         switch (parameters.decod_format) {
1736         case PGX_DFMT:
1737             image = pgxtoimage(parameters.infile, &parameters);
1738             if (!image) {
1739                 fprintf(stderr, "Unable to load pgx file\n");
1740                 return 1;
1741             }
1742             break;
1743
1744         case PXM_DFMT:
1745             image = pnmtoimage(parameters.infile, &parameters);
1746             if (!image) {
1747                 fprintf(stderr, "Unable to load pnm file\n");
1748                 return 1;
1749             }
1750             break;
1751
1752         case BMP_DFMT:
1753             image = bmptoimage(parameters.infile, &parameters);
1754             if (!image) {
1755                 fprintf(stderr, "Unable to load bmp file\n");
1756                 return 1;
1757             }
1758             break;
1759 #ifdef OPJ_HAVE_LIBTIFF
1760         case TIF_DFMT:
1761             image = tiftoimage(parameters.infile, &parameters);
1762             if (!image) {
1763                 fprintf(stderr, "Unable to load tiff file\n");
1764                 return 1;
1765             }
1766             break;
1767 #endif /* OPJ_HAVE_LIBTIFF */
1768         case RAW_DFMT:
1769             image = rawtoimage(parameters.infile, &parameters, &raw_cp);
1770             if (!image) {
1771                 fprintf(stderr, "Unable to load raw file\n");
1772                 return 1;
1773             }
1774             break;
1775
1776         case TGA_DFMT:
1777             image = tgatoimage(parameters.infile, &parameters);
1778             if (!image) {
1779                 fprintf(stderr, "Unable to load tga file\n");
1780                 return 1;
1781             }
1782             break;
1783 #ifdef OPJ_HAVE_LIBPNG
1784         case PNG_DFMT:
1785             image = pngtoimage(parameters.infile, &parameters);
1786             if (!image) {
1787                 fprintf(stderr, "Unable to load png file\n");
1788                 return 1;
1789             }
1790             break;
1791 #endif /* OPJ_HAVE_LIBPNG */
1792         }
1793         /* Can happen if input file is TIFF or PNG
1794          * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
1795         */
1796         if (!image) {
1797             fprintf(stderr, "Unable to load file: got no image\n");
1798             return 1;
1799         }
1800         /* Decide if MCT should be used */
1801         parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;
1802
1803         if (parameters.cp_cinema) {
1804             cinema_setup_encoder(&parameters, image, &img_fol);
1805         }
1806
1807         /* encode the destination image */
1808         /* ---------------------------- */
1809
1810         if (parameters.cod_format == J2K_CFMT) {    /* J2K format output */
1811             int codestream_length;
1812             size_t res;
1813             opj_cio_t *cio = NULL;
1814             FILE *f = NULL;
1815
1816             /* get a J2K compressor handle */
1817             opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
1818
1819             /* catch events using our callbacks and give a local context */
1820             opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
1821
1822             /* setup the encoder parameters using the current image and user parameters */
1823             opj_setup_encoder(cinfo, &parameters, image);
1824
1825             /* open a byte stream for writing */
1826             /* allocate memory for all tiles */
1827             cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
1828
1829             /* encode the image */
1830             if (*indexfilename) {               /* If need to extract codestream information*/
1831                 bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
1832             } else {
1833                 bSuccess = opj_encode(cinfo, cio, image, NULL);
1834             }
1835             if (!bSuccess) {
1836                 opj_cio_close(cio);
1837                 fprintf(stderr, "failed to encode image\n");
1838                 return 1;
1839             }
1840             codestream_length = cio_tell(cio);
1841
1842             /* write the buffer to disk */
1843             f = fopen(parameters.outfile, "wb");
1844             if (!f) {
1845                 fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
1846                 return 1;
1847             }
1848             res = fwrite(cio->buffer, 1, codestream_length, f);
1849             if (res < (size_t)codestream_length) {  /* FIXME */
1850                 fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
1851                         parameters.outfile);
1852                 return 1;
1853             }
1854             fclose(f);
1855
1856             fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
1857             /* close and free the byte stream */
1858             opj_cio_close(cio);
1859
1860             /* Write the index to disk */
1861             if (*indexfilename) {
1862                 bSuccess = write_index_file(&cstr_info, indexfilename);
1863                 if (bSuccess) {
1864                     fprintf(stderr, "Failed to output index file into [%s]\n", indexfilename);
1865                 }
1866             }
1867
1868             /* free remaining compression structures */
1869             opj_destroy_compress(cinfo);
1870             if (*indexfilename) {
1871                 opj_destroy_cstr_info(&cstr_info);
1872             }
1873         } else {            /* JP2 format output */
1874             int codestream_length;
1875             size_t res;
1876             opj_cio_t *cio = NULL;
1877             FILE *f = NULL;
1878             opj_cinfo_t *cinfo = NULL;
1879
1880             /* get a JP2 compressor handle */
1881             cinfo = opj_create_compress(CODEC_JP2);
1882
1883             /* catch events using our callbacks and give a local context */
1884             opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
1885
1886             /* setup the encoder parameters using the current image and using user parameters */
1887             opj_setup_encoder(cinfo, &parameters, image);
1888
1889             /* open a byte stream for writing */
1890             /* allocate memory for all tiles */
1891             cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
1892
1893             /* encode the image */
1894             if (*indexfilename /*|| parameters.jpip_on*/) { /* If need to extract codestream information*/
1895                 bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
1896             } else {
1897                 bSuccess = opj_encode(cinfo, cio, image, NULL);
1898             }
1899             if (!bSuccess) {
1900                 opj_cio_close(cio);
1901                 fprintf(stderr, "failed to encode image\n");
1902                 return 1;
1903             }
1904             codestream_length = cio_tell(cio);
1905
1906             /* write the buffer to disk */
1907             f = fopen(parameters.outfile, "wb");
1908             if (!f) {
1909                 fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
1910                 return 1;
1911             }
1912             res = fwrite(cio->buffer, 1, codestream_length, f);
1913             if (res < (size_t)codestream_length) {  /* FIXME */
1914                 fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
1915                         parameters.outfile);
1916                 return 1;
1917             }
1918             fclose(f);
1919             fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
1920             /* close and free the byte stream */
1921             opj_cio_close(cio);
1922
1923             /* Write the index to disk */
1924             if (*indexfilename) {
1925                 bSuccess = write_index_file(&cstr_info, indexfilename);
1926                 if (bSuccess) {
1927                     fprintf(stderr, "Failed to output index file\n");
1928                 }
1929             }
1930
1931             /* free remaining compression structures */
1932             opj_destroy_compress(cinfo);
1933             if (*indexfilename) {
1934                 opj_destroy_cstr_info(&cstr_info);
1935             }
1936         }
1937
1938         /* free image data */
1939         opj_image_destroy(image);
1940     }
1941
1942     /* free user parameters structure */
1943     if (parameters.cp_comment) {
1944         free(parameters.cp_comment);
1945     }
1946     if (parameters.cp_matrice) {
1947         free(parameters.cp_matrice);
1948     }
1949
1950     return 0;
1951 }