src/raster/geotiff/geotiff_read.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "terraingen/raster/geotiff/geotiff.h" | ||
| 4 | |||
| 5 | #include "raster/geotiff/tiff_codecs.h" | ||
| 6 | #include "raster/geotiff/tiff_format.h" | ||
| 7 | |||
| 8 | #include "terraingen/util/bits.h" | ||
| 9 | #include "terraingen/util/log.h" | ||
| 10 | |||
| 11 | #include <algorithm> | ||
| 12 | #include <array> | ||
| 13 | #include <atomic> | ||
| 14 | #include <cstdlib> | ||
| 15 | #include <cstring> | ||
| 16 | #include <fstream> | ||
| 17 | #include <limits> | ||
| 18 | #include <map> | ||
| 19 | #include <mutex> | ||
| 20 | #include <stdexcept> | ||
| 21 | |||
| 22 | namespace terraingen { | ||
| 23 | |||
| 24 | namespace { | ||
| 25 | |||
| 26 | using namespace detail; | ||
| 27 | |||
| 28 | /// `value` with its bytes reversed. | ||
| 29 | 9167 | template <typename T> T ByteSwap(T value) { | |
| 30 | 9167 | std::array<std::uint8_t, sizeof(T)> bytes{}; | |
| 31 | 9167 | std::memcpy(bytes.data(), &value, sizeof(T)); | |
| 32 | 9167 | std::reverse(bytes.begin(), bytes.end()); | |
| 33 | 9167 | std::memcpy(&value, bytes.data(), sizeof(T)); | |
| 34 | 9167 | return value; | |
| 35 | } | ||
| 36 | |||
| 37 | /// The name of an unsupported compression code, for error messages. | ||
| 38 | 7 | std::string CompressionName(std::uint64_t code) { | |
| 39 | 7 | switch (code) { | |
| 40 | 1 | case 7: | |
| 41 | 1 | return "JPEG"; | |
| 42 | 1 | case 34887: | |
| 43 | 1 | return "LERC"; | |
| 44 | 1 | case 34925: | |
| 45 | 1 | return "LZMA"; | |
| 46 | 2 | case 50000: | |
| 47 | 2 | return "ZSTD"; | |
| 48 | 1 | case 50001: | |
| 49 | 1 | return "WebP"; | |
| 50 | 1 | default: | |
| 51 | 2 | return "code " + std::to_string(code); | |
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | /// Throws a `GeoTiffError` for `reason`, which the entry points prefix with the file's path | ||
| 56 | /// (`WithPath`). | ||
| 57 | 37 | [[noreturn]] void Fail(const std::string& reason) { | |
| 58 | 37 | throw GeoTiffError(reason); | |
| 59 | } | ||
| 60 | |||
| 61 | /// `read()`, its `GeoTiffError`s prefixed with `path` (`ThrowFileError`). | ||
| 62 | 1399 | template <typename Read> auto WithPath(const std::filesystem::path& path, const Read& read) { | |
| 63 | try { | ||
| 64 | 1399 | return read(); | |
| 65 | 41 | } catch (const GeoTiffError& error) { | |
| 66 | 76 | ThrowFileError(path, error.what()); | |
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 70 | /// Random access to a TIFF file in its byte order. | ||
| 71 | 27 | class TiffReader { | |
| 72 | public: | ||
| 73 | 830 | explicit TiffReader(const std::filesystem::path& path) : m_file(path, std::ios::binary) { | |
| 74 | 830 | if (!m_file) { | |
| 75 | 22 | Fail("cannot open the file"); | |
| 76 | } | ||
| 77 | 819 | m_file.seekg(0, std::ios::end); | |
| 78 | 819 | m_size = static_cast<std::uint64_t>(m_file.tellg()); | |
| 79 | 819 | ReadHeader(); | |
| 80 | 830 | } | |
| 81 | |||
| 82 | 7488 | void Read(std::uint64_t offset, void* destination, std::uint64_t count) { | |
| 83 | 7488 | RequireInFile(offset, count); | |
| 84 | 7487 | m_file.seekg(static_cast<std::streamoff>(offset)); | |
| 85 | 7487 | m_file.read(static_cast<char*>(destination), static_cast<std::streamsize>(count)); | |
| 86 | 7487 | if (!m_file) { | |
| 87 | ✗ | Fail("read error"); | |
| 88 | } | ||
| 89 | 7487 | } | |
| 90 | |||
| 91 | 5834 | std::vector<std::uint8_t> ReadBytes(std::uint64_t offset, std::uint64_t count) { | |
| 92 | 5834 | RequireInFile(offset, count); | |
| 93 | 5833 | std::vector<std::uint8_t> bytes(static_cast<std::size_t>(count)); | |
| 94 | 5833 | Read(offset, bytes.data(), count); | |
| 95 | 5833 | return bytes; | |
| 96 | } | ||
| 97 | |||
| 98 | /// The unsigned integer of type `T` at `p`, in the file's byte order. | ||
| 99 | 102575 | template <typename T> T Unsigned(const std::uint8_t* p) const { | |
| 100 | 102575 | T value = 0; | |
| 101 | 102575 | std::memcpy(&value, p, sizeof(T)); | |
| 102 | 89084 | return m_bigEndian ? ByteSwap(value) : value; | |
| 103 | } | ||
| 104 | |||
| 105 | 67985 | std::uint16_t U16(const std::uint8_t* p) const { | |
| 106 | 122479 | return Unsigned<std::uint16_t>(p); | |
| 107 | } | ||
| 108 | |||
| 109 | 23943 | std::uint32_t U32(const std::uint8_t* p) const { | |
| 110 | ✗ | return Unsigned<std::uint32_t>(p); | |
| 111 | } | ||
| 112 | |||
| 113 | 10647 | std::uint64_t U64(const std::uint8_t* p) const { | |
| 114 | 9973 | return Unsigned<std::uint64_t>(p); | |
| 115 | } | ||
| 116 | |||
| 117 | /// An unsigned value of `size` bytes, 2, 4 or 8. | ||
| 118 | 63967 | std::uint64_t Word(const std::uint8_t* p, std::size_t size) const { | |
| 119 | 63967 | switch (size) { | |
| 120 | 40166 | case 2: | |
| 121 | 45200 | return U16(p); | |
| 122 | 23147 | case 4: | |
| 123 | 24471 | return U32(p); | |
| 124 | 654 | default: | |
| 125 | 654 | return U64(p); | |
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | /// The entries of the first IFD. | ||
| 130 | 816 | std::map<std::uint16_t, IfdEntry> ReadFirstIfd() { | |
| 131 | 816 | const IfdFormat format = IfdLayout(m_bigTiff); | |
| 132 | 816 | std::array<std::uint8_t, 8> countBytes{}; | |
| 133 | 816 | Read(m_firstIfd, countBytes.data(), format.countSize); | |
| 134 | 816 | const std::uint64_t entries = Word(countBytes.data(), format.countSize); | |
| 135 | 816 | if (entries > 4096) { | |
| 136 | ✗ | Fail("implausible number of IFD entries"); | |
| 137 | } | ||
| 138 | 816 | const std::vector<std::uint8_t> table = | |
| 139 | 816 | ReadBytes(m_firstIfd + format.countSize, entries * format.EntrySize()); | |
| 140 | 816 | std::map<std::uint16_t, IfdEntry> result; | |
| 141 | 14307 | for (std::uint64_t i = 0; i < entries; ++i) { | |
| 142 | 13491 | const std::uint8_t* p = table.data() + i * format.EntrySize(); | |
| 143 | 13491 | const std::uint16_t tag = U16(p); | |
| 144 | 13491 | IfdEntry entry; | |
| 145 | 13491 | entry.type = U16(p + 2); | |
| 146 | 13491 | entry.count = Word(p + 4, format.wordSize); | |
| 147 | 13491 | const std::size_t fieldSize = FieldSize(entry.type); | |
| 148 | 13491 | if (fieldSize == 0) { | |
| 149 | ✗ | continue; | |
| 150 | } | ||
| 151 | 13491 | if (entry.count > m_size / fieldSize + 1) { | |
| 152 | ✗ | Fail("implausible count for tag " + std::to_string(tag)); | |
| 153 | } | ||
| 154 | 13491 | const std::uint8_t* value = p + format.ValueAt(); | |
| 155 | 13491 | const std::uint64_t bytes = entry.count * fieldSize; | |
| 156 | 13491 | if (bytes <= format.wordSize) { | |
| 157 | 9730 | entry.bytes.assign(value, value + bytes); | |
| 158 | } else { | ||
| 159 | 7522 | entry.bytes = ReadBytes(Word(value, format.wordSize), bytes); | |
| 160 | } | ||
| 161 | 13491 | result.emplace(tag, std::move(entry)); | |
| 162 | 13491 | } | |
| 163 | 816 | return result; | |
| 164 | 816 | } | |
| 165 | |||
| 166 | /// Unsigned integer values of an entry of any integer type. | ||
| 167 | 10023 | std::vector<std::uint64_t> Integers(const IfdEntry& entry) const { | |
| 168 | 10023 | std::vector<std::uint64_t> values(static_cast<std::size_t>(entry.count)); | |
| 169 | 10023 | const std::size_t size = FieldSize(entry.type); | |
| 170 | 55922 | for (std::size_t i = 0; i < values.size(); ++i) { | |
| 171 | 45899 | const std::uint8_t* p = entry.bytes.data() + i * size; | |
| 172 | 45899 | switch (entry.type) { | |
| 173 | ✗ | case kByte: | |
| 174 | ✗ | case kUndefined: | |
| 175 | ✗ | values[i] = p[0]; | |
| 176 | ✗ | break; | |
| 177 | 45899 | case kShort: | |
| 178 | 45899 | case kLong: | |
| 179 | 45899 | case kLong8: | |
| 180 | 45899 | case kIfd8: | |
| 181 | 45899 | values[i] = Word(p, size); | |
| 182 | 45899 | break; | |
| 183 | ✗ | default: | |
| 184 | ✗ | Fail("unexpected field type " + std::to_string(entry.type)); | |
| 185 | } | ||
| 186 | } | ||
| 187 | 10023 | return values; | |
| 188 | } | ||
| 189 | |||
| 190 | 1906 | std::vector<double> Doubles(const IfdEntry& entry) const { | |
| 191 | 1906 | if (entry.type != kDouble && entry.type != kFloat) { | |
| 192 | ✗ | Fail("expected floating-point values"); | |
| 193 | } | ||
| 194 | 1906 | std::vector<double> values(static_cast<std::size_t>(entry.count)); | |
| 195 | 11879 | for (std::size_t i = 0; i < values.size(); ++i) { | |
| 196 | 9973 | if (entry.type == kDouble) { | |
| 197 | 10874 | values[i] = BitCast<double>(U64(entry.bytes.data() + i * 8)); | |
| 198 | } else { | ||
| 199 | ✗ | values[i] = static_cast<double>(BitCast<float>(U32(entry.bytes.data() + i * 4))); | |
| 200 | } | ||
| 201 | } | ||
| 202 | 1906 | return values; | |
| 203 | } | ||
| 204 | |||
| 205 | 529 | static std::string Ascii(const IfdEntry& entry) { | |
| 206 | 529 | std::string text(entry.bytes.begin(), entry.bytes.end()); | |
| 207 | 1057 | while (!text.empty() && text.back() == '\0') { | |
| 208 | 528 | text.pop_back(); | |
| 209 | } | ||
| 210 | 529 | return text; | |
| 211 | } | ||
| 212 | |||
| 213 | 816 | bool BigEndian() const { | |
| 214 | 816 | return m_bigEndian; | |
| 215 | } | ||
| 216 | |||
| 217 | 816 | bool BigTiff() const { | |
| 218 | 816 | return m_bigTiff; | |
| 219 | } | ||
| 220 | |||
| 221 | private: | ||
| 222 | 13322 | void RequireInFile(std::uint64_t offset, std::uint64_t count) const { | |
| 223 | 13322 | if (offset > m_size || count > m_size - offset) { | |
| 224 | 2 | Fail("data lies past the end of the file"); | |
| 225 | } | ||
| 226 | 13320 | } | |
| 227 | |||
| 228 | 819 | void ReadHeader() { | |
| 229 | 819 | std::array<std::uint8_t, 16> header{}; | |
| 230 | 819 | Read(0, header.data(), 8); | |
| 231 | 818 | if (header[0] == 'I' && header[1] == 'I') { | |
| 232 | 764 | m_bigEndian = false; | |
| 233 | 54 | } else if (header[0] == 'M' && header[1] == 'M') { | |
| 234 | 53 | m_bigEndian = true; | |
| 235 | } else { | ||
| 236 | 2 | Fail("not a TIFF file"); | |
| 237 | } | ||
| 238 | 817 | const std::uint16_t version = U16(header.data() + 2); | |
| 239 | 817 | if (version == 42) { | |
| 240 | 849 | m_firstIfd = U32(header.data() + 4); | |
| 241 | 21 | } else if (version == 43) { | |
| 242 | 20 | m_bigTiff = true; | |
| 243 | 20 | Read(0, header.data(), 16); | |
| 244 | 20 | if (U16(header.data() + 4) != 8) { | |
| 245 | ✗ | Fail("unsupported BigTIFF offset size"); | |
| 246 | } | ||
| 247 | 20 | m_firstIfd = U64(header.data() + 8); | |
| 248 | } else { | ||
| 249 | 2 | Fail("unknown TIFF version " + std::to_string(version)); | |
| 250 | } | ||
| 251 | 816 | } | |
| 252 | |||
| 253 | std::ifstream m_file; | ||
| 254 | std::uint64_t m_size = 0; | ||
| 255 | std::uint64_t m_firstIfd = 0; | ||
| 256 | bool m_bigEndian = false; | ||
| 257 | bool m_bigTiff = false; | ||
| 258 | }; | ||
| 259 | |||
| 260 | /// The first IFD of a file and the reader to interpret it. | ||
| 261 | 18 | struct Ifd { | |
| 262 | TiffReader& reader; | ||
| 263 | std::map<std::uint16_t, IfdEntry> entries; | ||
| 264 | |||
| 265 | 19259 | const IfdEntry* Find(Tag tag) const { | |
| 266 | 19259 | const auto found = entries.find(tag); | |
| 267 | 19259 | return found == entries.end() ? nullptr : &found->second; | |
| 268 | } | ||
| 269 | |||
| 270 | /// The one value of `tag`, the same for every band, or `fallback` without the tag. | ||
| 271 | 7820 | std::uint64_t Single(Tag tag, std::uint64_t fallback) const { | |
| 272 | 7820 | const IfdEntry* entry = Find(tag); | |
| 273 | 7820 | if (entry == nullptr) { | |
| 274 | return fallback; | ||
| 275 | } | ||
| 276 | 7723 | const std::vector<std::uint64_t> values = reader.Integers(*entry); | |
| 277 | 7723 | if (values.empty()) { | |
| 278 | ✗ | Fail("tag " + std::to_string(tag) + " has no value"); | |
| 279 | } | ||
| 280 | 15658 | for (const std::uint64_t value : values) { | |
| 281 | 7935 | if (value != values.front()) { | |
| 282 | ✗ | Fail("bands with different values of tag " + std::to_string(tag) + | |
| 283 | " are not supported"); | ||
| 284 | } | ||
| 285 | } | ||
| 286 | 7723 | return values.front(); | |
| 287 | 7723 | } | |
| 288 | |||
| 289 | 2691 | std::uint64_t Required(Tag tag) const { | |
| 290 | 2691 | if (Find(tag) == nullptr) { | |
| 291 | 2 | Fail("missing required tag " + std::to_string(tag)); | |
| 292 | } | ||
| 293 | 2690 | return Single(tag, 0); | |
| 294 | } | ||
| 295 | }; | ||
| 296 | |||
| 297 | /// Everything needed to decode the image of the first IFD. | ||
| 298 | struct Layout { | ||
| 299 | GeoTiffInfo info; | ||
| 300 | bool planar = false; | ||
| 301 | std::size_t chunkWidth = 0; ///< Tile width, or the image width for strips. | ||
| 302 | std::size_t chunkHeight = 0; ///< Tile length, or rows per strip. | ||
| 303 | std::size_t across = 0; ///< Chunks per row of chunks. | ||
| 304 | std::size_t down = 0; ///< Rows of chunks. | ||
| 305 | std::vector<std::uint64_t> offsets; | ||
| 306 | std::vector<std::uint64_t> byteCounts; | ||
| 307 | |||
| 308 | /// Samples per pixel within one chunk: 1 for planar bands, otherwise every band. | ||
| 309 | 3765 | std::size_t SamplesInChunk() const { | |
| 310 | 3684 | return planar ? 1 : info.bands; | |
| 311 | } | ||
| 312 | }; | ||
| 313 | |||
| 314 | /// The bytes of one sample. | ||
| 315 | 2511 | std::size_t SampleBytes(const GeoTiffInfo& info) { | |
| 316 | 2511 | return static_cast<std::size_t>(info.bitsPerSample) / 8; | |
| 317 | } | ||
| 318 | |||
| 319 | 816 | void ImageSize(const Ifd& ifd, GeoTiffInfo& info) { | |
| 320 | 816 | info.grid.width = static_cast<std::size_t>(ifd.Required(kImageWidth)); | |
| 321 | 815 | info.grid.height = static_cast<std::size_t>(ifd.Required(kImageLength)); | |
| 322 | 815 | if (info.grid.width == 0 || info.grid.height == 0 || info.grid.width > (1u << 30) || | |
| 323 | info.grid.height > (1u << 30)) { | ||
| 324 | 1 | Fail("implausible image size"); | |
| 325 | } | ||
| 326 | 814 | } | |
| 327 | |||
| 328 | 814 | void ParseSampleFormat(const Ifd& ifd, GeoTiffInfo& info) { | |
| 329 | 814 | info.bitsPerSample = static_cast<int>(ifd.Single(kBitsPerSample, 1)); | |
| 330 | 814 | if (info.bitsPerSample != 8 && info.bitsPerSample != 16 && info.bitsPerSample != 32 && | |
| 331 | info.bitsPerSample != 64) { | ||
| 332 | 4 | Fail(std::to_string(info.bitsPerSample) + "-bit samples are not supported"); | |
| 333 | } | ||
| 334 | 813 | switch (ifd.Single(kSampleFormat, 1)) { | |
| 335 | 81 | case 1: | |
| 336 | 81 | info.sampleFormat = TiffSampleFormat::UnsignedInteger; | |
| 337 | 81 | break; | |
| 338 | 94 | case 2: | |
| 339 | 94 | info.sampleFormat = TiffSampleFormat::SignedInteger; | |
| 340 | 94 | break; | |
| 341 | 637 | case 3: | |
| 342 | 637 | info.sampleFormat = TiffSampleFormat::Float; | |
| 343 | 637 | if (info.bitsPerSample != 32 && info.bitsPerSample != 64) { | |
| 344 | 4 | Fail(std::to_string(info.bitsPerSample) + "-bit floats are not supported"); | |
| 345 | } | ||
| 346 | break; | ||
| 347 | 1 | default: | |
| 348 | 1 | Fail("unsupported sample format (complex or undefined)"); | |
| 349 | } | ||
| 350 | 811 | } | |
| 351 | |||
| 352 | 811 | void ParseCompression(const Ifd& ifd, GeoTiffInfo& info) { | |
| 353 | 811 | const std::uint64_t code = ifd.Single(kCompression, kCompressionNone); | |
| 354 | 811 | const std::optional<TiffCompression> compression = CompressionFromCode(code); | |
| 355 | 811 | if (!compression) { | |
| 356 | 21 | Fail(CompressionName(code) + " compression is not supported; convert with " | |
| 357 | "gdal_translate -co COMPRESS=DEFLATE"); | ||
| 358 | } | ||
| 359 | 804 | info.compression = *compression; | |
| 360 | 804 | } | |
| 361 | |||
| 362 | 804 | void ParsePredictor(const Ifd& ifd, GeoTiffInfo& info) { | |
| 363 | 804 | info.predictor = static_cast<int>(ifd.Single(kPredictor, 1)); | |
| 364 | 804 | if (info.predictor < 1 || info.predictor > 3) { | |
| 365 | 3 | Fail("unknown predictor " + std::to_string(info.predictor)); | |
| 366 | } | ||
| 367 | 803 | if (info.predictor == 3 && info.sampleFormat != TiffSampleFormat::Float) { | |
| 368 | 1 | Fail("the floating-point predictor needs float samples"); | |
| 369 | } | ||
| 370 | 802 | } | |
| 371 | |||
| 372 | /// Reads the tile or strip sizes, counts, offsets and byte counts into `layout`. | ||
| 373 | 802 | void ReadChunks(const Ifd& ifd, Layout& layout) { | |
| 374 | 802 | const GeoTiffInfo& info = layout.info; | |
| 375 | 802 | Tag offsetsTag = kStripOffsets; | |
| 376 | 802 | Tag countsTag = kStripByteCounts; | |
| 377 | 802 | if (info.tiled) { | |
| 378 | 530 | layout.chunkWidth = static_cast<std::size_t>(ifd.Required(kTileWidth)); | |
| 379 | 530 | layout.chunkHeight = static_cast<std::size_t>(ifd.Required(kTileLength)); | |
| 380 | 530 | offsetsTag = kTileOffsets; | |
| 381 | 530 | countsTag = kTileByteCounts; | |
| 382 | } else { | ||
| 383 | 272 | layout.chunkWidth = info.grid.width; | |
| 384 | 544 | layout.chunkHeight = static_cast<std::size_t>( | |
| 385 | 272 | std::min<std::uint64_t>(ifd.Single(kRowsPerStrip, info.grid.height), info.grid.height)); | |
| 386 | } | ||
| 387 | 802 | const IfdEntry* offsets = ifd.Find(offsetsTag); | |
| 388 | 802 | const IfdEntry* counts = ifd.Find(countsTag); | |
| 389 | 802 | if (offsets == nullptr || counts == nullptr) { | |
| 390 | 13 | Fail(std::string("missing ") + (info.tiled ? "tile" : "strip") + " offsets or byte counts"); | |
| 391 | } | ||
| 392 | 800 | layout.offsets = ifd.reader.Integers(*offsets); | |
| 393 | 800 | layout.byteCounts = ifd.reader.Integers(*counts); | |
| 394 | 800 | if (layout.chunkWidth == 0 || layout.chunkHeight == 0) { | |
| 395 | 2 | Fail("zero tile or strip size"); | |
| 396 | } | ||
| 397 | 799 | layout.across = CeilDiv(info.grid.width, layout.chunkWidth); | |
| 398 | 799 | layout.down = CeilDiv(info.grid.height, layout.chunkHeight); | |
| 399 | 799 | const std::size_t chunks = layout.across * layout.down * (layout.planar ? info.bands : 1); | |
| 400 | 799 | if (layout.offsets.size() < chunks || layout.byteCounts.size() < chunks) { | |
| 401 | 1 | Fail("fewer tile or strip offsets than the image needs"); | |
| 402 | } | ||
| 403 | 798 | } | |
| 404 | |||
| 405 | 798 | GeoKeys ReadGeoKeys(const Ifd& ifd) { | |
| 406 | 798 | GeoKeys keys; | |
| 407 | 798 | if (const IfdEntry* directory = ifd.Find(kGeoKeyDirectory)) { | |
| 408 | 33636 | for (const std::uint64_t value : ifd.reader.Integers(*directory)) { | |
| 409 | 32936 | keys.directory.push_back(static_cast<std::uint16_t>(value)); | |
| 410 | 700 | } | |
| 411 | } | ||
| 412 | 798 | if (const IfdEntry* doubles = ifd.Find(kGeoDoubleParams)) { | |
| 413 | 359 | keys.doubleParams = ifd.reader.Doubles(*doubles); | |
| 414 | } | ||
| 415 | 798 | if (const IfdEntry* ascii = ifd.Find(kGeoAsciiParams)) { | |
| 416 | 342 | keys.asciiParams = TiffReader::Ascii(*ascii); | |
| 417 | } | ||
| 418 | 798 | return keys; | |
| 419 | } | ||
| 420 | |||
| 421 | /// The model tags the transform is read from: ModelTransformation when there is one, otherwise | ||
| 422 | /// ModelPixelScale and ModelTiepoint when there are both. | ||
| 423 | 798 | ModelTags ReadModelTags(const Ifd& ifd) { | |
| 424 | 798 | ModelTags tags; | |
| 425 | 798 | if (const IfdEntry* matrix = ifd.Find(kModelTransformation)) { | |
| 426 | 21 | tags.transformation = ifd.reader.Doubles(*matrix); | |
| 427 | 21 | return tags; | |
| 428 | } | ||
| 429 | 777 | const IfdEntry* scale = ifd.Find(kModelPixelScale); | |
| 430 | 777 | const IfdEntry* tiepoint = ifd.Find(kModelTiepoint); | |
| 431 | 777 | if (scale != nullptr && tiepoint != nullptr) { | |
| 432 | 763 | tags.pixelScale = ifd.reader.Doubles(*scale); | |
| 433 | 763 | tags.tiepoint = ifd.reader.Doubles(*tiepoint); | |
| 434 | } | ||
| 435 | return tags; | ||
| 436 | } | ||
| 437 | |||
| 438 | /// Sets the pixel-to-world transform of the model tags, and whether there were any. | ||
| 439 | 798 | void ReadTransform(const Ifd& ifd, GeoTiffInfo& info) { | |
| 440 | 798 | const std::optional<GeoTransform> transform = | |
| 441 | 798 | DecodeTransform(ReadModelTags(ifd), info.geoKeys.PixelIsPoint()); | |
| 442 | 798 | info.georeferenced = transform.has_value(); | |
| 443 | 798 | info.grid.transform = transform.value_or(GeoTransform{}); | |
| 444 | 798 | } | |
| 445 | |||
| 446 | 798 | std::optional<double> ParseNoData(const Ifd& ifd) { | |
| 447 | 798 | const IfdEntry* noData = ifd.Find(kGdalNoData); | |
| 448 | 798 | if (noData == nullptr) { | |
| 449 | 652 | return std::nullopt; | |
| 450 | } | ||
| 451 | 146 | const std::string text = TiffReader::Ascii(*noData); | |
| 452 | 146 | char* end = nullptr; | |
| 453 | 146 | const double value = std::strtod(text.c_str(), &end); | |
| 454 | 146 | return end != text.c_str() ? std::optional<double>(value) : std::nullopt; | |
| 455 | 146 | } | |
| 456 | |||
| 457 | 816 | Layout ReadLayout(TiffReader& reader) { | |
| 458 | 816 | const Ifd ifd{reader, reader.ReadFirstIfd()}; | |
| 459 | 816 | Layout layout; | |
| 460 | 816 | GeoTiffInfo& info = layout.info; | |
| 461 | 816 | info.bigEndian = reader.BigEndian(); | |
| 462 | 816 | info.bigTiff = reader.BigTiff(); | |
| 463 | 816 | ImageSize(ifd, info); | |
| 464 | 814 | info.bands = static_cast<std::size_t>(ifd.Single(kSamplesPerPixel, 1)); | |
| 465 | 814 | ParseSampleFormat(ifd, info); | |
| 466 | 811 | ParseCompression(ifd, info); | |
| 467 | 804 | ParsePredictor(ifd, info); | |
| 468 | 802 | layout.planar = ifd.Single(kPlanarConfiguration, 1) == 2; | |
| 469 | 802 | info.tiled = ifd.Find(kTileWidth) != nullptr; | |
| 470 | 802 | ReadChunks(ifd, layout); | |
| 471 | 798 | info.geoKeys = ReadGeoKeys(ifd); | |
| 472 | 798 | ReadTransform(ifd, info); | |
| 473 | 798 | const IfdEntry* metadata = ifd.Find(kGdalMetadata); | |
| 474 | 1596 | info.bandScaling = detail::ParseGdalBandScaling( | |
| 475 | 1596 | metadata != nullptr ? TiffReader::Ascii(*metadata) : std::string(), info.bands); | |
| 476 | 798 | info.noData = ParseNoData(ifd); | |
| 477 | 798 | return layout; | |
| 478 | 816 | } | |
| 479 | |||
| 480 | /// Adds each sample of a row to the one `stride` samples before it (horizontal predictor). | ||
| 481 | template <typename T> | ||
| 482 | 1368 | void AccumulateRow(std::uint8_t* p, std::size_t rowSamples, std::size_t stride) { | |
| 483 | 37848 | for (std::size_t i = stride; i < rowSamples; ++i) { | |
| 484 | T current = 0; | ||
| 485 | T previous = 0; | ||
| 486 | 36480 | std::memcpy(¤t, p + i * sizeof(T), sizeof(T)); | |
| 487 | 36480 | std::memcpy(&previous, p + (i - stride) * sizeof(T), sizeof(T)); | |
| 488 | 36480 | current = static_cast<T>(current + previous); | |
| 489 | 36480 | std::memcpy(p + i * sizeof(T), ¤t, sizeof(T)); | |
| 490 | } | ||
| 491 | 1368 | } | |
| 492 | |||
| 493 | 1368 | void UndoHorizontalPredictor(std::uint8_t* p, std::size_t sampleBytes, std::size_t rowSamples, | |
| 494 | std::size_t stride) { | ||
| 495 | 1368 | switch (sampleBytes) { | |
| 496 | ✗ | case 1: | |
| 497 | ✗ | AccumulateRow<std::uint8_t>(p, rowSamples, stride); | |
| 498 | ✗ | break; | |
| 499 | 912 | case 2: | |
| 500 | 912 | AccumulateRow<std::uint16_t>(p, rowSamples, stride); | |
| 501 | 912 | break; | |
| 502 | 456 | case 4: | |
| 503 | 456 | AccumulateRow<std::uint32_t>(p, rowSamples, stride); | |
| 504 | 456 | break; | |
| 505 | ✗ | default: | |
| 506 | ✗ | AccumulateRow<std::uint64_t>(p, rowSamples, stride); | |
| 507 | ✗ | break; | |
| 508 | } | ||
| 509 | 1368 | } | |
| 510 | |||
| 511 | /// Reverses a chunk's predictor in place; `bytes` holds `rows` rows of `rowSamples` samples. | ||
| 512 | 1255 | void UndoPredictor(std::vector<std::uint8_t>& bytes, const GeoTiffInfo& info, std::size_t rows, | |
| 513 | std::size_t rowSamples, std::size_t stride) { | ||
| 514 | 1255 | const std::size_t sampleBytes = SampleBytes(info); | |
| 515 | 1255 | if (info.predictor == 3) { | |
| 516 | 885 | DecodeFloatPredictor(bytes.data(), rows, sampleBytes, rowSamples, stride); | |
| 517 | 885 | return; | |
| 518 | } | ||
| 519 | 370 | if (info.predictor != 2) { | |
| 520 | return; | ||
| 521 | } | ||
| 522 | 1440 | for (std::size_t row = 0; row < rows; ++row) { | |
| 523 | 1368 | UndoHorizontalPredictor(bytes.data() + row * rowSamples * sampleBytes, sampleBytes, | |
| 524 | rowSamples, stride); | ||
| 525 | } | ||
| 526 | } | ||
| 527 | |||
| 528 | /// Swaps each sample of `bytes` from big- to little-endian. | ||
| 529 | 63 | void SwapSamples(std::vector<std::uint8_t>& bytes, std::size_t sampleBytes) { | |
| 530 | 63 | if (sampleBytes == 1) { | |
| 531 | return; | ||
| 532 | } | ||
| 533 | 19623 | for (std::size_t i = 0; i + sampleBytes <= bytes.size(); i += sampleBytes) { | |
| 534 | 19560 | std::reverse(bytes.begin() + static_cast<std::ptrdiff_t>(i), | |
| 535 | 19560 | bytes.begin() + static_cast<std::ptrdiff_t>(i + sampleBytes)); | |
| 536 | } | ||
| 537 | } | ||
| 538 | |||
| 539 | /// Calls `visit(T{})` with `T` the type the samples of `info` are stored as. | ||
| 540 | 1255 | template <typename Visit> void VisitSampleType(const GeoTiffInfo& info, const Visit& visit) { | |
| 541 | 1255 | const int bits = info.bitsPerSample; | |
| 542 | 1255 | switch (info.sampleFormat) { | |
| 543 | 1078 | case TiffSampleFormat::Float: | |
| 544 | 1078 | return bits == 32 ? visit(float{}) : visit(double{}); | |
| 545 | 77 | case TiffSampleFormat::SignedInteger: | |
| 546 | 77 | return bits == 8 ? visit(std::int8_t{}) | |
| 547 | 65 | : bits == 16 ? visit(std::int16_t{}) | |
| 548 | 24 | : bits == 32 ? visit(std::int32_t{}) | |
| 549 | 12 | : visit(std::int64_t{}); | |
| 550 | 100 | default: | |
| 551 | 100 | return bits == 8 ? visit(std::uint8_t{}) | |
| 552 | 88 | : bits == 16 ? visit(std::uint16_t{}) | |
| 553 | 39 | : bits == 32 ? visit(std::uint32_t{}) | |
| 554 | ✗ | : visit(std::uint64_t{}); | |
| 555 | } | ||
| 556 | } | ||
| 557 | |||
| 558 | /// The bytes stored for chunk `chunk`, none for a chunk without any. | ||
| 559 | 1257 | std::vector<std::uint8_t> StoredBytes(TiffReader& reader, const Layout& layout, std::size_t chunk) { | |
| 560 | 1257 | const std::uint64_t stored = layout.byteCounts[chunk]; | |
| 561 | 1257 | return stored == 0 ? std::vector<std::uint8_t>() | |
| 562 | 1257 | : reader.ReadBytes(layout.offsets[chunk], stored); | |
| 563 | } | ||
| 564 | |||
| 565 | /// The bytes `raw` stored for chunk `chunk` decompressed, or zeros for a chunk with none. | ||
| 566 | 1256 | std::vector<std::uint8_t> Decompress(const Layout& layout, std::size_t chunk, | |
| 567 | std::vector<std::uint8_t> raw, std::size_t expected) { | ||
| 568 | 1256 | if (layout.byteCounts[chunk] == 0) { | |
| 569 | ✗ | return std::vector<std::uint8_t>(expected, 0); | |
| 570 | } | ||
| 571 | 1256 | switch (layout.info.compression) { | |
| 572 | 625 | case TiffCompression::Lzw: | |
| 573 | 625 | return DecodeLzw(raw, expected); | |
| 574 | 12 | case TiffCompression::PackBits: | |
| 575 | 12 | return DecodePackBits(raw, expected); | |
| 576 | 425 | case TiffCompression::Deflate: | |
| 577 | 425 | return DecodeDeflate(raw, expected); | |
| 578 | 194 | default: | |
| 579 | 194 | break; | |
| 580 | } | ||
| 581 | 194 | if (raw.size() < expected) { | |
| 582 | ✗ | Fail("truncated uncompressed chunk"); | |
| 583 | } | ||
| 584 | 194 | raw.resize(expected); | |
| 585 | 194 | return raw; | |
| 586 | } | ||
| 587 | |||
| 588 | std::atomic<std::size_t> decodedChunks{0}; | ||
| 589 | |||
| 590 | /// Chunk `chunk`, holding `rows` rows and stored as `raw`, as little-endian samples without a | ||
| 591 | /// predictor. | ||
| 592 | 1256 | std::vector<std::uint8_t> DecodeChunk(const Layout& layout, std::size_t chunk, | |
| 593 | std::vector<std::uint8_t> raw, std::size_t rows) { | ||
| 594 | 1256 | ++decodedChunks; | |
| 595 | 1256 | const GeoTiffInfo& info = layout.info; | |
| 596 | 1256 | const std::size_t sampleBytes = SampleBytes(info); | |
| 597 | 1256 | const std::size_t rowSamples = layout.chunkWidth * layout.SamplesInChunk(); | |
| 598 | 1256 | std::vector<std::uint8_t> bytes = | |
| 599 | 1256 | Decompress(layout, chunk, std::move(raw), rows * rowSamples * sampleBytes); | |
| 600 | 1254 | if (info.bigEndian && info.predictor != 3) { | |
| 601 | 63 | SwapSamples(bytes, sampleBytes); | |
| 602 | } | ||
| 603 | 2481 | UndoPredictor(bytes, info, rows, rowSamples, layout.SamplesInChunk()); | |
| 604 | 1255 | return bytes; | |
| 605 | } | ||
| 606 | |||
| 607 | /// Copies sample `sampleIndex`, stored as `T`, of the image's cells `cells` in the decoded chunk | ||
| 608 | /// at column `cx` and row `cy` of chunks into `raster`, which holds the cells of `window`. | ||
| 609 | template <typename T> | ||
| 610 | 1255 | void CopySamples(const std::vector<std::uint8_t>& bytes, const Layout& layout, std::size_t cx, | |
| 611 | std::size_t cy, std::size_t sampleIndex, const PixelWindow& cells, | ||
| 612 | const PixelWindow& window, Raster<float>& raster) { | ||
| 613 | 1255 | const std::size_t samplesInChunk = layout.SamplesInChunk(); | |
| 614 | 1255 | const std::size_t rowBytes = layout.chunkWidth * samplesInChunk * sizeof(T); | |
| 615 | 1255 | const std::size_t x0 = cx * layout.chunkWidth; | |
| 616 | 1255 | const std::size_t y0 = cy * layout.chunkHeight; | |
| 617 | 18438 | for (std::size_t y = cells.rowBegin; y < cells.rowEnd; ++y) { | |
| 618 | 17183 | const std::uint8_t* row = bytes.data() + (y - y0) * rowBytes; | |
| 619 | 360798 | for (std::size_t x = cells.colBegin; x < cells.colEnd; ++x) { | |
| 620 | T value{}; | ||
| 621 | 343615 | std::memcpy(&value, row + ((x - x0) * samplesInChunk + sampleIndex) * sizeof(T), | |
| 622 | sizeof(T)); | ||
| 623 | 343615 | raster(x - window.colBegin, y - window.rowBegin) = static_cast<float>(value); | |
| 624 | } | ||
| 625 | } | ||
| 626 | 1255 | } | |
| 627 | |||
| 628 | 473 | void RequireBand(const GeoTiffInfo& info, std::size_t band) { | |
| 629 | 473 | if (band >= info.bands) { | |
| 630 | 24 | Fail("band " + std::to_string(band) + " requested of " + std::to_string(info.bands)); | |
| 631 | } | ||
| 632 | 469 | } | |
| 633 | |||
| 634 | /// The rows chunk row `cy` holds: whole tiles, or a last strip cut at the image. | ||
| 635 | 1256 | std::size_t ChunkRows(const Layout& layout, std::size_t cy) { | |
| 636 | 1256 | return layout.info.tiled | |
| 637 | 1256 | ? layout.chunkHeight | |
| 638 | 236 | : std::min(layout.chunkHeight, layout.info.grid.height - cy * layout.chunkHeight); | |
| 639 | } | ||
| 640 | |||
| 641 | /// The index of the chunk at column `cx` and row `cy` of chunks holding band `band`. | ||
| 642 | 1254 | std::size_t ChunkIndex(const Layout& layout, std::size_t band, std::size_t cx, std::size_t cy) { | |
| 643 | 1254 | const std::size_t planeOffset = layout.planar ? band * layout.across * layout.down : 0; | |
| 644 | 1254 | return planeOffset + cy * layout.across + cx; | |
| 645 | } | ||
| 646 | |||
| 647 | /// Where band `band` lies among a chunk's samples. | ||
| 648 | 1255 | std::size_t SampleIndex(const Layout& layout, std::size_t band) { | |
| 649 | 1255 | return layout.planar ? 0 : band; | |
| 650 | } | ||
| 651 | |||
| 652 | /// A raster over the image's cells `cells`, with their transform and the file's no-data value. | ||
| 653 | 902 | Raster<float> WindowRaster(const GeoTiffInfo& info, const PixelWindow& cells) { | |
| 654 | 902 | Raster<float> raster(Subgrid(info.grid, cells)); | |
| 655 | 902 | if (info.noData) { | |
| 656 | 223 | raster.SetNoData(static_cast<float>(*info.noData)); | |
| 657 | } | ||
| 658 | 902 | return raster; | |
| 659 | } | ||
| 660 | |||
| 661 | /// Reads and decodes the chunk at column `cx` and row `cy` of chunks holding band `band`, and | ||
| 662 | /// copies its cells `cells` into `raster`, which holds the cells of `window`; `file` is held while | ||
| 663 | /// the stored bytes are read. | ||
| 664 | 1254 | void ReadChunkInto(TiffReader& reader, const Layout& layout, std::size_t band, std::size_t cx, | |
| 665 | std::size_t cy, const PixelWindow& cells, const PixelWindow& window, | ||
| 666 | Raster<float>& raster, std::mutex& file) { | ||
| 667 | 1254 | const std::size_t chunk = ChunkIndex(layout, band, cx, cy); | |
| 668 | 1254 | std::vector<std::uint8_t> raw; | |
| 669 | 1254 | { | |
| 670 | 1254 | const std::lock_guard<std::mutex> lock(file); | |
| 671 | 2513 | raw = StoredBytes(reader, layout, chunk); | |
| 672 | 1 | } | |
| 673 | 1256 | const std::vector<std::uint8_t> bytes = | |
| 674 | 1256 | DecodeChunk(layout, chunk, std::move(raw), ChunkRows(layout, cy)); | |
| 675 | 1255 | VisitSampleType(layout.info, [&](auto type) { | |
| 676 | 1255 | CopySamples<decltype(type)>(bytes, layout, cx, cy, SampleIndex(layout, band), cells, window, | |
| 677 | raster); | ||
| 678 | 1255 | }); | |
| 679 | 1257 | } | |
| 680 | |||
| 681 | } // namespace | ||
| 682 | |||
| 683 | 74 | std::size_t detail::DecodedChunkCount() { | |
| 684 | 74 | return decodedChunks; | |
| 685 | } | ||
| 686 | |||
| 687 | struct GeoTiffBlockReader::State { | ||
| 688 | std::filesystem::path path; | ||
| 689 | TiffReader reader; | ||
| 690 | Layout layout; | ||
| 691 | std::size_t band = 0; | ||
| 692 | std::mutex file; ///< Guards the reader's file position. | ||
| 693 | }; | ||
| 694 | |||
| 695 | 135 | GeoTiffBlockReader::GeoTiffBlockReader(const std::filesystem::path& path, std::size_t band) | |
| 696 | 135 | : m_state(WithPath(path, [&] { | |
| 697 | 135 | TiffReader reader(path); | |
| 698 | 134 | Layout layout = ReadLayout(reader); | |
| 699 | 134 | RequireBand(layout.info, band); | |
| 700 | 133 | return std::unique_ptr<State>( | |
| 701 | 133 | new State{path, std::move(reader), std::move(layout), band, {}}); | |
| 702 | 134 | })) {} | |
| 703 | |||
| 704 | 133 | GeoTiffBlockReader::~GeoTiffBlockReader() = default; | |
| 705 | |||
| 706 | 26 | const GeoTiffInfo& GeoTiffBlockReader::Info() const { | |
| 707 | 26 | return m_state->layout.info; | |
| 708 | } | ||
| 709 | |||
| 710 | 362922 | std::size_t GeoTiffBlockReader::BlockWidth() const { | |
| 711 | 362922 | return m_state->layout.chunkWidth; | |
| 712 | } | ||
| 713 | |||
| 714 | 362817 | std::size_t GeoTiffBlockReader::BlockHeight() const { | |
| 715 | 362817 | return m_state->layout.chunkHeight; | |
| 716 | } | ||
| 717 | |||
| 718 | 571 | Raster<float> GeoTiffBlockReader::ReadBlock(std::size_t col, std::size_t row) const { | |
| 719 | 571 | State& state = *m_state; | |
| 720 | 571 | const Layout& layout = state.layout; | |
| 721 | 571 | const GeoTiffInfo& info = layout.info; | |
| 722 | 571 | if (col >= layout.across || row >= layout.down) { | |
| 723 | 6 | throw std::invalid_argument("Block (" + std::to_string(col) + ", " + std::to_string(row) + | |
| 724 | 10 | ") is beyond the " + std::to_string(layout.across) + " x " + | |
| 725 | 8 | std::to_string(layout.down) + " blocks of the image"); | |
| 726 | } | ||
| 727 | 569 | const PixelWindow cells = TileWindow(col, row, layout.chunkWidth, layout.chunkHeight, | |
| 728 | 569 | {0, info.grid.width, 0, info.grid.height}); | |
| 729 | 569 | Raster<float> block = WindowRaster(info, cells); | |
| 730 | 563 | WithPath(state.path, [&] { | |
| 731 | 569 | ReadChunkInto(state.reader, layout, state.band, col, row, cells, cells, block, state.file); | |
| 732 | 567 | }); | |
| 733 | 566 | return block; | |
| 734 | } | ||
| 735 | |||
| 736 | 332 | GeoTiffInfo ReadGeoTiffInfo(const std::filesystem::path& path) { | |
| 737 | 989 | return WithPath(path, [&] { | |
| 738 | 332 | TiffReader reader(path); | |
| 739 | 325 | return ReadLayout(reader).info; | |
| 740 | 657 | }); | |
| 741 | } | ||
| 742 | |||
| 743 | 143 | GeoTiff ReadGeoTiff(const std::filesystem::path& path, std::size_t band) { | |
| 744 | 143 | return ReadGeoTiffWindow( | |
| 745 | path, band, | ||
| 746 | 143 | {0, std::numeric_limits<std::size_t>::max(), 0, std::numeric_limits<std::size_t>::max()}); | |
| 747 | } | ||
| 748 | |||
| 749 | 363 | GeoTiff ReadGeoTiffWindow(const std::filesystem::path& path, std::size_t band, | |
| 750 | const PixelWindow& window) { | ||
| 751 | 363 | const Stopwatch stopwatch; | |
| 752 | 1057 | GeoTiff result = WithPath(path, [&] { | |
| 753 | 363 | TiffReader reader(path); | |
| 754 | 357 | const Layout layout = ReadLayout(reader); | |
| 755 | 339 | const GeoTiffInfo& info = layout.info; | |
| 756 | 339 | RequireBand(info, band); | |
| 757 | 672 | const PixelWindow cells{window.colBegin, std::min(window.colEnd, info.grid.width), | |
| 758 | 481 | window.rowBegin, std::min(window.rowEnd, info.grid.height)}; | |
| 759 | 336 | if (cells.Empty()) { | |
| 760 | 9 | throw std::invalid_argument(path.string() + ": the window to read misses the image"); | |
| 761 | } | ||
| 762 | 333 | GeoTiff read{WindowRaster(info, cells), info.geoKeys}; | |
| 763 | 333 | std::mutex file; | |
| 764 | 333 | ForEachTileIn(cells, layout.chunkWidth, layout.chunkHeight, | |
| 765 | 333 | [&](std::size_t cx, std::size_t cy, const PixelWindow& chunkCells) { | |
| 766 | 688 | ReadChunkInto(reader, layout, band, cx, cy, chunkCells, cells, | |
| 767 | 688 | read.raster, file); | |
| 768 | 686 | }); | |
| 769 | 662 | return read; | |
| 770 | 702 | }); | |
| 771 | 331 | LogInfo("raster", "Read ", result.raster.Width(), "x", result.raster.Height(), " GeoTIFF ", | |
| 772 | 993 | path.string(), " in ", FormatDuration(stopwatch.Milliseconds())); | |
| 773 | 331 | return result; | |
| 774 | } | ||
| 775 | |||
| 776 | } // namespace terraingen | ||
| 777 |