File: pmtiles_source.hpp

package info (click to toggle)
mapnik 4.2.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,656 kB
  • sloc: cpp: 163,870; python: 1,332; sh: 690; xml: 161; makefile: 123; perl: 28; lisp: 13
file content (591 lines) | stat: -rw-r--r-- 19,085 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
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
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2025 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_PMTILES_SOURCE_HPP
#define MAPNIK_PMTILES_SOURCE_HPP

#include <mapnik/global.hpp>
#include <mapnik/util/mapped_memory_file.hpp>
#include <mapnik/datasource.hpp>
#include "tiles_source.hpp"
// stl
#include <iostream>
#include <tuple>
#include <fstream>

// mapnik_vector_tile
#include "vector_tile_compression.hpp"

namespace mapnik {

enum class compression_type : std::uint8_t { UNKNOWN = 0x0, NONE = 0x1, GZIP = 0x2, BROTLI = 0x3, ZSTD = 0x4 };

enum class tile_type : std::uint8_t { UNKNOWN = 0x00, MVT = 0x01, PNG = 0x02, JPEG = 0x03, WEBP = 0x04, AVIF = 0x05 };

struct entryv3
{
    std::uint64_t tile_id;
    std::uint64_t offset;
    std::uint32_t length;
    std::uint32_t run_length;

    entryv3()
        : tile_id(0),
          offset(0),
          length(0),
          run_length(0)
    {}

