src/raster/geotiff/geotiff_write.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 | #include "util/text.h" | ||
| 11 | |||
| 12 | #include <cstring> | ||
| 13 | #include <fstream> | ||
| 14 | #include <map> | ||
| 15 | |||
| 16 | namespace terraingen { | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | using namespace detail; | ||
| 21 | |||
| 22 | /// Builds an IFD with values stored inline or in a block after it. | ||
| 23 | ✗ | class IfdWriter { | |
| 24 | public: | ||
| 25 | 116 | explicit IfdWriter(bool bigTiff) : m_format(IfdLayout(bigTiff)) {} | |
| 26 | |||
| 27 | template <typename T> | ||
| 28 | 1822 | void Add(std::uint16_t tag, FieldType type, const std::vector<T>& values) { | |
| 29 | 1822 | std::vector<std::uint8_t> bytes(values.size() * sizeof(T)); | |
| 30 | 1822 | std::memcpy(bytes.data(), values.data(), bytes.size()); | |
| 31 | 1822 | m_entries[tag] = {type, values.size(), std::move(bytes)}; | |
| 32 | 3644 | } | |
| 33 | |||
| 34 | 30 | void AddAscii(std::uint16_t tag, const std::string& text) { | |
| 35 | 30 | std::vector<std::uint8_t> bytes(text.begin(), text.end()); | |
| 36 | 30 | bytes.push_back(0); | |
| 37 | 30 | m_entries[tag] = {kAscii, bytes.size(), std::move(bytes)}; | |
| 38 | 60 | } | |
| 39 | |||
| 40 | /// The IFD and its out-of-line values, to be written at `offset`. | ||
| 41 | 116 | std::vector<std::uint8_t> Serialize(std::uint64_t offset) const { | |
| 42 | 116 | const std::size_t tableSize = | |
| 43 | 116 | m_format.countSize + m_entries.size() * m_format.EntrySize() + m_format.wordSize; | |
| 44 | 116 | std::vector<std::uint8_t> table(tableSize, 0); | |
| 45 | 116 | std::vector<std::uint8_t> extra; | |
| 46 | 6180 | const auto put = [&table](std::size_t at, std::uint64_t value, std::size_t size) { | |
| 47 | 6064 | std::memcpy(table.data() + at, &value, size); | |
| 48 | 6180 | }; | |
| 49 | 116 | put(0, m_entries.size(), m_format.countSize); | |
| 50 | 116 | std::size_t at = m_format.countSize; | |
| 51 | 1968 | for (const auto& [tag, entry] : m_entries) { | |
| 52 | 1852 | put(at, tag, 2); | |
| 53 | 1852 | put(at + 2, entry.type, 2); | |
| 54 | 1852 | put(at + 4, entry.count, m_format.wordSize); | |
| 55 | 1852 | const std::size_t valueAt = at + m_format.ValueAt(); | |
| 56 | 1852 | if (entry.bytes.size() <= m_format.wordSize) { | |
| 57 | 1460 | std::memcpy(table.data() + valueAt, entry.bytes.data(), entry.bytes.size()); | |
| 58 | } else { | ||
| 59 | 392 | if (extra.size() % 2 != 0) { | |
| 60 | 3 | extra.push_back(0); | |
| 61 | } | ||
| 62 | 392 | put(valueAt, offset + tableSize + extra.size(), m_format.wordSize); | |
| 63 | 392 | extra.insert(extra.end(), entry.bytes.begin(), entry.bytes.end()); | |
| 64 | } | ||
| 65 | 1852 | at += m_format.EntrySize(); | |
| 66 | } | ||
| 67 | 116 | table.insert(table.end(), extra.begin(), extra.end()); | |
| 68 | 116 | return table; | |
| 69 | 116 | } | |
| 70 | |||
| 71 | private: | ||
| 72 | IfdFormat m_format; | ||
| 73 | std::map<std::uint16_t, IfdEntry> m_entries; | ||
| 74 | }; | ||
| 75 | |||
| 76 | /// Where the tiles were written, and where the file ends. | ||
| 77 | 232 | struct TileIndex { | |
| 78 | std::vector<std::uint64_t> offsets; | ||
| 79 | std::vector<std::uint64_t> counts; | ||
| 80 | std::uint64_t end = 0; | ||
| 81 | }; | ||
| 82 | |||
| 83 | /// The tiles of each band: `across` by `down` tiles of `tile` pixels square. | ||
| 84 | struct TileGrid { | ||
| 85 | std::size_t tile = 0; ///< Tile edge in pixels. | ||
| 86 | std::size_t across = 0; ///< Tiles per row of tiles. | ||
| 87 | std::size_t down = 0; ///< Rows of tiles. | ||
| 88 | }; | ||
| 89 | |||
| 90 | 118 | TileGrid MakeTileGrid(const Raster<float>& raster, std::size_t tile) { | |
| 91 | 118 | return {tile, CeilDiv(raster.Width(), tile), CeilDiv(raster.Height(), tile)}; | |
| 92 | } | ||
| 93 | |||
| 94 | 127 | void CheckBands(const std::filesystem::path& path, const std::vector<const Raster<float>*>& bands, | |
| 95 | const GeoTiffWriteOptions& options) { | ||
| 96 | 127 | if (bands.empty() || bands.front()->Empty()) { | |
| 97 | 6 | ThrowFileError(path, "cannot write an empty raster"); | |
| 98 | } | ||
| 99 | const Raster<float>& first = *bands.front(); | ||
| 100 | 261 | for (const Raster<float>* band : bands) { | |
| 101 | 139 | if (band->Width() != first.Width() || band->Height() != first.Height() || | |
| 102 | 138 | !(band->Transform() == first.Transform())) { | |
| 103 | 4 | ThrowFileError(path, "the bands written must share one grid"); | |
| 104 | } | ||
| 105 | } | ||
| 106 | 122 | if (options.compression == TiffCompression::PackBits) { | |
| 107 | 2 | ThrowFileError(path, "writing PackBits is not supported; use None, Lzw or Deflate"); | |
| 108 | } | ||
| 109 | 121 | if (options.tileSize == 0 || options.tileSize % 16 != 0) { | |
| 110 | 3 | ThrowFileError(path, "the tile size must be a positive multiple of 16"); | |
| 111 | } | ||
| 112 | 118 | } | |
| 113 | |||
| 114 | /// Whether `bands` bands of uncompressed float32 tiles could pass 4 GiB. | ||
| 115 | 115 | bool NeedsBigTiff(const TileGrid& tiles, std::size_t bands) { | |
| 116 | 115 | const std::uint64_t estimate = static_cast<std::uint64_t>(tiles.across * tiles.down * bands) * | |
| 117 | 115 | tiles.tile * tiles.tile * 4 + | |
| 118 | (1u << 20); | ||
| 119 | 115 | return estimate >= (std::uint64_t{1} << 32); | |
| 120 | } | ||
| 121 | |||
| 122 | /// The bytes stored for the tile at column `tx` and row `ty` of tiles of `band`, padded with | ||
| 123 | /// `fill`. | ||
| 124 | 346 | std::vector<std::uint8_t> EncodeTile(const Raster<float>& band, std::size_t tx, std::size_t ty, | |
| 125 | std::size_t tile, float fill, TiffCompression compression) { | ||
| 126 | 346 | std::vector<std::uint8_t> bytes(tile * tile * sizeof(float)); | |
| 127 | 33002 | for (std::size_t y = 0; y < tile; ++y) { | |
| 128 | 7497872 | for (std::size_t x = 0; x < tile; ++x) { | |
| 129 | 7465216 | const std::size_t col = tx * tile + x; | |
| 130 | 7465216 | const std::size_t row = ty * tile + y; | |
| 131 | 7465216 | const float value = col < band.Width() && row < band.Height() ? band(col, row) : fill; | |
| 132 | 7465216 | std::memcpy(bytes.data() + (y * tile + x) * sizeof(float), &value, sizeof(float)); | |
| 133 | } | ||
| 134 | } | ||
| 135 | 346 | if (compression == TiffCompression::None) { | |
| 136 | 36 | return bytes; | |
| 137 | } | ||
| 138 | 310 | EncodeFloatPredictor(bytes.data(), tile, sizeof(float), tile, 1); | |
| 139 | 310 | return compression == TiffCompression::Lzw ? EncodeLzw(bytes) : EncodeDeflate(bytes); | |
| 140 | 346 | } | |
| 141 | |||
| 142 | /// Writes every tile of every band from `start`, each at an even offset. | ||
| 143 | 116 | TileIndex WriteTiles(std::ofstream& file, const std::vector<const Raster<float>*>& bands, | |
| 144 | const TileGrid& tiles, TiffCompression compression, std::uint64_t start) { | ||
| 145 | 116 | const float fill = bands.front()->NoData().value_or(0.0f); | |
| 146 | 116 | TileIndex index; | |
| 147 | 116 | index.end = start; | |
| 148 | 245 | for (const Raster<float>* band : bands) { | |
| 149 | 299 | for (std::size_t ty = 0; ty < tiles.down; ++ty) { | |
| 150 | 516 | for (std::size_t tx = 0; tx < tiles.across; ++tx) { | |
| 151 | 346 | const std::vector<std::uint8_t> bytes = | |
| 152 | 346 | EncodeTile(*band, tx, ty, tiles.tile, fill, compression); | |
| 153 | 346 | index.offsets.push_back(index.end); | |
| 154 | 346 | index.counts.push_back(bytes.size()); | |
| 155 | 346 | file.write(reinterpret_cast<const char*>(bytes.data()), | |
| 156 | 346 | static_cast<std::streamsize>(bytes.size())); | |
| 157 | 346 | index.end += bytes.size(); | |
| 158 | 346 | if (index.end % 2 != 0) { | |
| 159 | 159 | file.put(0); | |
| 160 | 159 | ++index.end; | |
| 161 | } | ||
| 162 | 346 | } | |
| 163 | } | ||
| 164 | } | ||
| 165 | 116 | return index; | |
| 166 | } | ||
| 167 | |||
| 168 | /// Writes the little-endian header of classic TIFF or BigTIFF with the first IFD's offset zeroed. | ||
| 169 | /// @return Where the first IFD's offset is, just before the end of the header. | ||
| 170 | 116 | std::uint64_t WriteHeader(std::ofstream& file, bool bigTiff) { | |
| 171 | 229 | std::vector<std::uint8_t> header = {'I', 'I', static_cast<std::uint8_t>(bigTiff ? 43 : 42), 0}; | |
| 172 | 116 | if (bigTiff) { | |
| 173 | 3 | header.insert(header.end(), {8, 0, 0, 0}); | |
| 174 | } | ||
| 175 | 116 | const std::uint64_t ifdOffsetAt = header.size(); | |
| 176 | 229 | header.resize(header.size() + IfdLayout(bigTiff).wordSize, 0); | |
| 177 | 116 | file.write(reinterpret_cast<const char*>(header.data()), | |
| 178 | 116 | static_cast<std::streamsize>(header.size())); | |
| 179 | 116 | return ifdOffsetAt; | |
| 180 | 116 | } | |
| 181 | |||
| 182 | /// Adds the tags describing the image, its samples and its tiles. | ||
| 183 | 116 | void AddImageTags(IfdWriter& ifd, const Raster<float>& raster, std::size_t bandCount, | |
| 184 | const GeoTiffWriteOptions& options, const TileIndex& tiles, bool bigTiff) { | ||
| 185 | 116 | const auto bands = static_cast<std::uint16_t>(bandCount); | |
| 186 | 116 | ifd.Add<std::uint32_t>(kImageWidth, kLong, {static_cast<std::uint32_t>(raster.Width())}); | |
| 187 | 116 | ifd.Add<std::uint32_t>(kImageLength, kLong, {static_cast<std::uint32_t>(raster.Height())}); | |
| 188 | 116 | ifd.Add<std::uint16_t>(kBitsPerSample, kShort, std::vector<std::uint16_t>(bands, 32)); | |
| 189 | 116 | ifd.Add<std::uint16_t>(kCompression, kShort, {TiffCompressionCode(options.compression)}); | |
| 190 | 116 | ifd.Add<std::uint16_t>(kPhotometric, kShort, {1}); | |
| 191 | 116 | ifd.Add<std::uint16_t>(kSamplesPerPixel, kShort, {bands}); | |
| 192 | 121 | ifd.Add<std::uint16_t>(kPlanarConfiguration, kShort, | |
| 193 | {static_cast<std::uint16_t>(bands == 1 ? 1 : 2)}); | ||
| 194 | 116 | if (options.compression != TiffCompression::None) { | |
| 195 | 113 | ifd.Add<std::uint16_t>(kPredictor, kShort, {3}); | |
| 196 | } | ||
| 197 | 116 | ifd.Add<std::uint32_t>(kTileWidth, kLong, {options.tileSize}); | |
| 198 | 116 | ifd.Add<std::uint32_t>(kTileLength, kLong, {options.tileSize}); | |
| 199 | 116 | if (bigTiff) { | |
| 200 | 3 | ifd.Add<std::uint64_t>(kTileOffsets, kLong8, tiles.offsets); | |
| 201 | 3 | ifd.Add<std::uint64_t>(kTileByteCounts, kLong8, tiles.counts); | |
| 202 | } else { | ||
| 203 | 113 | ifd.Add<std::uint32_t>( | |
| 204 | kTileOffsets, kLong, | ||
| 205 | 226 | std::vector<std::uint32_t>(tiles.offsets.begin(), tiles.offsets.end())); | |
| 206 | 113 | ifd.Add<std::uint32_t>( | |
| 207 | kTileByteCounts, kLong, | ||
| 208 | 226 | std::vector<std::uint32_t>(tiles.counts.begin(), tiles.counts.end())); | |
| 209 | } | ||
| 210 | 116 | if (bands > 1) { | |
| 211 | 5 | ifd.Add<std::uint16_t>(kExtraSamples, kShort, std::vector<std::uint16_t>(bands - 1u, 0)); | |
| 212 | } | ||
| 213 | 116 | ifd.Add<std::uint16_t>(kSampleFormat, kShort, std::vector<std::uint16_t>(bands, 3)); | |
| 214 | 116 | } | |
| 215 | |||
| 216 | /// Adds the georeferencing, projection keys and no-data value. | ||
| 217 | 116 | void AddGeoTags(IfdWriter& ifd, const Raster<float>& raster, const GeoKeys& geoKeys) { | |
| 218 | 116 | const GeoTransform& transform = raster.Transform(); | |
| 219 | 116 | if (!geoKeys.Empty() || !(transform == GeoTransform{})) { | |
| 220 | 112 | const ModelTags tags = EncodeTransform(transform, geoKeys.PixelIsPoint()); | |
| 221 | 112 | if (tags.transformation.empty()) { | |
| 222 | 108 | ifd.Add<double>(kModelPixelScale, kDouble, tags.pixelScale); | |
| 223 | 108 | ifd.Add<double>(kModelTiepoint, kDouble, tags.tiepoint); | |
| 224 | } else { | ||
| 225 | 4 | ifd.Add<double>(kModelTransformation, kDouble, tags.transformation); | |
| 226 | } | ||
| 227 | 112 | } | |
| 228 | 116 | if (!geoKeys.Empty()) { | |
| 229 | 75 | ifd.Add<std::uint16_t>(kGeoKeyDirectory, kShort, geoKeys.directory); | |
| 230 | 75 | if (!geoKeys.doubleParams.empty()) { | |
| 231 | 17 | ifd.Add<double>(kGeoDoubleParams, kDouble, geoKeys.doubleParams); | |
| 232 | } | ||
| 233 | 75 | if (!geoKeys.asciiParams.empty()) { | |
| 234 | 8 | ifd.AddAscii(kGeoAsciiParams, geoKeys.asciiParams); | |
| 235 | } | ||
| 236 | } | ||
| 237 | 116 | if (raster.NoData()) { | |
| 238 | 44 | ifd.AddAscii(kGdalNoData, FormatNumber(static_cast<double>(*raster.NoData()), 9)); | |
| 239 | } | ||
| 240 | 116 | } | |
| 241 | |||
| 242 | /// `WriteGeoTiff` of the rasters `bands` point to. | ||
| 243 | 127 | void WriteBands(const std::filesystem::path& path, const std::vector<const Raster<float>*>& bands, | |
| 244 | const GeoKeys& geoKeys, const GeoTiffWriteOptions& options) { | ||
| 245 | 127 | const Stopwatch stopwatch; | |
| 246 | 127 | CheckBands(path, bands, options); | |
| 247 | 118 | const Raster<float>& raster = *bands.front(); | |
| 248 | 118 | const TileGrid tiles = MakeTileGrid(raster, options.tileSize); | |
| 249 | 118 | const bool bigTiff = options.bigTiff || NeedsBigTiff(tiles, bands.size()); | |
| 250 | const IfdFormat format = IfdLayout(bigTiff); | ||
| 251 | |||
| 252 | 118 | std::ofstream file(path, std::ios::binary); | |
| 253 | 118 | if (!file) { | |
| 254 | 4 | ThrowFileError(path, "cannot open the file for writing"); | |
| 255 | } | ||
| 256 | 116 | const std::uint64_t ifdOffsetAt = WriteHeader(file, bigTiff); | |
| 257 | 116 | TileIndex index; | |
| 258 | 116 | try { | |
| 259 | 116 | index = WriteTiles(file, bands, tiles, options.compression, ifdOffsetAt + format.wordSize); | |
| 260 | ✗ | } catch (const GeoTiffError& error) { | |
| 261 | ✗ | ThrowFileError(path, error.what()); | |
| 262 | } | ||
| 263 | 116 | if (!bigTiff && index.end >= (std::uint64_t{1} << 32) - (1u << 20)) { | |
| 264 | ✗ | ThrowFileError(path, "data too large for classic TIFF; set bigTiff"); | |
| 265 | } | ||
| 266 | IfdWriter ifd(bigTiff); | ||
| 267 | 116 | AddImageTags(ifd, raster, bands.size(), options, index, bigTiff); | |
| 268 | 116 | AddGeoTags(ifd, raster, geoKeys); | |
| 269 | 116 | const std::vector<std::uint8_t> table = ifd.Serialize(index.end); | |
| 270 | 116 | file.write(reinterpret_cast<const char*>(table.data()), | |
| 271 | 116 | static_cast<std::streamsize>(table.size())); | |
| 272 | 116 | file.seekp(static_cast<std::streamoff>(ifdOffsetAt)); | |
| 273 | 116 | file.write(reinterpret_cast<const char*>(&index.end), | |
| 274 | static_cast<std::streamsize>(format.wordSize)); | ||
| 275 | 116 | if (!file) { | |
| 276 | ✗ | ThrowFileError(path, "write error"); | |
| 277 | } | ||
| 278 | 116 | LogInfo("raster", "Wrote ", raster.Width(), "x", raster.Height(), "x", bands.size(), | |
| 279 | 348 | " GeoTIFF ", path.string(), " in ", FormatDuration(stopwatch.Milliseconds())); | |
| 280 | 234 | } | |
| 281 | |||
| 282 | } // namespace | ||
| 283 | |||
| 284 | 113 | void WriteGeoTiff(const std::filesystem::path& path, const Raster<float>& raster, | |
| 285 | const GeoKeys& geoKeys, const GeoTiffWriteOptions& options) { | ||
| 286 | 113 | WriteBands(path, {&raster}, geoKeys, options); | |
| 287 | 105 | } | |
| 288 | |||
| 289 | 14 | void WriteGeoTiff(const std::filesystem::path& path, const std::vector<Raster<float>>& bands, | |
| 290 | const GeoKeys& geoKeys, const GeoTiffWriteOptions& options) { | ||
| 291 | 14 | std::vector<const Raster<float>*> pointers; | |
| 292 | 44 | for (const Raster<float>& band : bands) { | |
| 293 | 30 | pointers.push_back(&band); | |
| 294 | } | ||
| 295 | 14 | WriteBands(path, pointers, geoKeys, options); | |
| 296 | 14 | } | |
| 297 | |||
| 298 | } // namespace terraingen | ||
| 299 |