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