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