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