[trunk] Import patch from sumatrapdf team. This handle testcase 1610.pdf.SIGSEGV...
[openjpeg.git] / src / bin / mj2 / opj_mj2_compress.c
1 /*
2 * Copyright (c) 2003-2004, Francois-Olivier Devaux
3 * Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #include "opj_apps_config.h"
33 #include "openjpeg.h"
34 #include "j2k_lib.h"
35 #include "cio.h"
36 #include "j2k.h"
37 #include "jp2.h"
38 #include "mj2.h"
39 #include "mj2_convert.h"
40 #include "opj_getopt.h"
41
42 /**
43 Size of memory first allocated for MOOV box
44 */
45 #define TEMP_BUF 10000 
46
47
48 /* -------------------------------------------------------------------------- */
49
50 /**
51 sample error callback expecting a FILE* client object
52 */
53 static void error_callback(const char *msg, void *client_data) {
54         FILE *stream = (FILE*)client_data;
55         fprintf(stream, "[ERROR] %s", msg);
56 }
57 /**
58 sample warning callback expecting a FILE* client object
59 */
60 static void warning_callback(const char *msg, void *client_data) {
61         FILE *stream = (FILE*)client_data;
62         fprintf(stream, "[WARNING] %s", msg);
63 }
64 /**
65 sample debug callback expecting a FILE* client object
66 */
67 static void info_callback(const char *msg, void *client_data) {
68         FILE *stream = (FILE*)client_data;
69         fprintf(stream, "[INFO] %s", msg);
70 }
71
72 /* -------------------------------------------------------------------------- */
73
74
75 static void help_display()
76 {
77   fprintf(stdout,"HELP for frames_to_mj2\n----\n\n");
78   fprintf(stdout,"- the -h option displays this help information on screen\n\n");
79   
80   
81   fprintf(stdout,"List of parameters for the MJ2 encoder:\n");
82   fprintf(stdout,"\n");
83   fprintf(stdout,"REMARKS:\n");
84   fprintf(stdout,"---------\n");
85   fprintf(stdout,"\n");
86   fprintf
87     (stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
88   fprintf
89     (stdout,"COD and QCD never appear in the tile_header.\n");
90   fprintf(stdout,"\n");
91   fprintf(stdout,"By default:\n");
92   fprintf(stdout,"------------\n");
93   fprintf(stdout,"\n");
94   fprintf(stdout," * Lossless\n");
95   fprintf(stdout," * 1 tile\n");
96   fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
97   fprintf(stdout," * Size of code-block : 64 x 64\n");
98   fprintf(stdout," * Number of resolutions: 6\n");
99   fprintf(stdout," * No SOP marker in the codestream\n");
100   fprintf(stdout," * No EPH marker in the codestream\n");
101   fprintf(stdout," * No sub-sampling in x or y direction\n");
102   fprintf(stdout," * No mode switch activated\n");
103   fprintf(stdout," * Progression order: LRCP\n");
104   fprintf(stdout," * No index file\n");
105   fprintf(stdout," * No ROI upshifted\n");
106   fprintf(stdout," * No offset of the origin of the image\n");
107   fprintf(stdout," * No offset of the origin of the tiles\n");
108   fprintf(stdout," * Reversible DWT 5-3\n");
109   fprintf(stdout,"\n");
110   fprintf(stdout,"Parameters:\n");
111   fprintf(stdout,"------------\n");
112   fprintf(stdout,"\n");
113   fprintf
114     (stdout,"Required Parameters (except with -h):\n");
115   fprintf
116     (stdout,"-i : source file      (-i source.yuv) \n");
117   fprintf
118     (stdout,"-o : destination file (-o dest.mj2) \n");
119   fprintf
120     (stdout,"Optional Parameters:\n");
121   fprintf(stdout,"-h : display the help information \n");
122   fprintf(stdout,"-r : different compression ratios for successive layers (-r 20,10,5)\n");
123   fprintf(stdout,"     - The rate specified for each quality level is the desired \n");
124   fprintf(stdout,"       compression factor.\n");
125   fprintf(stdout,"       Example: -r 20,10,1 means quality 1: compress 20x, \n");
126   fprintf(stdout,"       quality 2: compress 10x and quality 3: compress lossless\n");
127   fprintf(stdout,"       (options -r and -q cannot be used together)\n");
128   
129   fprintf(stdout,"-q : different psnr for successive layers (-q 30,40,50) \n");
130   fprintf(stdout,"        (options -r and -q cannot be used together)\n");
131   
132   fprintf(stdout,"-n : number of resolutions (-n 3) \n");
133   fprintf(stdout,"-b : size of code block (-b 32,32) \n");
134   fprintf(stdout,"-c : size of precinct (-c 128,128) \n");
135   fprintf(stdout,"-t : size of tile (-t 512,512) \n");
136   fprintf
137     (stdout,"-p : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
138   fprintf
139     (stdout,"-s : subsampling factor (-s 2,2) [-s X,Y] \n");
140   fprintf(stdout,"     Remark: subsampling bigger than 2 can produce error\n");
141   fprintf
142     (stdout,"-S : write SOP marker before each packet \n");
143   fprintf
144     (stdout,"-E : write EPH marker after each header packet \n");
145   fprintf
146     (stdout,"-M : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
147   fprintf
148     (stdout,"             8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
149   fprintf
150     (stdout,"             Indicate multiple modes by adding their values. \n");
151   fprintf
152     (stdout,"             Example: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
153   fprintf
154     (stdout,"-R : c=%%d,U=%%d : quantization indices upshifted \n");
155   fprintf
156     (stdout,"             for component c=%%d [%%d = 0,1,2]\n");
157   fprintf
158     (stdout,"             with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
159   fprintf
160     (stdout,"-d : offset of the origin of the image (-d 150,300) \n");
161   fprintf
162     (stdout,"-T : offset of the origin of the tiles (-T 100,75) \n");
163   fprintf(stdout,"-I : use the irreversible DWT 9-7 (-I) \n");
164   fprintf(stdout,"-W : image width, height and the dx and dy subsampling \n");
165   fprintf(stdout,"        of the Cb and Cr components for YUV files \n");
166   fprintf(stdout,"        (default is '352,288,2,2' for CIF format's 352x288 and 4:2:0)\n");
167   fprintf(stdout,"-F : video frame rate (set to 25 by default)\n");
168   fprintf(stdout,"-D : depth, precision in bits [8 .. 16]; default:8\n");
169   fprintf(stdout,"-C : comment\n");
170   fprintf(stdout,"\n");
171   fprintf(stdout,"IMPORTANT:\n");
172   fprintf(stdout,"-----------\n");
173   fprintf(stdout,"\n");
174   fprintf(stdout,"The index file has the structure below:\n");
175   fprintf(stdout,"---------------------------------------\n");
176   fprintf(stdout,"\n");
177   fprintf(stdout,"Image_height Image_width\n");
178   fprintf(stdout,"progression order\n");
179   fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
180   fprintf(stdout,"Components_nb\n");
181   fprintf(stdout,"Layers_nb\n");
182   fprintf(stdout,"decomposition_levels\n");
183   fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
184   fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
185   fprintf(stdout,"Main_header_end_position\n");
186   fprintf(stdout,"Codestream_size\n");
187   fprintf(stdout,"Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
188   fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''\n");
189   fprintf(stdout,"...\n");
190   fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''\n");
191   fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
192   fprintf(stdout,"...\n");
193   fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
194   
195   fprintf(stdout,"MaxDisto\n");
196   
197   fprintf(stdout,"TotalDisto\n\n");
198 }
199
200 static OPJ_PROG_ORDER give_progression(const char progression[5])
201 {
202   if (progression[0] == 'L' && progression[1] == 'R'
203     && progression[2] == 'C' && progression[3] == 'P') {
204     return LRCP;
205   } else {
206     if (progression[0] == 'R' && progression[1] == 'L'
207       && progression[2] == 'C' && progression[3] == 'P') {
208       return RLCP;
209     } else {
210       if (progression[0] == 'R' && progression[1] == 'P'
211                                 && progression[2] == 'C' && progression[3] == 'L') {
212                                 return RPCL;
213       } else {
214                                 if (progression[0] == 'P' && progression[1] == 'C'
215                                         && progression[2] == 'R' && progression[3] == 'L') {
216                                         return PCRL;
217                                 } else {
218                                         if (progression[0] == 'C' && progression[1] == 'P'
219                                                 && progression[2] == 'R' && progression[3] == 'L') {
220                                                 return CPRL;
221                                         } else {
222                                                 return PROG_UNKNOWN;
223                                         }
224                                 }
225       }
226     }
227   }
228 }
229
230
231
232
233 int main(int argc, char **argv)
234 {
235         mj2_cparameters_t mj2_parameters;       /* MJ2 compression parameters */
236         opj_cparameters_t *j2k_parameters;      /* J2K compression parameters */
237         opj_event_mgr_t event_mgr;              /* event manager */
238         opj_cio_t *cio;
239         int value;
240         opj_mj2_t *movie;
241         opj_image_t *img;
242         int i, j;
243         char *s, S1, S2, S3;
244         unsigned char *buf;
245         int x1, y1,  len;
246         long mdat_initpos, offset;
247         FILE *mj2file;
248         int sampleno;  
249         opj_cinfo_t* cinfo;
250         opj_bool bSuccess;
251         int numframes;
252         int prec = 8;/* DEFAULT */
253         double total_time = 0;  
254
255         memset(&mj2_parameters, 0, sizeof(mj2_cparameters_t));
256   /* default value */
257   /* ------------- */
258         mj2_parameters.w = 352;                 /* CIF default value*/
259         mj2_parameters.h = 288;                 /* CIF default value*/
260         mj2_parameters.CbCr_subsampling_dx = 2; /* CIF default value*/
261         mj2_parameters.CbCr_subsampling_dy = 2; /* CIF default value*/
262         mj2_parameters.frame_rate = 25;
263         mj2_parameters.prec = 8; /* DEFAULT */
264         mj2_parameters.enumcs = ENUMCS_SYCC; /* FIXME: ENUMCS_YUV420 */
265         mj2_parameters.meth = 1; /* enumerated color space */
266
267 /*
268         configure the event callbacks (not required)
269         setting of each callback is optionnal
270 */
271         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
272         event_mgr.error_handler = error_callback;
273         event_mgr.warning_handler = warning_callback;
274         event_mgr.info_handler = NULL;
275     
276         /* set J2K encoding parameters to default values */
277         opj_set_default_encoder_parameters(&mj2_parameters.j2k_parameters);
278         j2k_parameters = &mj2_parameters.j2k_parameters;
279
280         /* Create comment for codestream */
281         if(j2k_parameters->cp_comment == NULL) {
282     const char comment[] = "Created by OpenJPEG version ";
283                 const size_t clen = strlen(comment);
284     const char *version = opj_version();
285                 j2k_parameters->cp_comment = (char*)malloc(clen+strlen(version)+1);
286                 sprintf(j2k_parameters->cp_comment,"%s%s", comment, version);
287         }
288
289   while (1) {
290     int c = opj_getopt(argc, argv,
291       "i:o:r:q:f:t:n:c:b:p:s:d:P:S:E:M:R:T:C:I:W:F:D:h");
292     if (c == -1)
293       break;
294     switch (c) {
295     case 'i':                   /* IN fill */
296                         {
297                                 char *infile = opj_optarg;
298                                 s = opj_optarg;
299                                 while (*s) {
300                                         s++;
301                                 }
302                                 s--;
303                                 S3 = *s;
304                                 s--;
305                                 S2 = *s;
306                                 s--;
307                                 S1 = *s;
308                                 
309                                 if ((S1 == 'y' && S2 == 'u' && S3 == 'v')
310                                         || (S1 == 'Y' && S2 == 'U' && S3 == 'V')) {
311                                         mj2_parameters.decod_format = YUV_DFMT;                         
312                                 }
313                                 else {
314                                         fprintf(stderr,
315                                                 "!! Unrecognized format for infile : %c%c%c [accept only *.yuv] !!\n\n",
316                                                 S1, S2, S3);
317                                         return 1;
318                                 }
319                                 strncpy(mj2_parameters.infile, infile, sizeof(mj2_parameters.infile)-1);
320                         }
321       break;
322       /* ----------------------------------------------------- */
323     case 'o':                   /* OUT fill */
324                         {
325                                 char *outfile = opj_optarg;
326                                 while (*outfile) {
327                                         outfile++;
328                                 }
329                                 outfile--;
330                                 S3 = *outfile;
331                                 outfile--;
332                                 S2 = *outfile;
333                                 outfile--;
334                                 S1 = *outfile;
335                                 
336                                 outfile = opj_optarg;
337                                 
338                                 if ((S1 == 'm' && S2 == 'j' && S3 == '2')
339                                         || (S1 == 'M' && S2 == 'J' && S3 == '2'))
340                                         mj2_parameters.cod_format = MJ2_CFMT;
341                                 else {
342                                         fprintf(stderr,
343                                                 "Unknown output format image *.%c%c%c [only *.mj2]!! \n",
344                                                 S1, S2, S3);
345                                         return 1;
346                                 }
347                                 strncpy(mj2_parameters.outfile, outfile, sizeof(mj2_parameters.outfile)-1);      
348       }
349       break;
350       /* ----------------------------------------------------- */
351     case 'r':                   /* rates rates/distorsion */
352                         {
353                                 float rate;
354                                 s = opj_optarg;
355                                 while (sscanf(s, "%f", &rate) == 1) {
356                                         j2k_parameters->tcp_rates[j2k_parameters->tcp_numlayers] = rate * 2;
357                                         j2k_parameters->tcp_numlayers++;
358                                         while (*s && *s != ',') {
359                                                 s++;
360                                         }
361                                         if (!*s)
362                                                 break;
363                                         s++;
364                                 }
365                                 j2k_parameters->cp_disto_alloc = 1;
366                         }
367       break;
368       /* ----------------------------------------------------- */
369     case 'q':                   /* add fixed_quality */
370       s = opj_optarg;
371                         while (sscanf(s, "%f", &j2k_parameters->tcp_distoratio[j2k_parameters->tcp_numlayers]) == 1) {
372                                 j2k_parameters->tcp_numlayers++;
373                                 while (*s && *s != ',') {
374                                         s++;
375                                 }
376                                 if (!*s)
377                                         break;
378                                 s++;
379                         }
380                         j2k_parameters->cp_fixed_quality = 1;
381       break;
382       /* dda */
383       /* ----------------------------------------------------- */
384     case 'f':                   /* mod fixed_quality (before : -q) */
385                         {
386                                 int *row = NULL, *col = NULL;
387                                 int numlayers = 0, numresolution = 0, matrix_width = 0;
388                                 
389                                 s = opj_optarg;
390                                 sscanf(s, "%d", &numlayers);
391                                 s++;
392                                 if (numlayers > 9)
393                                         s++;
394                                 
395                                 j2k_parameters->tcp_numlayers = numlayers;
396                                 numresolution = j2k_parameters->numresolution;
397                                 matrix_width = numresolution * 3;
398                                 j2k_parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
399                                 s = s + 2;
400                                 
401                                 for (i = 0; i < numlayers; i++) {
402                                         row = &j2k_parameters->cp_matrice[i * matrix_width];
403                                         col = row;
404                                         j2k_parameters->tcp_rates[i] = 1;
405                                         sscanf(s, "%d,", &col[0]);
406                                         s += 2;
407                                         if (col[0] > 9)
408                                                 s++;
409                                         col[1] = 0;
410                                         col[2] = 0;
411                                         for (j = 1; j < numresolution; j++) {
412                                                 col += 3;
413                                                 sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
414                                                 s += 6;
415                                                 if (col[0] > 9)
416                                                         s++;
417                                                 if (col[1] > 9)
418                                                         s++;
419                                                 if (col[2] > 9)
420                                                         s++;
421                                         }
422                                         if (i < numlayers - 1)
423                                                 s++;
424                                 }
425                                 j2k_parameters->cp_fixed_alloc = 1;
426                         }
427                         break;
428       /* ----------------------------------------------------- */
429     case 't':                   /* tiles */
430       sscanf(opj_optarg, "%d,%d", &j2k_parameters->cp_tdx, &j2k_parameters->cp_tdy);
431                         j2k_parameters->tile_size_on = OPJ_TRUE;
432       break;
433       /* ----------------------------------------------------- */
434     case 'n':                   /* resolution */
435       sscanf(opj_optarg, "%d", &j2k_parameters->numresolution);
436       break;
437       /* ----------------------------------------------------- */
438     case 'c':                   /* precinct dimension */
439                         {
440                                 char sep;
441                                 int res_spec = 0;
442
443                                 char *s = opj_optarg;
444                                 do {
445                                         sep = 0;
446                                         sscanf(s, "[%d,%d]%c", &j2k_parameters->prcw_init[res_spec],
447                                  &j2k_parameters->prch_init[res_spec], &sep);
448                                         j2k_parameters->csty |= 0x01;
449                                         res_spec++;
450                                         s = strpbrk(s, "]") + 2;
451                                 }
452                                 while (sep == ',');
453                                 j2k_parameters->res_spec = res_spec;
454                         }
455                         break;
456
457       /* ----------------------------------------------------- */
458     case 'b':                   /* code-block dimension */
459                         {
460                                 int cblockw_init = 0, cblockh_init = 0;
461                                 sscanf(opj_optarg, "%d,%d", &cblockw_init, &cblockh_init);
462                                 if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
463                                         || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
464                                         fprintf(stderr,
465                                                 "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
466             "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
467                                         return 1;
468                                 }
469                                 j2k_parameters->cblockw_init = cblockw_init;
470                                 j2k_parameters->cblockh_init = cblockh_init;
471                         }
472                         break;
473       /* ----------------------------------------------------- */
474     case 'p':                   /* progression order */
475                         {
476                                 char progression[5];
477                                 
478                                 strncpy(progression, opj_optarg, 5);
479                                 j2k_parameters->prog_order = give_progression(progression);
480                                 if (j2k_parameters->prog_order == -1) {
481                                         fprintf(stderr, "Unrecognized progression order "
482             "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
483                                         return 1;
484                                 }
485                         }
486                         break;
487       /* ----------------------------------------------------- */
488     case 's':                   /* subsampling factor */
489       {
490                                 if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->subsampling_dx,
491                                     &j2k_parameters->subsampling_dy) != 2) {
492                                         fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
493                                         return 1;
494                                 }
495                         }
496                         break;
497       /* ----------------------------------------------------- */
498     case 'd':                   /* coordonnate of the reference grid */
499       {
500                                 if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->image_offset_x0,
501                                     &j2k_parameters->image_offset_y0) != 2) {
502                                         fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
503             "error !! [-d x0,y0]\n");
504                                         return 1;
505                                 }
506                         }
507                         break;
508       /* ----------------------------------------------------- */
509     case 'h':                   /* Display an help description */
510       help_display();
511       return 0;
512       break;
513       /* ----------------------------------------------------- */
514     case 'P':                   /* POC */
515       {
516                                 int numpocs = 0;                /* number of progression order change (POC) default 0 */
517                                 opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
518
519                                 char *s = opj_optarg;
520                                 POC = j2k_parameters->POC;
521
522                                 while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
523                                         &POC[numpocs].resno0, &POC[numpocs].compno0,
524                                         &POC[numpocs].layno1, &POC[numpocs].resno1,
525                                         &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
526                                         POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
527                                         numpocs++;
528                                         while (*s && *s != '/') {
529                                                 s++;
530                                         }
531                                         if (!*s) {
532                                                 break;
533                                         }
534                                         s++;
535                                 }
536                                 j2k_parameters->numpocs = numpocs;
537                         }
538                         break;
539       /* ------------------------------------------------------ */
540     case 'S':                   /* SOP marker */
541       j2k_parameters->csty |= 0x02;
542       break;
543       /* ------------------------------------------------------ */
544     case 'E':                   /* EPH marker */
545       j2k_parameters->csty |= 0x04;
546       break;
547       /* ------------------------------------------------------ */
548     case 'M':                   /* Mode switch pas tous au point !! */
549       if (sscanf(opj_optarg, "%d", &value) == 1) {
550                                 for (i = 0; i <= 5; i++) {
551                                         int cache = value & (1 << i);
552                                         if (cache)
553                                                 j2k_parameters->mode |= (1 << i);
554                                 }
555       }
556       break;
557       /* ------------------------------------------------------ */
558     case 'R':                   /* ROI */
559       {
560                                 if (sscanf(opj_optarg, "OI:c=%d,U=%d", &j2k_parameters->roi_compno,
561                                            &j2k_parameters->roi_shift) != 2) {
562                                         fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
563                                         return 1;
564                                 }
565                         }
566                         break;
567       /* ------------------------------------------------------ */
568     case 'T':                   /* Tile offset */
569                         {
570                                 if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->cp_tx0, &j2k_parameters->cp_ty0) != 2) {
571                                         fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
572                                         return 1;
573                                 }
574                         }
575                         break;
576       /* ------------------------------------------------------ */
577     case 'C':                   /* Add a comment */
578                         {
579                                 j2k_parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
580                                 if(j2k_parameters->cp_comment) {
581                                         strcpy(j2k_parameters->cp_comment, opj_optarg);
582                                 }
583                         }
584                         break;
585       /* ------------------------------------------------------ */
586     case 'I':                   /* reversible or not */
587                         {
588                                 j2k_parameters->irreversible = 1;
589                         }
590                         break;
591       /* ------------------------------------------------------ */
592     case 'W':                   /* Width and Height and Cb and Cr subsampling in case of YUV format files */
593       if (sscanf
594                                 (opj_optarg, "%d,%d,%d,%d", &mj2_parameters.w, &mj2_parameters.h, &mj2_parameters.CbCr_subsampling_dx,
595                                 &mj2_parameters.CbCr_subsampling_dy) != 4) {
596                                 fprintf(stderr, "-W argument error");
597                                 return 1;
598       }
599       break;
600       /* ------------------------------------------------------ */
601     case 'F':                   /* Video frame rate */
602       if (sscanf(opj_optarg, "%d", &mj2_parameters.frame_rate) != 1) {
603                                 fprintf(stderr, "-F argument error");
604                                 return 1;
605       }
606       break;
607       /* ------------------------------------------------------ */
608         case 'D': /* Depth: the precision */
609                 if(sscanf(opj_optarg, "%d", &prec) != 1) prec = 0;
610                 break;
611
612     default:
613       return 1;
614     }
615   }
616     
617   /* Error messages */
618   /* -------------- */
619         if (!mj2_parameters.cod_format || !mj2_parameters.decod_format) {
620     fprintf(stderr,
621       "Usage: %s -i yuv-file -o mj2-file (+ options)\n",argv[0]);
622     return 1;
623   }
624     if(prec < 1 || prec > 16)
625   {
626         fprintf(stderr, "Error: Depth %d must be in the range 8 .. 16\n",prec);
627         return 1;       
628   }
629         if ((j2k_parameters->cp_disto_alloc || j2k_parameters->cp_fixed_alloc || j2k_parameters->cp_fixed_quality)
630                 && (!(j2k_parameters->cp_disto_alloc ^ j2k_parameters->cp_fixed_alloc ^ j2k_parameters->cp_fixed_quality))) {
631                 fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
632                 return 1;
633         }                               /* mod fixed_quality */
634
635         /* if no rate entered, lossless by default */
636         if (j2k_parameters->tcp_numlayers == 0) {
637                 j2k_parameters->tcp_rates[0] = 0;       /* MOD antonin : losslessbug */
638                 j2k_parameters->tcp_numlayers++;
639                 j2k_parameters->cp_disto_alloc = 1;
640         }
641
642         if((j2k_parameters->cp_tx0 > j2k_parameters->image_offset_x0) || (j2k_parameters->cp_ty0 > j2k_parameters->image_offset_y0)) {
643                 fprintf(stderr,
644                         "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
645                         j2k_parameters->cp_tx0, j2k_parameters->image_offset_x0, j2k_parameters->cp_ty0, j2k_parameters->image_offset_y0);
646                 return 1;
647         }
648
649         for (i = 0; i < j2k_parameters->numpocs; i++) {
650                 if (j2k_parameters->POC[i].prg == -1) {
651                         fprintf(stderr,
652                                 "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
653                                 i + 1);
654                 }
655         }
656   
657   if (j2k_parameters->cp_tdx > mj2_parameters.Dim[0] || j2k_parameters->cp_tdy > mj2_parameters.Dim[1]) {
658     fprintf(stderr,
659       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
660       j2k_parameters->cp_tdx, mj2_parameters.Dim[0], j2k_parameters->cp_tdy, mj2_parameters.Dim[1]);
661     return 1;
662   }
663     
664   /* to respect profile - 0 */
665   /* ---------------------- */
666   
667   x1 = !mj2_parameters.Dim[0] ? (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx 
668                 + 1 : mj2_parameters.Dim[0] + (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx + 1;
669   y1 = !mj2_parameters.Dim[1] ? (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy 
670                 + 1 : mj2_parameters.Dim[1] + (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy + 1;   
671         mj2_parameters.numcomps = 3; /* YUV files only have 3 components */ 
672
673         mj2_parameters.prec = prec;
674
675         j2k_parameters->tcp_mct = 0;
676     
677         mj2file = fopen(mj2_parameters.outfile, "wb");
678   
679         if (!mj2file) {
680     fprintf(stderr, "failed to open %s for writing\n", argv[2]);
681     return 1;
682         }
683     
684         /* get a MJ2 decompressor handle */
685         cinfo = mj2_create_compress();
686         movie = (opj_mj2_t*)cinfo->mj2_handle;
687         
688         /* catch events using our callbacks and give a local context */
689         opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
690
691         /* setup encoder parameters */
692         mj2_setup_encoder(movie, &mj2_parameters);   
693   
694         movie->tk[0].num_samples = 
695          yuv_num_frames(&movie->tk[0],mj2_parameters.infile);
696
697         if (movie->tk[0].num_samples == 0) {
698                 return 1;
699         }
700
701   /* One sample per chunk*/
702         movie->tk[0].chunk = (mj2_chunk_t*) 
703          malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));     
704         movie->tk[0].sample = (mj2_sample_t*) 
705          malloc(movie->tk[0].num_samples * sizeof(mj2_sample_t));
706   
707         if (mj2_init_stdmovie(movie)) {
708     fprintf(stderr, "Error with movie initialization");
709     return 1;
710         }    
711   
712 /* Writing JP, FTYP and MDAT boxes */
713 /* Assuming that the JP and FTYP boxes won't be longer than 300 bytes:*/
714         buf = (unsigned char*) 
715          malloc (300 * sizeof(unsigned char));
716
717         cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, 300);
718
719         mj2_write_jp(cio);
720         mj2_write_ftyp(movie, cio);
721
722         mdat_initpos = cio_tell(cio);
723         cio_skip(cio, 4);
724
725         cio_write(cio, MJ2_MDAT, 4);    
726
727         fwrite(buf,cio_tell(cio),1,mj2file);
728
729         offset = cio_tell(cio);
730         opj_cio_close(cio);
731         free(buf);
732
733         for(i = 0; i < movie->num_stk + movie->num_htk + movie->num_vtk; i++) 
734    {
735     if(movie->tk[i].track_type != 0) 
736   {
737         fprintf(stderr, "Unable to write sound or hint tracks\n");
738   }
739         else 
740   {
741         mj2_tk_t *tk;
742         int buflen = 0;
743   
744         tk = &movie->tk[i];     
745         tk->num_chunks = tk->num_samples;
746         numframes = tk->num_samples;
747         tk->depth = prec; 
748
749         fprintf(stderr, "Video Track number %d\n", i);
750
751         img = mj2_image_create(tk, j2k_parameters);          
752
753         buflen = 2 * (tk->w * tk->h * 8);
754         buf = (unsigned char *) malloc(buflen*sizeof(unsigned char));   
755
756         for(sampleno = 0; sampleno < numframes; sampleno++) 
757  {
758         double init_time = opj_clock();
759         double elapsed_time;
760
761                 if(yuvtoimage(tk, img, sampleno, j2k_parameters, 
762                         mj2_parameters.infile))
763            {
764                 fprintf(stderr, "Error with frame number %d in YUV file\n", sampleno);
765                 return 1;
766            }
767
768 /* setup the encoder parameters using the current image and user parameters */
769         opj_setup_encoder(cinfo, j2k_parameters, img);
770
771         cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, buflen);
772                                                                 
773         cio_skip(cio, 4);
774         cio_write(cio, JP2_JP2C, 4);    /* JP2C*/
775
776 /* encode the image */
777         bSuccess = opj_encode(cinfo, cio, img, NULL);
778
779         if (!bSuccess) {
780         opj_cio_close(cio);
781         fprintf(stderr, "failed to encode image\n");
782         return 1;
783         }
784
785         len = cio_tell(cio) - 8;
786         cio_seek(cio, 0);
787         cio_write(cio, len+8,4);
788         opj_cio_close(cio);
789
790         tk->sample[sampleno].sample_size = len+8;                               
791         tk->sample[sampleno].offset = offset;
792         tk->chunk[sampleno].offset = offset;    /* There is one sample per chunk */
793         fwrite(buf, 1, len+8, mj2file);                         
794         offset += len+8;                                
795
796         elapsed_time = opj_clock()-init_time;
797         fprintf(stderr, "Frame number %d/%d encoded in %.2f mseconds\n", 
798                 sampleno + 1, numframes, elapsed_time*1000);
799         total_time += elapsed_time;
800  }      /* for(sampleno */
801
802         free(buf);
803         opj_image_destroy(img);
804   }
805    }/* for(i */
806   
807         fseek(mj2file, mdat_initpos, SEEK_SET);
808         
809         buf = (unsigned char*) malloc(4*sizeof(unsigned char));
810
811 /* Init a cio to write box length variable in a little endian way */
812         cio = opj_cio_open(NULL, buf, 4);
813         cio_write(cio, offset - mdat_initpos, 4);
814         fwrite(buf, 4, 1, mj2file);
815         fseek(mj2file,0,SEEK_END);
816         free(buf);
817
818 /* Writing MOOV box */
819         buf = (unsigned char*) 
820          malloc ((TEMP_BUF+numframes*20) * sizeof(unsigned char));
821         cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+numframes*20));
822         mj2_write_moov(movie, cio);
823         fwrite(buf,cio_tell(cio),1,mj2file);
824         free(buf);
825
826         fprintf(stdout,"Total encoding time: %.2f s for %d frames (%.1f fps)\n",
827          total_time, numframes, (float)numframes/total_time);
828
829   /* Ending program */
830   
831         fclose(mj2file);
832 /* free remaining compression structures */
833         mj2_destroy_compress(movie);
834         free(cinfo);
835
836         if(j2k_parameters->cp_comment) free(j2k_parameters->cp_comment);
837         if(j2k_parameters->cp_matrice) free(j2k_parameters->cp_matrice);
838         opj_cio_close(cio);
839
840         return 0;
841 }