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