File: cache_tiff.c

package info (click to toggle)
mapcache 1.4.1-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,892 kB
  • ctags: 2,572
  • sloc: ansic: 25,570; xml: 367; sh: 92; makefile: 66; python: 48
file content (870 lines) | stat: -rw-r--r-- 30,714 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
/******************************************************************************
 * $Id$
 *
 * Project:  MapServer
 * Purpose:  MapCache tile caching: tiled tiff filesytem cache backend.
 * Author:   Thomas Bonfort, Frank Warmerdam and the MapServer team.
 *
 ******************************************************************************
 * Copyright (c) 2011 Regents of the University of Minnesota.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies of this Software or works derived from this Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

#include "mapcache-config.h"
#ifdef USE_TIFF

#include "mapcache.h"
#include <apr_file_info.h>
#include <apr_strings.h>
#include <apr_file_io.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <tiffio.h>

#ifdef USE_GEOTIFF
#include "xtiffio.h"
#include "geovalues.h"
#include "geotiff.h"
#include "geo_normalize.h"
#include "geo_tiffp.h"
#include "geo_keyp.h"
#define MyTIFFOpen XTIFFOpen
#define MyTIFFClose XTIFFClose
#else
#define MyTIFFOpen TIFFOpen
#define MyTIFFClose TIFFClose
#endif


/**
 * \brief return filename for given tile
 *
 * \param tile the tile to get the key from
 * \param path pointer to a char* that will contain the filename
 * \param r
 * \private \memberof mapcache_cache_tiff
 */