    entryv3(std::uint64_t _tile_id, std::uint64_t _offset, std::uint32_t _length, std::uint32_t _run_length)
        : tile_id(_tile_id),
          offset(_offset),
          length(_length),
          run_length(_run_length)
    {}
};
namespace {
struct varint_too_long_exception : std::exception
{
    char const* what() const noexcept override { return "varint too long exception"; }
};

struct end_of_buffer_exception : std::exception
{
    char const* what() const noexcept override { return "end of buffer exception"; }
};
struct malformed_directory_exception : std::exception
{
    char const* what() const noexcept override { return "malformed directory exception"; }
};

constexpr int8_t const max_varint_length = sizeof(std::uint64_t) * 8 / 7 + 1;
// from https://github.com/mapbox/protozero/blob/master/include/protozero/varint.hpp
std::uint64_t decode_varint_impl(char const** data, char const* end)
{
    auto const* begin = reinterpret_cast<std::int8_t const*>(*data);
    auto const* iend = reinterpret_cast<std::int8_t const*>(end);
    std::int8_t const* p = begin;
    std::uint64_t val = 0;
    if (iend - begin >= max_varint_length)
    { // fast path
        do
        {
            std::int64_t b = *p++;
            val = ((std::uint64_t(b) & 0x7fU));
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 7U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 14U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 21U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 28U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 35U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 42U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 49U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((std::uint64_t(b) & 0x7fU) << 56U);
            if (b >= 0)
            {
                break;
            }
            b = *p++;
            val |= ((uint64_t(b) & 0x01U) << 63U);
            if (b >= 0)
            {
                break;
            }
            throw varint_too_long_exception{};
        } while (false);
    }
    else
    {
        unsigned int shift = 0;
        while (p != iend && *p < 0)
        {
            val |= (std::uint64_t(*p++) & 0x7fU) << shift;
            shift += 7;
        }
        if (p == iend)
        {
            throw end_of_buffer_exception{};
        }
        val |= std::uint64_t(*p++) << shift;
    }

    *data = reinterpret_cast<char const*>(p);
    return val;
}

std::uint64_t decode_varint(char const** data, char const* end)
{
    // If this is a one-byte varint, decode it here.
    if (end != *data && ((static_cast<std::uint64_t>(**data) & 0x80U) == 0))
    {
        auto const val = static_cast<std::uint64_t>(**data);
        ++(*data);
        return val;
    }
    // If this varint is more than one byte, defer to complete implementation.
    return decode_varint_impl(data, end);
}

inline std::vector<entryv3> deserialize_directory(std::string const& decompressed)
{
    char const* t = decompressed.data();
    char const* end = t + decompressed.size();

    std::uint64_t const num_entries_64bit = decode_varint(&t, end);
    // Sanity check to avoid excessive memory allocation attempt:
    // each directory entry takes at least 4 bytes
    if (num_entries_64bit / 4U > decompressed.size())
    {
        throw malformed_directory_exception();
    }
    std::size_t const num_entries = static_cast<std::size_t>(num_entries_64bit);
    std::vector<entryv3> result;
    result.resize(num_entries);

    std::uint64_t last_id = 0;
    for (std::size_t i = 0; i < num_entries; ++i)
    {
        std::uint64_t const val = decode_varint(&t, end);
        if (val > std::numeric_limits<std::uint64_t>::max() - last_id)
        {
            throw malformed_directory_exception();
        }
        std::uint64_t const tile_id = last_id + val;
        result[i].tile_id = tile_id;
        last_id = tile_id;
    }

    for (std::size_t i = 0; i < num_entries; ++i)
    {
        std::uint64_t const val = decode_varint(&t, end);
        if (val > std::numeric_limits<std::uint32_t>::max())
        {
            throw malformed_directory_exception();
        }
        result[i].run_length = static_cast<std::uint32_t>(val);
    }

    for (std::size_t i = 0; i < num_entries; ++i)
    {
        std::uint64_t const val = decode_varint(&t, end);
        if (val > std::numeric_limits<std::uint32_t>::max())
        {
            throw malformed_directory_exception();
        }
        result[i].length = static_cast<std::uint32_t>(val);
    }

    for (std::size_t i = 0; i < num_entries; ++i)
    {
        std::uint64_t tmp = decode_varint(&t, end);

        if (i > 0 && tmp == 0)
        {
            if (result[i - 1].offset > std::numeric_limits<std::uint64_t>::max() - result[i - 1].length)
            {
                throw malformed_directory_exception();
            }
            result[i].offset = result[i - 1].offset + result[i - 1].length;
        }
        else
        {
            result[i].offset = tmp - 1;
        }
    }

    // assert the directory has been fully consumed
    if (t != end)
    {
        throw malformed_directory_exception();
    }
    return result;
}

// use a 0 length entry as a null value.
entryv3 find_tile(std::vector<entryv3> const& entries, std::uint64_t tile_id)
{
    int m = 0;
    int n = static_cast<int>(entries.size()) - 1;
    while (m <= n)
    {
        int k = (n + m) >> 1;
        if (tile_id > entries[k].tile_id)
        {
            m = k + 1;
        }
        else if (tile_id < entries[k].tile_id)
        {
            n = k - 1;
        }
        else
        {
            return entries[k];
        }
    }

    if (n >= 0)
    {
        if (entries[n].run_length == 0)
        {
            return entries[n];
        }
        if (tile_id - entries[n].tile_id < entries[n].run_length)
        {
            return entries[n];
        }
    }

    return entryv3{0, 0, 0, 0};
}
void rotate(std::int64_t n, std::uint32_t& x, std::uint32_t& y, std::uint32_t rx, std::uint32_t ry)
{
    if (ry == 0)
    {
        if (rx != 0)
        {
            x = n - 1 - x;
            y = n - 1 - y;
        }
        std::uint32_t t = x;
        x = y;
        y = t;
    }
}

inline std::uint64_t zxy_to_tileid(std::uint8_t z, std::uint32_t x, std::uint32_t y)
{
    if (z > 31)
    {
        throw std::overflow_error("tile zoom exceeds 64-bit limit");
    }
    if (x > (1U << z) - 1U || y > (1U << z) - 1U)
    {
        throw std::overflow_error("tile x/y outside zoom level bounds");
    }
    std::uint64_t acc = ((1LL << (z * 2U)) - 1) / 3;
    std::uint32_t tx = x, ty = y;
    int a = z - 1;
    for (std::uint32_t s = 1LL << a; s > 0; s >>= 1)
    {
        std::uint32_t rx = s & tx;
        std::uint32_t ry = s & ty;
        rotate(s, tx, ty, rx, ry);
        acc += ((3LL * rx) ^ ry) << a;
        a--;
    }
    return acc;
}

} // namespace

inline std::int32_t read_int32_ndr(char const* buf, std::size_t pos)
{
    std::int32_t val;
    std::memcpy(&val, &buf[pos], 4);
    return val;
}

inline std::uint64_t read_uint64_xdr(char const* buf, std::size_t pos)
{
    std::uint64_t val;
    std::memcpy(&val, &buf[pos], 8);
    return val;
}

class pmtiles_source : public tiles_source,
                       util::mapped_memory_file
{
    std::size_t const HEADER_SIZE = 127;
    struct header
    {
        explicit header(char const* data)
            : data_(data)
        {}
        char const* data_;
        bool check_valid() const { return (std::string(data_, data_ + 7) == "PMTiles"); }
        int version() const { return data_[7]; }
        std::uint64_t root_dir_offset() const { return read_uint64_xdr(data_, 8); }
        std::uint64_t root_dir_length() const { return read_uint64_xdr(data_, 16); }
        std::uint64_t metadata_offset() const { return read_uint64_xdr(data_, 24); }
        std::uint64_t metadata_length() const { return read_uint64_xdr(data_, 32); }
        std::uint64_t leaf_directories_offset() const { return read_uint64_xdr(data_, 40); }
        std::uint64_t leaf_directories_length() const { return read_uint64_xdr(data_, 48); }
        std::uint64_t tile_data_offset() const { return read_uint64_xdr(data_, 56); }
        std::uint64_t tile_data_length() const { return read_uint64_xdr(data_, 64); }
        std::uint64_t addressed_tile_count() const { return read_uint64_xdr(data_, 72); }
        std::uint64_t tile_entries_count() const { return read_uint64_xdr(data_, 80); }
        std::uint64_t tile_content_count() const { return read_uint64_xdr(data_, 88); }

        int min_zoom() const { return static_cast<int>(data_[100]); }
        int max_zoom() const { return static_cast<int>(data_[101]); }
        double minx() const { return read_int32_ndr(data_, 102) / 1e7; }
        double miny() const { return read_int32_ndr(data_, 106) / 1e7; }
        double maxx() const { return read_int32_ndr(data_, 110) / 1e7; }
        double maxy() const { return read_int32_ndr(data_, 114) / 1e7; }
        compression_type internal_compression() const { return compression_type(data_[97]); }
        compression_type tile_compression() const { return compression_type(data_[98]); }
        tile_type type() const { return tile_type(data_[99]); }
    };

  public:

    pmtiles_source() {}
    pmtiles_source(std::string const& file_name)
        : mapped_memory_file(file_name)
    {
        if (!is_good())
        {
            throw mapnik::datasource_exception("Failed to create memory mapping for " + file_name);
        }
        init();
    }

    ~pmtiles_source() = default;

    void init()
    {
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
        std::string_view buffer{file_.buffer().first, HEADER_SIZE};
#else
        std::string buffer;
        buffer.resize(HEADER_SIZE);
        file_.seekg(0);
        file_.read(buffer.data(), HEADER_SIZE);
#endif
        header h(buffer.data());
        if (!h.check_valid())
        {
            throw mapnik::datasource_exception("PMTiles: invalid magic number");
        }
        else
        {
            // std::cerr << "Version:" << h.version() << std::endl;
            // std::cerr << "Min zoom:" << h.min_zoom() << std::endl;
            // std::cerr << "Max zoom:" << h.max_zoom() << std::endl;
            // std::cerr << "Min Lon/Lat:" << h.minx() << "," << h.miny() << std::endl;
            // std::cerr << "Max Lon/Lat:" << h.maxx() << "," << h.maxy() << std::endl;

            minzoom_ = h.min_zoom();
            maxzoom_ = h.max_zoom();
            extent_ = mapnik::box2d<double>{h.minx(), h.miny(), h.maxx(), h.maxy()};
            root_dir_offset_ = h.root_dir_offset();
            root_dir_length_ = h.root_dir_length();
            metadata_offset_ = h.metadata_offset();
            metadata_length_ = h.metadata_length();
            tile_data_offset_ = h.tile_data_offset();
            leaf_directories_offset_ = h.leaf_directories_offset();
            internal_compression_ = h.internal_compression();
            tile_compression_ = h.tile_compression();
            type_ = h.type();
            // std::cerr << "Metadata offset/length:" << metadata_offset_ << "," << metadata_length_ << std::endl;
            // std::cerr << "Internal compression:" << (int)h.internal_compression() << std::endl;
            // std::cerr << "Tile compression:" << (int)h.tile_compression() << std::endl;
            // std::cerr << "Addressed tile count:" << h.addressed_tile_count() << std::endl;
        }
    }

    inline bool is_good() const { return file_.good(); }
    inline bool is_raster() const { return type_ != tile_type::MVT; }

  private:
    std::uint64_t root_dir_offset_;
    std::uint64_t root_dir_length_;
    std::uint64_t metadata_offset_;
    std::uint64_t metadata_length_;
    std::uint64_t tile_data_offset_;
    std::uint64_t leaf_directories_offset_;
    std::uint8_t minzoom_ = 0;
    std::uint8_t maxzoom_ = 14;
    mapnik::box2d<double> extent_;
    compression_type internal_compression_;
    compression_type tile_compression_;
    tile_type type_;

    std::pair<std::uint64_t, std::uint32_t> get_tile_position(std::uint8_t z, std::uint32_t x, std::uint32_t y) const
    {
        try
        {
            auto tile_id = zxy_to_tileid(z, x, y);
            std::uint64_t dir_offset = root_dir_offset_;
            std::uint64_t dir_length = root_dir_length_;
            for (std::size_t depth = 0; depth < 4; ++depth)
            {
                std::string decompressed_dir;
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
                std::string_view buffer{file_.buffer().first + dir_offset, static_cast<std::size_t>(dir_length)};
#else
                std::string buffer;
                buffer.resize(dir_length);
                file_.seekg(dir_offset, std::ios::beg);
                file_.read(buffer.data(), dir_length);
#endif
                mapnik::vector_tile_impl::zlib_decompress(buffer.data(), buffer.size(), decompressed_dir);
                auto dir_entries = deserialize_directory(decompressed_dir);
                auto entry = find_tile(dir_entries, tile_id);
                if (entry.length > 0)
                {
                    if (entry.run_length > 0)
                    {
                        return std::make_pair(tile_data_offset_ + entry.offset, entry.length);
                    }
                    else
                    {
                        dir_offset = leaf_directories_offset_ + entry.offset;
                        dir_length = entry.length;
                    }
                }
                else
                {
                    return std::make_pair(0, 0);
                }
            }
            return std::make_pair(0, 0);
        }
        catch (std::exception const& ex)
        {
            return std::make_pair(0, 0);
        }
    }

  public:

    std::uint8_t minzoom() const { return minzoom_; }

    std::uint8_t maxzoom() const { return maxzoom_; }

    mapnik::box2d<double> const& extent() const { return extent_; }

    std::string get_tile(std::uint8_t z, std::uint32_t x, std::uint32_t y) const
    {
        auto tile = get_tile_position(z, x, y);
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
        std::string_view buffer{file_.buffer().first + tile.first, tile.second};
#else
        std::string buffer;
        buffer.resize(tile.second);
        file_.seekg(tile.first, std::ios::beg);
        file_.read(buffer.data(), tile.second);
#endif
        if (tile_compression_ == compression_type::GZIP)
        {
            if (mapnik::vector_tile_impl::is_gzip_compressed(buffer.data(), buffer.size()) ||
                mapnik::vector_tile_impl::is_zlib_compressed(buffer.data(), buffer.size()))
            {
                std::string decompressed;
                mapnik::vector_tile_impl::zlib_decompress(buffer.data(), buffer.size(), decompressed);
                return decompressed;
            }
        }
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
        return std::string{buffer};
#else
        return buffer;
#endif
    }

    std::string get_tile_raw(std::uint8_t z, std::uint32_t x, std::uint32_t y) const
    {
        auto tile = get_tile_position(z, x, y);
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
        std::string_view buffer{file_.buffer().first + tile.first, tile.second};
#else
        std::string buffer;
        buffer.resize(tile.second);
        file_.seekg(tile.first, std::ios::beg);
        file_.read(buffer.data(), tile.second);
#endif
        return std::string{buffer};
    }

    boost::json::value metadata() const
    {
        std::string metadata;
#if defined(MAPNIK_MEMORY_MAPPED_FILE)
        std::string_view buffer{file_.buffer().first + metadata_offset_, static_cast<std::size_t>(metadata_length_)};
#else
        std::string buffer;
        buffer.resize(metadata_length_);
        file_.seekg(metadata_offset_);
        file_.read(buffer.data(), metadata_length_);
#endif
        if (internal_compression_ == compression_type::GZIP)
        {
            mapnik::vector_tile_impl::zlib_decompress(buffer.data(), buffer.size(), metadata);
        }
        else
        {
            metadata = std::move(buffer);
        }
        boost::json::value json_value;
        try
        {
            json_value = boost::json::parse(metadata);
        }
        catch (std::exception const& ex)
        {
            std::cerr << ex.what() << std::endl;
        }
        return json_value;
    }
};
} // namespace mapnik

#endif // MAPNIK_PMTILES_SOURCE_HPP