/
geotiff.cpp
19355 lines (17142 loc) · 719 KB
/
geotiff.cpp
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: GeoTIFF Driver
* Purpose: GDAL GeoTIFF support.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1998, 2002, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys dot com>
*
* 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 or substantial portions of the 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.
****************************************************************************/
// If we use sunpro compiler on linux. Weird idea indeed!
#if defined(__SUNPRO_CC) && defined(__linux__)
#define _GNU_SOURCE
#elif defined(__GNUC__) && !defined(_GNU_SOURCE)
// Required to use RTLD_DEFAULT of dlfcn.h.
#define _GNU_SOURCE
#endif
#include "cpl_port.h" // Must be first.
#include "gtiff.h"
#include <cassert>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#include <algorithm>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "cpl_config.h"
#include "cpl_conv.h"
#include "cpl_csv.h"
#include "cpl_error.h"
#include "cpl_minixml.h"
#include "cpl_multiproc.h"
#include "cpl_port.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "cpl_virtualmem.h"
#include "cpl_vsi.h"
#include "cpl_vsi_virtual.h"
#include "cpl_worker_thread_pool.h"
#include "cplkeywordparser.h"
#include "gdal.h"
#include "gdal_csv.h"
#include "gdal_frmts.h"
#include "gdal_mdreader.h"
#include "gdal_pam.h"
#include "gdal_priv.h"
#include "gdal_priv_templates.hpp"
#include "geo_normalize.h"
#include "geotiff.h"
#include "geovalues.h"
#include "gt_jpeg_copy.h"
#include "gt_overview.h"
#include "gt_wkt_srs.h"
#include "gt_wkt_srs_priv.h"
#include "ogr_spatialref.h"
#include "tiff.h"
#include "tif_float.h"
#include "tiffio.h"
#ifdef INTERNAL_LIBTIFF
# include "tiffiop.h"
# include "tif_lerc.h"
# ifdef WEBP_SUPPORT
# include "webp/encode.h"
# endif
#endif
#include "tiffvers.h"
#include "tifvsi.h"
#include "xtiffio.h"
CPL_CVSID("$Id$")
static bool bGlobalInExternalOvr = false;
static std::mutex gMutexThreadPool;
CPLWorkerThreadPool *gpoCompressThreadPool = nullptr;
// Only libtiff 4.0.4 can handle between 32768 and 65535 directories.
#if TIFFLIB_VERSION >= 20120922
#define SUPPORTS_MORE_THAN_32768_DIRECTORIES
#endif
const char* const szJPEGGTiffDatasetTmpPrefix = "/vsimem/gtiffdataset_jpg_tmp_";
typedef enum
{
GTIFFTAGTYPE_STRING,
GTIFFTAGTYPE_SHORT,
GTIFFTAGTYPE_FLOAT,
GTIFFTAGTYPE_BYTE_STRING
} GTIFFTagTypes;
typedef struct
{
const char *pszTagName;
int nTagVal;
GTIFFTagTypes eType;
} GTIFFTags;
static const GTIFFTags asTIFFTags[] =
{
{ "TIFFTAG_DOCUMENTNAME", TIFFTAG_DOCUMENTNAME, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_IMAGEDESCRIPTION", TIFFTAG_IMAGEDESCRIPTION,
GTIFFTAGTYPE_STRING },
{ "TIFFTAG_SOFTWARE", TIFFTAG_SOFTWARE, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_DATETIME", TIFFTAG_DATETIME, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_ARTIST", TIFFTAG_ARTIST, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_HOSTCOMPUTER", TIFFTAG_HOSTCOMPUTER, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_COPYRIGHT", TIFFTAG_COPYRIGHT, GTIFFTAGTYPE_STRING },
{ "TIFFTAG_XRESOLUTION", TIFFTAG_XRESOLUTION, GTIFFTAGTYPE_FLOAT },
{ "TIFFTAG_YRESOLUTION", TIFFTAG_YRESOLUTION, GTIFFTAGTYPE_FLOAT },
// Dealt as special case.
{ "TIFFTAG_RESOLUTIONUNIT", TIFFTAG_RESOLUTIONUNIT, GTIFFTAGTYPE_SHORT },
{ "TIFFTAG_MINSAMPLEVALUE", TIFFTAG_MINSAMPLEVALUE, GTIFFTAGTYPE_SHORT },
{ "TIFFTAG_MAXSAMPLEVALUE", TIFFTAG_MAXSAMPLEVALUE, GTIFFTAGTYPE_SHORT },
// GeoTIFF DGIWG tags
{ "GEO_METADATA", TIFFTAG_GEO_METADATA, GTIFFTAGTYPE_BYTE_STRING },
{ "TIFF_RSID", TIFFTAG_TIFF_RSID, GTIFFTAGTYPE_STRING },
};
const char szPROFILE_BASELINE[] = "BASELINE";
const char szPROFILE_GeoTIFF[] = "GeoTIFF";
const char szPROFILE_GDALGeoTIFF[] = "GDALGeoTIFF";
/************************************************************************/
/* GTIFFSetInExternalOvr() */
/************************************************************************/
void GTIFFSetInExternalOvr( bool b )
{
bGlobalInExternalOvr = b;
}
/************************************************************************/
/* GTIFFGetOverviewBlockSize() */
/************************************************************************/
void GTIFFGetOverviewBlockSize( int* pnBlockXSize, int* pnBlockYSize )
{
const char* pszVal = CPLGetConfigOption("GDAL_TIFF_OVR_BLOCKSIZE", "128");
int nOvrBlockSize = atoi(pszVal);
if( nOvrBlockSize < 64 || nOvrBlockSize > 4096 ||
!CPLIsPowerOfTwo(nOvrBlockSize) )
{
static bool bHasWarned = false;
if( !bHasWarned )
{
CPLError( CE_Warning, CPLE_NotSupported,
"Wrong value for GDAL_TIFF_OVR_BLOCKSIZE : %s. "
"Should be a power of 2 between 64 and 4096. "
"Defaulting to 128",
pszVal );
bHasWarned = true;
}
nOvrBlockSize = 128;
}
*pnBlockXSize = nOvrBlockSize;
*pnBlockYSize = nOvrBlockSize;
}
enum
{
ENDIANNESS_NATIVE,
ENDIANNESS_LITTLE,
ENDIANNESS_BIG
};
/************************************************************************/
/* ==================================================================== */
/* GTiffDataset */
/* ==================================================================== */
/************************************************************************/
class GTiffBitmapBand;
class GTiffDataset;
class GTiffJPEGOverviewBand;
class GTiffJPEGOverviewDS;
class GTiffRasterBand;
class GTiffRGBABand;
typedef enum
{
VIRTUAL_MEM_IO_NO,
VIRTUAL_MEM_IO_YES,
VIRTUAL_MEM_IO_IF_ENOUGH_RAM
} VirtualMemIOEnum;
#if !defined(__MINGW32__)
namespace {
#endif
typedef struct
{
GTiffDataset *poDS;
bool bTIFFIsBigEndian;
char *pszTmpFilename;
int nHeight;
uint16 nPredictor;
GByte *pabyBuffer;
int nBufferSize;
int nStripOrTile;
GByte *pabyCompressedBuffer; // Owned by pszTmpFilename.
int nCompressedBufferSize;
bool bReady;
} GTiffCompressionJob;
#if !defined(__MINGW32__)
}
#endif
class GTiffDataset final : public GDALPamDataset
{
CPL_DISALLOW_COPY_ASSIGN(GTiffDataset)
friend class GTiffBitmapBand;
friend class GTiffJPEGOverviewDS;
friend class GTiffJPEGOverviewBand;
friend class GTiffOddBitsBand;
friend class GTiffRasterBand;
friend class GTiffRGBABand;
friend class GTiffSplitBand;
friend class GTiffSplitBitmapBand;
friend void GTIFFSetJpegQuality( GDALDatasetH hGTIFFDS, int nJpegQuality );
friend void GTIFFSetJpegTablesMode( GDALDatasetH hGTIFFDS, int nJpegTablesMode );
TIFF *hTIFF;
VSILFILE *fpL;
#if defined(INTERNAL_LIBTIFF) && defined(DEFER_STRILE_LOAD)
uint32 nStripArrayAlloc;
vsi_l_offset m_nFileSize; // 0 when unknown, only valid in GA_ReadOnly mode
#endif
bool bStreamingIn;
bool bStreamingOut;
CPLString osTmpFilename{};
VSILFILE* fpToWrite;
int nLastWrittenBlockId;
GTiffDataset **ppoActiveDSRef;
GTiffDataset *poActiveDS; // Only used in actual base.
bool bScanDeferred;
void ScanDirectories();
toff_t nDirOffset;
bool bBase;
// Useful for closing TIFF handle opened by GTIFF_DIR:
bool bCloseTIFFHandle;
uint16 nPlanarConfig;
uint16 nSamplesPerPixel;
uint16 nBitsPerSample;
uint32 nRowsPerStrip;
uint16 nPhotometric;
uint16 nSampleFormat;
uint16 nCompression;
int nBlocksPerBand;
int nBlockXSize;
int nBlockYSize;
int nLoadedBlock; // Or tile.
bool bLoadedBlockDirty;
GByte *pabyBlockBuf;
CPLErr LoadBlockBuf( int nBlockId, bool bReadFromDisk = true );
CPLErr FlushBlockBuf();
bool bWriteErrorInFlushBlockBuf;
char *pszProjection;
CPLString m_osVertUnit{};
bool bLookedForProjection;
bool bLookedForMDAreaOrPoint;
void LoadMDAreaOrPoint();
void LookForProjection();
#ifdef ESRI_BUILD
void AdjustLinearUnit( short UOMLength );
#endif
double adfGeoTransform[6];
bool bGeoTransformValid;
bool bTreatAsRGBA;
bool bCrystalized;
void Crystalize(); // TODO: Spelling.
GDALColorTable *poColorTable;
void WriteGeoTIFFInfo();
bool SetDirectory( toff_t nDirOffset = 0 );
int nOverviewCount;
GTiffDataset **papoOverviewDS;
// If > 0, the implicit JPEG overviews are visible through
// GetOverviewCount().
int nJPEGOverviewVisibilityCounter;
// Currently visible overviews. Generally == nJPEGOverviewCountOri.
int nJPEGOverviewCount;
int nJPEGOverviewCountOri; // Size of papoJPEGOverviewDS.
GTiffJPEGOverviewDS **papoJPEGOverviewDS;
int GetJPEGOverviewCount();
int nGCPCount;
GDAL_GCP *pasGCPList;
bool IsBlockAvailable( int nBlockId,
vsi_l_offset* pnOffset = nullptr,
vsi_l_offset* pnSize = nullptr,
bool *pbErrOccurred = nullptr );
bool bGeoTIFFInfoChanged;
bool bForceUnsetGTOrGCPs;
bool bForceUnsetProjection;
bool bNoDataChanged;
bool bNoDataSet;
double dfNoDataValue;
bool bMetadataChanged;
bool bColorProfileMetadataChanged;
bool m_bForceUnsetRPC = false;
bool bNeedsRewrite;
void ApplyPamInfo();
void PushMetadataToPam();
GDALMultiDomainMetadata oGTiffMDMD{};
CPLString osProfile{};
char **papszCreationOptions;
bool bLoadingOtherBands;
void* pabyTempWriteBuffer;
int nTempWriteBufferSize;
bool WriteEncodedTile( uint32 tile, GByte* pabyData,
int bPreserveDataBuffer );
bool WriteEncodedStrip( uint32 strip, GByte* pabyData,
int bPreserveDataBuffer );
template<class T>
bool HasOnlyNoDataT( const T* pBuffer, int nWidth, int nHeight,
int nLineStride, int nComponents ) const;
bool HasOnlyNoData( const void* pBuffer, int nWidth, int nHeight,
int nLineStride, int nComponents );
inline bool IsFirstPixelEqualToNoData( const void* pBuffer );
GTiffDataset* poMaskDS;
GTiffDataset* poBaseDS;
bool bIsOverview_ = false;
CPLString osFilename{};
bool bWriteEmptyTiles;
bool bFillEmptyTilesAtClosing;
void FillEmptyTiles();
void FlushDirectory();
CPLErr CleanOverviews();
// Used for the all-in-on-strip case.
int nLastLineRead;
int nLastBandRead;
bool bTreatAsSplit;
bool bTreatAsSplitBitmap;
bool bClipWarn;
bool bIMDRPCMetadataLoaded;
char** papszMetadataFiles;
void LoadMetadata();
bool bEXIFMetadataLoaded;
void LoadEXIFMetadata();
bool bICCMetadataLoaded;
void LoadICCProfile();
bool bHasWarnedDisableAggressiveBandCaching;
bool bDontReloadFirstBlock; // Hack for libtiff 3.X and #3633.
int nZLevel;
int nLZMAPreset;
int nZSTDLevel;
int nWebPLevel;
bool bWebPLossless;
int nJpegQuality;
int nJpegTablesMode;
#if HAVE_LERC
double dfMaxZError = 0.0;
uint32 anLercAddCompressionAndVersion[2]{0,0};
#endif
bool bPromoteTo8Bits;
bool bDebugDontWriteBlocks;
CPLErr RegisterNewOverviewDataset( toff_t nOverviewOffset, int l_nJpegQuality );
CPLErr CreateOverviewsFromSrcOverviews( GDALDataset* poSrcDS );
CPLErr CreateInternalMaskOverviews( int nOvrBlockXSize,
int nOvrBlockYSize );
bool bIsFinalized;
int Finalize();
bool bIgnoreReadErrors;
CPLString osGeorefFilename{};
bool bDirectIO;
VirtualMemIOEnum eVirtualMemIOUsage;
CPLVirtualMem* psVirtualMemIOMapping;
GTIFFKeysFlavorEnum eGeoTIFFKeysFlavor;
CPLVirtualMem *pBaseMapping;
int nRefBaseMapping;
bool bHasDiscardedLsb;
std::vector<int> anMaskLsb{};
std::vector<int> anOffsetLsb{};
void DiscardLsb(GByte* pabyBuffer, int nBytes, int iBand) const;
void GetDiscardLsbOption( char** papszOptions );
CPLWorkerThreadPool *poCompressThreadPool;
std::vector<GTiffCompressionJob> asCompressionJobs{};
CPLMutex *hCompressThreadPoolMutex;
void InitCompressionThreads( char** papszOptions );
void InitCreationOrOpenOptions( char** papszOptions );
static void ThreadCompressionFunc( void* pData );
void WaitCompletionForBlock( int nBlockId );
void WriteRawStripOrTile( int nStripOrTile,
GByte* pabyCompressedBuffer,
int nCompressedBufferSize );
bool SubmitCompressionJob( int nStripOrTile, GByte* pabyData,
int cc, int nHeight) ;
int GuessJPEGQuality( bool& bOutHasQuantizationTable,
bool& bOutHasHuffmanTable );
void SetJPEGQualityAndTablesModeFromFile();
int DirectIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg );
int VirtualMemIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg );
GByte *m_pTempBufferForCommonDirectIO;
size_t m_nTempBufferForCommonDirectIOSize;
template<class FetchBuffer> CPLErr CommonDirectIO(
FetchBuffer& oFetcher,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace );
bool m_bReadGeoTransform;
bool m_bLoadPam;
void LoadGeoreferencingAndPamIfNeeded();
bool m_bHasGotSiblingFiles;
char **GetSiblingFiles();
void IdentifyAuthorizedGeoreferencingSources();
bool m_bHasIdentifiedAuthorizedGeoreferencingSources;
int m_nPAMGeorefSrcIndex;
int m_nINTERNALGeorefSrcIndex;
int m_nTABFILEGeorefSrcIndex;
int m_nWORLDFILEGeorefSrcIndex;
int m_nGeoTransformGeorefSrcIndex;
void FlushCacheInternal( bool bFlushDirectory );
int m_nHasOptimizedReadMultiRange = -1;
int HasOptimizedReadMultiRange();
protected:
virtual int CloseDependentDatasets() override;
public:
GTiffDataset();
virtual ~GTiffDataset();
virtual const char *GetProjectionRef() override;
virtual CPLErr SetProjection( const char * ) override;
virtual CPLErr GetGeoTransform( double * ) override;
virtual CPLErr SetGeoTransform( double * ) override;
virtual int GetGCPCount() override;
virtual const char *GetGCPProjection() override;
virtual const GDAL_GCP *GetGCPs() override;
CPLErr SetGCPs( int, const GDAL_GCP *, const char * ) override;
virtual CPLErr IRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg ) override;
virtual char **GetFileList() override;
virtual CPLErr IBuildOverviews( const char *, int, int *, int, int *,
GDALProgressFunc, void * ) override;
CPLErr OpenOffset( TIFF *, GTiffDataset **ppoActiveDSRef,
toff_t nDirOffset, bool bBaseIn, GDALAccess,
bool bAllowRGBAInterface = true,
bool bReadGeoTransform = false );
static GDALDataset *OpenDir( GDALOpenInfo * );
static GDALDataset *Open( GDALOpenInfo * );
static int Identify( GDALOpenInfo * );
static GDALDataset *Create( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType, char ** papszParmList );
static GDALDataset *CreateCopy( const char * pszFilename,
GDALDataset *poSrcDS,
int bStrict, char ** papszOptions,
GDALProgressFunc pfnProgress,
void * pProgressData );
virtual void FlushCache() override;
virtual char **GetMetadataDomainList() override;
virtual CPLErr SetMetadata( char **, const char * = "" ) override;
virtual char **GetMetadata( const char * pszDomain = "" ) override;
virtual CPLErr SetMetadataItem( const char*, const char*,
const char* = "" ) override;
virtual const char *GetMetadataItem( const char * pszName,
const char * pszDomain = "" ) override;
virtual void *GetInternalHandle( const char * ) override;
virtual CPLErr CreateMaskBand( int nFlags ) override;
// Only needed by createcopy and close code.
static void WriteRPC( GDALDataset *, TIFF *, int, const char *,
const char *, char **,
bool bWriteOnlyInPAMIfNeeded = false );
static bool WriteMetadata( GDALDataset *, TIFF *, bool, const char *,
const char *, char **,
bool bExcludeRPBandIMGFileWriting = false );
static void WriteNoDataValue( TIFF *, double );
static void UnsetNoDataValue( TIFF * );
static TIFF * CreateLL( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType,
double dfExtraSpaceForOverviews,
char **papszParmList,
VSILFILE** pfpL,
CPLString& osTmpFilename );
CPLErr WriteEncodedTileOrStrip( uint32 tile_or_strip, void* data,
int bPreserveDataBuffer );
static void SaveICCProfile( GTiffDataset *pDS, TIFF *hTIFF,
char **papszParmList, uint32 nBitsPerSample );
static bool HasVerticalCS(const char* pszProjectionIn);
};
/************************************************************************/
/* ==================================================================== */
/* GTiffJPEGOverviewDS */
/* ==================================================================== */
/************************************************************************/
class GTiffJPEGOverviewDS final : public GDALDataset
{
CPL_DISALLOW_COPY_ASSIGN(GTiffJPEGOverviewDS)
friend class GTiffJPEGOverviewBand;
GTiffDataset* poParentDS;
int nOverviewLevel;
int nJPEGTableSize;
GByte *pabyJPEGTable;
CPLString osTmpFilenameJPEGTable{};
CPLString osTmpFilename{};
GDALDataset* poJPEGDS;
// Valid block id of the parent DS that match poJPEGDS.
int nBlockId;
public:
GTiffJPEGOverviewDS( GTiffDataset* poParentDS, int nOverviewLevel,
const void* pJPEGTable, int nJPEGTableSize );
virtual ~GTiffJPEGOverviewDS();
virtual CPLErr IRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg ) override;
};
class GTiffJPEGOverviewBand final : public GDALRasterBand
{
public:
GTiffJPEGOverviewBand( GTiffJPEGOverviewDS* poDS, int nBand );
virtual ~GTiffJPEGOverviewBand() {}
virtual CPLErr IReadBlock( int, int, void * ) override;
};
/************************************************************************/
/* GTiffJPEGOverviewDS() */
/************************************************************************/
GTiffJPEGOverviewDS::GTiffJPEGOverviewDS( GTiffDataset* poParentDSIn,
int nOverviewLevelIn,
const void* pJPEGTable,
int nJPEGTableSizeIn ) :
poParentDS(poParentDSIn),
nOverviewLevel(nOverviewLevelIn),
nJPEGTableSize(nJPEGTableSizeIn),
pabyJPEGTable(nullptr),
poJPEGDS(nullptr),
nBlockId(-1)
{
osTmpFilenameJPEGTable.Printf("/vsimem/jpegtable_%p", this);
const GByte abyAdobeAPP14RGB[] = {
0xFF, 0xEE, 0x00, 0x0E, 0x41, 0x64, 0x6F, 0x62, 0x65, 0x00,
0x64, 0x00, 0x00, 0x00, 0x00, 0x00 };
const bool bAddAdobe =
poParentDS->nPlanarConfig == PLANARCONFIG_CONTIG &&
poParentDS->nPhotometric != PHOTOMETRIC_YCBCR &&
poParentDS->nBands == 3;
pabyJPEGTable =
static_cast<GByte*>( CPLMalloc(
nJPEGTableSize + (bAddAdobe ? sizeof(abyAdobeAPP14RGB) : 0)) );
memcpy(pabyJPEGTable, pJPEGTable, nJPEGTableSize);
if( bAddAdobe )
{
memcpy( pabyJPEGTable + nJPEGTableSize, abyAdobeAPP14RGB,
sizeof(abyAdobeAPP14RGB) );
nJPEGTableSize += sizeof(abyAdobeAPP14RGB);
}
CPL_IGNORE_RET_VAL(
VSIFCloseL(
VSIFileFromMemBuffer(
osTmpFilenameJPEGTable, pabyJPEGTable, nJPEGTableSize, TRUE )));
const int nScaleFactor = 1 << nOverviewLevel;
nRasterXSize = (poParentDS->nRasterXSize + nScaleFactor - 1) / nScaleFactor;
nRasterYSize = (poParentDS->nRasterYSize + nScaleFactor - 1) / nScaleFactor;
for( int i = 1; i <= poParentDS->nBands; ++i )
SetBand(i, new GTiffJPEGOverviewBand(this, i));
SetMetadataItem( "INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE" );
if( poParentDS->nPhotometric == PHOTOMETRIC_YCBCR )
SetMetadataItem( "COMPRESSION", "YCbCr JPEG", "IMAGE_STRUCTURE" );
else
SetMetadataItem( "COMPRESSION", "JPEG", "IMAGE_STRUCTURE" );
}
/************************************************************************/
/* ~GTiffJPEGOverviewDS() */
/************************************************************************/
GTiffJPEGOverviewDS::~GTiffJPEGOverviewDS()
{
if( poJPEGDS != nullptr )
GDALClose( poJPEGDS );
VSIUnlink(osTmpFilenameJPEGTable);
if( !osTmpFilename.empty() )
VSIUnlink(osTmpFilename);
}
/************************************************************************/
/* IRasterIO() */
/************************************************************************/
CPLErr GTiffJPEGOverviewDS::IRasterIO(
GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void * pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg )
{
// For non-single strip JPEG-IN-TIFF, the block based strategy will
// be the most efficient one, to avoid decompressing the JPEG content
// for each requested band.
if( nBandCount > 1 && poParentDS->nPlanarConfig == PLANARCONFIG_CONTIG &&
(poParentDS->nBlockXSize < poParentDS->nRasterXSize ||
poParentDS->nBlockYSize > 1) )
{
return BlockBasedRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType, nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace,
psExtraArg );
}
return GDALDataset::IRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize, eBufType,
nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
psExtraArg );
}
/************************************************************************/
/* GTiffJPEGOverviewBand() */
/************************************************************************/
GTiffJPEGOverviewBand::GTiffJPEGOverviewBand( GTiffJPEGOverviewDS* poDSIn,
int nBandIn )
{
poDS = poDSIn;
nBand = nBandIn;
eDataType =
poDSIn->poParentDS->GetRasterBand(nBandIn)->GetRasterDataType();
poDSIn->poParentDS->GetRasterBand(nBandIn)->
GetBlockSize(&nBlockXSize, &nBlockYSize);
const int nScaleFactor = 1 << poDSIn->nOverviewLevel;
nBlockXSize = (nBlockXSize + nScaleFactor - 1) / nScaleFactor;
nBlockYSize = (nBlockYSize + nScaleFactor - 1) / nScaleFactor;
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr GTiffJPEGOverviewBand::IReadBlock( int nBlockXOff, int nBlockYOff,
void *pImage )
{
GTiffJPEGOverviewDS* poGDS = cpl::down_cast<GTiffJPEGOverviewDS *>(poDS);
// Compute the source block ID.
int nBlockId = 0;
int nParentBlockXSize, nParentBlockYSize;
poGDS->poParentDS->GetRasterBand(1)->
GetBlockSize(&nParentBlockXSize, &nParentBlockYSize);
const bool bIsSingleStripAsSplit = (nParentBlockYSize == 1 &&
poGDS->poParentDS->nBlockYSize != nParentBlockYSize);
if( !bIsSingleStripAsSplit )
{
int l_nBlocksPerRow = DIV_ROUND_UP(poGDS->poParentDS->nRasterXSize,
poGDS->poParentDS->nBlockXSize);
nBlockId = nBlockYOff * l_nBlocksPerRow + nBlockXOff;
}
if( poGDS->poParentDS->nPlanarConfig == PLANARCONFIG_SEPARATE )
{
nBlockId += (nBand-1) * poGDS->poParentDS->nBlocksPerBand;
}
if( !poGDS->poParentDS->SetDirectory() )
return CE_Failure;
// Make sure it is available.
const int nDataTypeSize = GDALGetDataTypeSizeBytes(eDataType);
vsi_l_offset nOffset = 0;
vsi_l_offset nByteCount = 0;
bool bErrOccurred = false;
if( !poGDS->poParentDS->IsBlockAvailable(nBlockId, &nOffset, &nByteCount, &bErrOccurred) )
{
memset(pImage, 0, nBlockXSize * nBlockYSize * nDataTypeSize );
if( bErrOccurred )
return CE_Failure;
return CE_None;
}
const int nScaleFactor = 1 << poGDS->nOverviewLevel;
if( poGDS->poJPEGDS == nullptr || nBlockId != poGDS->nBlockId )
{
if( nByteCount < 2 )
return CE_Failure;
nOffset += 2; // Skip leading 0xFF 0xF8.
nByteCount -= 2;
// Special case for last strip that might be smaller than other strips
// In which case we must invalidate the dataset.
TIFF* hTIFF = poGDS->poParentDS->hTIFF;
if( !TIFFIsTiled( hTIFF ) && !bIsSingleStripAsSplit &&
(nBlockYOff + 1 ==
DIV_ROUND_UP( poGDS->poParentDS->nRasterYSize,
poGDS->poParentDS->nBlockYSize ) ||
(poGDS->poJPEGDS != nullptr &&
poGDS->poJPEGDS->GetRasterYSize() !=
nBlockYSize * nScaleFactor)) )
{
if( poGDS->poJPEGDS != nullptr )
GDALClose( poGDS->poJPEGDS );
poGDS->poJPEGDS = nullptr;
}
CPLString osFileToOpen;
poGDS->osTmpFilename.Printf("/vsimem/sparse_%p", poGDS);
VSILFILE* fp = VSIFOpenL(poGDS->osTmpFilename, "wb+");
// If the size of the JPEG strip/tile is small enough, we will
// read it from the TIFF file and forge a in-memory JPEG file with
// the JPEG table followed by the JPEG data.
const bool bInMemoryJPEGFile = nByteCount < 256 * 256;
if( bInMemoryJPEGFile )
{
// If the previous file was opened as a /vsisparse/, must re-open.
if( poGDS->poJPEGDS != nullptr &&
STARTS_WITH(poGDS->poJPEGDS->GetDescription(), "/vsisparse/") )
{
GDALClose( poGDS->poJPEGDS );
poGDS->poJPEGDS = nullptr;
}
osFileToOpen = poGDS->osTmpFilename;
bool bError = false;
if( VSIFSeekL(fp, poGDS->nJPEGTableSize + nByteCount - 1, SEEK_SET)
!= 0 )
bError = true;
char ch = 0;
if( !bError && VSIFWriteL(&ch, 1, 1, fp) != 1 )
bError = true;
GByte* pabyBuffer =
VSIGetMemFileBuffer( poGDS->osTmpFilename, nullptr, FALSE);
memcpy(pabyBuffer, poGDS->pabyJPEGTable, poGDS->nJPEGTableSize);
VSILFILE* fpTIF = VSI_TIFFGetVSILFile(TIFFClientdata( hTIFF ));
if( !bError && VSIFSeekL(fpTIF, nOffset, SEEK_SET) != 0 )
bError = true;
if( VSIFReadL( pabyBuffer + poGDS->nJPEGTableSize,
static_cast<size_t>(nByteCount), 1, fpTIF) != 1 )
bError = true;
if( bError )
{
CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
return CE_Failure;
}
}
else
{
// If the JPEG strip/tile is too big (e.g. a single-strip
// JPEG-in-TIFF), we will use /vsisparse mechanism to make a
// fake JPEG file.
// Always re-open.
GDALClose( poGDS->poJPEGDS );
poGDS->poJPEGDS = nullptr;
osFileToOpen =
CPLSPrintf("/vsisparse/%s", poGDS->osTmpFilename.c_str());
if( VSIFPrintfL(
fp,
"<VSISparseFile><SubfileRegion>"
"<Filename relative='0'>%s</Filename>"
"<DestinationOffset>0</DestinationOffset>"
"<SourceOffset>0</SourceOffset>"
"<RegionLength>%d</RegionLength>"
"</SubfileRegion>"
"<SubfileRegion>"
"<Filename relative='0'>%s</Filename>"
"<DestinationOffset>%d</DestinationOffset>"
"<SourceOffset>" CPL_FRMT_GUIB "</SourceOffset>"
"<RegionLength>" CPL_FRMT_GUIB "</RegionLength>"
"</SubfileRegion></VSISparseFile>",
poGDS->osTmpFilenameJPEGTable.c_str(),
static_cast<int>(poGDS->nJPEGTableSize),
poGDS->poParentDS->GetDescription(),
static_cast<int>(poGDS->nJPEGTableSize),
nOffset,
nByteCount) < 0 )
{
CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
return CE_Failure;
}
}
CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
if( poGDS->poJPEGDS == nullptr )
{
const char* apszDrivers[] = { "JPEG", nullptr };
CPLString osOldVal;
if( poGDS->poParentDS->nPlanarConfig == PLANARCONFIG_CONTIG &&
poGDS->nBands == 4 )
{
osOldVal =
CPLGetThreadLocalConfigOption("GDAL_JPEG_TO_RGB", "");
CPLSetThreadLocalConfigOption("GDAL_JPEG_TO_RGB", "NO");
}
poGDS->poJPEGDS =
static_cast<GDALDataset *>( GDALOpenEx(
osFileToOpen,
GDAL_OF_RASTER | GDAL_OF_INTERNAL,
apszDrivers, nullptr, nullptr) );
if( poGDS->poJPEGDS != nullptr )
{
// Force all implicit overviews to be available, even for
// small tiles.
CPLSetThreadLocalConfigOption( "JPEG_FORCE_INTERNAL_OVERVIEWS",
"YES");
GDALGetOverviewCount(GDALGetRasterBand(poGDS->poJPEGDS, 1));
CPLSetThreadLocalConfigOption( "JPEG_FORCE_INTERNAL_OVERVIEWS",
nullptr);
poGDS->nBlockId = nBlockId;
}
if( poGDS->poParentDS->nPlanarConfig == PLANARCONFIG_CONTIG &&
poGDS->nBands == 4 )
{
CPLSetThreadLocalConfigOption(
"GDAL_JPEG_TO_RGB",
!osOldVal.empty() ? osOldVal.c_str() : nullptr );
}
}
else
{
// Trick: we invalidate the JPEG dataset to force a reload
// of the new content.
CPLErrorReset();
poGDS->poJPEGDS->FlushCache();
if( CPLGetLastErrorNo() != 0 )
{
GDALClose( poGDS->poJPEGDS );
poGDS->poJPEGDS = nullptr;
return CE_Failure;
}
poGDS->nBlockId = nBlockId;
}
}
CPLErr eErr = CE_Failure;
if( poGDS->poJPEGDS )
{
GDALDataset* l_poDS = poGDS->poJPEGDS;
int nReqXOff = 0;
int nReqYOff = 0;