File: tildataset.cpp

package info (click to toggle)
gdal 3.11.3%2Bdfsg-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 89,016 kB
  • sloc: cpp: 1,165,048; ansic: 208,864; python: 26,958; java: 5,972; xml: 4,611; sh: 3,776; cs: 2,508; yacc: 1,306; makefile: 213
file content (465 lines) | stat: -rw-r--r-- 17,585 bytes parent folder | download
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
/******************************************************************************
 *
 * Project:  EarthWatch .TIL Driver
 * Purpose:  Implementation of the TILDataset class.
 * Author:   Frank Warmerdam, warmerdam@pobox.com
 *
 ******************************************************************************
 * Copyright (c) 2009, Frank Warmerdam
 * Copyright (c) 2009-2011, Even Rouault <even dot rouault at spatialys.com>
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "cplkeywordparser.h"
#include "gdal_mdreader.h"
#include "gdal_frmts.h"
#include "gdal_pam.h"
#include "ogr_spatialref.h"
#include "vrtdataset.h"

/************************************************************************/
/* ==================================================================== */
/*                              TILDataset                              */
/* ==================================================================== */
/************************************************************************/

class TILDataset final : public GDALPamDataset
{
    VRTDataset *poVRTDS;
    std::vector<std::string> m_aosFilenames;

    char **papszMetadataFiles;

  protected:
    virtual int CloseDependentDatasets() override;

  public:
    TILDataset();
    virtual ~TILDataset();

    virtual char **GetFileList(void) override;

    static GDALDataset *Open(GDALOpenInfo *);
    static int Identify(GDALOpenInfo *poOpenInfo);
};

/************************************************************************/
/* ==================================================================== */
/*                            TILRasterBand                             */
/* ==================================================================== */
/************************************************************************/

class TILRasterBand final : public GDALPamRasterBand
{
    friend class TILDataset;

    VRTSourcedRasterBand *poVRTBand;

  public:
    TILRasterBand(TILDataset *, int, VRTSourcedRasterBand *);

    virtual ~TILRasterBand()
    {
    }

    virtual CPLErr IReadBlock(int, int, void *) override;
    virtual CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
                             GDALDataType, GSpacing nPixelSpace,
                             GSpacing nLineSpace,
                             GDALRasterIOExtraArg *psExtraArg) override;
};

/************************************************************************/
/*                           TILRasterBand()                            */
/************************************************************************/

TILRasterBand::TILRasterBand(TILDataset *poTILDS, int nBandIn,
                             VRTSourcedRasterBand *poVRTBandIn)

{
    poDS = poTILDS;
    poVRTBand = poVRTBandIn;
    nBand = nBandIn;
    eDataType = poVRTBandIn->GetRasterDataType();

    poVRTBandIn->GetBlockSize(&nBlockXSize, &nBlockYSize);
}

/************************************************************************/
/*                             IReadBlock()                             */
/************************************************************************/

CPLErr TILRasterBand::IReadBlock(int iBlockX, int iBlockY, void *pBuffer)

{
    return poVRTBand->ReadBlock(iBlockX, iBlockY, pBuffer);
}

/************************************************************************/
/*                             IRasterIO()                              */
/************************************************************************/

CPLErr TILRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
                                int nXSize, int nYSize, void *pData,
                                int nBufXSize, int nBufYSize,
                                GDALDataType eBufType, GSpacing nPixelSpace,
                                GSpacing nLineSpace,
                                GDALRasterIOExtraArg *psExtraArg)

{
    if (GetOverviewCount() > 0)
    {
        return GDALPamRasterBand::IRasterIO(
            eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
            eBufType, nPixelSpace, nLineSpace, psExtraArg);
    }

    // If not exist TIL overviews, try to use band source overviews.
    return poVRTBand->IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
                                nBufXSize, nBufYSize, eBufType, nPixelSpace,
                                nLineSpace, psExtraArg);
}

/************************************************************************/
/* ==================================================================== */
/*                             TILDataset                               */
/* ==================================================================== */
/************************************************************************/

/************************************************************************/
/*                             TILDataset()                             */
/************************************************************************/

TILDataset::TILDataset() : poVRTDS(nullptr), papszMetadataFiles(nullptr)
{
}

/************************************************************************/
/*                            ~TILDataset()                             */
/************************************************************************/

TILDataset::~TILDataset()

{
    TILDataset::CloseDependentDatasets();
    CSLDestroy(papszMetadataFiles);
}

/************************************************************************/
/*                        CloseDependentDatasets()                      */
/************************************************************************/

int TILDataset::CloseDependentDatasets()
{
    int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();

    if (poVRTDS)
    {
        bHasDroppedRef = TRUE;
        delete poVRTDS;
        poVRTDS = nullptr;
    }

    return bHasDroppedRef;
}

/************************************************************************/
/*                              Identify()                              */
/************************************************************************/

int TILDataset::Identify(GDALOpenInfo *poOpenInfo)

