Merge pull request #1090 from stweil/utf8
[openjpeg.git] / src / bin / jp3d / opj_jp3d_compress.c
1 /*
2  * Copyright (c) 2001-2003, David Janssens
3  * Copyright (c) 2002-2003, Yannick Verschueren
4  * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
5  * Copyright (c) 2005, Herve Drolon, FreeImage Team
6  * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
7  * Copyright (c) 2006, Mónica Díez García, Image Processing Laboratory, University of Valladolid, Spain
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34
35 #include "opj_config.h"
36 #include "openjp3d.h"
37 #include "opj_getopt.h"
38 #include "convert.h"
39
40 #ifdef _WIN32
41 #include <windows.h>
42 #else
43 #define stricmp strcasecmp
44 #define strnicmp strncasecmp
45 #endif /* _WIN32 */
46
47 /* ----------------------------------------------------------------------- */
48
49 void encode_help_display()
50 {
51     fprintf(stdout, "List of parameters for the JPEG2000 Part 10 encoder:\n");
52     fprintf(stdout, "------------\n");
53     fprintf(stdout, "\n");
54     fprintf(stdout, "Required Parameters (except with -h):\n");
55     fprintf(stdout, "\n");
56     fprintf(stdout,
57             "-i           : source file  (-i source.bin or source*.pgx) \n");
58     fprintf(stdout, "\n");
59     fprintf(stdout,
60             "-m           : source characteristics file (-m imgfile.img) \n");
61     fprintf(stdout, "\n");
62     fprintf(stdout, "-o           : destination file (-o dest.jp3d) \n");
63     fprintf(stdout, "\n");
64     fprintf(stdout, "Optional Parameters:\n");
65     fprintf(stdout, "\n");
66     fprintf(stdout, "-h           : display the help information \n ");
67     fprintf(stdout, "\n");
68     fprintf(stdout, "-n           : number of resolutions (-n 3,3,3) \n");
69     fprintf(stdout, "\n");
70     fprintf(stdout,
71             "-I           : use the irreversible transforms: ICT + DWT 9-7 (-I) \n");
72     fprintf(stdout, "\n");
73     fprintf(stdout, "-C           : coding algorithm (-C 2EB) [2EB, 3EB] \n");
74     fprintf(stdout, "\n");
75     fprintf(stdout,
76             "-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
77     fprintf(stdout,
78             "            - The rate specified for each quality level is the desired compression factor.\n");
79     fprintf(stdout, "            - Rate 1 means lossless compression\n");
80     fprintf(stdout,
81             "               (options -r and -q cannot be used together)\n ");
82     fprintf(stdout, "\n");
83     fprintf(stdout,
84             "-q           : different psnr for successive layers (-q 30,40,50) \n ");
85     fprintf(stdout,
86             "               (options -r and -q cannot be used together)\n ");
87     fprintf(stdout, "\n");
88     fprintf(stdout, "-b           : size of code block (-b 32,32,32) \n");
89     fprintf(stdout, "\n");
90     fprintf(stdout, "-c           : size of precinct (-c 128,128,128) \n");
91     fprintf(stdout, "\n");
92     fprintf(stdout, "-t           : size of tile (-t 512,512,512) \n");
93     fprintf(stdout, "\n");
94     fprintf(stdout,
95             "-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
96     fprintf(stdout, "\n");
97     fprintf(stdout, "-s           : subsampling factor (-s 2,2,2) [-s X,Y,Z] \n");
98     fprintf(stdout, "                     - Remark: subsampling bigger than 2 can produce error\n");
99     fprintf(stdout, "\n");
100     fprintf(stdout, "-SOP         : write SOP marker before each packet \n");
101     fprintf(stdout, "\n");
102     fprintf(stdout, "-EPH         : write EPH marker after each header packet \n");
103     fprintf(stdout, "\n");
104     fprintf(stdout,
105             "-M           : code-block style (-M 0) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
106     fprintf(stdout, "                 8=VSC 16=PTERM 32=SEGSYM 64=3DCTXT] \n");
107     fprintf(stdout,
108             "                 Indicate multiple modes by adding their values. \n");
109     fprintf(stdout,
110             "                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
111     fprintf(stdout, "\n");
112     fprintf(stdout, "-D           : define DC offset (-D 12) \n");
113     fprintf(stdout, "\n");
114     fprintf(stdout,
115             "-x           : create an index file *.Idx (-x index_name.Idx) \n");
116     fprintf(stdout, "\n");
117     fprintf(stdout,
118             "-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
119     fprintf(stdout, "               for component c=%%d [%%d = 0,1,2]\n");
120     fprintf(stdout,
121             "               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
122     fprintf(stdout, "\n");
123     fprintf(stdout,
124             "-d           : offset of the origin of the volume (-d 150,300,100) \n");
125     fprintf(stdout, "\n");
126     fprintf(stdout,
127             "-l           : offset of the origin of the tiles (-l 100,75,25) \n");
128     fprintf(stdout, "\n");
129     fprintf(stdout, "\n");
130     fprintf(stdout, "DEFAULT CODING:\n");
131     fprintf(stdout, "------------\n");
132     fprintf(stdout, "\n");
133     fprintf(stdout, " * Lossless\n");
134     fprintf(stdout, " * 1 tile\n");
135     fprintf(stdout,
136             " * Size of precinct : 2^15 x 2^15 x 2^15 (means 1 precinct)\n");
137     fprintf(stdout, " * Size of code-block : 64 x 64 x 64\n");
138     fprintf(stdout, " * Number of resolutions in x, y and z axis: 3\n");
139     fprintf(stdout, " * No SOP marker in the codestream\n");
140     fprintf(stdout, " * No EPH marker in the codestream\n");
141     fprintf(stdout, " * No sub-sampling in x, y or z direction\n");
142     fprintf(stdout, " * No mode switch activated\n");
143     fprintf(stdout, " * Progression order: LRCP\n");
144     fprintf(stdout, " * No index file\n");
145     fprintf(stdout, " * No ROI upshifted\n");
146     fprintf(stdout, " * No offset of the origin of the volume\n");
147     fprintf(stdout, " * No offset of the origin of the tiles\n");
148     fprintf(stdout, " * Reversible DWT 5-3 on each 2D slice\n");
149     fprintf(stdout, " * Coding algorithm: 2D-EBCOT \n");
150     fprintf(stdout, "\n");
151     fprintf(stdout, "REMARKS:\n");
152     fprintf(stdout, "---------\n");
153     fprintf(stdout, "\n");
154     fprintf(stdout,
155             "- The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
156     fprintf(stdout,
157             "- COD and QCD markers will never appear in the tile_header.\n");
158     fprintf(stdout, "\n");
159     fprintf(stdout,
160             "- You need enough disk space memory (twice the original) to encode \n");
161     fprintf(stdout,
162             "the volume,i.e. for a 1.5 GB volume you need a minimum of 3GB of disk memory)\n");
163     fprintf(stdout, "\n");
164     fprintf(stdout,
165             "- When loading *.pgx files, a relative path to directory is needed for input argument \n");
166     fprintf(stdout,
167             " followed by the common prefix of the slices and a '*' character representing sequential numeration.\n");
168     fprintf(stdout, "( -i relativepath/slices*.pgx )\n");
169     fprintf(stdout, "\n");
170     fprintf(stdout, " - The index file has the structure below:\n");
171     fprintf(stdout, "\n");
172     fprintf(stdout, "\t Image_height Image_width Image_depth\n");
173     fprintf(stdout, "\t Progression order: 0 (LRCP)\n");
174     fprintf(stdout, "\t Tiles_size_X Tiles_size_Y Tiles_size_Z\n");
175     fprintf(stdout, "\t Components_nb\n");
176     fprintf(stdout, "\t Layers_nb\n");
177     fprintf(stdout, "\t Decomposition_levels\n");
178     fprintf(stdout,
179             "\t [Precincts_size_X_res_Nr Precincts_size_Y_res_Nr Precincts_size_Z_res_Nr]\n\t  ...\n");
180     fprintf(stdout,
181             "\t [Precincts_size_X_res_0 Precincts_size_Y_res_0 Precincts_size_Z_res_0]\n");
182     fprintf(stdout, "\t Main_header_end_position\n");
183     fprintf(stdout, "\t Codestream_size\n");
184     fprintf(stdout,
185             "\t Tile_0 [start_pos end_header end_pos TotalDisto NumPix MaxMSE]\n");
186     fprintf(stdout, "\t ...\n");
187     fprintf(stdout,
188             "\t Tile_Nt [  ''         ''        ''        ''       ''    ''  ]\n");
189     fprintf(stdout,
190             "\t  Tpacket_0 [Tile layer res. comp. prec. start_pos end_pos disto]\n");
191     fprintf(stdout, "\t  ...\n");
192     fprintf(stdout,
193             "\t  Tpacket_Np [''   ''    ''   ''    ''       ''       ''     '' ]\n");
194     fprintf(stdout, "\t  MaxDisto\n");
195     fprintf(stdout, "\t  TotalDisto\n\n");
196     fprintf(stdout, "\n");
197
198 }
199
200 OPJ_PROG_ORDER give_progression(char progression[4])
201 {
202     if (strncmp(progression, "LRCP", 4) == 0) {
203         return LRCP;
204     }
205     if (strncmp(progression, "RLCP", 4) == 0) {
206         return RLCP;
207     }
208     if (strncmp(progression, "RPCL", 4) == 0) {
209         return RPCL;
210     }
211     if (strncmp(progression, "PCRL", 4) == 0) {
212         return PCRL;
213     }
214     if (strncmp(progression, "CPRL", 4) == 0) {
215         return CPRL;
216     }
217
218     return PROG_UNKNOWN;
219 }
220
221 OPJ_TRANSFORM give_transform(char transform[4])
222 {
223     if (strncmp(transform, "2DWT", 4) == 0) {
224         return TRF_2D_DWT;
225     }
226     if (strncmp(transform, "3DWT", 4) == 0) {
227         return TRF_3D_DWT;
228     }
229     return TRF_UNKNOWN;
230 }
231
232 OPJ_ENTROPY_CODING give_coding(char coding[3])
233 {
234
235     if (strncmp(coding, "2EB", 3) == 0) {
236         return ENCOD_2EB;
237     }
238     if (strncmp(coding, "3EB", 3) == 0) {
239         return ENCOD_3EB;
240     }
241     /*if(strncmp(coding, "2GR", 3) == 0) {
242         return ENCOD_2GR;
243     }
244     if(strncmp(coding, "3GR", 3) == 0) {
245         return ENCOD_3GR;
246     }*/
247
248     return ENCOD_UNKNOWN;
249 }
250
251 int get_file_format(char *filename)
252 {
253     int i;
254     static const char *extension[] = {"pgx", "bin", "img", "j3d", "jp3d", "j2k"};
255     static const int format[] = { PGX_DFMT, BIN_DFMT, IMG_DFMT, J3D_CFMT, J3D_CFMT, J2K_CFMT};
256     char * ext = strrchr(filename, '.');
257     if (ext) {
258         ext++;
259         for (i = 0; i < sizeof(format) / sizeof(*format); i++) {
260             if (strnicmp(ext, extension[i], 3) == 0) {
261                 return format[i];
262             }
263         }
264     }
265
266     return -1;
267 }
268
269 /* ------------------------------------------------------------------------------------ */
270
271 int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters)
272 {
273     int i, value;
274
275     /* parse the command line */
276
277     while (1) {
278         int c = opj_getopt(argc, argv,
279                            "i:m:o:r:q:f:t:n:c:b:x:p:s:d:hP:S:E:M:D:R:l:T:C:A:I");
280         if (c == -1) {
281             break;
282         }
283         switch (c) {
284         case 'i': {         /* input file */
285             char *infile = opj_optarg;
286             parameters->decod_format = get_file_format(infile);
287             switch (parameters->decod_format) {
288             case PGX_DFMT:
289             case BIN_DFMT:
290             case IMG_DFMT:
291                 break;
292             default:
293                 fprintf(stdout,
294                         "[ERROR] Unrecognized format for infile : %s [accept only *.pgx or *.bin] !!\n\n",
295                         infile);
296                 return 1;
297                 break;
298             }
299             strncpy(parameters->infile, infile, MAX_PATH);
300             fprintf(stdout, "[INFO] Infile: %s \n", parameters->infile);
301
302         }
303         break;
304
305         /* ----------------------------------------------------- */
306         case 'm': {         /* input IMG file */
307             char *imgfile = opj_optarg;
308             int imgformat = get_file_format(imgfile);
309             switch (imgformat) {
310             case IMG_DFMT:
311                 break;
312             default:
313                 fprintf(stdout,
314                         "[ERROR] Unrecognized format for imgfile : %s [accept only *.img] !!\n\n",
315                         imgfile);
316                 return 1;
317                 break;
318             }
319             strncpy(parameters->imgfile, imgfile, MAX_PATH);
320             fprintf(stdout, "[INFO] Imgfile: %s Format: %d\n", parameters->imgfile,
321                     imgformat);
322         }
323         break;
324
325         /* ----------------------------------------------------- */
326         case 'o': {         /* output file */
327             char *outfile = opj_optarg;
328             parameters->cod_format = get_file_format(outfile);
329             switch (parameters->cod_format) {
330             case J3D_CFMT:
331             case J2K_CFMT:
332             case LSE_CFMT:
333                 break;
334             default:
335                 fprintf(stdout,
336                         "[ERROR] Unknown output format volume %s [only *.j2k, *.lse3d or *.jp3d]!! \n",
337                         outfile);
338                 return 1;
339                 break;
340             }
341             strncpy(parameters->outfile, outfile, MAX_PATH);
342             fprintf(stdout, "[INFO] Outfile: %s \n", parameters->outfile);
343         }
344         break;
345
346         /* ----------------------------------------------------- */
347
348         case 'r': {         /* define compression rates for each layer */
349             char *s = opj_optarg;
350             while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) ==
351                     1) {
352                 parameters->tcp_numlayers++;
353                 while (*s && *s != ',') {
354                     s++;
355                 }
356                 if (!*s) {
357                     break;
358                 }
359                 s++;
360             }
361             parameters->cp_disto_alloc = 1;
362         }
363         break;
364
365         /* ----------------------------------------------------- */
366
367         case 'q': {         /* define distorsion (PSNR) for each layer */
368             char *s = opj_optarg;
369             while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers])
370                     == 1) {
371                 parameters->tcp_numlayers++;
372                 while (*s && *s != ',') {
373                     s++;
374                 }
375                 if (!*s) {
376                     break;
377                 }
378                 s++;
379             }
380             parameters->cp_fixed_quality = 1;
381         }
382         break;
383
384         /* ----------------------------------------------------- */
385
386         case 'f': {
387             fprintf(stdout, "/---------------------------------------------------\\\n");
388             fprintf(stdout, "|  Fixed layer allocation option not implemented !!  |\n");
389             fprintf(stdout, "\\---------------------------------------------------/\n");
390             /*int *row = NULL, *col = NULL;
391             int numlayers = 0, matrix_width = 0;
392
393             char *s = opj_optarg;
394             sscanf(s, "%d", &numlayers);
395             s++;
396             if (numlayers > 9)
397                 s++;
398
399             parameters->tcp_numlayers = numlayers;
400             matrix_width = parameters->numresolution[0] + parameters->numresolution[1] + parameters->numresolution[2];
401             parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
402             s = s + 2;
403
404             for (i = 0; i < numlayers; i++) {
405                 row = &parameters->cp_matrice[i * matrix_width];
406                 col = row;
407                 parameters->tcp_rates[i] = 1;
408                 sscanf(s, "%d,", &col[0]);
409                 s += 2;
410                 if (col[0] > 9)
411                     s++;
412                 col[1] = 0;
413                 col[2] = 0;
414                 for (j = 1; j < matrix_width; j++) {
415                     col += 3; j+=2;
416                     sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
417                     s += 6;
418                     if (col[0] > 9)
419                         s++;
420                     if (col[1] > 9)
421                         s++;
422                     if (col[2] > 9)
423                         s++;
424                 }
425                 if (i < numlayers - 1)
426                     s++;
427             }
428             parameters->cp_fixed_alloc = 1; */
429         }
430         break;
431
432         /* ----------------------------------------------------- */
433
434         case 't': {         /* tiles */
435             if (sscanf(opj_optarg, "%d,%d,%d", &parameters->cp_tdx, &parameters->cp_tdy,
436                        &parameters->cp_tdz) != 3) {
437                 fprintf(stdout,
438                         "[ERROR] '-t' 'dimensions of tiles' argument error !  [-t tdx,tdy,tdz]\n");
439                 return 1;
440             }
441             parameters->tile_size_on = true;
442         }
443         break;
444
445         /* ----------------------------------------------------- */
446
447         case 'n': {         /* resolution */
448             int aux;
449             aux = sscanf(opj_optarg, "%d,%d,%d", &parameters->numresolution[0],
450                          &parameters->numresolution[1], &parameters->numresolution[2]);
451             if (aux == 2) {
452                 parameters->numresolution[2] = 1;
453             } else if (aux == 1) {
454                 parameters->numresolution[1] = parameters->numresolution[0];
455                 parameters->numresolution[2] = 1;
456             } else if (aux == 0) {
457                 parameters->numresolution[0] = 1;
458                 parameters->numresolution[1] = 1;
459                 parameters->numresolution[2] = 1;
460             }
461         }
462         break;
463
464         /* ----------------------------------------------------- */
465         case 'c': {         /* precinct dimension */
466             char sep;
467             int res_spec = 0;
468             int aux;
469             char *s = opj_optarg;
470             do {
471                 sep = 0;
472                 aux = sscanf(s, "[%d,%d,%d]%c", &parameters->prct_init[0][res_spec],
473                              &parameters->prct_init[1][res_spec], &parameters->prct_init[2][res_spec], &sep);
474                 if (sep == ',' && aux != 4) {
475                     fprintf(stdout,
476                             "[ERROR] '-c' 'dimensions of precincts' argument error !  [-c [prcx_res0,prcy_res0,prcz_res0],...,[prcx_resN,prcy_resN,prcz_resN]]\n");
477                     return 1;
478                 }
479                 parameters->csty |= 0x01;
480                 res_spec++;
481                 s = strpbrk(s, "]") + 2;
482             } while (sep == ',');
483             parameters->res_spec = res_spec; /* number of precinct size specifications */
484         }
485         break;
486
487         /* ----------------------------------------------------- */
488
489         case 'b': {         /* code-block dimension */
490             int cblockw_init = 0, cblockh_init = 0, cblockl_init = 0;
491             if (sscanf(opj_optarg, "%d,%d,%d", &cblockw_init, &cblockh_init,
492                        &cblockl_init) != 3) {
493                 fprintf(stdout,
494                         "[ERROR] '-b' 'dimensions of codeblocks' argument error !  [-b cblkx,cblky,cblkz]\n");
495                 return 1;
496             }
497             if (cblockw_init * cblockh_init * cblockl_init > (1 << 18) ||
498                     cblockw_init > 1024 || cblockw_init < 4 || cblockh_init > 1024 ||
499                     cblockh_init < 4 || cblockl_init > 1024 || cblockl_init < 4) {
500                 fprintf(stdout,
501                         "[ERROR] Size of code_block error (option -b) !!\n\nRestriction :\n * width*height*length<=4096\n * 4<=width,height,length<= 1024\n\n");
502                 return 1;
503             }
504             parameters->cblock_init[0] = cblockw_init;
505             parameters->cblock_init[1] = cblockh_init;
506             parameters->cblock_init[2] = cblockl_init;
507         }
508         break;
509
510         /* ----------------------------------------------------- */
511
512         case 'x': {         /* creation of index file */
513             char *index = opj_optarg;
514             strncpy(parameters->index, index, MAX_PATH);
515             parameters->index_on = 1;
516         }
517         break;
518
519         /* ----------------------------------------------------- */
520
521         case 'p': {         /* progression order */
522             char progression[4];
523
524             strncpy(progression, opj_optarg, 4);
525             parameters->prog_order = give_progression(progression);
526             if (parameters->prog_order == -1) {
527                 fprintf(stdout,
528                         "[ERROR] Unrecognized progression order [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
529                 return 1;
530             }
531         }
532         break;
533
534         /* ----------------------------------------------------- */
535
536         case 's': {         /* subsampling factor */
537             if (sscanf(opj_optarg, "%d,%d,%d", &parameters->subsampling_dx,
538                        &parameters->subsampling_dy, &parameters->subsampling_dz) != 3) {
539                 fprintf(stdout, "[ERROR] '-s' sub-sampling argument error !  [-s dx,dy,dz]\n");
540                 return 1;
541             }
542         }
543         break;
544
545         /* ----------------------------------------------------- */
546
547         case 'd': {         /* coordonnate of the reference grid */
548             if (sscanf(opj_optarg, "%d,%d,%d", &parameters->volume_offset_x0,
549                        &parameters->volume_offset_y0, &parameters->volume_offset_z0) != 3) {
550                 fprintf(stdout,
551                         "[ERROR] -d 'coordonnate of the reference grid' argument error !! [-d x0,y0,z0]\n");
552                 return 1;
553             }
554         }
555         break;
556
557         /* ----------------------------------------------------- */
558
559         case 'h': {         /* display an help description */
560             encode_help_display();
561             return 1;
562         }
563         break;
564
565         /* ----------------------------------------------------- */
566
567         case 'P': {         /* POC */
568             int numpocs = 0;        /* number of progression order change (POC) default 0 */
569             opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
570
571             char *s = opj_optarg;
572             POC = parameters->POC;
573
574             fprintf(stdout, "/----------------------------------\\\n");
575             fprintf(stdout, "|  POC option not fully tested !!  |\n");
576             fprintf(stdout, "\\----------------------------------/\n");
577
578             while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%s", &POC[numpocs].tile,
579                           &POC[numpocs].resno0, &POC[numpocs].compno0,
580                           &POC[numpocs].layno1, &POC[numpocs].resno1,
581                           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
582                 POC[numpocs].prg = give_progression(POC[numpocs].progorder);
583                 /* POC[numpocs].tile; */
584                 numpocs++;
585                 while (*s && *s != '/') {
586                     s++;
587                 }
588                 if (!*s) {
589                     break;
590                 }
591                 s++;
592             }
593             parameters->numpocs = numpocs;
594         }
595         break;
596
597         /* ------------------------------------------------------ */
598
599         case 'S': {         /* SOP marker */
600             parameters->csty |= 0x02;
601         }
602         break;
603
604         /* ------------------------------------------------------ */
605
606         case 'E': {         /* EPH marker */
607             parameters->csty |= 0x04;
608         }
609         break;
610
611         /* ------------------------------------------------------ */
612
613         case 'M': {         /* Codification mode switch */
614             fprintf(stdout, "[INFO] Mode switch option not fully tested !!\n");
615             value = 0;
616             if (sscanf(opj_optarg, "%d", &value) == 1) {
617                 for (i = 0; i <= 6; i++) {
618                     int cache = value & (1 << i);
619                     if (cache) {
620                         parameters->mode |= (1 << i);
621                     }
622                 }
623             }
624         }
625         break;
626
627         /* ------------------------------------------------------ */
628
629         case 'D': {         /* DCO */
630             if (sscanf(opj_optarg, "%d", &parameters->dcoffset) != 1) {
631                 fprintf(stdout, "[ERROR] DC offset error !! [-D %d]\n", parameters->dcoffset);
632                 return 1;
633             }
634         }
635         break;
636
637         /* ------------------------------------------------------ */
638
639         case 'R': {         /* ROI */
640             if (sscanf(opj_optarg, "OI:c=%d,U=%d", &parameters->roi_compno,
641                        &parameters->roi_shift) != 2) {
642                 fprintf(stdout, "[ERROR] ROI error !! [-ROI:c='compno',U='shift']\n");
643                 return 1;
644             }
645         }
646         break;
647
648         /* ------------------------------------------------------ */
649
650         case 'l': {         /* Tile offset */
651             if (sscanf(opj_optarg, "%d,%d,%d", &parameters->cp_tx0, &parameters->cp_ty0,
652                        &parameters->cp_tz0) != 3) {
653                 fprintf(stdout, "[ERROR] -l 'tile offset' argument error !! [-l X0,Y0,Z0]");
654                 return 1;
655             }
656         }
657         break;
658
659         /* ------------------------------------------------------
660
661         case 'T':            // Transformation of original data (2D-DWT/3D-DWT/3D-RLS/2D-DWT+1D-RLS)
662         {
663         char transform[4];
664
665         strncpy(transform, opj_optarg, 4);
666         parameters->transform_format = give_transform(transform);
667         if (parameters->transform_format == -1) {
668             fprintf(stdout, "[ERROR] -T 'Transform domain' argument error !! [-T 2DWT, 3DWT, 3RLS or 3LSE only]");
669              return 1;
670         }
671         }
672         break;
673
674          ------------------------------------------------------ */
675
676         case 'C': {         /* Coding of transformed data */
677             char coding[3];
678
679             strncpy(coding, opj_optarg, 3);
680             parameters->encoding_format = give_coding(coding);
681             if (parameters->encoding_format == -1) {
682                 fprintf(stdout,
683                         "[ERROR] -C 'Coding algorithm' argument error !! [-C 2EB, 3EB, 2GR, 3GR or GRI only]");
684                 return 1;
685             }
686         }
687         break;
688
689         /* ------------------------------------------------------ */
690
691         case 'I': {         /* reversible or not */
692             parameters->irreversible = 1;
693         }
694         break;
695
696         default:
697             fprintf(stdout, "[ERROR] This option is not valid \"-%c %s\"\n", c, opj_optarg);
698             return 1;
699         }
700     }
701
702     /* check for possible errors */
703
704     if ((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
705         fprintf(stdout, "usage: jp3d_vm_enc -i volume-file -o jp3d-file (+ options)\n");
706         return 1;
707     }
708
709     if ((parameters->decod_format == BIN_DFMT) && (parameters->imgfile[0] == 0)) {
710         fprintf(stdout,
711                 "usage: jp3d_vm_enc -i bin-volume-file -m img-file -o jp3d-file (+ options)\n");
712         return 1;
713     }
714
715     if ((parameters->decod_format != BIN_DFMT) &&
716             (parameters->decod_format != PGX_DFMT) &&
717             (parameters->decod_format != IMG_DFMT)) {
718         fprintf(stdout,
719                 "usage: jp3d_vm_enc -i input-volume-file [*.bin,*.pgx,*.img] -o jp3d-file [*.jp3d,*.j2k] (+ options)\n");
720         return 1;
721     }
722     if ((parameters->cod_format != J3D_CFMT) &&
723             (parameters->cod_format != J2K_CFMT)) {
724         fprintf(stdout,
725                 "usage: jp3d_vm_enc -i input-volume-file [*.bin,*.pgx,*.img] -o jp3d-file [*.jp3d,*.j2k] (+ options)\n");
726         return 1;
727     }
728
729     if ((parameters->encoding_format == ENCOD_2GR ||
730             parameters->encoding_format == ENCOD_3GR) &&
731             parameters->transform_format != TRF_3D_LSE &&
732             parameters->transform_format != TRF_3D_RLS) {
733         fprintf(stdout,
734                 "[ERROR] Entropy coding options -C [2GR,3GR] are only compatible with predictive-based transform algorithms: -T [3RLS,3LSE].\n");
735         return 1;
736     }
737     if (parameters->encoding_format == ENCOD_3EB) {
738         parameters->mode |= (1 << 6);
739     }
740
741     if ((parameters->mode >> 6) & 1) {
742         parameters->encoding_format = ENCOD_3EB;
743     }
744
745     if ((parameters->numresolution[2] == 0 || (parameters->numresolution[1] == 0) ||
746             (parameters->numresolution[0] == 0))) {
747         fprintf(stdout,
748                 "[ERROR] -n 'resolution levels' argument error ! Resolutions must be greater than 1 in order to perform DWT.\n");
749         return 1;
750     }
751     if (parameters->numresolution[1] != parameters->numresolution[0]) {
752         fprintf(stdout,
753                 "[ERROR] -n 'resolution levels' argument error ! Resolutions in X and Y axis must be the same in this implementation.\n");
754         return 1;
755     }
756
757     if (parameters->numresolution[2] > parameters->numresolution[0]) {
758         fprintf(stdout,
759                 "[ERROR] -n 'resolution levels' argument error ! Resolutions in Z axis must be lower than in X-Y axis.\n");
760         return 1;
761     }
762
763     if (parameters->dcoffset >= 128 && parameters->dcoffset <= -128) {
764         fprintf(stdout,
765                 "[ERROR] -D 'DC offset' argument error ! Value must be -128<=DCO<=128.\n");
766         return 1;
767     }
768
769     if (parameters->numresolution[2] != 1) {
770         parameters->transform_format = TRF_3D_DWT;
771         /*fprintf(stdout, "[Warning] Resolution level in axial dim > 1 : 3D-DWT will be performed... \n");*/
772     } else if (parameters->numresolution[2] == 1) {
773         parameters->transform_format = TRF_2D_DWT;
774         /*fprintf(stdout, "[Warning] Resolution level in axial dim == 1 : 2D-DWT will be performed... \n");*/
775     }
776
777     if ((parameters->cod_format == J2K_CFMT) &&
778             (parameters->transform_format != TRF_2D_DWT ||
779              parameters->encoding_format != ENCOD_2EB)) {
780         fprintf(stdout,
781                 "[WARNING] Incompatible options -o *.j2k and defined transform or encoding algorithm. Latter will be ignored\n");
782         parameters->transform_format = TRF_2D_DWT;
783         parameters->encoding_format = ENCOD_2EB;
784     }
785
786     if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc ||
787             parameters->cp_fixed_quality) &&
788             (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_quality))) {
789         fprintf(stdout, "[ERROR] Options -r and -q cannot be used together !!\n");
790         return 1;
791     }               /* mod fixed_quality */
792
793     /* if no rate entered, lossless by default */
794     if (parameters->tcp_numlayers == 0) {
795         parameters->tcp_rates[0] = 0.0; /* MOD antonin : losslessbug */
796         parameters->tcp_numlayers++;
797         parameters->cp_disto_alloc = 1;
798     }
799
800     if ((parameters->cp_tx0 > parameters->volume_offset_x0) ||
801             (parameters->cp_ty0 > parameters->volume_offset_y0) ||
802             (parameters->cp_tz0 > parameters->volume_offset_z0)) {
803         fprintf(stdout,
804                 "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) TZO(%d)<=IMG_Z0(%d)\n",
805                 parameters->cp_tx0, parameters->volume_offset_x0, parameters->cp_ty0,
806                 parameters->volume_offset_y0,
807                 parameters->cp_tz0, parameters->volume_offset_z0);
808         return 1;
809     }
810
811     for (i = 0; i < parameters->numpocs; i++) {
812         if (parameters->POC[i].prg == -1) {
813             fprintf(stdout,
814                     "[ERROR] Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
815                     i + 1);
816         }
817     }
818     return 0;
819 }
820
821 /* -------------------------------------------------------------------------- */
822
823 /**
824 sample error callback expecting a FILE* client object
825 */
826 void error_callback(const char *msg, void *client_data)
827 {
828     FILE *stream = (FILE*)client_data;
829     fprintf(stream, "[ERROR] %s", msg);
830 }
831 /**
832 sample warning callback expecting a FILE* client object
833 */
834 void warning_callback(const char *msg, void *client_data)
835 {
836     FILE *stream = (FILE*)client_data;
837     fprintf(stream, "[WARNING] %s", msg);
838 }
839 /**
840 sample debug callback expecting a FILE* client object
841 */
842 void info_callback(const char *msg, void *client_data)
843 {
844     FILE *stream = (FILE*)client_data;
845     fprintf(stream, "[INFO] %s", msg);
846 }
847
848 /* -------------------------------------------------------------------------- */
849
850 int main(int argc, char **argv)
851 {
852     bool bSuccess;
853     bool delete_comment = true;
854     opj_cparameters_t parameters;   /* compression parameters */
855     opj_event_mgr_t event_mgr;      /* event manager */
856     opj_volume_t *volume = NULL;
857
858     /*
859     configure the event callbacks (not required)
860     setting of each callback is optional
861     */
862     memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
863     event_mgr.error_handler = error_callback;
864     event_mgr.warning_handler = warning_callback;
865     event_mgr.info_handler = info_callback;
866
867     /* set encoding parameters to default values */
868     opj_set_default_encoder_parameters(&parameters);
869
870     /* parse input and get user encoding parameters */
871     if (parse_cmdline_encoder(argc, argv, &parameters) == 1) {
872         return 0;
873     }
874
875     if (parameters.cp_comment == NULL) {
876         parameters.cp_comment = "Created by OpenJPEG version JP3D";
877         /* no need to delete parameters.cp_comment on exit */
878         delete_comment = false;
879     }
880
881     /* encode the destination volume */
882     /* ---------------------------- */
883     if (parameters.cod_format == J3D_CFMT || parameters.cod_format == J2K_CFMT) {
884         int codestream_length, pixels, bitsin;
885         opj_cio_t *cio = NULL;
886         FILE *f = NULL;
887         opj_cinfo_t* cinfo = NULL;
888
889         /* decode the source volume */
890         /* ----------------------- */
891         switch (parameters.decod_format) {
892         case PGX_DFMT:
893             fprintf(stdout, "[INFO] Loading pgx file(s)\n");
894             volume = pgxtovolume(parameters.infile, &parameters);
895             if (!volume) {
896                 fprintf(stdout, "[ERROR] Unable to load pgx files\n");
897                 return 1;
898             }
899             break;
900
901         case BIN_DFMT:
902             fprintf(stdout, "[INFO] Loading bin file\n");
903             volume = bintovolume(parameters.infile, parameters.imgfile, &parameters);
904             if (!volume) {
905                 fprintf(stdout, "[ERROR] Unable to load bin file\n");
906                 return 1;
907             }
908             break;
909
910         case IMG_DFMT:
911             fprintf(stdout, "[INFO] Loading img file\n");
912             volume = imgtovolume(parameters.infile, &parameters);
913             if (!volume) {
914                 fprintf(stderr, "[ERROR] Unable to load img file\n");
915                 return 1;
916             }
917             break;
918         }
919
920         /* get a JP3D or J2K compressor handle */
921         if (parameters.cod_format == J3D_CFMT) {
922             cinfo = opj_create_compress(CODEC_J3D);
923         } else if (parameters.cod_format == J2K_CFMT) {
924             cinfo = opj_create_compress(CODEC_J2K);
925         }
926
927         /* catch events using our callbacks and give a local context */
928         opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stdout);
929
930         /* setup the encoder parameters using the current volume and using user parameters */
931         opj_setup_encoder(cinfo, &parameters, volume);
932
933         /* open a byte stream for writing */
934         /* allocate memory for all tiles */
935         cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
936
937         /* encode the volume */
938         /*fprintf(stdout, "[INFO] Encode the volume\n");*/
939         bSuccess = opj_encode(cinfo, cio, volume, parameters.index);
940         if (!bSuccess) {
941             opj_cio_close(cio);
942             fprintf(stdout, "[ERROR] Failed to encode volume\n");
943             return 1;
944         }
945         codestream_length = cio_tell(cio);
946         pixels = (volume->x1 - volume->x0) * (volume->y1 - volume->y0) *
947                  (volume->z1 - volume->z0);
948         bitsin = pixels * volume->comps[0].prec;
949         fprintf(stdout,
950                 "[RESULT] Volume: %d x %d x %d (x %d bpv)\n Codestream: %d B,  Ratio: %5.3f bpv,  (%5.3f : 1) \n",
951                 (volume->x1 - volume->x0), (volume->y1 - volume->y0), (volume->z1 - volume->z0),
952                 volume->comps[0].prec,
953                 codestream_length, ((double)codestream_length * 8.0 / (double)pixels),
954                 ((double)bitsin / (8.0 * (double)codestream_length)));
955
956         /* write the buffer to disk */
957         f = fopen(parameters.outfile, "wb");
958         if (!f) {
959             fprintf(stdout, "[ERROR] Failed to open %s for writing\n", parameters.outfile);
960             return 1;
961         }
962         fwrite(cio->buffer, 1, codestream_length, f);
963         fclose(f);
964
965         /* close and free the byte stream */
966         opj_cio_close(cio);
967
968         /* free remaining compression structures */
969         opj_destroy_compress(cinfo);
970     } else {
971         fprintf(stdout, "[ERROR] Cod_format != JP3d !!! \n");
972         return 1;
973     }
974
975     /* free user parameters structure */
976     if (delete_comment) {
977         if (parameters.cp_comment) {
978             free(parameters.cp_comment);
979         }
980     }
981     if (parameters.cp_matrice) {
982         free(parameters.cp_matrice);
983     }
984
985     /* free volume data */
986     opj_volume_destroy(volume);
987
988     return 0;
989 }