File: source_gdal.c

package info (click to toggle)
mapcache 1.14.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,844 kB
  • sloc: ansic: 33,609; xml: 889; sh: 183; makefile: 61; python: 48
file content (755 lines) | stat: -rw-r--r-- 28,045 bytes parent folder | download | duplicates (3)
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
/******************************************************************************
 * $Id$
 *
 * Project:  MapServer
 * Purpose:  MapCache tile caching support file: GDAL datasource support (incomplete and disabled)
 * Author:   Thomas Bonfort, Even Rouault and the MapServer team.
 *
 ******************************************************************************
 * Copyright (c) 1996-2011 Regents of the University of Minnesota.
 * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com> (for GDALAutoCreateWarpedVRT who CreateWarpedVRT is derived from)
 *
 * 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.h"
#include "ezxml.h"
#include <apr_tables.h>
#include <apr_strings.h>

#ifdef USE_GDAL

#include <gdal.h>
#include <cpl_conv.h>

#include "gdalwarper.h"
#include "cpl_string.h"
#include "ogr_srs_api.h"
#include "gdal_vrt.h"

#define MAPCACHE_DEFAULT_RESAMPLE_ALG           GRA_Bilinear

/* Note: this will also work with GDAL >= 2.0 */
#if GDAL_VERSION_MAJOR < 2
#define USE_PRE_GDAL2_METHOD
#endif
/*#define USE_PRE_GDAL2_METHOD*/

typedef struct mapcache_source_gdal mapcache_source_gdal;

/**\class mapcache_source_gdal
 * \brief GDAL mapcache_source
 * \implements mapcache_source
 */
struct mapcache_source_gdal {
  mapcache_source source;
  const char *datastr; /**< the gdal source string*/
  const char *srs_wkt;
  GDALResampleAlg eResampleAlg; /**< resampling algorithm */
  const char *srcOvrLevel; /**< strategy to pickup source overview: AUTO, NONE, 
                                AUTO-xxx, xxxx. See -ovr doc in http://www.gdal.org/gdalwarp.html.
                                Only used for GDAL >= 2.0 (could probably be made to work for USE_PRE_GDAL2_METHOD with more work) */
  int bUseConnectionPool;
};

typedef struct {
  mapcache_source_gdal *gdal;
  const char *gdal_data;
  const char *dst_srs;
} gdal_connection_params;

typedef struct {
  GDALDatasetH hSrcDS;
  char *dst_srs_wkt;
} gdal_connection;

void mapcache_source_gdal_connection_constructor(mapcache_context *ctx, void **conn_, void *params) {
  gdal_connection_params *p = (gdal_connection_params*)params;
  gdal_connection *c = malloc(sizeof(gdal_connection));
  OGRSpatialReferenceH hDstSRS;

  *conn_ = NULL;
  /* -------------------------------------------------------------------- */
  /*      Open source dataset.                                            */
  /* -------------------------------------------------------------------- */
  c->hSrcDS = GDALOpen( p->gdal_data, GA_ReadOnly );

  if( c->hSrcDS == NULL ) {
    ctx->set_error(ctx, 500, "Cannot open gdal source for %s .\n", p->gdal->source.name );
    free(c);
    return;
  }

  /* -------------------------------------------------------------------- */
  /*      Check that there's 3 or 4 raster bands.                         */
  /* -------------------------------------------------------------------- */
  if ( GDALGetRasterCount(c->hSrcDS) != 3 && GDALGetRasterCount(c->hSrcDS) != 4) {
    ctx->set_error(ctx, 500, "Input gdal source for %s has %d raster bands, but only 3 or 4 are supported.\n",
                   p->gdal->source.name, GDALGetRasterCount(c->hSrcDS) );
    GDALClose(c->hSrcDS);
    free(c);
    return;
  }



  hDstSRS = OSRNewSpatialReference( NULL );
  if( OSRSetFromUserInput( hDstSRS, p->dst_srs ) == OGRERR_NONE ) {
    c->dst_srs_wkt = NULL;
    OSRExportToWkt( hDstSRS, &c->dst_srs_wkt );
  }
  else {
    ctx->set_error(ctx,500,"failed to parse gdal srs %s",p->dst_srs);
    GDALClose(c->hSrcDS);
    free(c);
    return;
  }

  OSRDestroySpatialReference( hDstSRS );
  *conn_ = c;
}

