[trunk] Fix openmj2/mj2 compilation
[openjpeg.git] / src / bin / mj2 / opj_mj2_wrap.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "openjpeg.h"
34 #include "cio.h"
35 #include "j2k.h"
36 #include "jp2.h"
37 #include "mj2.h"
38
39 static int int_ceildiv(int a, int b) {
40         return (a + b - 1) / b;
41 }
42
43 /**
44 Size of memory first allocated for MOOV box
45 */
46 #define TEMP_BUF 10000 
47
48 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
49
50 /* -------------------------------------------------------------------------- */
51
52 static int test_image(const char *fname, mj2_cparameters_t *cp)
53 {
54         FILE *reader;
55         opj_image_t *image;
56         unsigned char *src;
57         opj_dinfo_t *dinfo;
58         opj_cio_t *cio;
59         opj_dparameters_t dparameters;
60         int success;
61         long src_len;
62
63         success = 0;
64
65         if((reader = fopen(fname, "rb")) == NULL) return success;
66
67         fseek(reader, 0, SEEK_END);
68         src_len = ftell(reader);
69         fseek(reader, 0, SEEK_SET);
70         src = (unsigned char*) malloc(src_len);
71         fread(src, 1, src_len, reader);
72         fclose(reader);
73
74         if(memcmp(src, J2K_CODESTREAM_MAGIC, 4) != 0)
75    {
76         free(src); return success;
77    }
78         memset(&dparameters, 0, sizeof(opj_dparameters_t));
79
80         opj_set_default_decoder_parameters(&dparameters);
81
82         dinfo = opj_create_decompress(CODEC_J2K);
83
84         opj_setup_decoder(dinfo, &dparameters);
85
86         cio = opj_cio_open((opj_common_ptr)dinfo, src, src_len);
87
88 #if 0 /* MM: FIXME */
89         image = opj_decode(dinfo, cio);
90 #endif
91
92         free(src); cio->buffer = NULL;
93         opj_cio_close(cio);
94
95         if(image == NULL) goto fin;
96
97         cp->numcomps = image->numcomps;
98         cp->w = image->comps[0].w;
99         cp->h = image->comps[0].h;
100         cp->prec = image->comps[0].prec;
101
102         if(image->numcomps > 2 )
103    {
104         if((image->comps[0].dx == 1)
105         && (image->comps[1].dx == 2)
106         && (image->comps[2].dx == 2)
107         && (image->comps[0].dy == 1)
108         && (image->comps[1].dy == 2)
109         && (image->comps[2].dy == 2))/* horizontal and vertical*/
110   {
111 /*   Y420*/
112         cp->enumcs = ENUMCS_SYCC;
113         cp->CbCr_subsampling_dx = 2;
114         cp->CbCr_subsampling_dy = 2;
115   }
116         else
117         if((image->comps[0].dx == 1)
118         && (image->comps[1].dx == 2)
119         && (image->comps[2].dx == 2)
120         && (image->comps[0].dy == 1)
121         && (image->comps[1].dy == 1)
122         && (image->comps[2].dy == 1))/* horizontal only*/
123   {
124 /*   Y422*/
125         cp->enumcs = ENUMCS_SYCC;
126         cp->CbCr_subsampling_dx = 2;
127         cp->CbCr_subsampling_dy = 1;
128   }
129         else
130         if((image->comps[0].dx == 1)
131         && (image->comps[1].dx == 1)
132         && (image->comps[2].dx == 1)
133         && (image->comps[0].dy == 1)
134         && (image->comps[1].dy == 1)
135         && (image->comps[2].dy == 1))
136   {
137 /*   Y444 or RGB */
138
139         if(image->color_space ==  CLRSPC_SRGB)
140  {
141         cp->enumcs = ENUMCS_SRGB;
142
143 /*    cp->CbCr_subsampling_dx = 0; */
144 /*    cp->CbCr_subsampling_dy = 0; */
145  }
146         else
147  {
148         cp->enumcs = ENUMCS_SYCC;
149
150         cp->CbCr_subsampling_dx = 1;
151         cp->CbCr_subsampling_dy = 1;
152  }
153   }
154         else
155   {
156         goto fin;
157   }
158    }
159         else
160    {
161         cp->enumcs = ENUMCS_GRAY;
162 /*  cp->CbCr_subsampling_dx = 0; */
163 /*  cp->CbCr_subsampling_dy = 0; */
164    }
165         if(image->icc_profile_buf)
166    {
167         cp->meth = 2;
168         free(image->icc_profile_buf); image->icc_profile_buf = NULL;
169    }
170         else cp->meth = 1;
171
172         success = 1;
173 fin:
174         if(dinfo)
175          opj_destroy_decompress(dinfo);
176
177         if(image)
178          opj_image_destroy(image);
179
180         return success;
181 }
182
183 /**
184 sample error callback expecting a FILE* client object
185 */
186 void error_callback(const char *msg, void *client_data) {
187         FILE *stream = (FILE*)client_data;
188         fprintf(stream, "[ERROR] %s", msg);
189 }
190 /**
191 sample warning callback expecting a FILE* client object
192 */
193 void warning_callback(const char *msg, void *client_data) {
194         FILE *stream = (FILE*)client_data;
195         fprintf(stream, "[WARNING] %s", msg);
196 }
197 /**
198 sample debug callback expecting a FILE* client object
199 */
200 void info_callback(const char *msg, void *client_data) {
201         FILE *stream = (FILE*)client_data;
202         fprintf(stream, "[INFO] %s", msg);
203 }
204
205 /* -------------------------------------------------------------------------- */
206
207
208
209 static void read_siz_marker(FILE *file, opj_image_t *image)
210 {
211   int len,i;
212   char buf, buf2[2];
213   unsigned char *siz_buffer;
214         opj_cio_t *cio;
215   
216   fseek(file, 0, SEEK_SET);
217   do {
218     fread(&buf,1,1, file);
219     if (buf==(char)0xff)
220       fread(&buf,1,1, file);
221   }
222   while (!(buf==(char)0x51));
223   
224   fread(buf2,2,1,file);         /* Lsiz                */
225   len = ((buf2[0])<<8) + buf2[1];
226   
227   siz_buffer = (unsigned char*) malloc(len * sizeof(unsigned char));
228   fread(siz_buffer,len, 1, file);
229         cio = opj_cio_open(NULL, siz_buffer, len);
230   
231   cio_read(cio, 2);                     /* Rsiz (capabilities) */
232   image->x1 = cio_read(cio, 4); /* Xsiz                */
233   image->y1 = cio_read(cio, 4); /* Ysiz                */
234   image->x0 = cio_read(cio, 4); /* X0siz               */
235   image->y0 = cio_read(cio, 4); /* Y0siz               */
236   cio_skip(cio, 16);                    /* XTsiz, YTsiz, XT0siz, YT0siz        */
237   
238   image->numcomps = cio_read(cio,2);    /* Csiz                */
239   image->comps =
240     (opj_image_comp_t *) malloc(image->numcomps * sizeof(opj_image_comp_t));
241         
242   for (i = 0; i < image->numcomps; i++) {
243     int tmp;
244     tmp = cio_read(cio,1);              /* Ssiz_i          */
245     image->comps[i].prec = (tmp & 0x7f) + 1;
246     image->comps[i].sgnd = tmp >> 7;
247     image->comps[i].dx = cio_read(cio,1);       /* XRsiz_i         */
248     image->comps[i].dy = cio_read(cio,1);       /* YRsiz_i         */
249     image->comps[i].resno_decoded = 0;  /* number of resolution decoded */
250     image->comps[i].factor = 0; /* reducing factor by component */
251   }
252   fseek(file, 0, SEEK_SET);
253         opj_cio_close(cio);
254   free(siz_buffer);
255 }
256
257 static void setparams(opj_mj2_t *movie, opj_image_t *image) {
258   int i, depth_0, depth, sign;
259   
260   movie->tk[0].w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
261   movie->tk[0].h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
262   mj2_init_stdmovie(movie);
263   
264   movie->tk[0].depth = image->comps[0].prec;
265         
266   if (image->numcomps==3) {
267     if ((image->comps[0].dx == 1) 
268         && (image->comps[1].dx == 1) 
269         && (image->comps[2].dx == 1)) 
270       movie->tk[0].CbCr_subsampling_dx = 1;
271     else 
272         if ((image->comps[0].dx == 1) 
273         && (image->comps[1].dx == 2) 
274         && (image->comps[2].dx == 2))
275       movie->tk[0].CbCr_subsampling_dx = 2;
276     else
277       fprintf(stderr,"Image component sizes are incoherent\n");
278     
279     if ((image->comps[0].dy == 1) 
280         && (image->comps[1].dy == 1) 
281         && (image->comps[2].dy == 1)) 
282       movie->tk[0].CbCr_subsampling_dy = 1;
283     else 
284         if ((image->comps[0].dy == 1) 
285         && (image->comps[1].dy == 2) 
286         && (image->comps[2].dy == 2))
287       movie->tk[0].CbCr_subsampling_dy = 2;
288     else
289       fprintf(stderr,"Image component sizes are incoherent\n");
290   }
291   
292   movie->tk[0].sample_rate = 25;
293   
294   movie->tk[0].jp2_struct.numcomps = image->numcomps;   /* NC */
295         
296         /* Init Standard jp2 structure */
297         
298         movie->tk[0].jp2_struct.comps =
299     (opj_jp2_comps_t *) malloc(movie->tk[0].jp2_struct.numcomps * sizeof(opj_jp2_comps_t));
300   movie->tk[0].jp2_struct.precedence = 0;   /* PRECEDENCE*/
301   movie->tk[0].jp2_struct.approx = 0;   /* APPROX*/
302   movie->tk[0].jp2_struct.brand = JP2_JP2;      /* BR         */
303   movie->tk[0].jp2_struct.minversion = 0;       /* MinV       */
304   movie->tk[0].jp2_struct.numcl = 1;
305   movie->tk[0].jp2_struct.cl = (unsigned int *) malloc(movie->tk[0].jp2_struct.numcl * sizeof(int));
306   movie->tk[0].jp2_struct.cl[0] = JP2_JP2;      /* CL0 : JP2  */
307   movie->tk[0].jp2_struct.C = 7;      /* C : Always 7*/
308   movie->tk[0].jp2_struct.UnkC = 0;      /* UnkC, colorspace specified in colr box*/
309   movie->tk[0].jp2_struct.IPR = 0;      /* IPR, no intellectual property*/
310   movie->tk[0].jp2_struct.w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
311   movie->tk[0].jp2_struct.h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
312   
313   depth_0 = image->comps[0].prec - 1;
314   sign = image->comps[0].sgnd;
315   movie->tk[0].jp2_struct.bpc = depth_0 + (sign << 7);
316   
317   for (i = 1; i < image->numcomps; i++) {
318     depth = image->comps[i].prec - 1;
319     sign = image->comps[i].sgnd;
320     if (depth_0 != depth)
321       movie->tk[0].jp2_struct.bpc = 255;
322   }
323   
324   for (i = 0; i < image->numcomps; i++)
325     movie->tk[0].jp2_struct.comps[i].bpcc =
326     image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
327   
328   if ((image->numcomps == 1 || image->numcomps == 3)
329     && (movie->tk[0].jp2_struct.bpc != 255))
330     movie->tk[0].jp2_struct.meth = 1;
331   else
332     movie->tk[0].jp2_struct.meth = 2;
333         
334     if (image->numcomps == 1)
335      movie->tk[0].jp2_struct.enumcs = 17;  /* Grayscale */
336   
337     else   
338         if ((image->comps[0].dx == 1) 
339         && (image->comps[1].dx == 1) 
340         && (image->comps[2].dx == 1) 
341     && (image->comps[0].dy == 1) 
342         && (image->comps[1].dy == 1) 
343         && (image->comps[2].dy == 1)) 
344      movie->tk[0].jp2_struct.enumcs = 16;    /* RGB */
345   
346     else   
347         if ((image->comps[0].dx == 1) 
348         && (image->comps[1].dx == 2) 
349         && (image->comps[2].dx == 2) 
350     && (image->comps[0].dy == 1) 
351         && (image->comps[1].dy == 2) 
352         && (image->comps[2].dy == 2)) 
353      movie->tk[0].jp2_struct.enumcs = 18;  /* YUV */
354   
355   else
356     movie->tk[0].jp2_struct.enumcs = 0; /* Unkown profile */
357 }
358
359 int main(int argc, char *argv[]) {
360         opj_cinfo_t* cinfo; 
361         opj_event_mgr_t event_mgr;              /* event manager */  
362   unsigned int snum;
363   opj_mj2_t *movie;
364   mj2_sample_t *sample;
365   unsigned char* frame_codestream;
366   FILE *mj2file, *j2kfile;
367   char *j2kfilename;
368   unsigned char *buf;
369   int offset, mdat_initpos;
370   opj_image_t img;
371         opj_cio_t *cio;
372         mj2_cparameters_t parameters;
373         
374   if (argc != 3) {
375     printf("Usage: %s source_location mj2_filename\n",argv[0]);
376     printf("Example: %s input/input output.mj2\n",argv[0]);
377     return 1;
378   }
379   
380   mj2file = fopen(argv[2], "wb");
381   
382   if (!mj2file) {
383     fprintf(stderr, "failed to open %s for writing\n", argv[2]);
384     return 1;
385   }
386         memset(&img, 0, sizeof(opj_image_t));
387         /*
388         configure the event callbacks (not required)
389         setting of each callback is optionnal
390         */
391         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
392         event_mgr.error_handler = error_callback;
393         event_mgr.warning_handler = warning_callback;
394         event_mgr.info_handler = info_callback;
395
396         /* get a MJ2 decompressor handle */
397         cinfo = mj2_create_compress();
398
399         /* catch events using our callbacks and give a local context */
400         opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);   
401         
402         /* setup the decoder encoding parameters using user parameters */
403         memset(&parameters, 0, sizeof(mj2_cparameters_t));
404         movie = (opj_mj2_t*) cinfo->mj2_handle;
405
406         j2kfilename = (char*)malloc(strlen(argv[1]) + 12);/* max. '%6d' */
407         sprintf(j2kfilename, "%s_00001.j2k",argv[1]);
408
409         if(test_image(j2kfilename, &parameters) == 0) goto fin;
410
411         parameters.frame_rate = 25; /* DEFAULT */
412
413         mj2_setup_encoder(movie, &parameters);
414
415   
416         /* Writing JP, FTYP and MDAT boxes 
417         Assuming that the JP and FTYP boxes won't be longer than 300 bytes */
418         
419   buf = (unsigned char*) malloc (300 * sizeof(unsigned char)); 
420   cio = opj_cio_open(movie->cinfo, buf, 300);
421   mj2_write_jp(cio);
422   mj2_write_ftyp(movie, cio);
423   mdat_initpos = cio_tell(cio);
424   cio_skip(cio, 4);
425   cio_write(cio,MJ2_MDAT, 4);   
426   fwrite(buf,cio_tell(cio),1,mj2file);
427   free(buf);
428         
429   /* Insert each j2k codestream in a JP2C box */
430   snum=0;
431   offset = 0;  
432   while(1)
433   {
434     mj2_sample_t * new_sample;
435     mj2_chunk_t * new_chunk;
436     sample = &movie->tk[0].sample[snum];
437     sprintf(j2kfilename,"%s_%05d.j2k",argv[1],snum);
438     j2kfile = fopen(j2kfilename, "rb");
439     if (!j2kfile) {
440       if (snum==0) {  /* Could not open a single codestream */
441                                 fprintf(stderr, "failed to open %s for reading\n",j2kfilename);
442                                 return 1;
443       }
444       else {          /* Tried to open a inexistant codestream */
445                                 fprintf(stdout,"%d frames are being added to the MJ2 file\n",snum);
446                                 break;
447       }
448     }
449
450     /* Calculating offset for samples and chunks */
451     offset += cio_tell(cio);     
452     sample->offset = offset;
453     movie->tk[0].chunk[snum].offset = offset;  /* There will be one sample per chunk */
454     
455     /* Calculating sample size */
456     fseek(j2kfile,0,SEEK_END);  
457     sample->sample_size = ftell(j2kfile) + 8; /* Sample size is codestream + JP2C box header */
458     fseek(j2kfile,0,SEEK_SET);
459     
460     /* Reading siz marker of j2k image for the first codestream */
461     if (snum==0)              
462       read_siz_marker(j2kfile, &img);
463     
464     /* Writing JP2C box header */
465     frame_codestream = (unsigned char*) malloc (sample->sample_size+8); 
466                 cio = opj_cio_open(movie->cinfo, frame_codestream, sample->sample_size);    
467     cio_write(cio,sample->sample_size, 4);  /* Sample size */
468     cio_write(cio,JP2_JP2C, 4); /* JP2C */
469     
470     /* Writing codestream from J2K file to MJ2 file */
471     fread(frame_codestream+8,sample->sample_size-8,1,j2kfile);
472     fwrite(frame_codestream,sample->sample_size,1,mj2file);
473     cio_skip(cio, sample->sample_size-8);
474     
475     /* Ending loop */
476     fclose(j2kfile);
477     snum++;
478     new_sample = (mj2_sample_t*)
479                 realloc(movie->tk[0].sample, (snum+1) * sizeof(mj2_sample_t));
480     new_chunk = (mj2_chunk_t*)
481                 realloc(movie->tk[0].chunk, (snum+1) * sizeof(mj2_chunk_t));
482     if (new_sample && new_chunk) {
483         movie->tk[0].sample = new_sample;
484         movie->tk[0].chunk = new_chunk;
485     } else {
486        fprintf(stderr, "Failed to allocate enough memory to read %s\n", j2kfilename);
487        return 1;
488     }
489     free(frame_codestream);
490   }
491   
492   /* Writing the MDAT box length in header */
493   offset += cio_tell(cio);
494   buf = (unsigned char*) malloc (4 * sizeof(unsigned char));
495         cio = opj_cio_open(movie->cinfo, buf, 4);
496   cio_write(cio,offset-mdat_initpos,4); 
497   fseek(mj2file,(long)mdat_initpos,SEEK_SET);
498   fwrite(buf,4,1,mj2file);
499   fseek(mj2file,0,SEEK_END);
500   free(buf);
501         
502   /* Setting movie parameters */
503   movie->tk[0].num_samples=snum;
504   movie->tk[0].num_chunks=snum;
505   setparams(movie, &img);
506         
507   /* Writing MOOV box */
508         buf = (unsigned char*) malloc ((TEMP_BUF+snum*20) * sizeof(unsigned char));
509         cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+snum*20));
510         mj2_write_moov(movie, cio);
511   fwrite(buf,cio_tell(cio),1,mj2file);
512         
513   /* Ending program */
514   free(img.comps);
515   opj_cio_close(cio);
516
517 fin:
518   fclose(mj2file);
519   mj2_destroy_compress(movie);
520   free(j2kfilename);
521
522   return 0;
523 }