{
    if (poOpenInfo->nHeaderBytes < 200 ||
        !poOpenInfo->IsExtensionEqualToCI("TIL"))
        return FALSE;

    if (strstr((const char *)poOpenInfo->pabyHeader, "numTiles") == nullptr)
        return FALSE;

    return TRUE;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

GDALDataset *TILDataset::Open(GDALOpenInfo *poOpenInfo)

{
    if (!Identify(poOpenInfo) || poOpenInfo->fpL == nullptr)
        return nullptr;

    /* -------------------------------------------------------------------- */
    /*      Confirm the requested access is supported.                      */
    /* -------------------------------------------------------------------- */
    if (poOpenInfo->eAccess == GA_Update)
    {
        ReportUpdateNotSupportedByDriver("TIL");
        return nullptr;
    }

    CPLString osDirname = CPLGetDirnameSafe(poOpenInfo->pszFilename);

    // get metadata reader

    GDALMDReaderManager mdreadermanager;
    GDALMDReaderBase *mdreader = mdreadermanager.GetReader(
        poOpenInfo->pszFilename, poOpenInfo->GetSiblingFiles(), MDR_DG);

    if (nullptr == mdreader)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Unable to open .TIL dataset due to missing metadata file.");
        return nullptr;
    }
    /* -------------------------------------------------------------------- */
    /*      Try to find the corresponding .IMD file.                        */
    /* -------------------------------------------------------------------- */
    char **papszIMD = mdreader->GetMetadataDomain(MD_DOMAIN_IMD);

    if (papszIMD == nullptr)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Unable to open .TIL dataset due to missing .IMD file.");
        return nullptr;
    }

    if (CSLFetchNameValue(papszIMD, "numRows") == nullptr ||
        CSLFetchNameValue(papszIMD, "numColumns") == nullptr ||
        CSLFetchNameValue(papszIMD, "bitsPerPixel") == nullptr)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Missing a required field in the .IMD file.");
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      Try to load and parse the .TIL file.                            */
    /* -------------------------------------------------------------------- */
    VSILFILE *fp = poOpenInfo->fpL;
    poOpenInfo->fpL = nullptr;

    CPLKeywordParser oParser;

    if (!oParser.Ingest(fp))
    {
        VSIFCloseL(fp);
        return nullptr;
    }

    VSIFCloseL(fp);

    char **papszTIL = oParser.GetAllKeywords();

    /* -------------------------------------------------------------------- */
    /*      Create a corresponding GDALDataset.                             */
    /* -------------------------------------------------------------------- */
    TILDataset *poDS = new TILDataset();
    poDS->papszMetadataFiles = mdreader->GetMetadataFiles();
    mdreader->FillMetadata(&poDS->oMDMD);
    poDS->nRasterXSize =
        atoi(CSLFetchNameValueDef(papszIMD, "numColumns", "0"));
    poDS->nRasterYSize = atoi(CSLFetchNameValueDef(papszIMD, "numRows", "0"));
    if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize))
    {
        delete poDS;
        return nullptr;
    }

    /* -------------------------------------------------------------------- */
    /*      We need to open one of the images in order to establish         */
    /*      details like the band count and types.                          */
    /* -------------------------------------------------------------------- */
    const char *pszFilename = CSLFetchNameValue(papszTIL, "TILE_1.filename");
    if (pszFilename == nullptr)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Missing TILE_1.filename in .TIL file.");
        delete poDS;
        return nullptr;
    }

    // trim double quotes.
    if (pszFilename[0] == '"')
        pszFilename++;
    if (pszFilename[strlen(pszFilename) - 1] == '"')
        const_cast<char *>(pszFilename)[strlen(pszFilename) - 1] = '\0';

    CPLString osFilename = CPLFormFilenameSafe(osDirname, pszFilename, nullptr);
    GDALDataset *poTemplateDS =
        GDALDataset::FromHandle(GDALOpen(osFilename, GA_ReadOnly));
    if (poTemplateDS == nullptr || poTemplateDS->GetRasterCount() == 0)
    {
        delete poDS;
        if (poTemplateDS != nullptr)
            GDALClose(poTemplateDS);
        return nullptr;
    }

    GDALRasterBand *poTemplateBand = poTemplateDS->GetRasterBand(1);
    const GDALDataType eDT = poTemplateBand->GetRasterDataType();
    const int nBandCount = poTemplateDS->GetRasterCount();

    // we suppose the first tile have the same projection as others (usually so)
    CPLString pszProjection(poTemplateDS->GetProjectionRef());
    if (!pszProjection.empty())
        poDS->SetProjection(pszProjection);

    // we suppose the first tile have the same GeoTransform as others (usually
    // so)
    double adfGeoTransform[6];
    if (poTemplateDS->GetGeoTransform(adfGeoTransform) == CE_None)
    {
        // According to
        // https://www.digitalglobe.com/sites/default/files/ISD_External.pdf,
        // ulx=originX and is "Easting of the center of the upper left pixel of
        // the image."
        adfGeoTransform[0] = CPLAtof(CSLFetchNameValueDef(
                                 papszIMD, "MAP_PROJECTED_PRODUCT.ULX", "0")) -
                             adfGeoTransform[1] / 2;
        adfGeoTransform[3] = CPLAtof(CSLFetchNameValueDef(
                                 papszIMD, "MAP_PROJECTED_PRODUCT.ULY", "0")) -
                             adfGeoTransform[5] / 2;
        poDS->SetGeoTransform(adfGeoTransform);
    }

    poTemplateBand = nullptr;
    GDALClose(poTemplateDS);

    /* -------------------------------------------------------------------- */
    /*      Create and initialize the corresponding VRT dataset used to     */
    /*      manage the tiled data access.                                   */
    /* -------------------------------------------------------------------- */
    poDS->poVRTDS = new VRTDataset(poDS->nRasterXSize, poDS->nRasterYSize);

    for (int iBand = 0; iBand < nBandCount; iBand++)
        poDS->poVRTDS->AddBand(eDT, nullptr);

    /* Don't try to write a VRT file */
    poDS->poVRTDS->SetWritable(FALSE);

    /* -------------------------------------------------------------------- */
    /*      Create band information objects.                                */
    /* -------------------------------------------------------------------- */
    for (int iBand = 1; iBand <= nBandCount; iBand++)
        poDS->SetBand(
            iBand, new TILRasterBand(poDS, iBand,
                                     reinterpret_cast<VRTSourcedRasterBand *>(
                                         poDS->poVRTDS->GetRasterBand(iBand))));

    /* -------------------------------------------------------------------- */
    /*      Add tiles as sources for each band.                             */
    /* -------------------------------------------------------------------- */
    const int nTileCount =
        atoi(CSLFetchNameValueDef(papszTIL, "numTiles", "0"));
    int iTile = 0;

    for (iTile = 1; iTile <= nTileCount; iTile++)
    {
        CPLString osKey;
        osKey.Printf("TILE_%d.filename", iTile);
        pszFilename = CSLFetchNameValue(papszTIL, osKey);
        if (pszFilename == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Missing TILE_%d.filename in .TIL file.", iTile);
            delete poDS;
            return nullptr;
        }

        // trim double quotes.
        if (pszFilename[0] == '"')
            pszFilename++;
        if (pszFilename[strlen(pszFilename) - 1] == '"')
            const_cast<char *>(pszFilename)[strlen(pszFilename) - 1] = '\0';
        osFilename = CPLFormFilenameSafe(osDirname, pszFilename, nullptr);
        poDS->m_aosFilenames.push_back(osFilename);

        osKey.Printf("TILE_%d.ULColOffset", iTile);
        const int nULX = atoi(CSLFetchNameValueDef(papszTIL, osKey, "0"));

        osKey.Printf("TILE_%d.ULRowOffset", iTile);
        const int nULY = atoi(CSLFetchNameValueDef(papszTIL, osKey, "0"));

        osKey.Printf("TILE_%d.LRColOffset", iTile);
        const int nLRX = atoi(CSLFetchNameValueDef(papszTIL, osKey, "0"));

        osKey.Printf("TILE_%d.LRRowOffset", iTile);
        const int nLRY = atoi(CSLFetchNameValueDef(papszTIL, osKey, "0"));

        for (int iBand = 1; iBand <= nBandCount; iBand++)
        {
            VRTSourcedRasterBand *poVRTBand =
                reinterpret_cast<VRTSourcedRasterBand *>(
                    poDS->poVRTDS->GetRasterBand(iBand));

            poVRTBand->AddSimpleSource(osFilename, iBand, 0, 0, nLRX - nULX + 1,
                                       nLRY - nULY + 1, nULX, nULY,
                                       nLRX - nULX + 1, nLRY - nULY + 1);
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Initialize any PAM information.                                 */
    /* -------------------------------------------------------------------- */
    poDS->SetDescription(poOpenInfo->pszFilename);
    poDS->TryLoadXML();

    /* -------------------------------------------------------------------- */
    /*      Check for overviews.                                            */
    /* -------------------------------------------------------------------- */
    poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);

    return poDS;
}

/************************************************************************/
/*                            GetFileList()                             */
/************************************************************************/

char **TILDataset::GetFileList()

{
    char **papszFileList = GDALPamDataset::GetFileList();

    for (const auto &osFilename : m_aosFilenames)
        papszFileList = CSLAddString(papszFileList, osFilename.c_str());

    if (nullptr != papszMetadataFiles)
    {
        for (int i = 0; papszMetadataFiles[i] != nullptr; i++)
        {
            papszFileList = CSLAddString(papszFileList, papszMetadataFiles[i]);
        }
    }

    return papszFileList;
}

/************************************************************************/
/*                          GDALRegister_TIL()                          */
/************************************************************************/

void GDALRegister_TIL()

{
    if (GDALGetDriverByName("TIL") != nullptr)
        return;

    GDALDriver *poDriver = new GDALDriver();

    poDriver->SetDescription("TIL");
    poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "EarthWatch .TIL");
    poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/til.html");
    poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");

    poDriver->pfnOpen = TILDataset::Open;
    poDriver->pfnIdentify = TILDataset::Identify;

    GetGDALDriverManager()->RegisterDriver(poDriver);
}