void mapcache_source_gdal_connection_destructor(void *conn_) {
  gdal_connection *c = (gdal_connection*)conn_;
  CPLFree(c->dst_srs_wkt);
  GDALClose(c->hSrcDS);
  free(c);
}

static mapcache_pooled_connection* _gdal_get_connection(mapcache_context *ctx, mapcache_source_gdal *gdal, const char *dst_srs, const char *gdal_data)
{
  mapcache_pooled_connection *pc;
  gdal_connection_params params;
  char *key;

  params.gdal = gdal;
  params.dst_srs = dst_srs;
  params.gdal_data = gdal_data;

  key = apr_pstrcat(ctx->pool, gdal_data, dst_srs, NULL);

  pc = mapcache_connection_pool_get_connection(ctx,key,mapcache_source_gdal_connection_constructor,
          mapcache_source_gdal_connection_destructor, &params);
  return pc;
}
#ifdef USE_PRE_GDAL2_METHOD
/* Creates a (virtual) dataset that matches an overview level of the source
   dataset. This dataset has references on the source dataset, so it should
   be closed before it.
*/
static GDALDatasetH CreateOverviewVRTDataset(GDALDatasetH hSrcDS,
                                             int iOvrLevel)
{
  double adfSrcGeoTransform[6];
  int iBand;
  GDALRasterBandH hFirstBand = GDALGetRasterBand(hSrcDS, 1);
  GDALRasterBandH hOvr = GDALGetOverview( hFirstBand, iOvrLevel );
  int nFullResXSize = GDALGetRasterBandXSize(hFirstBand);
  int nFullResYSize = GDALGetRasterBandYSize(hFirstBand);
  int nVRTXSize = GDALGetRasterBandXSize(hOvr);
  int nVRTYSize = GDALGetRasterBandYSize(hOvr);

  VRTDatasetH hVRTDS = VRTCreate( nVRTXSize, nVRTYSize );

  /* Scale geotransform */
  if( GDALGetGeoTransform( hSrcDS, adfSrcGeoTransform) == CE_None )
  {
    adfSrcGeoTransform[1] *= (double)nFullResXSize / nVRTXSize;
    adfSrcGeoTransform[2] *= (double)nFullResYSize / nVRTYSize;
    adfSrcGeoTransform[4] *= (double)nFullResXSize / nVRTXSize;
    adfSrcGeoTransform[5] *= (double)nFullResYSize / nVRTYSize;
    GDALSetProjection( hVRTDS, GDALGetProjectionRef(hSrcDS) );
    GDALSetGeoTransform( hVRTDS, adfSrcGeoTransform );
  }

  /* Scale GCPs */
  if( GDALGetGCPCount(hSrcDS) > 0 )
  {
    const GDAL_GCP* pasGCPsMain = GDALGetGCPs(hSrcDS);
    int nGCPCount = GDALGetGCPCount(hSrcDS);
    GDAL_GCP* pasGCPList = GDALDuplicateGCPs( nGCPCount, pasGCPsMain );
    int i;
    for(i = 0; i < nGCPCount; i++)
    {
        pasGCPList[i].dfGCPPixel *= (double)nVRTXSize / nFullResXSize;
        pasGCPList[i].dfGCPLine *= (double)nVRTYSize / nFullResYSize;
    }
    GDALSetGCPs( hVRTDS, nGCPCount, pasGCPList, GDALGetGCPProjection(hSrcDS) );
    GDALDeinitGCPs( nGCPCount, pasGCPList );
    CPLFree( pasGCPList );
  }

  /* Create bands */
  for(iBand = 1; iBand <= GDALGetRasterCount(hSrcDS); iBand++ )
  {
    GDALRasterBandH hSrcBand;
    GDALRasterBandH hVRTBand;
    int bNoDataSet = FALSE;
    double dfNoData;

    VRTAddBand( hVRTDS, GDT_Byte, NULL );
    hVRTBand = GDALGetRasterBand(hVRTDS, iBand);
    hSrcBand = GDALGetOverview(GDALGetRasterBand(hSrcDS, iBand), iOvrLevel);
    dfNoData = GDALGetRasterNoDataValue(hSrcBand, &bNoDataSet);
    if( bNoDataSet )
      GDALSetRasterNoDataValue(hVRTBand, dfNoData);

    /* Note: the consumer of this VRT is the warper, which doesn't do any */
    /* subsampled RasterIO requests, so NEAR is fine */
    VRTAddSimpleSource( hVRTBand, hSrcBand,
                        0, 0, nVRTXSize, nVRTYSize,
                        0, 0, nVRTXSize, nVRTYSize,
                        "NEAR", VRT_NODATA_UNSET );
  }

  return hVRTDS;
}
#endif

