Merge pull request #1301 from rouault/fix_1299
[openjpeg.git] / src / lib / openjpip / jpip_parser.c
1 /*
2  * $Id$
3  *
4  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
5  * Copyright (c) 2002-2014, Professor Benoit Macq
6  * Copyright (c) 2010-2011, Kaori Hagihara
7  * Copyright (c) 2011,      Lucian Corlaciu, GSoC
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <math.h>
35 #include "jpip_parser.h"
36 #include "channel_manager.h"
37 #include "imgreg_manager.h"
38
39 #ifdef SERVER
40 #include "fcgi_stdio.h"
41 #define logstream FCGI_stdout
42 #else
43 #define FCGI_stdout stdout
44 #define FCGI_stderr stderr
45 #define logstream stderr
46 #endif /*SERVER*/
47
48
49 OPJ_BOOL identify_target(query_param_t query_param,
50                          targetlist_param_t *targetlist, target_param_t **target)
51 {
52     if (query_param.tid) {
53         if (strcmp(query_param.tid, "0") != 0) {
54             if (query_param.cid[0] != '\0') {
55                 fprintf(FCGI_stdout,
56                         "Reason: Target can not be specified both through tid and cid\r\n");
57                 fprintf(FCGI_stdout, "Status: 400\r\n");
58                 return OPJ_FALSE;
59             }
60             if ((*target = search_targetBytid(query_param.tid, targetlist))) {
61                 return OPJ_TRUE;
62             }
63         }
64     }
65
66     if (query_param.target)
67         if (!(*target = search_target(query_param.target, targetlist)))
68             if (!(*target = gene_target(targetlist, query_param.target))) {
69                 return OPJ_FALSE;
70             }
71
72     if (*target) {
73         fprintf(FCGI_stdout, "JPIP-tid: %s\r\n", (*target)->tid);
74         return OPJ_TRUE;
75     } else {
76         fprintf(FCGI_stdout, "Reason: target not found\r\n");
77         fprintf(FCGI_stdout, "Status: 400\r\n");
78         return OPJ_FALSE;
79     }
80 }
81
82 OPJ_BOOL associate_channel(query_param_t    query_param,
83                            sessionlist_param_t *sessionlist,
84                            session_param_t **cursession,
85                            channel_param_t **curchannel)
86 {
87     if (search_session_and_channel(query_param.cid, sessionlist, cursession,
88                                    curchannel)) {
89
90         if (!query_param.cnew) {
91             set_channel_variable_param(query_param, *curchannel);
92         }
93     } else {
94         fprintf(FCGI_stderr, "Error: process canceled\n");
95         return OPJ_FALSE;
96     }
97     return OPJ_TRUE;
98 }
99
100 OPJ_BOOL open_channel(query_param_t query_param,
101                       sessionlist_param_t *sessionlist,
102                       auxtrans_param_t auxtrans,
103                       target_param_t *target,
104                       session_param_t **cursession,
105                       channel_param_t **curchannel)
106 {
107     cachemodel_param_t *cachemodel = NULL;
108
109     if (target) {
110         if (!(*cursession)) {
111             *cursession = gene_session(sessionlist);
112         }
113         if (!(cachemodel = search_cachemodel(target, (*cursession)->cachemodellist)))
114             if (!(cachemodel = gene_cachemodel((*cursession)->cachemodellist, target,
115                                                query_param.return_type == JPPstream))) {
116                 return OPJ_FALSE;
117             }
118     } else if (*curchannel) {
119         cachemodel = (*curchannel)->cachemodel;
120     }
121
122     *curchannel = gene_channel(query_param, auxtrans, cachemodel,
123                                (*cursession)->channellist);
124     if (*curchannel == NULL) {
125         return OPJ_FALSE;
126     }
127
128     return OPJ_TRUE;
129 }
130
131 OPJ_BOOL close_channel(query_param_t query_param,
132                        sessionlist_param_t *sessionlist,
133                        session_param_t **cursession,
134                        channel_param_t **curchannel)
135 {
136     char *cclose;
137     int i;
138
139     if (query_param.cclose[0] == '*') {
140 #ifndef SERVER
141         fprintf(logstream, "local log: close all\n");
142 #endif
143         /* all channels associatd with the session will be closed */
144         if (!delete_session(cursession, sessionlist)) {
145             return OPJ_FALSE;
146         }
147     } else {
148         /* check if all entry belonging to the same session */
149
150         for (i = 0, cclose = query_param.cclose; i < query_param.numOfcclose;
151                 i++, cclose += (strlen(cclose) + 1)) {
152
153             /* In case of the first entry of close cid */
154             if (*cursession == NULL) {
155                 if (!search_session_and_channel(cclose, sessionlist, cursession, curchannel)) {
156                     return OPJ_FALSE;
157                 }
158             } else /* second or more entry of close cid */
159                 if (!(*curchannel = search_channel(cclose, (*cursession)->channellist))) {
160                     fprintf(FCGI_stdout, "Reason: Cclose id %s is from another session\r\n",
161                             cclose);
162                     return OPJ_FALSE;
163                 }
164         }
165
166         /* delete channels */
167         for (i = 0, cclose = query_param.cclose; i < query_param.numOfcclose;
168                 i++, cclose += (strlen(cclose) + 1)) {
169             *curchannel = search_channel(cclose, (*cursession)->channellist);
170             delete_channel(curchannel, (*cursession)->channellist);
171         }
172
173         if ((*cursession)->channellist->first == NULL ||
174                 (*cursession)->channellist->last == NULL)
175             /* In case of empty session */
176         {
177             delete_session(cursession, sessionlist);
178         }
179     }
180     return OPJ_TRUE;
181 }
182
183
184 /**
185  * enqueue tiles or precincts into the message queue
186  *
187  * @param[in] query_param structured query
188  * @param[in] msgqueue    message queue pointer
189  */
190 void enqueue_imagedata(query_param_t query_param, msgqueue_param_t *msgqueue);
191
192 /**
193  * enqueue metadata bins into the message queue
194  *
195  * @param[in]     query_param  structured query
196  * @param[in]     metadatalist pointer to metadata bin list
197  * @param[in,out] msgqueue     message queue pointer
198  * @return                     if succeeded (true) or failed (false)
199  */
200 OPJ_BOOL enqueue_metabins(query_param_t query_param,
201                           metadatalist_param_t *metadatalist, msgqueue_param_t *msgqueue);
202
203
204 OPJ_BOOL gene_JPIPstream(query_param_t query_param,
205                          target_param_t *target,
206                          session_param_t *cursession,
207                          channel_param_t *curchannel,
208                          msgqueue_param_t **msgqueue)
209 {
210     index_param_t *codeidx;
211     cachemodel_param_t *cachemodel;
212
213     if (!cursession || !curchannel) { /* stateless */
214         if (!target) {
215             return OPJ_FALSE;
216         }
217         if (!(cachemodel = gene_cachemodel(NULL, target,
218                                            query_param.return_type == JPPstream))) {
219             return OPJ_FALSE;
220         }
221         *msgqueue = gene_msgqueue(OPJ_TRUE, cachemodel);
222     } else { /* session */
223         cachemodel  = curchannel->cachemodel;
224         target = cachemodel->target;
225         *msgqueue = gene_msgqueue(OPJ_FALSE, cachemodel);
226     }
227
228     codeidx = target->codeidx;
229
230     if (cachemodel->jppstream) {
231         fprintf(FCGI_stdout, "Content-type: image/jpp-stream\r\n");
232     } else {
233         fprintf(FCGI_stdout, "Content-type: image/jpt-stream\r\n");
234     }
235
236     if (query_param.layers != -1) {
237         if (query_param.layers  > codeidx->COD.numOflayers) {
238             fprintf(FCGI_stdout, "JPIP-layers: %d\r\n", codeidx->COD.numOflayers);
239             query_param.layers = codeidx->COD.numOflayers;
240         }
241     }
242
243     /*meta*/
244     if (query_param.box_type[0][0] != 0  && query_param.len != 0)
245         if (!enqueue_metabins(query_param, codeidx->metadatalist, *msgqueue)) {
246             return OPJ_FALSE;
247         }
248
249     if (query_param.metadata_only) {
250         return OPJ_TRUE;
251     }
252
253     /* main header */
254     if (!cachemodel->mhead_model && query_param.len != 0) {
255         enqueue_mainheader(*msgqueue);
256     }
257
258     /* image codestream */
259     if ((query_param.fx > 0 && query_param.fy > 0)) {
260         enqueue_imagedata(query_param, *msgqueue);
261     }
262
263     return OPJ_TRUE;
264 }
265
266
267 /**
268  * enqueue precinct data-bins into the queue
269  *
270  * @param[in] xmin      min x coordinate in the tile at the decomposition level
271  * @param[in] xmax      max x coordinate in the tile at the decomposition level
272  * @param[in] ymin      min y coordinate in the tile at the decomposition level
273  * @param[in] ymax      max y coordinate in the tile at the decomposition level
274  * @param[in] tile_id   tile index
275  * @param[in] level     decomposition level
276  * @param[in] lastcomp  last component number
277  * @param[in] comps     pointer to the array that stores the requested components
278  * @param[in] layers    number of quality layers
279  * @param[in] msgqueue  message queue
280  * @return
281  */
282 void enqueue_precincts(int xmin, int xmax, int ymin, int ymax, int tile_id,
283                        int level, int lastcomp, OPJ_BOOL *comps, int layers,
284                        msgqueue_param_t *msgqueue);
285
286 /**
287  * enqueue all precincts inside a tile into the queue
288  *
289  * @param[in] tile_id   tile index
290  * @param[in] level     decomposition level
291  * @param[in] lastcomp  last component number
292  * @param[in] comps     pointer to the array that stores the requested components
293  * @param[in] layers    number of quality layers
294  * @param[in] msgqueue  message queue
295  * @return
296  */
297 void enqueue_allprecincts(int tile_id, int level, int lastcomp, OPJ_BOOL *comps,
298                           int layers, msgqueue_param_t *msgqueue);
299
300 void enqueue_imagedata(query_param_t query_param, msgqueue_param_t *msgqueue)
301 {
302     index_param_t *codeidx;
303     imgreg_param_t imgreg;
304     range_param_t tile_Xrange, tile_Yrange;
305     Byte4_t u, v, tile_id;
306     int xmin, xmax, ymin, ymax;
307     int numOfreslev;
308
309     codeidx = msgqueue->cachemodel->target->codeidx;
310
311     if (!(msgqueue->cachemodel->jppstream)  &&
312             get_nmax(codeidx->tilepart) == 1) { /* normally not the case */
313         numOfreslev = 1;
314     } else {
315         numOfreslev = codeidx->COD.numOfdecomp + 1;
316     }
317
318     imgreg  = map_viewin2imgreg(query_param.fx, query_param.fy,
319                                 query_param.rx, query_param.ry, query_param.rw, query_param.rh,
320                                 (int)codeidx->SIZ.XOsiz, (int)codeidx->SIZ.YOsiz, (int)codeidx->SIZ.Xsiz,
321                                 (int)codeidx->SIZ.Ysiz,
322                                 numOfreslev);
323
324     if (query_param.len == 0) {
325         return;
326     }
327
328     for (u = 0, tile_id = 0; u < codeidx->SIZ.YTnum; u++) {
329         tile_Yrange = get_tile_Yrange(codeidx->SIZ, tile_id, imgreg.level);
330
331         for (v = 0; v < codeidx->SIZ.XTnum; v++, tile_id++) {
332             tile_Xrange = get_tile_Xrange(codeidx->SIZ, tile_id, imgreg.level);
333
334             if (tile_Xrange.minvalue < tile_Xrange.maxvalue &&
335                     tile_Yrange.minvalue < tile_Yrange.maxvalue) {
336                 if (tile_Xrange.maxvalue <= (Byte4_t)(imgreg.xosiz + imgreg.ox) ||
337                         tile_Xrange.minvalue >= (Byte4_t)(imgreg.xosiz + imgreg.ox + imgreg.sx) ||
338                         tile_Yrange.maxvalue <= (Byte4_t)(imgreg.yosiz + imgreg.oy) ||
339                         tile_Yrange.minvalue >= (Byte4_t)(imgreg.yosiz + imgreg.oy + imgreg.sy)) {
340                     /*printf("Tile completely excluded from view-window %d\n", tile_id);*/
341                     /* Tile completely excluded from view-window */
342                 } else if (tile_Xrange.minvalue >= (Byte4_t)(imgreg.xosiz + imgreg.ox) &&
343                            tile_Xrange.maxvalue <= (Byte4_t)(imgreg.xosiz + imgreg.ox + imgreg.sx) &&
344                            tile_Yrange.minvalue >= (Byte4_t)(imgreg.yosiz + imgreg.oy) &&
345                            tile_Yrange.maxvalue <= (Byte4_t)(imgreg.yosiz + imgreg.oy + imgreg.sy)) {
346                     /* Tile completely contained within view-window */
347                     /* high priority */
348                     /*printf("Tile completely contained within view-window %d\n", tile_id);*/
349                     if (msgqueue->cachemodel->jppstream) {
350                         enqueue_tileheader((int)tile_id, msgqueue);
351                         enqueue_allprecincts((int)tile_id, imgreg.level, query_param.lastcomp,
352                                              query_param.comps, query_param.layers, msgqueue);
353                     } else {
354                         enqueue_tile(tile_id, imgreg.level, msgqueue);
355                     }
356                 } else {
357                     /* Tile partially overlaps view-window */
358                     /* low priority */
359                     /*printf("Tile partially overlaps view-window %d\n", tile_id);*/
360                     if (msgqueue->cachemodel->jppstream) {
361                         enqueue_tileheader((int)tile_id, msgqueue);
362
363                         /* FIXME: The following code is suspicious it implicitly cast an unsigned int to int, which truncates values */
364                         xmin = tile_Xrange.minvalue >= (Byte4_t)(imgreg.xosiz + imgreg.ox) ? 0 :
365                                imgreg.xosiz + imgreg.ox - (int)tile_Xrange.minvalue;
366                         xmax = tile_Xrange.maxvalue <= (Byte4_t)(imgreg.xosiz + imgreg.ox + imgreg.sx)
367                                ? (int)(tile_Xrange.maxvalue - tile_Xrange.minvalue - 1) : (int)(
368                                    imgreg.xosiz + imgreg.ox + imgreg.sx - (int)tile_Xrange.minvalue - 1);
369                         ymin = tile_Yrange.minvalue >= (Byte4_t)(imgreg.yosiz + imgreg.oy) ? 0 :
370                                imgreg.yosiz + imgreg.oy - (int)tile_Yrange.minvalue;
371                         ymax = tile_Yrange.maxvalue <= (Byte4_t)(imgreg.yosiz + imgreg.oy + imgreg.sy)
372                                ? (int)(tile_Yrange.maxvalue - tile_Yrange.minvalue - 1) : (int)(
373                                    imgreg.yosiz + imgreg.oy + imgreg.sy - (int)tile_Yrange.minvalue - 1);
374                         enqueue_precincts(xmin, xmax, ymin, ymax, (int)tile_id, imgreg.level,
375                                           query_param.lastcomp, query_param.comps, query_param.layers, msgqueue);
376                     } else {
377                         enqueue_tile(tile_id, imgreg.level, msgqueue);
378                     }
379                 }
380             }
381         }
382     }
383 }
384
385
386 void enqueue_precincts(int xmin, int xmax, int ymin, int ymax, int tile_id,
387                        int level, int lastcomp, OPJ_BOOL *comps, int layers,
388                        msgqueue_param_t *msgqueue)
389 {
390     index_param_t *codeidx;
391     int c, u, v, res_lev, dec_lev;
392     int seq_id;
393     Byte4_t XTsiz, YTsiz;
394     Byte4_t XPsiz, YPsiz;
395     Byte4_t xminP, xmaxP, yminP, ymaxP;
396
397     codeidx  = msgqueue->cachemodel->target->codeidx;
398     /* MM: shouldn't xmin/xmax be Byte4_t instead ? */
399     if (xmin < 0 || xmax < 0 || ymin < 0 || ymax < 0) {
400         return;
401     }
402     /* MM: I think the API should not really be int should it ? */
403     if (tile_id < 0) {
404         return;
405     }
406
407     for (c = 0; c < codeidx->SIZ.Csiz; c++)
408         if (lastcomp == -1 /*all*/ || (c <= lastcomp && comps[c])) {
409             seq_id = 0;
410             for (res_lev = 0, dec_lev = codeidx->COD.numOfdecomp; dec_lev >= level;
411                     res_lev++, dec_lev--) {
412
413                 XTsiz = get_tile_XSiz(codeidx->SIZ, (Byte4_t)tile_id, dec_lev);
414                 YTsiz = get_tile_YSiz(codeidx->SIZ, (Byte4_t)tile_id, dec_lev);
415
416                 XPsiz = (codeidx->COD.Scod & 0x01) ? codeidx->COD.XPsiz[ res_lev] : XTsiz;
417                 YPsiz = (codeidx->COD.Scod & 0x01) ? codeidx->COD.YPsiz[ res_lev] : YTsiz;
418
419                 for (u = 0; u < ceil((double)YTsiz / (double)YPsiz); u++) {
420                     yminP = (Byte4_t)u * YPsiz;
421                     ymaxP = (Byte4_t)(u + 1) * YPsiz - 1;
422                     if (YTsiz <= ymaxP) {
423                         ymaxP = YTsiz - 1;
424                     }
425
426                     for (v = 0; v < ceil((double)XTsiz / (double)XPsiz); v++, seq_id++) {
427                         xminP = (Byte4_t)v * XPsiz;
428                         xmaxP = (Byte4_t)(v + 1) * XPsiz - 1;
429                         if (XTsiz <= xmaxP) {
430                             xmaxP = XTsiz - 1;
431                         }
432
433                         if (xmaxP < (Byte4_t)xmin || xminP > (Byte4_t)xmax || ymaxP < (Byte4_t)ymin ||
434                                 yminP > (Byte4_t)ymax) {
435                             /* Precinct completely excluded from view-window */
436                         } else if (xminP >= (Byte4_t)xmin && xmaxP <= (Byte4_t)xmax &&
437                                    yminP >= (Byte4_t)ymin && ymaxP <= (Byte4_t)ymax) {
438                             /* Precinct completely contained within view-window
439                              high priority */
440                             enqueue_precinct(seq_id, tile_id, c, (dec_lev > level) ? -1 : layers, msgqueue);
441                         } else {
442                             /* Precinct partially overlaps view-window
443                              low priority */
444                             enqueue_precinct(seq_id, tile_id, c, (dec_lev > level) ? -1 : layers, msgqueue);
445                         }
446                     }
447                 }
448             }
449         }
450 }
451
452 void enqueue_allprecincts(int tile_id, int level, int lastcomp, OPJ_BOOL *comps,
453                           int layers, msgqueue_param_t *msgqueue)
454 {
455     index_param_t *codeidx;
456     int c, i, res_lev, dec_lev;
457     int seq_id;
458     Byte4_t XTsiz, YTsiz;
459     Byte4_t XPsiz, YPsiz;
460
461     codeidx  = msgqueue->cachemodel->target->codeidx;
462     if (tile_id < 0) {
463         return;
464     }
465
466     for (c = 0; c < codeidx->SIZ.Csiz; c++)
467         if (lastcomp == -1 /*all*/ || (c <= lastcomp && comps[c])) {
468             seq_id = 0;
469             for (res_lev = 0, dec_lev = codeidx->COD.numOfdecomp; dec_lev >= level;
470                     res_lev++, dec_lev--) {
471
472                 XTsiz = get_tile_XSiz(codeidx->SIZ, (Byte4_t)tile_id, dec_lev);
473                 YTsiz = get_tile_YSiz(codeidx->SIZ, (Byte4_t)tile_id, dec_lev);
474
475                 XPsiz = (codeidx->COD.Scod & 0x01) ? codeidx->COD.XPsiz[ res_lev] : XTsiz;
476                 YPsiz = (codeidx->COD.Scod & 0x01) ? codeidx->COD.YPsiz[ res_lev] : YTsiz;
477
478                 for (i = 0;
479                         i < ceil((double)YTsiz / (double)YPsiz)*ceil((double)XTsiz / (double)XPsiz);
480                         i++, seq_id++) {
481                     enqueue_precinct(seq_id, tile_id, c, (dec_lev > level) ? -1 : layers,
482                                      msgqueue);
483                 }
484             }
485         }
486 }
487
488 OPJ_BOOL enqueue_metabins(query_param_t query_param,
489                           metadatalist_param_t *metadatalist, msgqueue_param_t *msgqueue)
490 {
491     int i;
492     for (i = 0; i < MAX_NUMOFBOX && query_param.box_type[i][0] != 0; i++) {
493         if (query_param.box_type[i][0] == '*') {
494             fprintf(FCGI_stdout, "Status: 501\r\n");
495             fprintf(FCGI_stdout,
496                     "Reason: metareq with all box-property * not implemented\r\n");
497             return OPJ_FALSE;
498         } else {
499             Byte8_t idx = search_metadataidx(query_param.box_type[i], metadatalist);
500
501             if (idx != (Byte8_t) - 1) {
502                 enqueue_metadata(idx, msgqueue);
503             } else {
504                 fprintf(FCGI_stdout, "Status: 400\r\n");
505                 fprintf(FCGI_stdout, "Reason: box-type %.4s not found\r\n",
506                         query_param.box_type[i]);
507                 return OPJ_FALSE;
508             }
509         }
510     }
511     return OPJ_TRUE;
512 }