forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjp2kakdataset.cpp
3097 lines (2678 loc) · 109 KB
/
jp2kakdataset.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: JPEG-2000
* Purpose: Implementation of the ISO/IEC 15444-1 standard based on Kakadu.
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 2002, Frank Warmerdam <[email protected]>
* Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "jp2kakdataset.h"
#include "jp2kakdrivercore.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "gdal_frmts.h"
#include "gdaljp2abstractdataset.h"
#include "gdaljp2metadata.h"
#include "jp2kak_headers.h"
#include "subfile_source.h"
#include "vsil_target.h"
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#if KDU_MAJOR_VERSION > 7 || (KDU_MAJOR_VERSION == 7 && KDU_MINOR_VERSION >= 5)
using namespace kdu_core;
using namespace kdu_supp;
#endif
// #define KAKADU_JPX 1
static bool kakadu_initialized = false;
/* -------------------------------------------------------------------- */
/* The number of tiles at a time we will push through the */
/* encoder per flush when writing jpeg2000 streams. */
/* -------------------------------------------------------------------- */
constexpr int TILE_CHUNK_SIZE = 1024;
/************************************************************************/
/* ==================================================================== */
/* JP2KAKRasterBand */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* JP2KAKRasterBand() */
/************************************************************************/
JP2KAKRasterBand::JP2KAKRasterBand(int nBandIn, kdu_codestream oCodeStreamIn,
kdu_client *jpip_clientIn,
jp2_channels oJP2Channels,
JP2KAKDataset *poBaseDSIn)
: poBaseDS(poBaseDSIn), jpip_client(jpip_clientIn),
oCodeStream(oCodeStreamIn), eInterp(GCI_Undefined)
{
nBand = nBandIn; // From GDALRasterBand.
if (oCodeStream.get_bit_depth(nBand - 1) > 8 &&
oCodeStream.get_bit_depth(nBand - 1) <= 16 &&
oCodeStream.get_signed(nBand - 1))
eDataType = GDT_Int16;
else if (oCodeStream.get_bit_depth(nBand - 1) > 8 &&
oCodeStream.get_bit_depth(nBand - 1) <= 16 &&
!oCodeStream.get_signed(nBand - 1))
eDataType = GDT_UInt16;
else if (oCodeStream.get_bit_depth(nBand - 1) > 16 &&
oCodeStream.get_signed(nBand - 1))
eDataType = GDT_Int32;
else if (oCodeStream.get_bit_depth(nBand - 1) > 16 &&
!oCodeStream.get_signed(nBand - 1))
eDataType = GDT_UInt32;
else
eDataType = GDT_Byte;
oCodeStream.apply_input_restrictions(0, 0, poBaseDSIn->m_nDiscardLevels, 0,
nullptr);
oCodeStream.get_dims(0, band_dims);
nRasterXSize = band_dims.size.x;
nRasterYSize = band_dims.size.y;
// Capture some useful metadata.
if (oCodeStream.get_bit_depth(nBand - 1) % 8 != 0 &&
!poBaseDSIn->bPromoteTo8Bit)
{
SetMetadataItem(
"NBITS",
CPLString().Printf("%d", oCodeStream.get_bit_depth(nBand - 1)),
"IMAGE_STRUCTURE");
}
SetMetadataItem("COMPRESSION", "JP2000", "IMAGE_STRUCTURE");
// Use tile dimension as block size, unless it is too big
kdu_dims valid_tiles;
kdu_dims tile_dims;
oCodeStream.get_valid_tiles(valid_tiles);
oCodeStream.get_tile_dims(valid_tiles.pos, -1, tile_dims);
// Configuration option only for testing purposes
if (CPLTestBool(CPLGetConfigOption("USE_TILE_AS_BLOCK", "NO")))
{
nBlockXSize = std::min(tile_dims.size.x, nRasterXSize);
nBlockYSize = std::min(tile_dims.size.y, nRasterYSize);
}
else
{
nBlockXSize = std::min(std::min(tile_dims.size.x, 2048), nRasterXSize);
nBlockYSize = std::min(std::min(tile_dims.size.y, 2048), nRasterYSize);
}
CPLDebug("JP2KAK",
"JP2KAKRasterBand::JP2KAKRasterBand() : "
"Tile dimension : %d X %d\n",
nBlockXSize, nBlockYSize);
// Figure out the color interpretation for this band.
eInterp = GCI_Undefined;
if (oJP2Channels.exists())
{
int nRedIndex = -1;
int nGreenIndex = -1;
int nBlueIndex = -1;
int nLutIndex = 0;
int nCSI = 0;
#if KDU_MAJOR_VERSION > 7 || (KDU_MAJOR_VERSION == 7 && KDU_MINOR_VERSION >= 8)
int nFMT = 0;
if (oJP2Channels.get_num_colours() == 3)
{
oJP2Channels.get_colour_mapping(0, nRedIndex, nLutIndex, nCSI,
nFMT);
oJP2Channels.get_colour_mapping(1, nGreenIndex, nLutIndex, nCSI,
nFMT);
oJP2Channels.get_colour_mapping(2, nBlueIndex, nLutIndex, nCSI,
nFMT);
}
else
{
oJP2Channels.get_colour_mapping(0, nRedIndex, nLutIndex, nCSI,
nFMT);
if (nBand == 1)
eInterp = GCI_GrayIndex;
}
#else
if (oJP2Channels.get_num_colours() == 3)
{
oJP2Channels.get_colour_mapping(0, nRedIndex, nLutIndex, nCSI);
oJP2Channels.get_colour_mapping(1, nGreenIndex, nLutIndex, nCSI);
oJP2Channels.get_colour_mapping(2, nBlueIndex, nLutIndex, nCSI);
}
else
{
oJP2Channels.get_colour_mapping(0, nRedIndex, nLutIndex, nCSI);
if (nBand == 1)
eInterp = GCI_GrayIndex;
}
#endif
if (eInterp != GCI_Undefined)
/* nothing to do */;
// If we have LUT info, it is a palette image.
else if (nLutIndex != -1)
eInterp = GCI_PaletteIndex;
// Establish color band this is.
else if (nRedIndex == nBand - 1)
eInterp = GCI_RedBand;
else if (nGreenIndex == nBand - 1)
eInterp = GCI_GreenBand;
else if (nBlueIndex == nBand - 1)
eInterp = GCI_BlueBand;
else
eInterp = GCI_Undefined;
// Could this band be an alpha band?
if (eInterp == GCI_Undefined)
{
for (int color_idx = 0; color_idx < oJP2Channels.get_num_colours();
color_idx++)
{
int opacity_idx = 0;
int lut_idx = 0;
// get_opacity_mapping sets that last 3 args by non-const refs.
#if KDU_MAJOR_VERSION > 7 || (KDU_MAJOR_VERSION == 7 && KDU_MINOR_VERSION >= 8)
if (oJP2Channels.get_opacity_mapping(color_idx, opacity_idx,
lut_idx, nCSI, nFMT))
#else
if (oJP2Channels.get_opacity_mapping(color_idx, opacity_idx,
lut_idx, nCSI))
#endif
{
if (opacity_idx == nBand - 1)
eInterp = GCI_AlphaBand;
}
#if KDU_MAJOR_VERSION > 7 || (KDU_MAJOR_VERSION == 7 && KDU_MINOR_VERSION >= 8)
if (oJP2Channels.get_premult_mapping(color_idx, opacity_idx,
lut_idx, nCSI, nFMT))
#else
if (oJP2Channels.get_premult_mapping(color_idx, opacity_idx,
lut_idx, nCSI))
#endif
{
if (opacity_idx == nBand - 1)
eInterp = GCI_AlphaBand;
}
}
}
}
else if (nBand == 1)
{
eInterp = GCI_RedBand;
}
else if (nBand == 2)
{
eInterp = GCI_GreenBand;
}
else if (nBand == 3)
{
eInterp = GCI_BlueBand;
}
else
{
eInterp = GCI_GrayIndex;
}
}
/************************************************************************/
/* ~JP2KAKRasterBand() */
/************************************************************************/
JP2KAKRasterBand::~JP2KAKRasterBand() = default;
/************************************************************************/
/* GetOverviewCount() */
/************************************************************************/
int JP2KAKRasterBand::GetOverviewCount()
{
if (!poBaseDS->AreOverviewsEnabled())
return 0;
const int nExtOvrCount = GDALPamRasterBand::GetOverviewCount();
if (nExtOvrCount > 0)
return nExtOvrCount;
return static_cast<int>(poBaseDS->m_apoOverviews.size());
}
/************************************************************************/
/* GetOverview() */
/************************************************************************/
GDALRasterBand *JP2KAKRasterBand::GetOverview(int iOverviewIndex)
{
if (GDALPamRasterBand::GetOverviewCount() > 0)
return GDALPamRasterBand::GetOverview(iOverviewIndex);
if (iOverviewIndex < 0 ||
iOverviewIndex >= static_cast<int>(poBaseDS->m_apoOverviews.size()))
return nullptr;
return poBaseDS->m_apoOverviews[iOverviewIndex]->GetRasterBand(nBand);
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr JP2KAKRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
void *pImage)
{
const int nWordSize = GDALGetDataTypeSizeBytes(eDataType);
CPLDebug("JP2KAK", "IReadBlock(%d,%d) on band %d.", nBlockXOff, nBlockYOff,
nBand);
// Compute the normal window, and buffer size.
const int nWXOff = nBlockXOff * nBlockXSize;
const int nWYOff = nBlockYOff * nBlockYSize;
int nWXSize = nBlockXSize;
int nWYSize = nBlockYSize;
int nXSize = nBlockXSize;
int nYSize = nBlockYSize;
// Adjust if we have a partial block on the right or bottom of
// the image. Unfortunately despite some care I can't seem to
// always get partial tiles to come from the desired overview
// level depending on how various things round - hopefully not
// a big deal.
if (nWXOff + nWXSize > poBaseDS->GetRasterXSize())
{
nWXSize = poBaseDS->GetRasterXSize() - nWXOff;
nXSize = nRasterXSize - nBlockXSize * nBlockXOff;
}
if (nWYOff + nWYSize > poBaseDS->GetRasterYSize())
{
nWYSize = poBaseDS->GetRasterYSize() - nWYOff;
nYSize = nRasterYSize - nBlockYSize * nBlockYOff;
}
if (nXSize != nBlockXSize || nYSize != nBlockYSize)
memset(pImage, 0,
static_cast<size_t>(nBlockXSize) * nBlockYSize * nWordSize);
// By default we invoke just for the requested band, directly
// into the target buffer.
GDALRasterIOExtraArg sExtraArg;
INIT_RASTERIO_EXTRA_ARG(sExtraArg);
if (!poBaseDS->bUseYCC)
{
return poBaseDS->DirectRasterIO(GF_Read, nWXOff, nWYOff, nWXSize,
nWYSize, pImage, nXSize, nYSize,
eDataType, 1, &nBand, nWordSize,
nWordSize * nBlockXSize, 0, &sExtraArg);
}
// But for YCC or possible other effectively pixel interleaved
// products, we read all bands into a single buffer, fetch out
// what we want, and push the rest into the block cache.
std::vector<int> anBands;
for (int iBand = 0; iBand < poBaseDS->GetRasterCount(); iBand++)
{
GDALRasterBand *poBand = poBaseDS->GetRasterBand(iBand + 1);
if (poBand->GetRasterDataType() != eDataType)
continue;
anBands.push_back(iBand + 1);
}
GByte *pabyWrkBuffer = static_cast<GByte *>(
VSIMalloc3(nWordSize * anBands.size(), nBlockXSize, nBlockYSize));
if (pabyWrkBuffer == nullptr)
return CE_Failure;
const CPLErr eErr = poBaseDS->DirectRasterIO(
GF_Read, nWXOff, nWYOff, nWXSize, nWYSize, pabyWrkBuffer, nXSize,
nYSize, eDataType, static_cast<int>(anBands.size()), &anBands[0],
nWordSize, nWordSize * nBlockXSize,
static_cast<GSpacing>(nWordSize) * nBlockXSize * nBlockYSize,
&sExtraArg);
if (eErr == CE_None)
{
int nBandStart = 0;
const int nTotalBands = static_cast<int>(anBands.size());
for (int iBand = 0; iBand < nTotalBands; iBand++)
{
if (anBands[iBand] == nBand)
{
// Application requested band.
memcpy(pImage, pabyWrkBuffer + nBandStart,
static_cast<size_t>(nWordSize) * nBlockXSize *
nBlockYSize);
}
else
{
// All others are pushed into cache.
GDALRasterBand *poBaseBand =
poBaseDS->GetRasterBand(anBands[iBand]);
JP2KAKRasterBand *poBand =
cpl::down_cast<JP2KAKRasterBand *>(poBaseBand);
GDALRasterBlock *poBlock = nullptr;
if (poBand != nullptr)
poBlock =
poBand->GetLockedBlockRef(nBlockXOff, nBlockYOff, TRUE);
if (poBlock)
{
memcpy(poBlock->GetDataRef(), pabyWrkBuffer + nBandStart,
static_cast<size_t>(nWordSize) * nBlockXSize *
nBlockYSize);
poBlock->DropLock();
}
}
nBandStart +=
static_cast<size_t>(nWordSize) * nBlockXSize * nBlockYSize;
}
}
VSIFree(pabyWrkBuffer);
return eErr;
}
/************************************************************************/
/* IRasterIO() */
/************************************************************************/
CPLErr JP2KAKRasterBand::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)
{
// Try to pass the request to the most appropriate overview dataset.
if (nBufXSize < nXSize && nBufYSize < nYSize)
{
int bTried = FALSE;
const CPLErr eErr = TryOverviewRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
eBufType, nPixelSpace, nLineSpace, psExtraArg, &bTried);
if (bTried)
return eErr;
}
// We need various criteria to skip out to block based methods.
if (poBaseDS->TestUseBlockIO(nXSize, nYSize, nBufXSize, nBufYSize, eBufType,
1, &nBand))
return GDALPamRasterBand::IRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
eBufType, nPixelSpace, nLineSpace, psExtraArg);
return poBaseDS->DirectRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
eBufType, 1, &nBand, nPixelSpace, nLineSpace, 0, psExtraArg);
}
/************************************************************************/
/* ApplyPalette() */
/************************************************************************/
namespace
{
inline short GetColorValue(const float *pafLUT, int nPos)
{
const short nVal = static_cast<short>(pafLUT[nPos] * 256.0f + 128.0f);
const short nMin = 0;
const short nMax = 255;
return std::max(nMin, std::min(nMax, nVal));
}
} // namespace
void JP2KAKRasterBand::ApplyPalette(jp2_palette oJP2Palette)
{
// Do we have a reasonable LUT configuration? RGB or RGBA?
if (!oJP2Palette.exists())
return;
if (oJP2Palette.get_num_luts() == 0 || oJP2Palette.get_num_entries() == 0)
return;
if (oJP2Palette.get_num_luts() < 3)
{
CPLDebug("JP2KAK",
"JP2KAKRasterBand::ApplyPalette()\n"
"Odd get_num_luts() value (%d)",
oJP2Palette.get_num_luts());
return;
}
// Fetch lut entries. They are normalized in the -0.5 to 0.5 range. */
const int nCount = oJP2Palette.get_num_entries();
float *const pafLUT =
static_cast<float *>(CPLCalloc(sizeof(float) * 4, nCount));
const int nRed = 0;
const int nGreen = 1;
const int nBlue = 2;
const int nAlpha = 3;
oJP2Palette.get_lut(nRed, pafLUT + 0);
oJP2Palette.get_lut(nGreen, pafLUT + nCount);
oJP2Palette.get_lut(nBlue, pafLUT + nCount * 2);
if (oJP2Palette.get_num_luts() == 4)
{
oJP2Palette.get_lut(nAlpha, pafLUT + nCount * 3);
}
else
{
for (int iColor = 0; iColor < nCount; iColor++)
{
pafLUT[nCount * 3 + iColor] = 0.5;
}
}
// Apply to GDAL colortable.
const int nRedOffset = nCount * nRed;
const int nGreenOffset = nCount * nGreen;
const int nBlueOffset = nCount * nBlue;
const int nAlphaOffset = nCount * nAlpha;
for (int iColor = 0; iColor < nCount; iColor++)
{
const GDALColorEntry sEntry = {
GetColorValue(pafLUT, iColor + nRedOffset),
GetColorValue(pafLUT, iColor + nGreenOffset),
GetColorValue(pafLUT, iColor + nBlueOffset),
GetColorValue(pafLUT, iColor + nAlphaOffset)};
oCT.SetColorEntry(iColor, &sEntry);
}
CPLFree(pafLUT);
eInterp = GCI_PaletteIndex;
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp JP2KAKRasterBand::GetColorInterpretation()
{
return eInterp;
}
/************************************************************************/
/* GetColorTable() */
/************************************************************************/
GDALColorTable *JP2KAKRasterBand::GetColorTable()
{
if (oCT.GetColorEntryCount() > 0)
return &oCT;
return nullptr;
}
/************************************************************************/
/* ==================================================================== */
/* JP2KAKDataset */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* JP2KAKDataset() */
/************************************************************************/
JP2KAKDataset::JP2KAKDataset() = default;
/************************************************************************/
/* JP2KAKDataset() */
/************************************************************************/
// Constructor for overview dataset
JP2KAKDataset::JP2KAKDataset(JP2KAKDataset *poMainDS, int nDiscardLevels,
const kdu_dims &dimsIn)
: m_osFilename(poMainDS->m_osFilename), oCodeStream(poMainDS->oCodeStream),
poInput(poMainDS->poInput), poRawInput(poMainDS->poRawInput),
family(poMainDS->family), jpip_client(poMainDS->jpip_client),
dims(dimsIn), nResCount(poMainDS->nResCount),
bPreferNPReads(poMainDS->bPreferNPReads),
poThreadEnv(poMainDS->poThreadEnv), m_nDiscardLevels(nDiscardLevels),
bCached(poMainDS->bCached), bResilient(poMainDS->bResilient),
bFussy(poMainDS->bFussy), bUseYCC(poMainDS->bUseYCC),
bPromoteTo8Bit(poMainDS->bPromoteTo8Bit)
{
nRasterXSize = dims.size.x;
nRasterYSize = dims.size.y;
}
/************************************************************************/
/* ~JP2KAKDataset() */
/************************************************************************/
JP2KAKDataset::~JP2KAKDataset()
{
FlushCache(true);
if (m_nDiscardLevels == 0)
{
if (poInput != nullptr)
{
oCodeStream.destroy();
poInput->close();
delete poInput;
if (family)
{
family->close();
delete family;
}
if (poRawInput != nullptr)
delete poRawInput;
#ifdef USE_JPIP
if (jpip_client != NULL)
{
jpip_client->close();
delete jpip_client;
}
#endif
}
if (poThreadEnv != nullptr)
{
poThreadEnv->terminate(nullptr, true);
poThreadEnv->destroy();
delete poThreadEnv;
}
}
}
/************************************************************************/
/* IBuildOverviews() */
/************************************************************************/
CPLErr JP2KAKDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
const int *panOverviewList,
int nListBands, const int *panBandList,
GDALProgressFunc pfnProgress,
void *pProgressData,
CSLConstList papszOptions)
{
// In order for building external overviews to work properly, we
// discard any concept of internal overviews when the user
// first requests to build external overviews.
m_apoOverviews.clear();
return GDALPamDataset::IBuildOverviews(
pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
pfnProgress, pProgressData, papszOptions);
}
/************************************************************************/
/* KakaduInitialize() */
/************************************************************************/
void JP2KAKDataset::KakaduInitialize()
{
// Initialize Kakadu warning/error reporting subsystem.
if (kakadu_initialized)
return;
kakadu_initialized = true;
kdu_cpl_error_message oErrHandler(CE_Failure);
kdu_cpl_error_message oWarningHandler(CE_Warning);
CPL_IGNORE_RET_VAL(oErrHandler);
CPL_IGNORE_RET_VAL(oWarningHandler);
kdu_customize_warnings(new kdu_cpl_error_message(CE_Warning));
kdu_customize_errors(new kdu_cpl_error_message(CE_Failure));
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *JP2KAKDataset::Open(GDALOpenInfo *poOpenInfo)
{
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
// During fuzzing, do not use Identify to reject crazy content.
if (!JP2KAKDatasetIdentify(poOpenInfo))
return nullptr;
#endif
subfile_source *poRawInput = nullptr;
bool bIsJPIP = false;
bool bIsSubfile = false;
const GByte *pabyHeader = nullptr;
const bool bResilient =
CPLTestBool(CPLGetConfigOption("JP2KAK_RESILIENT", "NO"));
// Doesn't seem to bring any real performance gain on Linux.
const bool bBuffered = CPLTestBool(CPLGetConfigOption("JP2KAK_BUFFERED",
#ifdef _WIN32
"YES"
#else
"NO"
#endif
));
KakaduInitialize();
// Handle setting up datasource for JPIP.
const char *pszExtension = CPLGetExtension(poOpenInfo->pszFilename);
std::vector<GByte> abySubfileHeader(16); // leave in this scope
if (poOpenInfo->nHeaderBytes < 16)
{
if ((STARTS_WITH_CI(poOpenInfo->pszFilename, "http://") ||
STARTS_WITH_CI(poOpenInfo->pszFilename, "https://") ||
STARTS_WITH_CI(poOpenInfo->pszFilename, "jpip://")) &&
EQUAL(pszExtension, "jp2"))
{
bIsJPIP = true;
}
else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "J2K_SUBFILE:"))
{
try
{
poRawInput = new subfile_source;
poRawInput->open(poOpenInfo->pszFilename, bResilient,
bBuffered);
poRawInput->seek(0);
poRawInput->read(&abySubfileHeader[0], 16);
poRawInput->seek(0);
}
catch (...)
{
return nullptr;
}
pabyHeader = abySubfileHeader.data();
bIsSubfile = true;
}
else
{
return nullptr;
}
}
else
{
pabyHeader = poOpenInfo->pabyHeader;
}
// If we think this should be access via vsil, then open it using
// subfile_source. We do this if it does not seem to open normally
// or if we want to operate in resilient (sequential) mode.
VSIStatBuf sStat;
if (poRawInput == nullptr && !bIsJPIP &&
(bBuffered || bResilient ||
VSIStat(poOpenInfo->pszFilename, &sStat) != 0))
{
try
{
poRawInput = new subfile_source;
poRawInput->open(poOpenInfo->pszFilename, bResilient, bBuffered);
poRawInput->seek(0);
}
catch (...)
{
delete poRawInput;
return nullptr;
}
}
// If the header is a JP2 header, mark this as a JP2 dataset.
if (pabyHeader && memcmp(pabyHeader, jp2_header, sizeof(jp2_header)) == 0)
pszExtension = "jp2";
// Try to open the file in a manner depending on the extension.
kdu_compressed_source *poInput = nullptr;
kdu_client *jpip_client = nullptr;
jp2_palette oJP2Palette;
jp2_channels oJP2Channels;
jp2_family_src *family = nullptr;
try
{
if (bIsJPIP)
{
#ifdef USE_JPIP
char *pszWrk =
CPLStrdup(strstr(poOpenInfo->pszFilename, "://") + 3);
char *pszRequest = strstr(pszWrk, "/");
if (pszRequest == NULL)
{
CPLDebug("JP2KAK", "Failed to parse JPIP server and request.");
CPLFree(pszWrk);
return NULL;
}
*(pszRequest++) = '\0';
CPLDebug("JP2KAK", "server=%s, request=%s", pszWrk, pszRequest);
CPLSleep(15.0);
jpip_client = new kdu_client;
jpip_client->connect(pszWrk, NULL, pszRequest, "http-tcp", "");
CPLDebug("JP2KAK", "After connect()");
bool bin0_complete = false;
while (jpip_client->get_databin_length(KDU_META_DATABIN, 0, 0,
&bin0_complete) <= 0 ||
!bin0_complete)
CPLSleep(0.25);
family = new jp2_family_src;
family->open(jpip_client);
// TODO(schwehr): Check for memory leaks.
jp2_source *jp2_src = new jp2_source;
jp2_src->open(family);
jp2_src->read_header();
while (!jpip_client->is_idle())
CPLSleep(0.25);
if (jpip_client->is_alive())
{
CPLDebug("JP2KAK", "connect() seems to be complete.");
}
else
{
CPLDebug("JP2KAK", "connect() seems to have failed.");
return NULL;
}
oJP2Channels = jp2_src->access_channels();
poInput = jp2_src;
#else
CPLError(CE_Failure, CPLE_OpenFailed,
"JPIP Protocol not supported by GDAL with "
"Kakadu 3.4 or on Unix.");
return nullptr;
#endif
}
else if (pszExtension != nullptr &&
(EQUAL(pszExtension, "jp2") || EQUAL(pszExtension, "jpx")))
{
family = new jp2_family_src;
if (poRawInput != nullptr)
family->open(poRawInput);
else
family->open(poOpenInfo->pszFilename, true);
jp2_source *jp2_src = new jp2_source;
poInput = jp2_src;
if (!jp2_src->open(family) || !jp2_src->read_header())
{
CPLDebug("JP2KAK", "Cannot read JP2 boxes");
delete jp2_src;
delete family;
delete poRawInput;
return nullptr;
}
oJP2Palette = jp2_src->access_palette();
oJP2Channels = jp2_src->access_channels();
jp2_colour oColors = jp2_src->access_colour();
if (oColors.get_space() != JP2_sRGB_SPACE &&
oColors.get_space() != JP2_sLUM_SPACE)
{
CPLDebug("JP2KAK",
"Unusual ColorSpace=%d, not further interpreted.",
static_cast<int>(oColors.get_space()));
}
}
else if (poRawInput == nullptr)
{
poInput = new kdu_simple_file_source(poOpenInfo->pszFilename);
}
else
{
poInput = poRawInput;
poRawInput = nullptr;
}
}
catch (...)
{
CPLDebug("JP2KAK", "Trapped Kakadu exception.");
delete family;
delete poRawInput;
delete poInput;
return nullptr;
}
// Create a corresponding GDALDataset.
JP2KAKDataset *poDS = nullptr;
try
{
poDS = new JP2KAKDataset();
poDS->poInput = poInput;
poDS->poRawInput = poRawInput;
poDS->family = family;
poDS->oCodeStream.create(poInput);
poDS->oCodeStream.set_persistent();
poDS->bCached = bBuffered;
poDS->bResilient = bResilient;
poDS->bFussy = CPLTestBool(CPLGetConfigOption("JP2KAK_FUSSY", "NO"));
if (poDS->bFussy)
poDS->oCodeStream.set_fussy();
if (poDS->bResilient)
poDS->oCodeStream.set_resilient();
poDS->jpip_client = jpip_client;
// Get overall image size.
poDS->oCodeStream.get_dims(0, poDS->dims);
poDS->nRasterXSize = poDS->dims.size.x;
poDS->nRasterYSize = poDS->dims.size.y;
// Ensure that all the components have the same dimensions. If
// not, just process the first dimension.
auto l_nBands = poDS->oCodeStream.get_num_components();
if (l_nBands > 1)
{
for (int iDim = 1; iDim < l_nBands; iDim++)
{
kdu_dims dim_this_comp;
poDS->oCodeStream.get_dims(iDim, dim_this_comp);
if (dim_this_comp != poDS->dims)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Some components have mismatched dimensions, "
"ignoring all but first.");
l_nBands = 1;
break;
}
}
}
// Setup the thread environment.
int nNumThreads = atoi(CPLGetConfigOption("JP2KAK_THREADS", "-1"));
if (nNumThreads == -1)
nNumThreads = kdu_get_num_processors() - 1;
if (nNumThreads > 1024)
nNumThreads = 1024;
if (nNumThreads > 0)
{
poDS->poThreadEnv = new kdu_thread_env;
poDS->poThreadEnv->create();
for (int iThread = 0; iThread < nNumThreads; iThread++)
{
if (!poDS->poThreadEnv->add_thread())
{
CPLError(CE_Warning, CPLE_AppDefined,
"JP2KAK_THREADS: Unable to create thread.");
break;
}
}
CPLDebug("JP2KAK", "Using %d threads.", nNumThreads);
}
else
{
CPLDebug("JP2KAK", "Operating in singlethreaded mode.");
}
// Is this a file with poor internal navigation that will end
// up using a great deal of memory if we use keep persistent
// parsed information around? (#3295)
siz_params *siz = poDS->oCodeStream.access_siz();
kdu_params *cod = siz->access_cluster(COD_params);
bool use_precincts = false;
cod->get(Cuse_precincts, 0, 0, use_precincts);
const char *pszPersist = CPLGetConfigOption("JP2KAK_PERSIST", "AUTO");
if (EQUAL(pszPersist, "AUTO"))
{
if (!use_precincts && !bIsJPIP &&
(poDS->nRasterXSize * static_cast<double>(poDS->nRasterYSize)) >
100000000.0)
poDS->bPreferNPReads = true;
}
else
{
poDS->bPreferNPReads = !CPLTestBool(pszPersist);
}
CPLDebug("JP2KAK", "Cuse_precincts=%d, PreferNonPersistentReads=%d",
use_precincts ? 1 : 0, poDS->bPreferNPReads ? 1 : 0);
// Deduce some other info about the dataset.
int order = 0;
cod->get(Corder, 0, 0, order);
const char *pszOrder = nullptr;
switch (order)
{
case Corder_LRCP:
pszOrder = "LRCP";