/* Derived from GDALAutoCreateWarpedVRT(), with various improvements. */
/* Returns a warped VRT that covers the passed extent, in pszDstWKT. */
/* The provided width and height are used, but the size of the returned dataset */
/* may not match those values. In the USE_PRE_GDAL2_METHOD, it should match them. */
/* In the non USE_PRE_GDAL2_METHOD case, it might be a multiple of those values. */
/* phTmpDS is an output parameter (a temporary VRT in the USE_PRE_GDAL2_METHOD case). */
static GDALDatasetH  
CreateWarpedVRT( GDALDatasetH hSrcDS, 
                 const char *pszSrcWKT,
                 const char *pszDstWKT,
                 int width, int height,
                 const mapcache_extent *extent,
                 GDALResampleAlg eResampleAlg, 
                 double dfMaxError, 
                 char** papszWarpOptions,
                 GDALDatasetH *phTmpDS )

{
    int i;
    GDALWarpOptions *psWO;
    double adfDstGeoTransform[6];
    GDALDatasetH hDstDS;
    int    nDstPixels, nDstLines;
    CPLErr eErr;
    int bHaveNodata = FALSE;
    char** papszOptions = NULL;

/* -------------------------------------------------------------------- */
/*      Populate the warp options.                                      */
/* -------------------------------------------------------------------- */

    psWO = GDALCreateWarpOptions();
    psWO->papszWarpOptions = CSLDuplicate(papszWarpOptions);

    psWO->eResampleAlg = eResampleAlg;

    psWO->hSrcDS = hSrcDS;

    psWO->nBandCount = GDALGetRasterCount( hSrcDS );
    if( psWO->nBandCount == 4 )
    {
        psWO->nBandCount = 3;
        psWO->nSrcAlphaBand = 4;
        psWO->nDstAlphaBand = 4;
    }
    /* Due to the reprojection, we might get transparency in the edges */
    else if( psWO->nBandCount == 3 )
        psWO->nDstAlphaBand = 4;

    psWO->panSrcBands = (int*)CPLMalloc( sizeof(int) * psWO->nBandCount );
    psWO->panDstBands = (int*)CPLMalloc( sizeof(int) * psWO->nBandCount );

    for( i = 0; i < psWO->nBandCount; i++ )
    {
        psWO->panSrcBands[i] = i+1;
        psWO->panDstBands[i] = i+1;
    }

/* -------------------------------------------------------------------- */
/*      Set nodata values if existing                                   */
/* -------------------------------------------------------------------- */
    GDALGetRasterNoDataValue( GDALGetRasterBand(hSrcDS, 1), &bHaveNodata);
    if( bHaveNodata )
    {
        psWO->padfSrcNoDataReal = (double *) 
            CPLMalloc(psWO->nBandCount*sizeof(double));
        psWO->padfSrcNoDataImag = (double *) 
            CPLCalloc(psWO->nBandCount, sizeof(double)); /* zero initialized */

        for( i = 0; i < psWO->nBandCount; i++ )
        {
            GDALRasterBandH hBand = GDALGetRasterBand( hSrcDS, i+1 );

            double dfReal = GDALGetRasterNoDataValue( hBand, &bHaveNodata );

            if( bHaveNodata )
            {
                psWO->padfSrcNoDataReal[i] = dfReal;
            }
            else
            {
                psWO->padfSrcNoDataReal[i] = -123456.789;
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Create the transformer.                                         */
/* -------------------------------------------------------------------- */
    psWO->pfnTransformer = GDALGenImgProjTransform;
    psWO->pTransformerArg = 
        GDALCreateGenImgProjTransformer( psWO->hSrcDS, pszSrcWKT, 
                                         NULL, pszDstWKT,
                                         TRUE, 1.0, 0 );

    if( psWO->pTransformerArg == NULL )
    {
        GDALDestroyWarpOptions( psWO );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Figure out the desired output bounds and resolution.            */
/* -------------------------------------------------------------------- */
    eErr =
        GDALSuggestedWarpOutput( hSrcDS, psWO->pfnTransformer, 
                                 psWO->pTransformerArg, 
                                 adfDstGeoTransform, &nDstPixels, &nDstLines );
    if( eErr != CE_None )
    {
        GDALDestroyTransformer( psWO->pTransformerArg );
        GDALDestroyWarpOptions( psWO );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      To minimize the risk of extra resampling done by generic        */
/*      RasterIO itself and maximize resampling done in the wraper,     */
/*      adjust the resolution so that the overview factor of the output */
/*      dataset that will indirectly query matches an exiting overview  */
/*      factor of the input dataset.                                    */
/* -------------------------------------------------------------------- */
    {
        double dfDesiredXRes = (extent->maxx - extent->minx) / width;
        double dfDesiredYRes = (extent->maxy - extent->miny) / height;
        double dfDesiredRes = MIN( dfDesiredXRes, dfDesiredYRes );
        double dfGuessedFullRes = MIN( adfDstGeoTransform[1],
                                   fabs(adfDstGeoTransform[5]) );
        double dfApproxDstOvrRatio = dfDesiredRes / dfGuessedFullRes;

        GDALRasterBandH hFirstBand = GDALGetRasterBand(hSrcDS, 1);
        int nOvrCount = GDALGetOverviewCount(hFirstBand);
        int nSrcXSize = GDALGetRasterBandXSize(hFirstBand);
        int i;
        double dfSrcOvrRatio = 1.0;
#ifdef USE_PRE_GDAL2_METHOD
        int iSelectedOvr = -1;
#endif
        for( i = 0; *phTmpDS == NULL && i < nOvrCount; i ++)
        {
            GDALRasterBandH hOvr = GDALGetOverview(hFirstBand, i);
            int nOvrXSize = GDALGetRasterBandXSize(hOvr);
            double dfCurOvrRatio = (double)nSrcXSize / nOvrXSize;
            if(dfCurOvrRatio > dfApproxDstOvrRatio+0.1 ) /* +0.1 to avoid rounding issues */
            {
                break;
            }
            dfSrcOvrRatio = dfCurOvrRatio;
#ifdef USE_PRE_GDAL2_METHOD
            iSelectedOvr = i;
#endif
        }

#ifdef USE_PRE_GDAL2_METHOD
        if( iSelectedOvr >= 0 )
        {
            GDALDestroyTransformer( psWO->pTransformerArg );
            GDALDestroyWarpOptions( psWO );

            *phTmpDS = CreateOverviewVRTDataset(hSrcDS, iSelectedOvr);
            return CreateWarpedVRT( *phTmpDS,
                                    pszSrcWKT,
                                    pszDstWKT,
                                    width, height,
                                    extent,
                                    eResampleAlg, 
                                    dfMaxError, 
                                    papszWarpOptions,
                                    phTmpDS );
        }
#endif

        adfDstGeoTransform[1] = dfDesiredXRes / dfSrcOvrRatio;
        adfDstGeoTransform[5] = -dfDesiredYRes / dfSrcOvrRatio;
    }

/* -------------------------------------------------------------------- */
/*      Compute geotransform and raster dimension for our extent of     */
/*      interest.                                                       */
/* -------------------------------------------------------------------- */
    adfDstGeoTransform[0] = extent->minx;
    adfDstGeoTransform[2] = 0.0;
    adfDstGeoTransform[3] = extent->maxy;
    adfDstGeoTransform[4] = 0.0;
    nDstPixels = (int)( (extent->maxx - extent->minx) / adfDstGeoTransform[1] + 0.5 );
    nDstLines = (int)( (extent->maxy - extent->miny) / fabs(adfDstGeoTransform[5]) + 0.5 );
    /*printf("nDstPixels=%d nDstLines=%d\n", nDstPixels, nDstLines);*/

/* -------------------------------------------------------------------- */
/*      Update the transformer to include an output geotransform        */
/*      back to pixel/line coordinates.                                 */
/* -------------------------------------------------------------------- */

    GDALSetGenImgProjTransformerDstGeoTransform( 
        psWO->pTransformerArg, adfDstGeoTransform );

/* -------------------------------------------------------------------- */
/*      Do we want to apply an approximating transformation?            */
/* -------------------------------------------------------------------- */
    if( dfMaxError > 0.0 )
    {
        psWO->pTransformerArg = 
            GDALCreateApproxTransformer( psWO->pfnTransformer, 
                                         psWO->pTransformerArg, 
                                         dfMaxError );
        psWO->pfnTransformer = GDALApproxTransform;
        GDALApproxTransformerOwnsSubtransformer(psWO->pTransformerArg, TRUE);
    }

/* -------------------------------------------------------------------- */
/*      Create the VRT file.                                            */
/* -------------------------------------------------------------------- */

    /* We could potentially used GDALCreateWarpedVRT() instead of this logic */
    /* but GDALCreateWarpedVRT() in GDAL < 2.0.1 doesn't create the destination */
    /* alpha band. */

    papszOptions = CSLSetNameValue(NULL, "SUBCLASS", "VRTWarpedDataset");
    hDstDS = GDALCreate( GDALGetDriverByName("VRT"), "", nDstPixels, nDstLines,
                         psWO->nBandCount + ((psWO->nDstAlphaBand != 0) ? 1 : 0),
                         GDT_Byte, papszOptions );
    CSLDestroy(papszOptions);
    if( hDstDS == NULL )
    {
        GDALDestroyWarpOptions( psWO );
        return NULL;
    }

    psWO->hDstDS = hDstDS;

    GDALSetGeoTransform( hDstDS, adfDstGeoTransform );
    if( GDALInitializeWarpedVRT( hDstDS, psWO ) != CE_None )
    {
        GDALClose(hDstDS);
        GDALDestroyWarpOptions( psWO );
        return NULL;
    }

    GDALDestroyWarpOptions( psWO );

    return hDstDS;
}

#define PREMULTIPLY(out,color,alpha)\
{\
  int temp = ((alpha) * (color)) + 0x80;\
  out =((temp + (temp >> 8)) >> 8);\
}

/**
 * \private \memberof mapcache_source_gdal
 * \sa mapcache_source::render_metatile()
 */
void _mapcache_source_gdal_render_metatile(mapcache_context *ctx, mapcache_source *psource, mapcache_map *map)
{
  mapcache_source_gdal *gdal = (mapcache_source_gdal*)psource;
  gdal_connection *gdal_conn;
  GDALDatasetH  hDstDS;
  GDALDatasetH hTmpDS = NULL;
  mapcache_buffer *data;
  unsigned char *rasterdata;
  unsigned char* rowptr;
  unsigned char** row_pointers;
  int i, j;
  CPLErr eErr;
  mapcache_pooled_connection *pc = NULL;
  int bands_bgra[] = { 3, 2, 1, 4 }; /* mapcache buffer order is BGRA */

  CPLErrorReset();

  if(gdal->bUseConnectionPool == MAPCACHE_TRUE) {
    pc = _gdal_get_connection(ctx, gdal, map->grid_link->grid->srs, gdal->datastr );
    GC_CHECK_ERROR(ctx);
    gdal_conn = (gdal_connection*) pc->connection;
  } else {
    gdal_connection_params params;
    params.gdal = gdal;
    params.dst_srs = map->grid_link->grid->srs;
    params.gdal_data = gdal->datastr;
    mapcache_source_gdal_connection_constructor(ctx, (void**)(&gdal_conn), &params);
    GC_CHECK_ERROR(ctx);
  }



  hDstDS = CreateWarpedVRT( gdal_conn->hSrcDS, gdal->srs_wkt, gdal_conn->dst_srs_wkt,
                            map->width, map->height,
                            &map->extent,
                            gdal->eResampleAlg, 0.125, NULL, &hTmpDS );

  if( hDstDS == NULL ) {
    ctx->set_error(ctx, 500,"CreateWarpedVRT() failed");
    if(gdal->bUseConnectionPool == MAPCACHE_TRUE) {
      mapcache_connection_pool_invalidate_connection(ctx,pc);
    } else {
      mapcache_source_gdal_connection_destructor(gdal_conn);
    }
    return;
  }

  if(GDALGetRasterCount(hDstDS) != 4) {
    ctx->set_error(ctx, 500,"gdal did not create a 4 band image");
    GDALClose(hDstDS); /* close first this one, as it references hSrcDS */
    if(gdal->bUseConnectionPool == MAPCACHE_TRUE) {
      mapcache_connection_pool_invalidate_connection(ctx,pc);
    } else {
      mapcache_source_gdal_connection_destructor(gdal_conn);
    }
    return;
  }

  data = mapcache_buffer_create(map->height*map->width*4,ctx->pool);
  rasterdata = data->buf;

#if GDAL_VERSION_MAJOR >= 2
  {
    GDALRasterIOExtraArg sExtraArg;
    INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    if( gdal->eResampleAlg == GRA_Bilinear )
      sExtraArg.eResampleAlg = GRIORA_Bilinear;
    else if( gdal->eResampleAlg == GRA_Cubic )
      sExtraArg.eResampleAlg = GRIORA_Cubic;
    else if( gdal->eResampleAlg == GRA_CubicSpline )
      sExtraArg.eResampleAlg = GRIORA_CubicSpline;
    else if( gdal->eResampleAlg == GRA_Lanczos )
      sExtraArg.eResampleAlg = GRIORA_Lanczos;
    else if( gdal->eResampleAlg == GRA_Average )
      sExtraArg.eResampleAlg = GRIORA_Average;

    if( gdal->srcOvrLevel != NULL )
    {
      /* If the user specified a particular strategy to choose the source */
      /* overview level, apply it now */
      GDALSetMetadataItem(hDstDS, "SrcOvrLevel",gdal->srcOvrLevel, NULL);
    }

    /* Hopefully, given how we adjust hDstDS resolution, we should query */
    /* exactly at the resolution of one overview level of hDstDS, and not */
    /* do extra resampling in generic RasterIO, but just in case specify */
    /* the resampling alg in sExtraArg. */
    eErr = GDALDatasetRasterIOEx( hDstDS, GF_Read,0,0,
                                  GDALGetRasterXSize(hDstDS),
                                  GDALGetRasterYSize(hDstDS),
                                  rasterdata,map->width,map->height,GDT_Byte,
                                  4, bands_bgra,
                                  4,4*map->width,1, &sExtraArg );
  }
#else
  eErr = GDALDatasetRasterIO( hDstDS, GF_Read,0,0,
                              GDALGetRasterXSize(hDstDS),
                              GDALGetRasterYSize(hDstDS),
                              rasterdata,map->width,map->height,GDT_Byte,
                              4, bands_bgra,
                              4,4*map->width,1 );
#endif

  if( eErr != CE_None ) {
    ctx->set_error(ctx, 500,"GDAL I/O error occurred");
    GDALClose(hDstDS); /* close first this one, as it references hTmpDS or hSrcDS */
    if( hTmpDS )
      GDALClose(hTmpDS); /* references hSrcDS, so close before */
    if(gdal->bUseConnectionPool == MAPCACHE_TRUE) {
      mapcache_connection_pool_invalidate_connection(ctx,pc);
    } else {
      mapcache_source_gdal_connection_destructor(gdal_conn);
    }
    return;
  }

  map->raw_image = mapcache_image_create(ctx);
  map->raw_image->w = map->width;
  map->raw_image->h = map->height;
  map->raw_image->stride = map->width * 4;
  map->raw_image->has_alpha = MC_ALPHA_UNKNOWN;

  // Handling of premulitiplication for GDAL sources.
  // Since the data is already in BGRA order, there is no need to swap the bytes around.

  row_pointers = malloc(map->raw_image->h * sizeof(unsigned char*));
  apr_pool_cleanup_register(ctx->pool, row_pointers, (void*)free, apr_pool_cleanup_null);

  rowptr = rasterdata;
  for(i = 0; i < map->raw_image->h; i++) {
    row_pointers[i] = rowptr;
    rowptr += map->raw_image->stride;
  }
  
  for(i = 0; i < map->raw_image->h; i++) {
    unsigned char pixel[4];
    unsigned char alpha;
    unsigned char* pixptr = row_pointers[i];
    for(j = 0; j < map->raw_image->w; j++) {
      memcpy(pixel, pixptr, sizeof(unsigned int));
      alpha = pixel[3];
      if(alpha == 0) {
        pixptr[0] = 0;
        pixptr[1] = 0;
        pixptr[2] = 0;
      } else if (alpha < 255) {
        PREMULTIPLY(pixptr[0], pixel[0], alpha);
        PREMULTIPLY(pixptr[1], pixel[1], alpha);
        PREMULTIPLY(pixptr[2], pixel[2], alpha);
      }
      pixptr += 4;
    }
  }

  map->raw_image->data = rasterdata;
  GDALClose( hDstDS ); /* close first this one, as it references hTmpDS or hSrcDS */
  if( hTmpDS )
    GDALClose(hTmpDS); /* references hSrcDS, so close before */
  if(gdal->bUseConnectionPool == MAPCACHE_TRUE) {
    mapcache_connection_pool_release_connection(ctx,pc);
  } else {
    mapcache_source_gdal_connection_destructor(gdal_conn);
  }
}

/**
 * \private \memberof mapcache_source_gdal
 * \sa mapcache_source::configuration_parse()
 */
void _mapcache_source_gdal_configuration_parse(mapcache_context *ctx, ezxml_t node, mapcache_source *source, mapcache_cfg *config)
{
  ezxml_t cur_node;
  mapcache_source_gdal *src = (mapcache_source_gdal*)source;

  if ((cur_node = ezxml_child(node,"data")) != NULL) {
    src->datastr = apr_pstrdup(ctx->pool,cur_node->txt);
  }
  if ((cur_node = ezxml_child(node,"connection_pooled")) != NULL) {
    if(!strcasecmp(cur_node->txt,"false")) {
      src->bUseConnectionPool = MAPCACHE_FALSE;
    } else if(!strcasecmp(cur_node->txt,"true")) {
      src->bUseConnectionPool = MAPCACHE_TRUE;
    } else {
      ctx->set_error(ctx,400,"failed to parse <connection_pooled> (%s). Expecting true or false",cur_node->txt);
      return;
    }
  }

  if ((cur_node = ezxml_child(node,"resample")) != NULL && *cur_node->txt) {
    if( EQUALN( cur_node->txt, "NEAR", 4) )
      src->eResampleAlg = GRA_NearestNeighbour;
    else if( EQUAL( cur_node->txt, "BILINEAR") )
      src->eResampleAlg = GRA_Bilinear;
    else if( EQUAL( cur_node->txt, "CUBIC") )
      src->eResampleAlg = GRA_Cubic;
    else if( EQUAL( cur_node->txt, "CUBICSPLINE") )
      src->eResampleAlg = GRA_CubicSpline;
    else if( EQUAL( cur_node->txt, "LANCZOS") )
      src->eResampleAlg = GRA_Lanczos;
#if GDAL_VERSION_MAJOR >= 2
    else if( EQUAL( cur_node->txt, "AVERAGE") )
      src->eResampleAlg = GRA_Average;
#endif
    else {
      ctx->set_error(ctx, 500, "unsupported gdal <resample>: %s", cur_node->txt);
      return;
    }
  }

  if ((cur_node = ezxml_child(node,"overview-strategy")) != NULL && *cur_node->txt) {
    src->srcOvrLevel = apr_pstrdup(ctx->pool,cur_node->txt);
  }
}

/**
 * \private \memberof mapcache_source_gdal
 * \sa mapcache_source::configuration_check()
 */
void _mapcache_source_gdal_configuration_check(mapcache_context *ctx, mapcache_cfg *cfg,
    mapcache_source *source)
{
  mapcache_source_gdal *src = (mapcache_source_gdal*)source;
  GDALDatasetH hDataset;

  /* check all required parameters are configured */
  if( src->datastr == NULL || !strlen(src->datastr)) {
    ctx->set_error(ctx, 500, "gdal source %s has no data",source->name);
    return;
  }
  hDataset = GDALOpen(src->datastr,GA_ReadOnly);
  if( hDataset == NULL ) {
    ctx->set_error(ctx, 500, "gdalOpen failed on data %s", src->datastr);
    return;
  }
  if( GDALGetProjectionRef( hDataset ) != NULL
      && strlen(GDALGetProjectionRef( hDataset )) > 0 ) {
    src->srs_wkt = apr_pstrdup(ctx->pool,GDALGetProjectionRef( hDataset ));
  } else if( GDALGetGCPProjection( hDataset ) != NULL
           && strlen(GDALGetGCPProjection(hDataset)) > 0
           && GDALGetGCPCount( hDataset ) > 1 ) {
    src->srs_wkt = apr_pstrdup(ctx->pool,GDALGetGCPProjection( hDataset ));
  } else {
    ctx->set_error(ctx, 500, "Input gdal source for %s has no defined SRS\n", source->name );
    GDALClose(hDataset);
    return;
  }
  GDALClose(hDataset);

}
#endif //USE_GDAL

mapcache_source* mapcache_source_gdal_create(mapcache_context *ctx)
{
#ifdef USE_GDAL
  mapcache_source_gdal *source = apr_pcalloc(ctx->pool, sizeof(mapcache_source_gdal));
  if(!source) {
    ctx->set_error(ctx, 500, "failed to allocate gdal source");
    return NULL;
  }
  mapcache_source_init(ctx, &(source->source));
  source->source.type = MAPCACHE_SOURCE_GDAL;
  source->source._render_map = _mapcache_source_gdal_render_metatile;
  source->source.configuration_check = _mapcache_source_gdal_configuration_check;
  source->source.configuration_parse_xml = _mapcache_source_gdal_configuration_parse;
  source->eResampleAlg = MAPCACHE_DEFAULT_RESAMPLE_ALG;
  source->bUseConnectionPool = MAPCACHE_TRUE;
  GDALAllRegister();
  return (mapcache_source*)source;
#else
  ctx->set_error(ctx, 400, "failed to create gdal source, GDAL support is not compiled in this version");
  return NULL;
#endif
}



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