static void _mapcache_cache_tiff_tile_key(mapcache_context *ctx, mapcache_cache_tiff *cache, mapcache_tile *tile, char **path)
{
  *path = cache->filename_template;

  /*
   * generic template substitutions
   */
  if(strstr(*path,"{tileset}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{tileset}",
                                      tile->tileset->name);
  if(strstr(*path,"{grid}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{grid}",
                                      tile->grid_link->grid->name);
  if(tile->dimensions && strstr(*path,"{dim}")) {
    char *dimstring="";
    const apr_array_header_t *elts = apr_table_elts(tile->dimensions);
    int i = elts->nelts;
    while(i--) {
      apr_table_entry_t *entry = &(APR_ARRAY_IDX(elts,i,apr_table_entry_t));
      const char *dimval = mapcache_util_str_sanitize(ctx->pool,entry->val,"/.",'#');
      dimstring = apr_pstrcat(ctx->pool,dimstring,"#",dimval,NULL);
    }
    *path = mapcache_util_str_replace(ctx->pool,*path, "{dim}", dimstring);
  }


  while(strstr(*path,"{z}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{z}",
                                      apr_psprintf(ctx->pool,cache->z_fmt,tile->z));
  /*
   * x and y replacing, when the tiff files are numbered with an increasing
   * x,y scheme (adjacent tiffs have x-x'=1 or y-y'=1
   */
  while(strstr(*path,"{div_x}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{div_x}",
                                      apr_psprintf(ctx->pool,cache->div_x_fmt,tile->x/cache->count_x));
  while(strstr(*path,"{div_y}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{div_y}",
                                      apr_psprintf(ctx->pool,cache->div_y_fmt,tile->y/cache->count_y));
  while(strstr(*path,"{inv_div_y}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{inv_div_y}",
                                      apr_psprintf(ctx->pool,cache->inv_div_y_fmt,(tile->grid_link->grid->levels[tile->z]->maxy - tile->y - 1)/cache->count_y));
  while(strstr(*path,"{inv_div_x}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{inv_div_x}",
                                      apr_psprintf(ctx->pool,cache->inv_div_x_fmt,(tile->grid_link->grid->levels[tile->z]->maxx - tile->x - 1)/cache->count_x));

  /*
   * x and y replacing, when the tiff files are numbered with the index
   * of their bottom-left tile
   * adjacent tiffs have x-x'=count_x or y-y'=count_y
   */
  while(strstr(*path,"{x}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{x}",
                                      apr_psprintf(ctx->pool,cache->x_fmt,tile->x/cache->count_x*cache->count_x));
  while(strstr(*path,"{y}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{y}",
                                      apr_psprintf(ctx->pool,cache->y_fmt,tile->y/cache->count_y*cache->count_y));
  while(strstr(*path,"{inv_y}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{inv_y}",
                                      apr_psprintf(ctx->pool,cache->inv_y_fmt,(tile->grid_link->grid->levels[tile->z]->maxy - tile->y - 1)/cache->count_y*cache->count_y));
  while(strstr(*path,"{inv_x}"))
    *path = mapcache_util_str_replace(ctx->pool,*path, "{inv_x}",
                                      apr_psprintf(ctx->pool,cache->inv_x_fmt,(tile->grid_link->grid->levels[tile->z]->maxx - tile->x - 1)/cache->count_x*cache->count_y));
  if(!*path) {
    ctx->set_error(ctx,500, "failed to allocate tile key");
  }
}

#ifdef DEBUG
static void check_tiff_format(mapcache_context *ctx, mapcache_cache_tiff *cache, mapcache_tile *tile, TIFF *hTIFF, const char *filename)
{
  uint32 imwidth,imheight,tilewidth,tileheight;
  int16 planarconfig,orientation;
  uint16 compression;
  uint16 photometric;
  int rv;
  mapcache_grid_level *level;
  int ntilesx;
  int ntilesy;
  TIFFGetField( hTIFF, TIFFTAG_IMAGEWIDTH, &imwidth );
  TIFFGetField( hTIFF, TIFFTAG_IMAGELENGTH, &imheight );
  TIFFGetField( hTIFF, TIFFTAG_TILEWIDTH, &tilewidth );
  TIFFGetField( hTIFF, TIFFTAG_TILELENGTH, &tileheight );

  /* Test that the TIFF is tiled and not stripped */
  if(!TIFFIsTiled(hTIFF)) {
    ctx->set_error(ctx,500,"TIFF file \"%s\" is not tiled", filename);
    return;
  }

  /* check we have jpeg compression */
  rv = TIFFGetField( hTIFF, TIFFTAG_COMPRESSION, &compression );
  if(rv == 1 && compression != COMPRESSION_JPEG) {
    ctx->set_error(ctx,500,"TIFF file \"%s\" is not jpeg compressed",
                   filename);
    return;
  }

  /* tiff must be pixel interleaved, not with a single image per band */
  rv = TIFFGetField( hTIFF, TIFFTAG_PLANARCONFIG, &planarconfig );
  if(rv == 1 && planarconfig != PLANARCONFIG_CONTIG) {
    ctx->set_error(ctx,500,"TIFF file \"%s\" is not pixel interleaved",
                   filename);
    return;
  }

  /* is this test needed once we now we have JPEG ? */
  rv = TIFFGetField( hTIFF, TIFFTAG_PHOTOMETRIC, &photometric );
  if(rv == 1 && (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_YCBCR)) {
    ctx->set_error(ctx,500,"TIFF file \"%s\" is not RGB: %d",
                   filename);
    return;
  }

  /* the default is top-left, but check just in case */
  rv = TIFFGetField( hTIFF, TIFFTAG_ORIENTATION, &orientation );
  if(rv == 1 && orientation != ORIENTATION_TOPLEFT) {
    ctx->set_error(ctx,500,"TIFF file \"%s\" is not top-left oriented",
                   filename);
    return;
  }

  /* check that the tiff internal tiling aligns with the mapcache_grid we are using:
   * - the tiff tile size must match the grid tile size
   * - the number of tiles in each direction in the tiff must match what has been
   *   configured for the cache
   */
  level = tile->grid_link->grid->levels[tile->z];
  ntilesx = MAPCACHE_MIN(cache->count_x, level->maxx);
  ntilesy = MAPCACHE_MIN(cache->count_y, level->maxy);
  if( tilewidth != tile->grid_link->grid->tile_sx ||
      tileheight != tile->grid_link->grid->tile_sy ||
      imwidth != tile->grid_link->grid->tile_sx * ntilesx ||
      imheight != tile->grid_link->grid->tile_sy * ntilesy ) {
    ctx->set_error(ctx,500,"TIFF file %s imagesize (%d,%d) and tilesize (%d,%d).\
            Expected (%d,%d),(%d,%d)",filename,imwidth,imheight,tilewidth,tileheight,
                   tile->grid_link->grid->tile_sx * ntilesx,
                   tile->grid_link->grid->tile_sy * ntilesy,
                   tile->grid_link->grid->tile_sx,
                   tile->grid_link->grid->tile_sy);
    return;
  }

  /* TODO: more tests ? */

  /* ok, success */
}
#endif

static int _mapcache_cache_tiff_has_tile(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  char *filename;
  TIFF *hTIFF;
  mapcache_cache_tiff *cache = (mapcache_cache_tiff*)pcache;
  _mapcache_cache_tiff_tile_key(ctx, cache, tile, &filename);
  if(GC_HAS_ERROR(ctx)) {
    return MAPCACHE_FALSE;
  }
  hTIFF = MyTIFFOpen(filename,"r");

  if(hTIFF) {
    do {
      uint32 nSubType = 0;
      int tiff_offx, tiff_offy; /* the x and y offset of the tile inside the tiff image */
      int tiff_off; /* the index of the tile inside the list of tiles of the tiff image */

      mapcache_grid_level *level;
      int ntilesx;
      int ntilesy;
      toff_t  *offsets=NULL, *sizes=NULL;

      if( !TIFFGetField(hTIFF, TIFFTAG_SUBFILETYPE, &nSubType) )
        nSubType = 0;

      /* skip overviews and masks */
      if( (nSubType & FILETYPE_REDUCEDIMAGE) ||
          (nSubType & FILETYPE_MASK) )
        continue;


#ifdef DEBUG
      check_tiff_format(ctx,cache,tile,hTIFF,filename);
      if(GC_HAS_ERROR(ctx)) {
        MyTIFFClose(hTIFF);
        return MAPCACHE_FALSE;
      }
#endif
      level = tile->grid_link->grid->levels[tile->z];
      ntilesx = MAPCACHE_MIN(cache->count_x, level->maxx);
      ntilesy = MAPCACHE_MIN(cache->count_y, level->maxy);

      /* x offset of the tile along a row */
      tiff_offx = tile->x % ntilesx;

      /*
       * y offset of the requested row. we inverse it as the rows are ordered
       * from top to bottom, whereas the tile y is bottom to top
       */
      tiff_offy = ntilesy - (tile->y % ntilesy) -1;
      tiff_off = tiff_offy * ntilesx + tiff_offx;

      if(1 != TIFFGetField( hTIFF, TIFFTAG_TILEOFFSETS, &offsets )) {
        MyTIFFClose(hTIFF);
        return MAPCACHE_FALSE;
      }
      if(1 != TIFFGetField( hTIFF, TIFFTAG_TILEBYTECOUNTS, &sizes )) {
        MyTIFFClose(hTIFF);
        return MAPCACHE_FALSE;
      }
      MyTIFFClose(hTIFF);
      if( offsets[tiff_off] > 0 && sizes[tiff_off] > 0 ) {
        return MAPCACHE_TRUE;
      } else {
        return MAPCACHE_FALSE;
      }
    } while( TIFFReadDirectory( hTIFF ) );
    return MAPCACHE_FALSE; /* TIFF only contains overviews ? */
  } else
    return MAPCACHE_FALSE;
}

static void _mapcache_cache_tiff_delete(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  ctx->set_error(ctx,500,"TIFF cache tile deleting not implemented");
}


/**
 * \brief get file content of given tile
 *
 * fills the mapcache_tile::data of the given tile with content stored in the file
 * \private \memberof mapcache_cache_tiff
 * \sa mapcache_cache::tile_get()
 */
static int _mapcache_cache_tiff_get(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  char *filename;
  TIFF *hTIFF = NULL;
  int rv;
  mapcache_cache_tiff *cache = (mapcache_cache_tiff*)pcache;
  _mapcache_cache_tiff_tile_key(ctx, cache, tile, &filename);
  if(GC_HAS_ERROR(ctx)) {
    return MAPCACHE_FALSE;
  }
#ifdef DEBUG
  ctx->log(ctx,MAPCACHE_DEBUG,"tile (%d,%d,%d) => filename %s)",
           tile->x,tile->y,tile->z,filename);
#endif

  hTIFF = MyTIFFOpen(filename,"r");

  /*
   * we currrently have no way of knowing if the opening failed because the tif
   * file does not exist (which is not an error condition, as it only signals
   * that the requested tile does not exist in the cache), or if an other error
   * that should be signaled occurred (access denied, not a tiff file, etc...)
   *
   * we ignore this case here and hope that further parts of the code will be
   * able to detect what's happening more precisely
   */

  if(hTIFF) {
    do {
      uint32 nSubType = 0;
      int tiff_offx, tiff_offy; /* the x and y offset of the tile inside the tiff image */
      int tiff_off; /* the index of the tile inside the list of tiles of the tiff image */

      mapcache_grid_level *level;
      int ntilesx;
      int ntilesy;
      toff_t  *offsets=NULL, *sizes=NULL;

      if( !TIFFGetField(hTIFF, TIFFTAG_SUBFILETYPE, &nSubType) )
        nSubType = 0;

      /* skip overviews */
      if( nSubType & FILETYPE_REDUCEDIMAGE )
        continue;


#ifdef DEBUG
      check_tiff_format(ctx,cache,tile,hTIFF,filename);
      if(GC_HAS_ERROR(ctx)) {
        MyTIFFClose(hTIFF);
        return MAPCACHE_FAILURE;
      }
#endif
      /*
       * compute the width and height of the full tiff file. This
       * is not simply the tile size times the number of tiles per
       * file for lower zoom levels
       */
      level = tile->grid_link->grid->levels[tile->z];
      ntilesx = MAPCACHE_MIN(cache->count_x, level->maxx);
      ntilesy = MAPCACHE_MIN(cache->count_y, level->maxy);

      /* x offset of the tile along a row */
      tiff_offx = tile->x % ntilesx;

      /*
       * y offset of the requested row. we inverse it as the rows are ordered
       * from top to bottom, whereas the tile y is bottom to top
       */
      tiff_offy = ntilesy - (tile->y % ntilesy) -1;
      tiff_off = tiff_offy * ntilesx + tiff_offx;

      /* get the offset of the jpeg data from the start of the file for each tile */
      rv = TIFFGetField( hTIFF, TIFFTAG_TILEOFFSETS, &offsets );
      if( rv != 1 ) {
        ctx->set_error(ctx,500,"Failed to read TIFF file \"%s\" tile offsets",
                       filename);
        MyTIFFClose(hTIFF);
        return MAPCACHE_FAILURE;
      }

      /* get the size of the jpeg data for each tile */
      rv = TIFFGetField( hTIFF, TIFFTAG_TILEBYTECOUNTS, &sizes );
      if( rv != 1 ) {
        ctx->set_error(ctx,500,"Failed to read TIFF file \"%s\" tile sizes",
                       filename);
        MyTIFFClose(hTIFF);
        return MAPCACHE_FAILURE;
      }

      /*
       * the tile data exists for the given tiff_off if both offsets and size
       * are not zero for that index.
       * if not, the tiff file is sparse and is missing the requested tile
       */
      if( offsets[tiff_off] > 0 && sizes[tiff_off] > 0 ) {
        apr_file_t *f;
        apr_finfo_t finfo;
        apr_status_t ret;

        /* read the jpeg header (common to all tiles) */
        uint32 jpegtable_size = 0;
        unsigned char* jpegtable_ptr;
        rv = TIFFGetField( hTIFF, TIFFTAG_JPEGTABLES, &jpegtable_size, &jpegtable_ptr );
        if( rv != 1 || !jpegtable_ptr || !jpegtable_size) {
          /* there is no common jpeg header in the tiff tags */
          ctx->set_error(ctx,500,"Failed to read TIFF file \"%s\" jpeg table",
                         filename);
          MyTIFFClose(hTIFF);
          return MAPCACHE_FAILURE;
        }

        /*
         * open the tiff file directly to access the jpeg image data with the given
         * offset
         */
        if((ret=apr_file_open(&f, filename,
                              APR_FOPEN_READ|APR_FOPEN_BUFFERED|APR_FOPEN_BINARY,APR_OS_DEFAULT,
                              ctx->pool)) == APR_SUCCESS) {
          char *bufptr;
          apr_off_t off;
          apr_size_t bytes;
          ret = apr_file_info_get(&finfo, APR_FINFO_MTIME, f);
          if(ret == APR_SUCCESS) {
            /*
             * extract the file modification time. this isn't guaranteed to be the
             * modification time of the actual tile, but it's the best we can do
             */
            tile->mtime = finfo.mtime;
          }

          /* create a memory buffer to contain the jpeg data */
          tile->encoded_data = mapcache_buffer_create((jpegtable_size+sizes[tiff_off]-4),ctx->pool);

          /*
           * copy the jpeg header to the beginning of the memory buffer,
           * omitting the last 2 bytes
           */
          memcpy(tile->encoded_data->buf,jpegtable_ptr,(jpegtable_size-2));

          /* advance the data pointer to after the header data */
          bufptr = ((char *)tile->encoded_data->buf) + (jpegtable_size-2);


          /* go to the specified offset in the tiff file, plus 2 bytes */
          off = offsets[tiff_off]+2;
          apr_file_seek(f,APR_SET,&off);

          /*
           * copy the jpeg body at the end of the memory buffer, accounting
           * for the two bytes we omitted in the previous step
           */
          bytes = sizes[tiff_off]-2;
          apr_file_read(f,bufptr,&bytes);

          /* check we have correctly read the requested number of bytes */
          if(bytes !=  sizes[tiff_off]-2) {
            ctx->set_error(ctx,500,"failed to read jpeg body in \"%s\".\
                        (read %d of %d bytes)", filename,bytes,sizes[tiff_off]-2);
            MyTIFFClose(hTIFF);
            return MAPCACHE_FAILURE;
          }

          tile->encoded_data->size = (jpegtable_size+sizes[tiff_off]-4);

          /* finalize and cleanup */
          apr_file_close(f);
          MyTIFFClose(hTIFF);
          return MAPCACHE_SUCCESS;
        } else {
          /* shouldn't usually happen. we managed to open the file with TIFFOpen,
           * but apr_file_open failed to do so.
           * nothing much to do except bail out.
           */
          ctx->set_error(ctx,500,"apr_file_open failed on already open tiff file \"%s\", giving up .... ",
                         filename);
          MyTIFFClose(hTIFF);
          return MAPCACHE_FAILURE;
        }
      } else {
        /* sparse tiff file without the requested tile */
        MyTIFFClose(hTIFF);
        return MAPCACHE_CACHE_MISS;
      }
    } /* loop through the tiff directories if there are multiple ones */
    while( TIFFReadDirectory( hTIFF ) );

    /*
     * should not happen?
     * finished looping through directories and didn't find anything suitable.
     * does the file only contain overviews?
     */
    MyTIFFClose(hTIFF);
    return MAPCACHE_CACHE_MISS;
  }
  /* failed to open tiff file */
  return MAPCACHE_CACHE_MISS;
}

/**
 * \brief write tile data to tiff
 *
 * writes the content of mapcache_tile::data to tiff.
 * \returns MAPCACHE_FAILURE if there is no data to write, or if the tile isn't locked
 * \returns MAPCACHE_SUCCESS if the tile has been successfully written to tiff
 * \private \memberof mapcache_cache_tiff
 * \sa mapcache_cache::tile_set()
 */
static void _mapcache_cache_tiff_set(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
#ifdef USE_TIFF_WRITE
  char *filename;
  TIFF *hTIFF = NULL;
  int rv;
  void *lock;
  int create;
  mapcache_cache_tiff *cache;
  mapcache_image_format_jpeg *format;
  int tilew;
  int tileh;
  unsigned char *rgb;
  int r,c;
  apr_finfo_t finfo;
  mapcache_grid_level *level;
  int ntilesx;
  int ntilesy;
  int tiff_offx, tiff_offy; /* the x and y offset of the tile inside the tiff image */
  int tiff_off; /* the index of the tile inside the list of tiles of the tiff image */

  cache = (mapcache_cache_tiff*)pcache;
  _mapcache_cache_tiff_tile_key(ctx, cache, tile, &filename);
  format = (mapcache_image_format_jpeg*) cache->format;
  if(GC_HAS_ERROR(ctx)) {
    return;
  }
#ifdef DEBUG
  ctx->log(ctx,MAPCACHE_DEBUG,"tile write (%d,%d,%d) => filename %s)",
           tile->x,tile->y,tile->z,filename);
#endif

  /*
   * create the directory where the tiff file will be stored
   */
  mapcache_make_parent_dirs(ctx,filename);
  GC_CHECK_ERROR(ctx);

  tilew = tile->grid_link->grid->tile_sx;
  tileh = tile->grid_link->grid->tile_sy;

  if(!tile->raw_image) {
    tile->raw_image = mapcache_imageio_decode(ctx, tile->encoded_data);
    GC_CHECK_ERROR(ctx);
  }

  /* remap xrgb to rgb */
  rgb = (unsigned char*)malloc(tilew*tileh*3);
  for(r=0; r<tile->raw_image->h; r++) {
    unsigned char *imptr = tile->raw_image->data + r * tile->raw_image->stride;
    unsigned char *rgbptr = rgb + r * tilew * 3;
    for(c=0; c<tile->raw_image->w; c++) {
      rgbptr[0] = imptr[2];
      rgbptr[1] = imptr[1];
      rgbptr[2] = imptr[0];
      rgbptr += 3;
      imptr += 4;
    }
  }

  /*
   * aquire a lock on the tiff file.
   */

  while(mapcache_lock_or_wait_for_resource(ctx,(cache->locker?cache->locker:ctx->config->locker),filename, &lock) == MAPCACHE_FALSE);

  /* check if the tiff file exists already */
  rv = apr_stat(&finfo,filename,0,ctx->pool);
  if(!APR_STATUS_IS_ENOENT(rv)) {
    hTIFF = MyTIFFOpen(filename,"r+");
    create = 0;
  } else {
    hTIFF = MyTIFFOpen(filename,"w+");
    create = 1;
  }
  if(!hTIFF) {
    ctx->set_error(ctx,500,"failed to open/create tiff file %s\n",filename);
    goto close_tiff;
  }


  /*
   * compute the width and height of the full tiff file. This
   * is not simply the tile size times the number of tiles per
   * file for lower zoom levels
   */
  level = tile->grid_link->grid->levels[tile->z];
  ntilesx = MAPCACHE_MIN(cache->count_x, level->maxx);
  ntilesy = MAPCACHE_MIN(cache->count_y, level->maxy);
  if(create) {
#ifdef USE_GEOTIFF
    double  adfPixelScale[3], adfTiePoints[6];
    mapcache_extent bbox;
    GTIF *gtif;
    int x,y;
#endif
    /* populate the TIFF tags if we are creating the file */

    TIFFSetField( hTIFF, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT );
    TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG );
    TIFFSetField( hTIFF, TIFFTAG_BITSPERSAMPLE, 8 );
    TIFFSetField( hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_JPEG );
    TIFFSetField( hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB );
    TIFFSetField( hTIFF, TIFFTAG_TILEWIDTH, tilew );
    TIFFSetField( hTIFF, TIFFTAG_TILELENGTH, tileh );
    TIFFSetField( hTIFF, TIFFTAG_IMAGEWIDTH, ntilesx * tilew );
    TIFFSetField( hTIFF, TIFFTAG_IMAGELENGTH, ntilesy * tileh );
    TIFFSetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL,3 );

#ifdef USE_GEOTIFF
    gtif = GTIFNew(hTIFF);
    if(gtif) {

      GTIFKeySet(gtif, GTRasterTypeGeoKey, TYPE_SHORT, 1,
                 RasterPixelIsArea);

      GTIFKeySet( gtif, GeographicTypeGeoKey, TYPE_SHORT, 1,
                  0 );
      GTIFKeySet( gtif, GeogGeodeticDatumGeoKey, TYPE_SHORT,
                  1, 0 );
      GTIFKeySet( gtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1,
                  0 );
      GTIFKeySet( gtif, GeogSemiMajorAxisGeoKey, TYPE_DOUBLE, 1,
                  0.0 );
      GTIFKeySet( gtif, GeogSemiMinorAxisGeoKey, TYPE_DOUBLE, 1,
                  0.0 );
      switch(tile->grid_link->grid->unit) {
        case MAPCACHE_UNIT_FEET:
          GTIFKeySet( gtif, ProjLinearUnitsGeoKey, TYPE_SHORT, 1,
                      Linear_Foot );
          break;
        case MAPCACHE_UNIT_METERS:
          GTIFKeySet( gtif, ProjLinearUnitsGeoKey, TYPE_SHORT, 1,
                      Linear_Meter );
          break;
        case MAPCACHE_UNIT_DEGREES:
          GTIFKeySet(gtif, GeogAngularUnitsGeoKey, TYPE_SHORT, 0,
                     Angular_Degree );
          break;
        default:
          break;
      }

      GTIFWriteKeys(gtif);
      GTIFFree(gtif);

      adfPixelScale[0] = adfPixelScale[1] = level->resolution;
      adfPixelScale[2] = 0.0;
      TIFFSetField( hTIFF, TIFFTAG_GEOPIXELSCALE, 3, adfPixelScale );


      /* top left tile x,y */
      x = (tile->x / cache->count_x)*(cache->count_x);
      y = (tile->y / cache->count_y)*(cache->count_y) + ntilesy - 1;

      mapcache_grid_get_extent(ctx, tile->grid_link->grid,
                               x,y,tile->z,&bbox);
      adfTiePoints[0] = 0.0;
      adfTiePoints[1] = 0.0;
      adfTiePoints[2] = 0.0;
      adfTiePoints[3] = bbox.minx;
      adfTiePoints[4] = bbox.maxy;
      adfTiePoints[5] = 0.0;
      TIFFSetField( hTIFF, TIFFTAG_GEOTIEPOINTS, 6, adfTiePoints );
    }

#endif
  }
  TIFFSetField(hTIFF, TIFFTAG_JPEGQUALITY, format->quality);
  if(format->photometric == MAPCACHE_PHOTOMETRIC_RGB) {
    TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
  } else {
    TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
  }
  TIFFSetField( hTIFF, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB );

  /* x offset of the tile along a row */
  tiff_offx = tile->x % ntilesx;

  /*
   * y offset of the requested row. we inverse it as the rows are ordered
   * from top to bottom, whereas the tile y is bottom to top
   */
  tiff_offy = ntilesy - (tile->y % ntilesy) -1;
  tiff_off = tiff_offy * ntilesx + tiff_offx;


  rv = TIFFWriteEncodedTile(hTIFF, tiff_off, rgb, tilew*tileh*3);
  free(rgb);
  if(!rv) {
    ctx->set_error(ctx,500,"failed TIFFWriteEncodedTile to %s",filename);
    goto close_tiff;
  }
  rv = TIFFWriteCheck( hTIFF, 1, "cache_set()");
  if(!rv) {
    ctx->set_error(ctx,500,"failed TIFFWriteCheck %s",filename);
    goto close_tiff;
  }

  if(create) {
    rv = TIFFWriteDirectory(hTIFF);
    if(!rv) {
      ctx->set_error(ctx,500,"failed TIFFWriteDirectory to %s",filename);
      goto close_tiff;
    }
  }

close_tiff:
  if(hTIFF)
    MyTIFFClose(hTIFF);
  mapcache_unlock_resource(ctx,cache->locker?cache->locker:ctx->config->locker,filename, lock);
#else
  ctx->set_error(ctx,500,"tiff write support disabled by default");
#endif

}

/**
 * \private \memberof mapcache_cache_tiff
 */
static void _mapcache_cache_tiff_configuration_parse_xml(mapcache_context *ctx, ezxml_t node, mapcache_cache *pcache, mapcache_cfg *config)
{
  ezxml_t cur_node;
  mapcache_cache_tiff *cache = (mapcache_cache_tiff*)pcache;
  char * format_name;
  mapcache_image_format *pformat;
  if ((cur_node = ezxml_child(node,"template")) != NULL) {
    char *fmt;
    cache->filename_template = apr_pstrdup(ctx->pool,cur_node->txt);
    fmt = (char*)ezxml_attr(cur_node,"x_fmt");
    if(fmt && *fmt) {
      cache->x_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"y_fmt");
    if(fmt && *fmt) {
      cache->y_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"z_fmt");
    if(fmt && *fmt) {
      cache->z_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"inv_x_fmt");
    if(fmt && *fmt) {
      cache->inv_x_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"inv_y_fmt");
    if(fmt && *fmt) {
      cache->inv_y_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"div_x_fmt");
    if(fmt && *fmt) {
      cache->div_x_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"div_y_fmt");
    if(fmt && *fmt) {
      cache->div_y_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"inv_div_x_fmt");
    if(fmt && *fmt) {
      cache->inv_div_x_fmt = apr_pstrdup(ctx->pool,fmt);
    }
    fmt = (char*)ezxml_attr(cur_node,"inv_div_y_fmt");
    if(fmt && *fmt) {
      cache->inv_div_y_fmt = apr_pstrdup(ctx->pool,fmt);
    }
  }
  cur_node = ezxml_child(node,"xcount");
  if(cur_node && cur_node->txt && *cur_node->txt) {
    char *endptr;
    cache->count_x = (int)strtol(cur_node->txt,&endptr,10);
    if(*endptr != 0) {
      ctx->set_error(ctx,400,"failed to parse xcount value %s for tiff cache %s", cur_node->txt,pcache->name);
      return;
    }
  }
  cur_node = ezxml_child(node,"ycount");
  if(cur_node && cur_node->txt && *cur_node->txt) {
    char *endptr;
    cache->count_y = (int)strtol(cur_node->txt,&endptr,10);
    if(*endptr != 0) {
      ctx->set_error(ctx,400,"failed to parse ycount value %s for tiff cache %s", cur_node->txt,pcache->name);
      return;
    }
  }
  cur_node = ezxml_child(node,"format");
  if(cur_node && cur_node->txt && *cur_node->txt) {
    format_name = cur_node->txt;
  } else {
    format_name = "JPEG";
  }
  pformat = mapcache_configuration_get_image_format(
              config,format_name);
  if(!pformat) {
    ctx->set_error(ctx,500,"TIFF cache %s references unknown image format %s",
                   pcache->name, format_name);
    return;
  }
  if(pformat->type != GC_JPEG) {
    ctx->set_error(ctx,500,"TIFF cache %s can only reference a JPEG image format",
                   pcache->name);
    return;
  }
  cache->format = (mapcache_image_format_jpeg*)pformat;

  cur_node = ezxml_child(node,"locker");
  if(cur_node) {
    mapcache_config_parse_locker(ctx, cur_node, &cache->locker);
  }

}

/**
 * \private \memberof mapcache_cache_tiff
 */
static void _mapcache_cache_tiff_configuration_post_config(mapcache_context *ctx, mapcache_cache *pcache,
    mapcache_cfg *cfg)
{
  mapcache_cache_tiff *cache = (mapcache_cache_tiff*)pcache;
  /* check all required parameters are configured */
  if((!cache->filename_template || !strlen(cache->filename_template))) {
    ctx->set_error(ctx, 400, "tiff cache %s has no template pattern",cache->cache.name);
    return;
  }
  if(cache->count_x <= 0 || cache->count_y <= 0) {
    ctx->set_error(ctx, 400, "tiff cache %s has invalid count (%d,%d)",cache->count_x,cache->count_y);
    return;
  }
}

/**
 * \brief creates and initializes a mapcache_tiff_cache
 */
mapcache_cache* mapcache_cache_tiff_create(mapcache_context *ctx)
{
  mapcache_cache_tiff *cache = apr_pcalloc(ctx->pool,sizeof(mapcache_cache_tiff));
  if(!cache) {
    ctx->set_error(ctx, 500, "failed to allocate tiff cache");
    return NULL;
  }
  cache->cache.metadata = apr_table_make(ctx->pool,3);
  cache->cache.type = MAPCACHE_CACHE_TIFF;
  cache->cache.tile_delete = _mapcache_cache_tiff_delete;
  cache->cache.tile_get = _mapcache_cache_tiff_get;
  cache->cache.tile_exists = _mapcache_cache_tiff_has_tile;
  cache->cache.tile_set = _mapcache_cache_tiff_set;
  cache->cache.configuration_post_config = _mapcache_cache_tiff_configuration_post_config;
  cache->cache.configuration_parse_xml = _mapcache_cache_tiff_configuration_parse_xml;
  cache->count_x = 10;
  cache->count_y = 10;
  cache->x_fmt = cache->y_fmt = cache->z_fmt
                                = cache->inv_x_fmt = cache->inv_y_fmt
                                    = cache->div_x_fmt = cache->div_y_fmt
                                        = cache->inv_div_x_fmt = cache->inv_div_y_fmt = apr_pstrdup(ctx->pool,"%d");
#ifndef DEBUG
  TIFFSetWarningHandler(NULL);
  TIFFSetErrorHandler(NULL);
#endif
  return (mapcache_cache*)cache;
}

#endif

/* vim: ts=2 sts=2 et sw=2
*/