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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467
|
/******************************************************************************
*
* Project: GDAL
* Purpose: Zarr driver
* Author: Even Rouault <even dot rouault at spatialys.com>
*
******************************************************************************
* Copyright (c) 2021, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_vsi_virtual.h"
#include "zarr.h"
#include "gdal_thread_pool.h"
#include "ucs4_utf8.hpp"
#include "cpl_float.h"
#include "netcdf_cf_constants.h" // for CF_UNITS, etc
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <limits>
#include <map>
#include <set>
#define ZARR_DEBUG_KEY "ZARR"
#define CRS_ATTRIBUTE_NAME "_CRS"
namespace
{
inline std::vector<GByte> UTF8ToUCS4(const char *pszStr, bool needByteSwap)
{
const size_t nLen = strlen(pszStr);
// Worst case if that we need 4 more bytes than the UTF-8 one
// (when the content is pure ASCII)
if (nLen > std::numeric_limits<size_t>::max() / sizeof(uint32_t))
throw std::bad_alloc();
std::vector<GByte> ret(nLen * sizeof(uint32_t));
size_t outPos = 0;
for (size_t i = 0; i < nLen; outPos += sizeof(uint32_t))
{
uint32_t ucs4 = 0;
int consumed = FcUtf8ToUcs4(
reinterpret_cast<const uint8_t *>(pszStr + i), &ucs4, nLen - i);
if (consumed <= 0)
{
ret.resize(outPos);
}
if (needByteSwap)
{
CPL_SWAP32PTR(&ucs4);
}
memcpy(&ret[outPos], &ucs4, sizeof(uint32_t));
i += consumed;
}
ret.resize(outPos);
return ret;
}
inline char *UCS4ToUTF8(const uint8_t *ucs4Ptr, size_t nSize, bool needByteSwap)
{
// A UCS4 char can require up to 6 bytes in UTF8.
if (nSize > (std::numeric_limits<size_t>::max() - 1) / 6 * 4)
return nullptr;
const size_t nOutSize = nSize / 4 * 6 + 1;
char *ret = static_cast<char *>(VSI_MALLOC_VERBOSE(nOutSize));
if (ret == nullptr)
return nullptr;
size_t outPos = 0;
for (size_t i = 0; i + sizeof(uint32_t) - 1 < nSize; i += sizeof(uint32_t))
{
uint32_t ucs4;
memcpy(&ucs4, ucs4Ptr + i, sizeof(uint32_t));
if (needByteSwap)
{
CPL_SWAP32PTR(&ucs4);
}
int written =
FcUcs4ToUtf8(ucs4, reinterpret_cast<uint8_t *>(ret + outPos));
outPos += written;
}
ret[outPos] = 0;
return ret;
}
} // namespace
/************************************************************************/
/* ZarrArray::ZarrArray() */
/************************************************************************/
ZarrArray::ZarrArray(
const std::shared_ptr<ZarrSharedResource> &poSharedResource,
const std::string &osParentName, const std::string &osName,
const std::vector<std::shared_ptr<GDALDimension>> &aoDims,
const GDALExtendedDataType &oType, const std::vector<DtypeElt> &aoDtypeElts,
const std::vector<GUInt64> &anBlockSize, bool bFortranOrder)
: GDALAbstractMDArray(osParentName, osName),
GDALPamMDArray(osParentName, osName, poSharedResource->GetPAM()),
m_poSharedResource(poSharedResource), m_aoDims(aoDims), m_oType(oType),
m_aoDtypeElts(aoDtypeElts), m_anBlockSize(anBlockSize),
m_bFortranOrder(bFortranOrder), m_oAttrGroup(osParentName)
{
m_oCompressorJSonV2.Deinit();
m_oCompressorJSonV3.Deinit();
// Compute individual tile size
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
m_nTileSize = nSourceSize;
for (const auto &nBlockSize : m_anBlockSize)
{
m_nTileSize *= static_cast<size_t>(nBlockSize);
}
}
/************************************************************************/
/* ZarrArray::Create() */
/************************************************************************/
std::shared_ptr<ZarrArray>
ZarrArray::Create(const std::shared_ptr<ZarrSharedResource> &poSharedResource,
const std::string &osParentName, const std::string &osName,
const std::vector<std::shared_ptr<GDALDimension>> &aoDims,
const GDALExtendedDataType &oType,
const std::vector<DtypeElt> &aoDtypeElts,
const std::vector<GUInt64> &anBlockSize, bool bFortranOrder)
{
uint64_t nTotalTileCount = 1;
for (size_t i = 0; i < aoDims.size(); ++i)
{
uint64_t nTileThisDim =
(aoDims[i]->GetSize() / anBlockSize[i]) +
(((aoDims[i]->GetSize() % anBlockSize[i]) != 0) ? 1 : 0);
if (nTileThisDim != 0 &&
nTotalTileCount >
std::numeric_limits<uint64_t>::max() / nTileThisDim)
{
CPLError(
CE_Failure, CPLE_NotSupported,
"Array %s has more than 2^64 tiles. This is not supported.",
osName.c_str());
return nullptr;
}
nTotalTileCount *= nTileThisDim;
}
auto arr = std::shared_ptr<ZarrArray>(
new ZarrArray(poSharedResource, osParentName, osName, aoDims, oType,
aoDtypeElts, anBlockSize, bFortranOrder));
arr->SetSelf(arr);
arr->m_nTotalTileCount = nTotalTileCount;
arr->m_bUseOptimizedCodePaths = CPLTestBool(
CPLGetConfigOption("GDAL_ZARR_USE_OPTIMIZED_CODE_PATHS", "YES"));
return arr;
}
/************************************************************************/
/* ~ZarrArray() */
/************************************************************************/
ZarrArray::~ZarrArray()
{
Flush();
if (m_pabyNoData)
{
m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
CPLFree(m_pabyNoData);
}
DeallocateDecodedTileData();
}
/************************************************************************/
/* Flush() */
/************************************************************************/
void ZarrArray::Flush()
{
FlushDirtyTile();
bool bSerializeV3 = false;
if (m_bDefinitionModified)
{
if (m_nVersion == 2)
{
SerializeV2();
}
else
{
bSerializeV3 = true;
}
m_bDefinitionModified = false;
}
CPLJSONArray j_ARRAY_DIMENSIONS;
if (!m_aoDims.empty())
{
for (const auto &poDim : m_aoDims)
{
if (dynamic_cast<const ZarrArray *>(
poDim->GetIndexingVariable().get()) != nullptr)
{
j_ARRAY_DIMENSIONS.Add(poDim->GetName());
}
else
{
j_ARRAY_DIMENSIONS = CPLJSONArray();
break;
}
}
}
CPLJSONObject oAttrs;
if (m_oAttrGroup.IsModified() ||
(m_bNew && j_ARRAY_DIMENSIONS.Size() != 0) || m_bUnitModified ||
m_bOffsetModified || m_bScaleModified || m_bSRSModified)
{
m_bNew = false;
m_bSRSModified = false;
m_oAttrGroup.UnsetModified();
oAttrs = m_oAttrGroup.Serialize();
if (j_ARRAY_DIMENSIONS.Size() != 0)
{
oAttrs.Delete("_ARRAY_DIMENSIONS");
oAttrs.Add("_ARRAY_DIMENSIONS", j_ARRAY_DIMENSIONS);
}
if (m_poSRS)
{
CPLJSONObject oCRS;
const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
char *pszWKT = nullptr;
if (m_poSRS->exportToWkt(&pszWKT, apszOptions) == OGRERR_NONE)
{
oCRS.Add("wkt", pszWKT);
}
CPLFree(pszWKT);
{
CPLErrorHandlerPusher quietError(CPLQuietErrorHandler);
CPLErrorStateBackuper errorStateBackuper;
char *projjson = nullptr;
if (m_poSRS->exportToPROJJSON(&projjson, nullptr) ==
OGRERR_NONE &&
projjson != nullptr)
{
CPLJSONDocument oDocProjJSON;
if (oDocProjJSON.LoadMemory(std::string(projjson)))
{
oCRS.Add("projjson", oDocProjJSON.GetRoot());
}
}
CPLFree(projjson);
}
const char *pszAuthorityCode = m_poSRS->GetAuthorityCode(nullptr);
const char *pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
if (pszAuthorityCode && pszAuthorityName &&
EQUAL(pszAuthorityName, "EPSG"))
{
oCRS.Add("url",
std::string("http://www.opengis.net/def/crs/EPSG/0/") +
pszAuthorityCode);
}
oAttrs.Add(CRS_ATTRIBUTE_NAME, oCRS);
}
if (m_osUnit.empty())
{
if (m_bUnitModified)
oAttrs.Delete(CF_UNITS);
}
else
{
oAttrs.Set(CF_UNITS, m_osUnit);
}
m_bUnitModified = false;
if (!m_bHasOffset)
{
oAttrs.Delete(CF_ADD_OFFSET);
}
else
{
oAttrs.Set(CF_ADD_OFFSET, m_dfOffset);
}
m_bOffsetModified = false;
if (!m_bHasScale)
{
oAttrs.Delete(CF_SCALE_FACTOR);
}
else
{
oAttrs.Set(CF_SCALE_FACTOR, m_dfScale);
}
m_bScaleModified = false;
if (m_nVersion == 2)
{
CPLJSONDocument oDoc;
oDoc.SetRoot(oAttrs);
const std::string osAttrFilename = CPLFormFilename(
CPLGetDirname(m_osFilename.c_str()), ".zattrs", nullptr);
oDoc.Save(osAttrFilename);
m_poSharedResource->SetZMetadataItem(osAttrFilename, oAttrs);
}
else
{
bSerializeV3 = true;
}
}
if (bSerializeV3)
{
SerializeV3(oAttrs);
}
}
/************************************************************************/
/* DeallocateDecodedTileData() */
/************************************************************************/
void ZarrArray::DeallocateDecodedTileData()
{
if (!m_abyDecodedTileData.empty())
{
const size_t nDTSize = m_oType.GetSize();
GByte *pDst = &m_abyDecodedTileData[0];
const size_t nValues = m_abyDecodedTileData.size() / nDTSize;
for (auto &elt : m_aoDtypeElts)
{
if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII ||
elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
{
for (size_t i = 0; i < nValues; i++, pDst += nDTSize)
{
char *ptr;
char **pptr =
reinterpret_cast<char **>(pDst + elt.gdalOffset);
memcpy(&ptr, pptr, sizeof(ptr));
VSIFree(ptr);
}
}
}
}
}
/************************************************************************/
/* EncodeElt() */
/************************************************************************/
/* Encode from GDAL raw type to Zarr native type */
static void EncodeElt(const std::vector<DtypeElt> &elts, const GByte *pSrc,
GByte *pDst)
{
for (const auto &elt : elts)
{
if (elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
{
const char *pStr =
*reinterpret_cast<const char *const *>(pSrc + elt.gdalOffset);
if (pStr)
{
try
{
const auto ucs4 = UTF8ToUCS4(pStr, elt.needByteSwapping);
const auto ucs4Len = ucs4.size();
memcpy(pDst + elt.nativeOffset, ucs4.data(),
std::min(ucs4Len, elt.nativeSize));
if (ucs4Len > elt.nativeSize)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Too long string truncated");
}
else if (ucs4Len < elt.nativeSize)
{
memset(pDst + elt.nativeOffset + ucs4Len, 0,
elt.nativeSize - ucs4Len);
}
}
catch (const std::exception &)
{
memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
}
}
else
{
memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
}
}
else if (elt.needByteSwapping)
{
if (elt.nativeSize == 2)
{
if (elt.gdalTypeIsApproxOfNative)
{
CPLAssert(elt.nativeType == DtypeElt::NativeType::IEEEFP);
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Float32);
const uint32_t uint32Val =
*reinterpret_cast<const uint32_t *>(pSrc +
elt.gdalOffset);
bool bHasWarned = false;
uint16_t uint16Val =
CPL_SWAP16(CPLFloatToHalf(uint32Val, bHasWarned));
memcpy(pDst + elt.nativeOffset, &uint16Val,
sizeof(uint16Val));
}
else
{
const uint16_t val =
CPL_SWAP16(*reinterpret_cast<const uint16_t *>(
pSrc + elt.gdalOffset));
memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
}
}
else if (elt.nativeSize == 4)
{
const uint32_t val = CPL_SWAP32(
*reinterpret_cast<const uint32_t *>(pSrc + elt.gdalOffset));
memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
}
else if (elt.nativeSize == 8)
{
if (elt.nativeType == DtypeElt::NativeType::COMPLEX_IEEEFP)
{
uint32_t val =
CPL_SWAP32(*reinterpret_cast<const uint32_t *>(
pSrc + elt.gdalOffset));
memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
val = CPL_SWAP32(*reinterpret_cast<const uint32_t *>(
pSrc + elt.gdalOffset + 4));
memcpy(pDst + elt.nativeOffset + 4, &val, sizeof(val));
}
else
{
const uint64_t val =
CPL_SWAP64(*reinterpret_cast<const uint64_t *>(
pSrc + elt.gdalOffset));
memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
}
}
else if (elt.nativeSize == 16)
{
uint64_t val = CPL_SWAP64(
*reinterpret_cast<const uint64_t *>(pSrc + elt.gdalOffset));
memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
val = CPL_SWAP64(*reinterpret_cast<const uint64_t *>(
pSrc + elt.gdalOffset + 8));
memcpy(pDst + elt.nativeOffset + 8, &val, sizeof(val));
}
else
{
CPLAssert(false);
}
}
else if (elt.gdalTypeIsApproxOfNative)
{
if (elt.nativeType == DtypeElt::NativeType::SIGNED_INT &&
elt.nativeSize == 1)
{
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Int16);
const int16_t int16Val =
*reinterpret_cast<const int16_t *>(pSrc + elt.gdalOffset);
const int8_t intVal = static_cast<int8_t>(int16Val);
memcpy(pDst + elt.nativeOffset, &intVal, sizeof(intVal));
}
else if (elt.nativeType == DtypeElt::NativeType::IEEEFP &&
elt.nativeSize == 2)
{
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Float32);
const uint32_t uint32Val =
*reinterpret_cast<const uint32_t *>(pSrc + elt.gdalOffset);
bool bHasWarned = false;
const uint16_t uint16Val =
CPLFloatToHalf(uint32Val, bHasWarned);
memcpy(pDst + elt.nativeOffset, &uint16Val, sizeof(uint16Val));
}
else
{
CPLAssert(false);
}
}
else if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII)
{
const char *pStr =
*reinterpret_cast<const char *const *>(pSrc + elt.gdalOffset);
if (pStr)
{
const size_t nLen = strlen(pStr);
memcpy(pDst + elt.nativeOffset, pStr,
std::min(nLen, elt.nativeSize));
if (nLen < elt.nativeSize)
memset(pDst + elt.nativeOffset + nLen, 0,
elt.nativeSize - nLen);
}
else
{
memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
}
}
else
{
CPLAssert(elt.nativeSize == elt.gdalSize);
memcpy(pDst + elt.nativeOffset, pSrc + elt.gdalOffset,
elt.nativeSize);
}
}
}
/************************************************************************/
/* StripUselessItemsFromCompressorConfiguration() */
/************************************************************************/
static void StripUselessItemsFromCompressorConfiguration(CPLJSONObject &o)
{
o.Delete("num_threads"); // Blosc
o.Delete("typesize"); // Blosc
o.Delete("header"); // LZ4
}
/************************************************************************/
/* ZarrArray::SerializeNumericNoData() */
/************************************************************************/
void ZarrArray::SerializeNumericNoData(CPLJSONObject &oRoot) const
{
if (m_oType.GetNumericDataType() == GDT_Int64)
{
const auto nVal = GetNoDataValueAsInt64();
oRoot.Add("fill_value", static_cast<GInt64>(nVal));
}
else if (m_oType.GetNumericDataType() == GDT_UInt64)
{
const auto nVal = GetNoDataValueAsUInt64();
if (nVal <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))
{
oRoot.Add("fill_value", static_cast<GInt64>(nVal));
}
else if (nVal == static_cast<uint64_t>(static_cast<double>(nVal)))
{
oRoot.Add("fill_value", static_cast<double>(nVal));
}
else
{
// not really compliant...
oRoot.Add("fill_value",
CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nVal)));
}
}
else
{
const double dfVal = GetNoDataValueAsDouble();
if (std::isnan(dfVal))
oRoot.Add("fill_value", "NaN");
else if (dfVal == std::numeric_limits<double>::infinity())
oRoot.Add("fill_value", "Infinity");
else if (dfVal == -std::numeric_limits<double>::infinity())
oRoot.Add("fill_value", "-Infinity");
else if (GDALDataTypeIsInteger(m_oType.GetNumericDataType()))
oRoot.Add("fill_value", static_cast<GInt64>(dfVal));
else
oRoot.Add("fill_value", dfVal);
}
}
/************************************************************************/
/* ZarrArray::SerializeV2() */
/************************************************************************/
void ZarrArray::SerializeV2()
{
CPLJSONDocument oDoc;
CPLJSONObject oRoot = oDoc.GetRoot();
CPLJSONArray oChunks;
for (const auto nBlockSize : m_anBlockSize)
{
oChunks.Add(static_cast<GInt64>(nBlockSize));
}
oRoot.Add("chunks", oChunks);
if (m_oCompressorJSonV2.IsValid())
{
oRoot.Add("compressor", m_oCompressorJSonV2);
CPLJSONObject compressor = oRoot["compressor"];
StripUselessItemsFromCompressorConfiguration(compressor);
}
else
{
oRoot.AddNull("compressor");
}
if (m_dtype.GetType() == CPLJSONObject::Type::Object)
oRoot.Add("dtype", m_dtype["dummy"]);
else
oRoot.Add("dtype", m_dtype);
if (m_pabyNoData == nullptr)
{
oRoot.AddNull("fill_value");
}
else
{
switch (m_oType.GetClass())
{
case GEDTC_NUMERIC:
{
SerializeNumericNoData(oRoot);
break;
}
case GEDTC_STRING:
{
char *pszStr;
char **ppszStr = reinterpret_cast<char **>(m_pabyNoData);
memcpy(&pszStr, ppszStr, sizeof(pszStr));
if (pszStr)
{
const size_t nNativeSize =
m_aoDtypeElts.back().nativeOffset +
m_aoDtypeElts.back().nativeSize;
char *base64 = CPLBase64Encode(
static_cast<int>(std::min(nNativeSize, strlen(pszStr))),
reinterpret_cast<const GByte *>(pszStr));
oRoot.Add("fill_value", base64);
CPLFree(base64);
}
else
{
oRoot.AddNull("fill_value");
}
break;
}
case GEDTC_COMPOUND:
{
const size_t nNativeSize = m_aoDtypeElts.back().nativeOffset +
m_aoDtypeElts.back().nativeSize;
std::vector<GByte> nativeNoData(nNativeSize);
EncodeElt(m_aoDtypeElts, m_pabyNoData, &nativeNoData[0]);
char *base64 = CPLBase64Encode(static_cast<int>(nNativeSize),
nativeNoData.data());
oRoot.Add("fill_value", base64);
CPLFree(base64);
}
}
}
if (m_oFiltersArray.Size() == 0)
oRoot.AddNull("filters");
else
oRoot.Add("filters", m_oFiltersArray);
oRoot.Add("order", m_bFortranOrder ? "F" : "C");
CPLJSONArray oShape;
for (const auto &poDim : m_aoDims)
{
oShape.Add(static_cast<GInt64>(poDim->GetSize()));
}
oRoot.Add("shape", oShape);
oRoot.Add("zarr_format", m_nVersion);
if (m_osDimSeparator != ".")
{
oRoot.Add("dimension_separator", m_osDimSeparator);
}
oDoc.Save(m_osFilename);
m_poSharedResource->SetZMetadataItem(m_osFilename, oRoot);
}
/************************************************************************/
/* ZarrArray::SerializeV3() */
/************************************************************************/
void ZarrArray::SerializeV3(const CPLJSONObject &oAttrs)
{
CPLJSONDocument oDoc;
CPLJSONObject oRoot = oDoc.GetRoot();
CPLJSONArray oShape;
for (const auto &poDim : m_aoDims)
{
oShape.Add(static_cast<GInt64>(poDim->GetSize()));
}
oRoot.Add("shape", oShape);
oRoot.Add("data_type", m_dtype.ToString());
CPLJSONObject oChunkGrid;
oChunkGrid.Add("type", "regular");
CPLJSONArray oChunks;
for (const auto nBlockSize : m_anBlockSize)
{
oChunks.Add(static_cast<GInt64>(nBlockSize));
}
oChunkGrid.Add("chunk_shape", oChunks);
oChunkGrid.Add("separator", m_osDimSeparator);
oRoot.Add("chunk_grid", oChunkGrid);
if (m_oCompressorJSonV3.IsValid())
{
oRoot.Add("compressor", m_oCompressorJSonV3);
CPLJSONObject oConfiguration = oRoot["compressor"]["configuration"];
StripUselessItemsFromCompressorConfiguration(oConfiguration);
}
if (m_pabyNoData == nullptr)
{
oRoot.AddNull("fill_value");
}
else
{
SerializeNumericNoData(oRoot);
}
oRoot.Add("chunk_memory_layout", m_bFortranOrder ? "F" : "C");
oRoot.Add("extensions", CPLJSONArray());
oRoot.Add("attributes", oAttrs);
oDoc.Save(m_osFilename);
}
/************************************************************************/
/* ZarrArray::NeedDecodedBuffer() */
/************************************************************************/
bool ZarrArray::NeedDecodedBuffer() const
{
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
if (m_oType.GetClass() == GEDTC_COMPOUND &&
nSourceSize != m_oType.GetSize())
{
return true;
}
else if (m_oType.GetClass() != GEDTC_STRING)
{
for (const auto &elt : m_aoDtypeElts)
{
if (elt.needByteSwapping || elt.gdalTypeIsApproxOfNative ||
elt.nativeType == DtypeElt::NativeType::STRING_ASCII ||
elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
{
return true;
}
}
}
return false;
}
/************************************************************************/
/* ZarrArray::AllocateWorkingBuffers() */
/************************************************************************/
bool ZarrArray::AllocateWorkingBuffers() const
{
if (m_bAllocateWorkingBuffersDone)
return m_bWorkingBuffersOK;
m_bAllocateWorkingBuffersDone = true;
size_t nSizeNeeded = m_nTileSize;
if (m_bFortranOrder || m_oFiltersArray.Size() != 0)
{
if (nSizeNeeded > std::numeric_limits<size_t>::max() / 2)
{
CPLError(CE_Failure, CPLE_AppDefined, "Too large chunk size");
return false;
}
nSizeNeeded *= 2;
}
if (NeedDecodedBuffer())
{
size_t nDecodedBufferSize = m_oType.GetSize();
for (const auto &nBlockSize : m_anBlockSize)
{
if (nDecodedBufferSize > std::numeric_limits<size_t>::max() /
static_cast<size_t>(nBlockSize))
{
CPLError(CE_Failure, CPLE_AppDefined, "Too large chunk size");
return false;
}
nDecodedBufferSize *= static_cast<size_t>(nBlockSize);
}
if (nSizeNeeded >
std::numeric_limits<size_t>::max() - nDecodedBufferSize)
{
CPLError(CE_Failure, CPLE_AppDefined, "Too large chunk size");
return false;
}
nSizeNeeded += nDecodedBufferSize;
}
// Reserve a buffer for tile content
if (nSizeNeeded > 1024 * 1024 * 1024 &&
!CPLTestBool(CPLGetConfigOption("ZARR_ALLOW_BIG_TILE_SIZE", "NO")))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Zarr tile allocation would require " CPL_FRMT_GUIB " bytes. "
"By default the driver limits to 1 GB. To allow that memory "
"allocation, set the ZARR_ALLOW_BIG_TILE_SIZE configuration "
"option to YES.",
static_cast<GUIntBig>(nSizeNeeded));
return false;
}
m_bWorkingBuffersOK = AllocateWorkingBuffers(
m_abyRawTileData, m_abyTmpRawTileData, m_abyDecodedTileData);
return m_bWorkingBuffersOK;
}
bool ZarrArray::AllocateWorkingBuffers(
std::vector<GByte> &abyRawTileData, std::vector<GByte> &abyTmpRawTileData,
std::vector<GByte> &abyDecodedTileData) const
{
// This method should NOT modify any ZarrArray member, as it is going to
// be called concurrently from several threads.
// Set those #define to avoid accidental use of some global variables
#define m_abyTmpRawTileData cannot_use_here
#define m_abyRawTileData cannot_use_here
#define m_abyDecodedTileData cannot_use_here
try
{
abyRawTileData.resize(m_nTileSize);
if (m_bFortranOrder || m_oFiltersArray.Size() != 0)
abyTmpRawTileData.resize(m_nTileSize);
}
catch (const std::bad_alloc &e)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
return false;
}
if (NeedDecodedBuffer())
{
size_t nDecodedBufferSize = m_oType.GetSize();
for (const auto &nBlockSize : m_anBlockSize)
{
nDecodedBufferSize *= static_cast<size_t>(nBlockSize);
}
try
{
abyDecodedTileData.resize(nDecodedBufferSize);
}
catch (const std::bad_alloc &e)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what());
return false;
}
}
return true;
#undef m_abyTmpRawTileData
#undef m_abyRawTileData
#undef m_abyDecodedTileData
}
/************************************************************************/
/* ZarrArray::GetSpatialRef() */
/************************************************************************/
std::shared_ptr<OGRSpatialReference> ZarrArray::GetSpatialRef() const
{
if (m_poSRS)
return m_poSRS;
return GDALPamMDArray::GetSpatialRef();
}
/************************************************************************/
/* SetRawNoDataValue() */
/************************************************************************/
bool ZarrArray::SetRawNoDataValue(const void *pRawNoData)
{
if (!m_bUpdatable)
{
CPLError(CE_Failure, CPLE_AppDefined, "Array opened in read-only mode");
return false;
}
m_bDefinitionModified = true;
RegisterNoDataValue(pRawNoData);
return true;
}
/************************************************************************/
/* RegisterNoDataValue() */
/************************************************************************/
void ZarrArray::RegisterNoDataValue(const void *pNoData)
{
if (m_pabyNoData)
{
m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
}
if (pNoData == nullptr)
{
CPLFree(m_pabyNoData);
m_pabyNoData = nullptr;
}
else
{
const auto nSize = m_oType.GetSize();
if (m_pabyNoData == nullptr)
{
m_pabyNoData = static_cast<GByte *>(CPLMalloc(nSize));
}
memset(m_pabyNoData, 0, nSize);
GDALExtendedDataType::CopyValue(pNoData, m_oType, m_pabyNoData,
m_oType);
}
}
/************************************************************************/
/* ZarrArray::BlockTranspose() */
/************************************************************************/
void ZarrArray::BlockTranspose(const std::vector<GByte> &abySrc,
std::vector<GByte> &abyDst, bool bDecode) const
{
// Perform transposition
const size_t nDims = m_anBlockSize.size();
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
struct Stack
{
size_t nIters = 0;
const GByte *src_ptr = nullptr;
GByte *dst_ptr = nullptr;
size_t src_inc_offset = 0;
size_t dst_inc_offset = 0;
};
std::vector<Stack> stack(nDims);
stack.emplace_back(
Stack()); // to make gcc 9.3 -O2 -Wnull-dereference happy
if (bDecode)
{
stack[0].src_inc_offset = nSourceSize;
for (size_t i = 1; i < nDims; ++i)
{
stack[i].src_inc_offset = stack[i - 1].src_inc_offset *
static_cast<size_t>(m_anBlockSize[i - 1]);
}
stack[nDims - 1].dst_inc_offset = nSourceSize;
for (size_t i = nDims - 1; i > 0;)
{
--i;
stack[i].dst_inc_offset = stack[i + 1].dst_inc_offset *
static_cast<size_t>(m_anBlockSize[i + 1]);
}
}
else
{
stack[0].dst_inc_offset = nSourceSize;
for (size_t i = 1; i < nDims; ++i)
{
stack[i].dst_inc_offset = stack[i - 1].dst_inc_offset *
static_cast<size_t>(m_anBlockSize[i - 1]);
}
stack[nDims - 1].src_inc_offset = nSourceSize;
for (size_t i = nDims - 1; i > 0;)
{
--i;
stack[i].src_inc_offset = stack[i + 1].src_inc_offset *
static_cast<size_t>(m_anBlockSize[i + 1]);
}
}
stack[0].src_ptr = abySrc.data();
stack[0].dst_ptr = &abyDst[0];
size_t dimIdx = 0;
lbl_next_depth:
if (dimIdx == nDims)
{
void *dst_ptr = stack[nDims].dst_ptr;
const void *src_ptr = stack[nDims].src_ptr;
if (nSourceSize == 1)
*stack[nDims].dst_ptr = *stack[nDims].src_ptr;
else if (nSourceSize == 2)
*static_cast<uint16_t *>(dst_ptr) =
*static_cast<const uint16_t *>(src_ptr);
else if (nSourceSize == 4)
*static_cast<uint32_t *>(dst_ptr) =
*static_cast<const uint32_t *>(src_ptr);
else if (nSourceSize == 8)
*static_cast<uint64_t *>(dst_ptr) =
*static_cast<const uint64_t *>(src_ptr);
else
memcpy(dst_ptr, src_ptr, nSourceSize);
}
else
{
stack[dimIdx].nIters = static_cast<size_t>(m_anBlockSize[dimIdx]);
while (true)
{
dimIdx++;
stack[dimIdx].src_ptr = stack[dimIdx - 1].src_ptr;
stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
goto lbl_next_depth;
lbl_return_to_caller:
dimIdx--;
if ((--stack[dimIdx].nIters) == 0)
break;
stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
}
}
if (dimIdx > 0)
goto lbl_return_to_caller;
}
/************************************************************************/
/* DecodeSourceElt() */
/************************************************************************/
static void DecodeSourceElt(const std::vector<DtypeElt> &elts,
const GByte *pSrc, GByte *pDst)
{
for (auto &elt : elts)
{
if (elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
{
char *ptr;
char **pDstPtr = reinterpret_cast<char **>(pDst + elt.gdalOffset);
memcpy(&ptr, pDstPtr, sizeof(ptr));
VSIFree(ptr);
char *pDstStr = UCS4ToUTF8(pSrc + elt.nativeOffset, elt.nativeSize,
elt.needByteSwapping);
memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
}
else if (elt.needByteSwapping)
{
if (elt.nativeSize == 2)
{
uint16_t val;
memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
if (elt.gdalTypeIsApproxOfNative)
{
CPLAssert(elt.nativeType == DtypeElt::NativeType::IEEEFP);
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Float32);
uint32_t uint32Val = CPLHalfToFloat(CPL_SWAP16(val));
memcpy(pDst + elt.gdalOffset, &uint32Val,
sizeof(uint32Val));
}
else
{
*reinterpret_cast<uint16_t *>(pDst + elt.gdalOffset) =
CPL_SWAP16(val);
}
}
else if (elt.nativeSize == 4)
{
uint32_t val;
memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
*reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset) =
CPL_SWAP32(val);
}
else if (elt.nativeSize == 8)
{
if (elt.nativeType == DtypeElt::NativeType::COMPLEX_IEEEFP)
{
uint32_t val;
memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
*reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset) =
CPL_SWAP32(val);
memcpy(&val, pSrc + elt.nativeOffset + 4, sizeof(val));
*reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset + 4) =
CPL_SWAP32(val);
}
else
{
uint64_t val;
memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
*reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset) =
CPL_SWAP64(val);
}
}
else if (elt.nativeSize == 16)
{
uint64_t val;
memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
*reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset) =
CPL_SWAP64(val);
memcpy(&val, pSrc + elt.nativeOffset + 8, sizeof(val));
*reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset + 8) =
CPL_SWAP64(val);
}
else
{
CPLAssert(false);
}
}
else if (elt.gdalTypeIsApproxOfNative)
{
if (elt.nativeType == DtypeElt::NativeType::SIGNED_INT &&
elt.nativeSize == 1)
{
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Int16);
int16_t intVal =
*reinterpret_cast<const int8_t *>(pSrc + elt.nativeOffset);
memcpy(pDst + elt.gdalOffset, &intVal, sizeof(intVal));
}
else if (elt.nativeType == DtypeElt::NativeType::IEEEFP &&
elt.nativeSize == 2)
{
CPLAssert(elt.gdalType.GetNumericDataType() == GDT_Float32);
uint16_t uint16Val;
memcpy(&uint16Val, pSrc + elt.nativeOffset, sizeof(uint16Val));
uint32_t uint32Val = CPLHalfToFloat(uint16Val);
memcpy(pDst + elt.gdalOffset, &uint32Val, sizeof(uint32Val));
}
else
{
CPLAssert(false);
}
}
else if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII)
{
char *ptr;
char **pDstPtr = reinterpret_cast<char **>(pDst + elt.gdalOffset);
memcpy(&ptr, pDstPtr, sizeof(ptr));
VSIFree(ptr);
char *pDstStr = static_cast<char *>(CPLMalloc(elt.nativeSize + 1));
memcpy(pDstStr, pSrc + elt.nativeOffset, elt.nativeSize);
pDstStr[elt.nativeSize] = 0;
memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
}
else
{
CPLAssert(elt.nativeSize == elt.gdalSize);
memcpy(pDst + elt.gdalOffset, pSrc + elt.nativeOffset,
elt.nativeSize);
}
}
}
/************************************************************************/
/* ZarrArray::LoadTileData() */
/************************************************************************/
bool ZarrArray::LoadTileData(const uint64_t *tileIndices,
bool &bMissingTileOut) const
{
return LoadTileData(tileIndices,
false, // use mutex
m_psDecompressor, m_abyRawTileData, m_abyTmpRawTileData,
m_abyDecodedTileData, bMissingTileOut);
}
bool ZarrArray::LoadTileData(const uint64_t *tileIndices, bool bUseMutex,
const CPLCompressor *psDecompressor,
std::vector<GByte> &abyRawTileData,
std::vector<GByte> &abyTmpRawTileData,
std::vector<GByte> &abyDecodedTileData,
bool &bMissingTileOut) const
{
// This method should NOT modify any ZarrArray member, as it is going to
// be called concurrently from several threads.
// Set those #define to avoid accidental use of some global variables
#define m_abyTmpRawTileData cannot_use_here
#define m_abyRawTileData cannot_use_here
#define m_abyDecodedTileData cannot_use_here
#define m_psDecompressor cannot_use_here
bMissingTileOut = false;
std::string osFilename;
if (m_aoDims.empty())
{
osFilename = "0";
}
else
{
for (size_t i = 0; i < m_aoDims.size(); ++i)
{
if (!osFilename.empty())
osFilename += m_osDimSeparator;
osFilename += std::to_string(tileIndices[i]);
}
}
if (m_nVersion == 2)
{
osFilename = CPLFormFilename(CPLGetDirname(m_osFilename.c_str()),
osFilename.c_str(), nullptr);
}
else
{
std::string osTmp = m_osRootDirectoryName + "/data/root";
if (GetFullName() != "/")
osTmp += GetFullName();
osFilename = osTmp + "/c" + osFilename;
}
// For network file systems, get the streaming version of the filename,
// as we don't need arbitrary seeking in the file
osFilename = VSIFileManager::GetHandler(osFilename.c_str())
->GetStreamingFilename(osFilename);
// First if we have a tile presence cache, check tile presence from it
if (bUseMutex)
m_oMutex.lock();
auto poTilePresenceArray = OpenTilePresenceCache(false);
if (poTilePresenceArray)
{
std::vector<GUInt64> anTileIdx(m_aoDims.size());
const std::vector<size_t> anCount(m_aoDims.size(), 1);
const std::vector<GInt64> anArrayStep(m_aoDims.size(), 0);
const std::vector<GPtrDiff_t> anBufferStride(m_aoDims.size(), 0);
const auto eByteDT = GDALExtendedDataType::Create(GDT_Byte);
for (size_t i = 0; i < m_aoDims.size(); ++i)
{
anTileIdx[i] = static_cast<GUInt64>(tileIndices[i]);
}
GByte byValue = 0;
if (poTilePresenceArray->Read(anTileIdx.data(), anCount.data(),
anArrayStep.data(), anBufferStride.data(),
eByteDT, &byValue) &&
byValue == 0)
{
if (bUseMutex)
m_oMutex.unlock();
CPLDebugOnly(ZARR_DEBUG_KEY, "Tile %s missing (=nodata)",
osFilename.c_str());
bMissingTileOut = true;
return true;
}
}
if (bUseMutex)
m_oMutex.unlock();
VSILFILE *fp = nullptr;
// This is the number of files returned in a S3 directory listing operation
constexpr uint64_t MAX_TILES_ALLOWED_FOR_DIRECTORY_LISTING = 1000;
if ((m_osDimSeparator == "/" &&
m_anBlockSize.back() > MAX_TILES_ALLOWED_FOR_DIRECTORY_LISTING) ||
(m_osDimSeparator != "/" &&
m_nTotalTileCount > MAX_TILES_ALLOWED_FOR_DIRECTORY_LISTING))
{
// Avoid issuing ReadDir() when a lot of files are expected
CPLConfigOptionSetter optionSetter("GDAL_DISABLE_READDIR_ON_OPEN",
"YES", true);
fp = VSIFOpenL(osFilename.c_str(), "rb");
}
else
{
fp = VSIFOpenL(osFilename.c_str(), "rb");
}
if (fp == nullptr)
{
// Missing files are OK and indicate nodata_value
CPLDebugOnly(ZARR_DEBUG_KEY, "Tile %s missing (=nodata)",
osFilename.c_str());
bMissingTileOut = true;
return true;
}
bMissingTileOut = false;
bool bRet = true;
size_t nRawDataSize = abyRawTileData.size();
if (psDecompressor == nullptr)
{
nRawDataSize = VSIFReadL(&abyRawTileData[0], 1, nRawDataSize, fp);
}
else
{
VSIFSeekL(fp, 0, SEEK_END);
const auto nSize = VSIFTellL(fp);
VSIFSeekL(fp, 0, SEEK_SET);
if (nSize > static_cast<vsi_l_offset>(std::numeric_limits<int>::max()))
{
CPLError(CE_Failure, CPLE_AppDefined, "Too large tile %s",
osFilename.c_str());
bRet = false;
}
else
{
std::vector<GByte> abyCompressedData;
try
{
abyCompressedData.resize(static_cast<size_t>(nSize));
}
catch (const std::exception &)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot allocate memory for tile %s",
osFilename.c_str());
bRet = false;
}
if (bRet &&
(abyCompressedData.empty() ||
VSIFReadL(&abyCompressedData[0], 1, abyCompressedData.size(),
fp) != abyCompressedData.size()))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Could not read tile %s correctly",
osFilename.c_str());
bRet = false;
}
else
{
void *out_buffer = &abyRawTileData[0];
if (!psDecompressor->pfnFunc(
abyCompressedData.data(), abyCompressedData.size(),
&out_buffer, &nRawDataSize, nullptr,
psDecompressor->user_data))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Decompression of tile %s failed",
osFilename.c_str());
bRet = false;
}
}
}
}
VSIFCloseL(fp);
if (!bRet)
return false;
for (int i = m_oFiltersArray.Size(); i > 0;)
{
--i;
const auto &oFilter = m_oFiltersArray[i];
const auto osFilterId = oFilter["id"].ToString();
const auto psFilterDecompressor =
CPLGetDecompressor(osFilterId.c_str());
CPLAssert(psFilterDecompressor);
CPLStringList aosOptions;
for (const auto &obj : oFilter.GetChildren())
{
aosOptions.SetNameValue(obj.GetName().c_str(),
obj.ToString().c_str());
}
void *out_buffer = &abyTmpRawTileData[0];
size_t nOutSize = abyTmpRawTileData.size();
if (!psFilterDecompressor->pfnFunc(
abyRawTileData.data(), nRawDataSize, &out_buffer, &nOutSize,
aosOptions.List(), psFilterDecompressor->user_data))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Filter %s for tile %s failed", osFilterId.c_str(),
osFilename.c_str());
return false;
}
nRawDataSize = nOutSize;
std::swap(abyRawTileData, abyTmpRawTileData);
}
if (nRawDataSize != abyRawTileData.size())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Decompressed tile %s has not expected size after filters",
osFilename.c_str());
return false;
}
if (m_bFortranOrder && !m_aoDims.empty())
{
BlockTranspose(abyRawTileData, abyTmpRawTileData, true);
std::swap(abyRawTileData, abyTmpRawTileData);
}
if (!abyDecodedTileData.empty())
{
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
const auto nDTSize = m_oType.GetSize();
const size_t nValues = abyDecodedTileData.size() / nDTSize;
const GByte *pSrc = abyRawTileData.data();
GByte *pDst = &abyDecodedTileData[0];
for (size_t i = 0; i < nValues;
i++, pSrc += nSourceSize, pDst += nDTSize)
{
DecodeSourceElt(m_aoDtypeElts, pSrc, pDst);
}
}
return true;
#undef m_abyTmpRawTileData
#undef m_abyRawTileData
#undef m_abyDecodedTileData
#undef m_psDecompressor
}
/************************************************************************/
/* ZarrArray::IAdviseRead() */
/************************************************************************/
bool ZarrArray::IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
CSLConstList papszOptions) const
{
const size_t nDims = m_aoDims.size();
std::vector<uint64_t> anIndicesCur(nDims);
std::vector<uint64_t> anIndicesMin(nDims);
std::vector<uint64_t> anIndicesMax(nDims);
// Compute min and max tile indices in each dimension, and the total
// nomber of tiles this represents.
uint64_t nReqTiles = 1;
for (size_t i = 0; i < nDims; ++i)
{
anIndicesMin[i] = arrayStartIdx[i] / m_anBlockSize[i];
anIndicesMax[i] = (arrayStartIdx[i] + count[i] - 1) / m_anBlockSize[i];
// Overflow on number of tiles already checked in Create()
nReqTiles *= (anIndicesMax[i] - anIndicesMin[i] + 1);
}
// Find available cache size
const size_t nCacheSize = [papszOptions]()
{
size_t nCacheSizeTmp;
const char *pszCacheSize =
CSLFetchNameValue(papszOptions, "CACHE_SIZE");
if (pszCacheSize)
{
const auto nCacheSizeBig = CPLAtoGIntBig(pszCacheSize);
if (nCacheSizeBig < 0 || static_cast<uint64_t>(nCacheSizeBig) >
std::numeric_limits<size_t>::max() / 2)
{
CPLError(CE_Failure, CPLE_OutOfMemory, "Too big CACHE_SIZE");
return std::numeric_limits<size_t>::max();
}
nCacheSizeTmp = static_cast<size_t>(nCacheSizeBig);
}
else
{
// Arbitrarily take half of remaining cache size
nCacheSizeTmp = static_cast<size_t>(std::min(
static_cast<uint64_t>(
(GDALGetCacheMax64() - GDALGetCacheUsed64()) / 2),
static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 2)));
CPLDebug(ZARR_DEBUG_KEY, "Using implicit CACHE_SIZE=" CPL_FRMT_GUIB,
static_cast<GUIntBig>(nCacheSizeTmp));
}
return nCacheSizeTmp;
}();
if (nCacheSize == std::numeric_limits<size_t>::max())
return false;
// Check that cache size is sufficient to hold all needed tiles.
// Also check that anReqTilesIndices size computation won't overflow.
if (nReqTiles > nCacheSize / std::max(m_nTileSize, nDims))
{
CPLError(
CE_Failure, CPLE_OutOfMemory,
"CACHE_SIZE=" CPL_FRMT_GUIB " is not big enough to cache "
"all needed tiles. "
"At least " CPL_FRMT_GUIB " bytes would be needed",
static_cast<GUIntBig>(nCacheSize),
static_cast<GUIntBig>(nReqTiles * std::max(m_nTileSize, nDims)));
return false;
}
const int nThreadsMax = [papszOptions]()
{
int nThreadsTmp;
const char *pszNumThreads = CSLFetchNameValueDef(
papszOptions, "NUM_THREADS",
CPLGetConfigOption("GDAL_NUM_THREADS", "ALL_CPUS"));
if (EQUAL(pszNumThreads, "ALL_CPUS"))
nThreadsTmp = CPLGetNumCPUs();
else
nThreadsTmp = std::max(1, atoi(pszNumThreads));
if (nThreadsTmp > 1024)
nThreadsTmp = 1024;
return nThreadsTmp;
}();
if (nThreadsMax <= 1)
return true;
CPLDebug(ZARR_DEBUG_KEY, "IAdviseRead(): Using up to %d threads",
nThreadsMax);
const int nThreads = static_cast<int>(
std::min(static_cast<uint64_t>(nThreadsMax), nReqTiles));
m_oMapTileIndexToCachedTile.clear();
std::vector<uint64_t> anReqTilesIndices;
// Overflow checked above
try
{
anReqTilesIndices.resize(static_cast<size_t>(nDims * nReqTiles));
}
catch (const std::bad_alloc &e)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot allocate anReqTilesIndices: %s", e.what());
return false;
}
size_t dimIdx = 0;
size_t nTileIter = 0;
lbl_next_depth:
if (dimIdx == nDims)
{
if (nDims == 2)
{
// optimize in common case
memcpy(&anReqTilesIndices[nTileIter * nDims], anIndicesCur.data(),
sizeof(uint64_t) * 2);
}
else if (nDims == 3)
{
// optimize in common case
memcpy(&anReqTilesIndices[nTileIter * nDims], anIndicesCur.data(),
sizeof(uint64_t) * 3);
}
else
{
memcpy(&anReqTilesIndices[nTileIter * nDims], anIndicesCur.data(),
sizeof(uint64_t) * nDims);
}
nTileIter++;
}
else
{
// This level of loop loops over blocks
anIndicesCur[dimIdx] = anIndicesMin[dimIdx];
while (true)
{
dimIdx++;
goto lbl_next_depth;
lbl_return_to_caller:
dimIdx--;
if (anIndicesCur[dimIdx] == anIndicesMax[dimIdx])
break;
++anIndicesCur[dimIdx];
}
}
if (dimIdx > 0)
goto lbl_return_to_caller;
assert(nTileIter == nReqTiles);
CPLWorkerThreadPool *wtp = GDALGetGlobalThreadPool(nThreadsMax);
if (wtp == nullptr)
return false;
struct JobStruct
{
JobStruct() = default;
JobStruct(const JobStruct &) = delete;
JobStruct &operator=(const JobStruct &) = delete;
JobStruct(JobStruct &&) = default;
JobStruct &operator=(JobStruct &&) = default;
const ZarrArray *poArray = nullptr;
bool *pbGlobalStatus = nullptr;
int *pnRemainingThreads = nullptr;
const std::vector<uint64_t> *panReqTilesIndices = nullptr;
size_t nFirstIdx = 0;
size_t nLastIdxNotIncluded = 0;
};
std::vector<JobStruct> asJobStructs;
bool bGlobalStatus = true;
int nRemainingThreads = nThreads;
// Check for very highly overflow in below loop
assert(static_cast<size_t>(nThreads) <
std::numeric_limits<size_t>::max() / nReqTiles);
// Setup jobs
for (int i = 0; i < nThreads; i++)
{
JobStruct jobStruct;
jobStruct.poArray = this;
jobStruct.pbGlobalStatus = &bGlobalStatus;
jobStruct.pnRemainingThreads = &nRemainingThreads;
jobStruct.panReqTilesIndices = &anReqTilesIndices;
jobStruct.nFirstIdx = static_cast<size_t>(i * nReqTiles / nThreads);
jobStruct.nLastIdxNotIncluded = std::min(
static_cast<size_t>((i + 1) * nReqTiles / nThreads), nTileIter);
asJobStructs.emplace_back(std::move(jobStruct));
}
const auto JobFunc = [](void *pThreadData)
{
const JobStruct *jobStruct =
static_cast<const JobStruct *>(pThreadData);
const auto poArray = jobStruct->poArray;
const auto &aoDims = poArray->m_aoDims;
const size_t l_nDims = poArray->GetDimensionCount();
std::vector<GByte> abyRawTileData;
std::vector<GByte> abyDecodedTileData;
std::vector<GByte> abyTmpRawTileData;
const CPLCompressor *psDecompressor =
CPLGetDecompressor(poArray->m_osDecompressorId.c_str());
for (size_t iReq = jobStruct->nFirstIdx;
iReq < jobStruct->nLastIdxNotIncluded; ++iReq)
{
// Check if we must early exit
{
std::lock_guard<std::mutex> oLock(poArray->m_oMutex);
if (!(*jobStruct->pbGlobalStatus))
return;
}
const uint64_t *tileIndices =
jobStruct->panReqTilesIndices->data() + iReq * l_nDims;
uint64_t nTileIdx = 0;
for (size_t j = 0; j < l_nDims; ++j)
{
if (j > 0)
nTileIdx *= aoDims[j - 1]->GetSize();
nTileIdx += tileIndices[j];
}
if (!poArray->AllocateWorkingBuffers(
abyRawTileData, abyTmpRawTileData, abyDecodedTileData))
{
std::lock_guard<std::mutex> oLock(poArray->m_oMutex);
*jobStruct->pbGlobalStatus = false;
break;
}
bool bIsEmpty = false;
bool success = poArray->LoadTileData(tileIndices,
true, // use mutex
psDecompressor, abyRawTileData,
abyTmpRawTileData,
abyDecodedTileData, bIsEmpty);
std::lock_guard<std::mutex> oLock(poArray->m_oMutex);
if (!success)
{
*jobStruct->pbGlobalStatus = false;
break;
}
CachedTile cachedTile;
if (!bIsEmpty)
{
if (!abyDecodedTileData.empty())
std::swap(cachedTile.abyDecoded, abyDecodedTileData);
else
std::swap(cachedTile.abyDecoded, abyRawTileData);
}
poArray->m_oMapTileIndexToCachedTile[nTileIdx] =
std::move(cachedTile);
}
std::lock_guard<std::mutex> oLock(poArray->m_oMutex);
(*jobStruct->pnRemainingThreads)--;
};
// Start jobs
for (int i = 0; i < nThreads; i++)
{
if (!wtp->SubmitJob(JobFunc, &asJobStructs[i]))
{
std::lock_guard<std::mutex> oLock(m_oMutex);
bGlobalStatus = false;
nRemainingThreads = i;
break;
}
}
// Wait for all jobs to be finished
while (true)
{
{
std::lock_guard<std::mutex> oLock(m_oMutex);
if (nRemainingThreads == 0)
break;
}
wtp->WaitEvent();
}
return bGlobalStatus;
}
/************************************************************************/
/* ZarrArray::IRead() */
/************************************************************************/
bool ZarrArray::IRead(const GUInt64 *arrayStartIdx, const size_t *count,
const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
const GDALExtendedDataType &bufferDataType,
void *pDstBuffer) const
{
if (!AllocateWorkingBuffers())
return false;
// Need to be kept in top-level scope
std::vector<GUInt64> arrayStartIdxMod;
std::vector<GInt64> arrayStepMod;
std::vector<GPtrDiff_t> bufferStrideMod;
const size_t nDims = m_aoDims.size();
bool negativeStep = false;
for (size_t i = 0; i < nDims; ++i)
{
if (arrayStep[i] < 0)
{
negativeStep = true;
break;
}
}
// const auto eBufferDT = bufferDataType.GetNumericDataType();
const auto nBufferDTSize = static_cast<int>(bufferDataType.GetSize());
// Make sure that arrayStep[i] are positive for sake of simplicity
if (negativeStep)
{
arrayStartIdxMod.resize(nDims);
arrayStepMod.resize(nDims);
bufferStrideMod.resize(nDims);
for (size_t i = 0; i < nDims; ++i)
{
if (arrayStep[i] < 0)
{
arrayStartIdxMod[i] =
arrayStartIdx[i] - (count[i] - 1) * (-arrayStep[i]);
arrayStepMod[i] = -arrayStep[i];
bufferStrideMod[i] = -bufferStride[i];
pDstBuffer =
static_cast<GByte *>(pDstBuffer) +
bufferStride[i] *
static_cast<GPtrDiff_t>(nBufferDTSize * (count[i] - 1));
}
else
{
arrayStartIdxMod[i] = arrayStartIdx[i];
arrayStepMod[i] = arrayStep[i];
bufferStrideMod[i] = bufferStride[i];
}
}
arrayStartIdx = arrayStartIdxMod.data();
arrayStep = arrayStepMod.data();
bufferStride = bufferStrideMod.data();
}
std::vector<uint64_t> indicesOuterLoop(nDims + 1);
std::vector<GByte *> dstPtrStackOuterLoop(nDims + 1);
std::vector<uint64_t> indicesInnerLoop(nDims + 1);
std::vector<GByte *> dstPtrStackInnerLoop(nDims + 1);
std::vector<GPtrDiff_t> dstBufferStrideBytes;
for (size_t i = 0; i < nDims; ++i)
{
dstBufferStrideBytes.push_back(bufferStride[i] *
static_cast<GPtrDiff_t>(nBufferDTSize));
}
dstBufferStrideBytes.push_back(0);
const auto nDTSize = m_oType.GetSize();
std::vector<uint64_t> tileIndices(nDims);
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
std::vector<size_t> countInnerLoopInit(nDims + 1, 1);
std::vector<size_t> countInnerLoop(nDims);
const bool bBothAreNumericDT = m_oType.GetClass() == GEDTC_NUMERIC &&
bufferDataType.GetClass() == GEDTC_NUMERIC;
const bool bSameNumericDT =
bBothAreNumericDT &&
m_oType.GetNumericDataType() == bufferDataType.GetNumericDataType();
const auto nSameDTSize = bSameNumericDT ? m_oType.GetSize() : 0;
const bool bSameCompoundAndNoDynamicMem =
m_oType.GetClass() == GEDTC_COMPOUND && m_oType == bufferDataType &&
!m_oType.NeedsFreeDynamicMemory();
std::vector<GByte> abyTargetNoData;
bool bNoDataIsZero = false;
size_t dimIdx = 0;
dstPtrStackOuterLoop[0] = static_cast<GByte *>(pDstBuffer);
lbl_next_depth:
if (dimIdx == nDims)
{
size_t dimIdxSubLoop = 0;
dstPtrStackInnerLoop[0] = dstPtrStackOuterLoop[nDims];
bool bEmptyTile = false;
const GByte *pabySrcTile = m_abyDecodedTileData.empty()
? m_abyRawTileData.data()
: m_abyDecodedTileData.data();
bool bMatchFoundInMapTileIndexToCachedTile = false;
// Use cache built by IAdviseRead() if possible
if (!m_oMapTileIndexToCachedTile.empty())
{
uint64_t nTileIdx = 0;
for (size_t j = 0; j < nDims; ++j)
{
if (j > 0)
nTileIdx *= m_aoDims[j - 1]->GetSize();
nTileIdx += tileIndices[j];
}
const auto oIter = m_oMapTileIndexToCachedTile.find(nTileIdx);
if (oIter != m_oMapTileIndexToCachedTile.end())
{
bMatchFoundInMapTileIndexToCachedTile = true;
if (oIter->second.abyDecoded.empty())
{
bEmptyTile = true;
}
else
{
pabySrcTile = oIter->second.abyDecoded.data();
}
}
else
{
CPLDebugOnly(ZARR_DEBUG_KEY,
"Cache miss for tile " CPL_FRMT_GUIB,
static_cast<GUIntBig>(nTileIdx));
}
}
if (!bMatchFoundInMapTileIndexToCachedTile)
{
if (!tileIndices.empty() && tileIndices == m_anCachedTiledIndices)
{
if (!m_bCachedTiledValid)
return false;
bEmptyTile = m_bCachedTiledEmpty;
}
else
{
if (!FlushDirtyTile())
return false;
m_anCachedTiledIndices = tileIndices;
m_bCachedTiledValid =
LoadTileData(tileIndices.data(), bEmptyTile);
if (!m_bCachedTiledValid)
{
return false;
}
m_bCachedTiledEmpty = bEmptyTile;
}
pabySrcTile = m_abyDecodedTileData.empty()
? m_abyRawTileData.data()
: m_abyDecodedTileData.data();
}
const size_t nSrcDTSize =
m_abyDecodedTileData.empty() ? nSourceSize : nDTSize;
for (size_t i = 0; i < nDims; ++i)
{
countInnerLoopInit[i] = 1;
if (arrayStep[i] != 0)
{
const auto nextBlockIdx =
std::min((1 + indicesOuterLoop[i] / m_anBlockSize[i]) *
m_anBlockSize[i],
arrayStartIdx[i] + count[i] * arrayStep[i]);
countInnerLoopInit[i] = static_cast<size_t>(
(nextBlockIdx - indicesOuterLoop[i] + arrayStep[i] - 1) /
arrayStep[i]);
}
}
if (bEmptyTile && bBothAreNumericDT && abyTargetNoData.empty())
{
abyTargetNoData.resize(nBufferDTSize);
if (m_pabyNoData)
{
GDALExtendedDataType::CopyValue(
m_pabyNoData, m_oType, &abyTargetNoData[0], bufferDataType);
bNoDataIsZero = true;
for (size_t i = 0; i < abyTargetNoData.size(); ++i)
{
if (abyTargetNoData[i] != 0)
bNoDataIsZero = false;
}
}
else
{
bNoDataIsZero = true;
GByte zero = 0;
GDALCopyWords(&zero, GDT_Byte, 0, &abyTargetNoData[0],
bufferDataType.GetNumericDataType(), 0, 1);
}
}
lbl_next_depth_inner_loop:
if (nDims == 0 || dimIdxSubLoop == nDims - 1)
{
indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
void *dst_ptr = dstPtrStackInnerLoop[dimIdxSubLoop];
if (m_bUseOptimizedCodePaths && bEmptyTile && bBothAreNumericDT &&
bNoDataIsZero &&
nBufferDTSize == dstBufferStrideBytes[dimIdxSubLoop])
{
memset(dst_ptr, 0,
nBufferDTSize * countInnerLoopInit[dimIdxSubLoop]);
goto end_inner_loop;
}
else if (m_bUseOptimizedCodePaths && bEmptyTile &&
!abyTargetNoData.empty() && bBothAreNumericDT &&
dstBufferStrideBytes[dimIdxSubLoop] <
std::numeric_limits<int>::max())
{
GDALCopyWords64(
abyTargetNoData.data(), bufferDataType.GetNumericDataType(),
0, dst_ptr, bufferDataType.GetNumericDataType(),
static_cast<int>(dstBufferStrideBytes[dimIdxSubLoop]),
static_cast<GPtrDiff_t>(countInnerLoopInit[dimIdxSubLoop]));
goto end_inner_loop;
}
else if (bEmptyTile)
{
for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
++i, dst_ptr = static_cast<uint8_t *>(dst_ptr) +
dstBufferStrideBytes[dimIdxSubLoop])
{
if (bNoDataIsZero)
{
if (nBufferDTSize == 1)
{
*static_cast<uint8_t *>(dst_ptr) = 0;
}
else if (nBufferDTSize == 2)
{
*static_cast<uint16_t *>(dst_ptr) = 0;
}
else if (nBufferDTSize == 4)
{
*static_cast<uint32_t *>(dst_ptr) = 0;
}
else if (nBufferDTSize == 8)
{
*static_cast<uint64_t *>(dst_ptr) = 0;
}
else if (nBufferDTSize == 16)
{
static_cast<uint64_t *>(dst_ptr)[0] = 0;
static_cast<uint64_t *>(dst_ptr)[1] = 0;
}
else
{
CPLAssert(false);
}
}
else if (m_pabyNoData)
{
if (bBothAreNumericDT)
{
const void *src_ptr_v = abyTargetNoData.data();
if (nBufferDTSize == 1)
*static_cast<uint8_t *>(dst_ptr) =
*static_cast<const uint8_t *>(src_ptr_v);
else if (nBufferDTSize == 2)
*static_cast<uint16_t *>(dst_ptr) =
*static_cast<const uint16_t *>(src_ptr_v);
else if (nBufferDTSize == 4)
*static_cast<uint32_t *>(dst_ptr) =
*static_cast<const uint32_t *>(src_ptr_v);
else if (nBufferDTSize == 8)
*static_cast<uint64_t *>(dst_ptr) =
*static_cast<const uint64_t *>(src_ptr_v);
else if (nBufferDTSize == 16)
{
static_cast<uint64_t *>(dst_ptr)[0] =
static_cast<const uint64_t *>(src_ptr_v)[0];
static_cast<uint64_t *>(dst_ptr)[1] =
static_cast<const uint64_t *>(src_ptr_v)[1];
}
else
{
CPLAssert(false);
}
}
else
{
GDALExtendedDataType::CopyValue(
m_pabyNoData, m_oType, dst_ptr, bufferDataType);
}
}
else
{
memset(dst_ptr, 0, nBufferDTSize);
}
}
goto end_inner_loop;
}
size_t nOffset = 0;
for (size_t i = 0; i < nDims; i++)
{
nOffset = static_cast<size_t>(
nOffset * m_anBlockSize[i] +
(indicesInnerLoop[i] - tileIndices[i] * m_anBlockSize[i]));
}
const GByte *src_ptr = pabySrcTile + nOffset * nSrcDTSize;
const auto step = nDims == 0 ? 0 : arrayStep[dimIdxSubLoop];
if (m_bUseOptimizedCodePaths && bBothAreNumericDT &&
step <= static_cast<GIntBig>(std::numeric_limits<int>::max() /
nDTSize) &&
dstBufferStrideBytes[dimIdxSubLoop] <=
std::numeric_limits<int>::max())
{
GDALCopyWords64(
src_ptr, m_oType.GetNumericDataType(),
static_cast<int>(step * nDTSize), dst_ptr,
bufferDataType.GetNumericDataType(),
static_cast<int>(dstBufferStrideBytes[dimIdxSubLoop]),
static_cast<GPtrDiff_t>(countInnerLoopInit[dimIdxSubLoop]));
goto end_inner_loop;
}
for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
++i, src_ptr += step * nSrcDTSize,
dst_ptr = static_cast<uint8_t *>(dst_ptr) +
dstBufferStrideBytes[dimIdxSubLoop])
{
if (bSameNumericDT)
{
const void *src_ptr_v = src_ptr;
if (nSameDTSize == 1)
*static_cast<uint8_t *>(dst_ptr) =
*static_cast<const uint8_t *>(src_ptr_v);
else if (nSameDTSize == 2)
{
*static_cast<uint16_t *>(dst_ptr) =
*static_cast<const uint16_t *>(src_ptr_v);
}
else if (nSameDTSize == 4)
{
*static_cast<uint32_t *>(dst_ptr) =
*static_cast<const uint32_t *>(src_ptr_v);
}
else if (nSameDTSize == 8)
{
*static_cast<uint64_t *>(dst_ptr) =
*static_cast<const uint64_t *>(src_ptr_v);
}
else if (nSameDTSize == 16)
{
static_cast<uint64_t *>(dst_ptr)[0] =
static_cast<const uint64_t *>(src_ptr_v)[0];
static_cast<uint64_t *>(dst_ptr)[1] =
static_cast<const uint64_t *>(src_ptr_v)[1];
}
else
{
CPLAssert(false);
}
}
else if (bSameCompoundAndNoDynamicMem)
{
memcpy(dst_ptr, src_ptr, nDTSize);
}
else if (m_oType.GetClass() == GEDTC_STRING)
{
if (m_aoDtypeElts.back().nativeType ==
DtypeElt::NativeType::STRING_UNICODE)
{
char *pDstStr =
UCS4ToUTF8(src_ptr, nSourceSize,
m_aoDtypeElts.back().needByteSwapping);
char **pDstPtr = static_cast<char **>(dst_ptr);
memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
}
else
{
char *pDstStr =
static_cast<char *>(CPLMalloc(nSourceSize + 1));
memcpy(pDstStr, src_ptr, nSourceSize);
pDstStr[nSourceSize] = 0;
char **pDstPtr = static_cast<char **>(dst_ptr);
memcpy(pDstPtr, &pDstStr, sizeof(char *));
}
}
else
{
GDALExtendedDataType::CopyValue(src_ptr, m_oType, dst_ptr,
bufferDataType);
}
}
}
else
{
// This level of loop loops over individual samples, within a
// block
indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
countInnerLoop[dimIdxSubLoop] = countInnerLoopInit[dimIdxSubLoop];
while (true)
{
dimIdxSubLoop++;
dstPtrStackInnerLoop[dimIdxSubLoop] =
dstPtrStackInnerLoop[dimIdxSubLoop - 1];
goto lbl_next_depth_inner_loop;
lbl_return_to_caller_inner_loop:
dimIdxSubLoop--;
--countInnerLoop[dimIdxSubLoop];
if (countInnerLoop[dimIdxSubLoop] == 0)
{
break;
}
indicesInnerLoop[dimIdxSubLoop] += arrayStep[dimIdxSubLoop];
dstPtrStackInnerLoop[dimIdxSubLoop] +=
dstBufferStrideBytes[dimIdxSubLoop];
}
}
end_inner_loop:
if (dimIdxSubLoop > 0)
goto lbl_return_to_caller_inner_loop;
}
else
{
// This level of loop loops over blocks
indicesOuterLoop[dimIdx] = arrayStartIdx[dimIdx];
tileIndices[dimIdx] = indicesOuterLoop[dimIdx] / m_anBlockSize[dimIdx];
while (true)
{
dimIdx++;
dstPtrStackOuterLoop[dimIdx] = dstPtrStackOuterLoop[dimIdx - 1];
goto lbl_next_depth;
lbl_return_to_caller:
dimIdx--;
if (count[dimIdx] == 1 || arrayStep[dimIdx] == 0)
break;
size_t nIncr;
if (static_cast<GUInt64>(arrayStep[dimIdx]) < m_anBlockSize[dimIdx])
{
// Compute index at next block boundary
auto newIdx =
indicesOuterLoop[dimIdx] +
(m_anBlockSize[dimIdx] -
(indicesOuterLoop[dimIdx] % m_anBlockSize[dimIdx]));
// And round up compared to arrayStartIdx, arrayStep
nIncr = static_cast<size_t>((newIdx - indicesOuterLoop[dimIdx] +
arrayStep[dimIdx] - 1) /
arrayStep[dimIdx]);
}
else
{
nIncr = 1;
}
indicesOuterLoop[dimIdx] += nIncr * arrayStep[dimIdx];
if (indicesOuterLoop[dimIdx] >
arrayStartIdx[dimIdx] + (count[dimIdx] - 1) * arrayStep[dimIdx])
break;
dstPtrStackOuterLoop[dimIdx] +=
bufferStride[dimIdx] *
static_cast<GPtrDiff_t>(nIncr * nBufferDTSize);
tileIndices[dimIdx] =
indicesOuterLoop[dimIdx] / m_anBlockSize[dimIdx];
}
}
if (dimIdx > 0)
goto lbl_return_to_caller;
return true;
}
/************************************************************************/
/* ZarrArray::FlushDirtyTile() */
/************************************************************************/
bool ZarrArray::FlushDirtyTile() const
{
if (!m_bDirtyTile)
return true;
m_bDirtyTile = false;
std::string osFilename;
if (m_anCachedTiledIndices.empty())
{
osFilename = "0";
}
else
{
for (const auto index : m_anCachedTiledIndices)
{
if (!osFilename.empty())
osFilename += m_osDimSeparator;
osFilename += std::to_string(index);
}
}
if (m_nVersion == 2)
{
osFilename = CPLFormFilename(CPLGetDirname(m_osFilename.c_str()),
osFilename.c_str(), nullptr);
}
else
{
std::string osTmp = m_osRootDirectoryName + "/data/root";
if (GetFullName() != "/")
osTmp += GetFullName();
osFilename = osTmp + "/c" + osFilename;
}
const size_t nSourceSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
auto &abyTile =
m_abyDecodedTileData.empty() ? m_abyRawTileData : m_abyDecodedTileData;
bool bEmptyTile = false;
if (m_pabyNoData == nullptr || (m_oType.GetClass() == GEDTC_NUMERIC &&
GetNoDataValueAsDouble() == 0.0))
{
const size_t nBytes = abyTile.size();
size_t i = 0;
bEmptyTile = true;
for (; i + (sizeof(size_t) - 1) < nBytes; i += sizeof(size_t))
{
if (*reinterpret_cast<const size_t *>(abyTile.data() + i) != 0)
{
bEmptyTile = false;
break;
}
}
if (bEmptyTile)
{
for (; i < nBytes; ++i)
{
if (abyTile[i] != 0)
{
bEmptyTile = false;
break;
}
}
}
}
else if (m_oType.GetClass() == GEDTC_NUMERIC &&
!GDALDataTypeIsComplex(m_oType.GetNumericDataType()))
{
const int nDTSize = static_cast<int>(m_oType.GetSize());
const size_t nElts = abyTile.size() / nDTSize;
const auto eDT = m_oType.GetNumericDataType();
bEmptyTile = GDALBufferHasOnlyNoData(
abyTile.data(), GetNoDataValueAsDouble(),
nElts, // nWidth
1, // nHeight
nElts, // nLineStride
1, // nComponents
nDTSize * 8, // nBitsPerSample
GDALDataTypeIsInteger(eDT)
? (GDALDataTypeIsSigned(eDT) ? GSF_SIGNED_INT
: GSF_UNSIGNED_INT)
: GSF_FLOATING_POINT);
}
if (bEmptyTile)
{
m_bCachedTiledEmpty = true;
VSIStatBufL sStat;
if (VSIStatL(osFilename.c_str(), &sStat) == 0)
{
CPLDebugOnly(ZARR_DEBUG_KEY,
"Deleting tile %s that has now empty content",
osFilename.c_str());
return VSIUnlink(osFilename.c_str()) == 0;
}
return true;
}
if (!m_abyDecodedTileData.empty())
{
const size_t nDTSize = m_oType.GetSize();
const size_t nValues = m_abyDecodedTileData.size() / nDTSize;
GByte *pDst = &m_abyRawTileData[0];
const GByte *pSrc = m_abyDecodedTileData.data();
for (size_t i = 0; i < nValues;
i++, pDst += nSourceSize, pSrc += nDTSize)
{
EncodeElt(m_aoDtypeElts, pSrc, pDst);
}
}
if (m_bFortranOrder && !m_aoDims.empty())
{
BlockTranspose(m_abyRawTileData, m_abyTmpRawTileData, false);
std::swap(m_abyRawTileData, m_abyTmpRawTileData);
}
size_t nRawDataSize = m_abyRawTileData.size();
for (const auto &oFilter : m_oFiltersArray)
{
const auto osFilterId = oFilter["id"].ToString();
const auto psFilterCompressor = CPLGetCompressor(osFilterId.c_str());
CPLAssert(psFilterCompressor);
CPLStringList aosOptions;
for (const auto &obj : oFilter.GetChildren())
{
aosOptions.SetNameValue(obj.GetName().c_str(),
obj.ToString().c_str());
}
void *out_buffer = &m_abyTmpRawTileData[0];
size_t nOutSize = m_abyTmpRawTileData.size();
if (!psFilterCompressor->pfnFunc(
m_abyRawTileData.data(), nRawDataSize, &out_buffer, &nOutSize,
aosOptions.List(), psFilterCompressor->user_data))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Filter %s for tile %s failed", osFilterId.c_str(),
osFilename.c_str());
return false;
}
nRawDataSize = nOutSize;
std::swap(m_abyRawTileData, m_abyTmpRawTileData);
}
if (m_osDimSeparator == "/")
{
std::string osDir = CPLGetDirname(osFilename.c_str());
VSIStatBufL sStat;
if (VSIStatL(osDir.c_str(), &sStat) != 0)
{
if (VSIMkdirRecursive(osDir.c_str(), 0755) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot create directory %s", osDir.c_str());
return false;
}
}
}
VSILFILE *fp = VSIFOpenL(osFilename.c_str(), "wb");
if (fp == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot create tile %s",
osFilename.c_str());
return false;
}
bool bRet = true;
if (m_psCompressor == nullptr)
{
if (VSIFWriteL(m_abyRawTileData.data(), 1, nRawDataSize, fp) !=
nRawDataSize)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Could not write tile %s correctly", osFilename.c_str());
bRet = false;
}
}
else
{
std::vector<GByte> abyCompressedData;
try
{
constexpr size_t MIN_BUF_SIZE = 64; // somewhat arbitrary
abyCompressedData.resize(static_cast<size_t>(
MIN_BUF_SIZE + nRawDataSize + nRawDataSize / 3));
}
catch (const std::exception &)
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot allocate memory for tile %s", osFilename.c_str());
bRet = false;
}
if (bRet)
{
void *out_buffer = &abyCompressedData[0];
size_t out_size = abyCompressedData.size();
CPLStringList aosOptions;
const auto compressorConfig =
m_nVersion == 2 ? m_oCompressorJSonV2
: m_oCompressorJSonV3["configuration"];
for (const auto &obj : compressorConfig.GetChildren())
{
aosOptions.SetNameValue(obj.GetName().c_str(),
obj.ToString().c_str());
}
if (EQUAL(m_psCompressor->pszId, "blosc") &&
m_oType.GetClass() == GEDTC_NUMERIC)
{
aosOptions.SetNameValue(
"TYPESIZE",
CPLSPrintf("%d", GDALGetDataTypeSizeBytes(
GDALGetNonComplexDataType(
m_oType.GetNumericDataType()))));
}
if (!m_psCompressor->pfnFunc(
m_abyRawTileData.data(), nRawDataSize, &out_buffer,
&out_size, aosOptions.List(), m_psCompressor->user_data))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Compression of tile %s failed", osFilename.c_str());
bRet = false;
}
abyCompressedData.resize(out_size);
}
if (bRet &&
VSIFWriteL(abyCompressedData.data(), 1, abyCompressedData.size(),
fp) != abyCompressedData.size())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Could not write tile %s correctly", osFilename.c_str());
bRet = false;
}
}
VSIFCloseL(fp);
return bRet;
}
/************************************************************************/
/* ZarrArray::IRead() */
/************************************************************************/
bool ZarrArray::IWrite(const GUInt64 *arrayStartIdx, const size_t *count,
const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
const GDALExtendedDataType &bufferDataType,
const void *pSrcBuffer)
{
if (!AllocateWorkingBuffers())
return false;
m_oMapTileIndexToCachedTile.clear();
// Need to be kept in top-level scope
std::vector<GUInt64> arrayStartIdxMod;
std::vector<GInt64> arrayStepMod;
std::vector<GPtrDiff_t> bufferStrideMod;
const size_t nDims = m_aoDims.size();
bool negativeStep = false;
for (size_t i = 0; i < nDims; ++i)
{
if (arrayStep[i] < 0)
{
negativeStep = true;
break;
}
}
const auto nBufferDTSize = static_cast<int>(bufferDataType.GetSize());
// Make sure that arrayStep[i] are positive for sake of simplicity
if (negativeStep)
{
arrayStartIdxMod.resize(nDims);
arrayStepMod.resize(nDims);
bufferStrideMod.resize(nDims);
for (size_t i = 0; i < nDims; ++i)
{
if (arrayStep[i] < 0)
{
arrayStartIdxMod[i] =
arrayStartIdx[i] - (count[i] - 1) * (-arrayStep[i]);
arrayStepMod[i] = -arrayStep[i];
bufferStrideMod[i] = -bufferStride[i];
pSrcBuffer =
static_cast<const GByte *>(pSrcBuffer) +
bufferStride[i] *
static_cast<GPtrDiff_t>(nBufferDTSize * (count[i] - 1));
}
else
{
arrayStartIdxMod[i] = arrayStartIdx[i];
arrayStepMod[i] = arrayStep[i];
bufferStrideMod[i] = bufferStride[i];
}
}
arrayStartIdx = arrayStartIdxMod.data();
arrayStep = arrayStepMod.data();
bufferStride = bufferStrideMod.data();
}
std::vector<uint64_t> indicesOuterLoop(nDims + 1);
std::vector<const GByte *> srcPtrStackOuterLoop(nDims + 1);
std::vector<uint64_t> indicesInnerLoop(nDims + 1);
std::vector<const GByte *> srcPtrStackInnerLoop(nDims + 1);
std::vector<GPtrDiff_t> srcBufferStrideBytes;
for (size_t i = 0; i < nDims; ++i)
{
srcBufferStrideBytes.push_back(bufferStride[i] *
static_cast<GPtrDiff_t>(nBufferDTSize));
}
srcBufferStrideBytes.push_back(0);
const auto nDTSize = m_oType.GetSize();
std::vector<uint64_t> tileIndices(nDims);
const size_t nNativeSize =
m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
std::vector<size_t> countInnerLoopInit(nDims + 1, 1);
std::vector<size_t> countInnerLoop(nDims);
const bool bBothAreNumericDT = m_oType.GetClass() == GEDTC_NUMERIC &&
bufferDataType.GetClass() == GEDTC_NUMERIC;
const bool bSameNumericDT =
bBothAreNumericDT &&
m_oType.GetNumericDataType() == bufferDataType.GetNumericDataType();
const auto nSameDTSize = bSameNumericDT ? m_oType.GetSize() : 0;
const bool bSameCompoundAndNoDynamicMem =
m_oType.GetClass() == GEDTC_COMPOUND && m_oType == bufferDataType &&
!m_oType.NeedsFreeDynamicMemory();
size_t dimIdx = 0;
srcPtrStackOuterLoop[0] = static_cast<const GByte *>(pSrcBuffer);
lbl_next_depth:
if (dimIdx == nDims)
{
bool bWriteWholeTile = true;
bool bPartialTile = false;
for (size_t i = 0; i < nDims; ++i)
{
countInnerLoopInit[i] = 1;
if (arrayStep[i] != 0)
{
const auto nextBlockIdx =
std::min((1 + indicesOuterLoop[i] / m_anBlockSize[i]) *
m_anBlockSize[i],
arrayStartIdx[i] + count[i] * arrayStep[i]);
countInnerLoopInit[i] = static_cast<size_t>(
(nextBlockIdx - indicesOuterLoop[i] + arrayStep[i] - 1) /
arrayStep[i]);
}
if (bWriteWholeTile)
{
const bool bWholePartialTileThisDim =
indicesOuterLoop[i] + countInnerLoopInit[i] ==
m_aoDims[i]->GetSize();
bWriteWholeTile = (countInnerLoopInit[i] == m_anBlockSize[i] ||
bWholePartialTileThisDim);
if (bWholePartialTileThisDim)
{
bPartialTile = true;
}
}
}
size_t dimIdxSubLoop = 0;
srcPtrStackInnerLoop[0] = srcPtrStackOuterLoop[nDims];
const size_t nCacheDTSize =
m_abyDecodedTileData.empty() ? nNativeSize : nDTSize;
auto &abyTile = m_abyDecodedTileData.empty() ? m_abyRawTileData
: m_abyDecodedTileData;
if (!tileIndices.empty() && tileIndices == m_anCachedTiledIndices)
{
if (!m_bCachedTiledValid)
return false;
}
else
{
if (!FlushDirtyTile())
return false;
m_anCachedTiledIndices = tileIndices;
m_bCachedTiledValid = true;
if (bWriteWholeTile)
{
if (bPartialTile)
{
DeallocateDecodedTileData();
memset(&abyTile[0], 0, abyTile.size());
}
}
else
{
// If we don't write the whole tile, we need to fetch a
// potentially existing one.
bool bEmptyTile = false;
m_bCachedTiledValid =
LoadTileData(tileIndices.data(), bEmptyTile);
if (!m_bCachedTiledValid)
{
return false;
}
if (bEmptyTile)
{
DeallocateDecodedTileData();
if (m_pabyNoData == nullptr)
{
memset(&abyTile[0], 0, abyTile.size());
}
else
{
const size_t nElts = abyTile.size() / nCacheDTSize;
GByte *dstPtr = &abyTile[0];
if (m_oType.GetClass() == GEDTC_NUMERIC)
{
GDALCopyWords64(
m_pabyNoData, m_oType.GetNumericDataType(), 0,
dstPtr, m_oType.GetNumericDataType(),
static_cast<int>(m_oType.GetSize()),
static_cast<GPtrDiff_t>(nElts));
}
else
{
for (size_t i = 0; i < nElts; ++i)
{
GDALExtendedDataType::CopyValue(
m_pabyNoData, m_oType, dstPtr, m_oType);
dstPtr += nCacheDTSize;
}
}
}
}
}
}
m_bDirtyTile = true;
m_bCachedTiledEmpty = false;
GByte *pabyTile = &abyTile[0];
lbl_next_depth_inner_loop:
if (nDims == 0 || dimIdxSubLoop == nDims - 1)
{
indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
const void *src_ptr = srcPtrStackInnerLoop[dimIdxSubLoop];
size_t nOffset = 0;
for (size_t i = 0; i < nDims; i++)
{
nOffset = static_cast<size_t>(
nOffset * m_anBlockSize[i] +
(indicesInnerLoop[i] - tileIndices[i] * m_anBlockSize[i]));
}
GByte *dst_ptr = pabyTile + nOffset * nCacheDTSize;
const auto step = nDims == 0 ? 0 : arrayStep[dimIdxSubLoop];
if (m_bUseOptimizedCodePaths && bBothAreNumericDT &&
step <= static_cast<GIntBig>(std::numeric_limits<int>::max() /
nDTSize) &&
srcBufferStrideBytes[dimIdxSubLoop] <=
std::numeric_limits<int>::max())
{
GDALCopyWords64(
src_ptr, bufferDataType.GetNumericDataType(),
static_cast<int>(srcBufferStrideBytes[dimIdxSubLoop]),
dst_ptr, m_oType.GetNumericDataType(),
static_cast<int>(step * nDTSize),
static_cast<GPtrDiff_t>(countInnerLoopInit[dimIdxSubLoop]));
goto end_inner_loop;
}
for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
++i, dst_ptr += step * nCacheDTSize,
src_ptr = static_cast<const uint8_t *>(src_ptr) +
srcBufferStrideBytes[dimIdxSubLoop])
{
if (bSameNumericDT)
{
void *dst_ptr_v = dst_ptr;
if (nSameDTSize == 1)
*static_cast<uint8_t *>(dst_ptr_v) =
*static_cast<const uint8_t *>(src_ptr);
else if (nSameDTSize == 2)
{
*static_cast<uint16_t *>(dst_ptr_v) =
*static_cast<const uint16_t *>(src_ptr);
}
else if (nSameDTSize == 4)
{
*static_cast<uint32_t *>(dst_ptr_v) =
*static_cast<const uint32_t *>(src_ptr);
}
else if (nSameDTSize == 8)
{
*static_cast<uint64_t *>(dst_ptr_v) =
*static_cast<const uint64_t *>(src_ptr);
}
else if (nSameDTSize == 16)
{
static_cast<uint64_t *>(dst_ptr_v)[0] =
static_cast<const uint64_t *>(src_ptr)[0];
static_cast<uint64_t *>(dst_ptr_v)[1] =
static_cast<const uint64_t *>(src_ptr)[1];
}
else
{
CPLAssert(false);
}
}
else if (bSameCompoundAndNoDynamicMem)
{
memcpy(dst_ptr, src_ptr, nDTSize);
}
else if (m_oType.GetClass() == GEDTC_STRING)
{
const char *pSrcStr =
*static_cast<const char *const *>(src_ptr);
if (pSrcStr)
{
const size_t nLen = strlen(pSrcStr);
if (m_aoDtypeElts.back().nativeType ==
DtypeElt::NativeType::STRING_UNICODE)
{
try
{
const auto ucs4 = UTF8ToUCS4(
pSrcStr,
m_aoDtypeElts.back().needByteSwapping);
const auto ucs4Len = ucs4.size();
memcpy(dst_ptr, ucs4.data(),
std::min(ucs4Len, nNativeSize));
if (ucs4Len > nNativeSize)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Too long string truncated");
}
else if (ucs4Len < nNativeSize)
{
memset(dst_ptr + ucs4Len, 0,
nNativeSize - ucs4Len);
}
}
catch (const std::exception &)
{
memset(dst_ptr, 0, nNativeSize);
}
}
else
{
memcpy(dst_ptr, pSrcStr,
std::min(nLen, nNativeSize));
if (nLen < nNativeSize)
memset(dst_ptr + nLen, 0, nNativeSize - nLen);
}
}
else
{
memset(dst_ptr, 0, nNativeSize);
}
}
else
{
if (m_oType.NeedsFreeDynamicMemory())
m_oType.FreeDynamicMemory(dst_ptr);
GDALExtendedDataType::CopyValue(src_ptr, bufferDataType,
dst_ptr, m_oType);
}
}
}
else
{
// This level of loop loops over individual samples, within a
// block
indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
countInnerLoop[dimIdxSubLoop] = countInnerLoopInit[dimIdxSubLoop];
while (true)
{
dimIdxSubLoop++;
srcPtrStackInnerLoop[dimIdxSubLoop] =
srcPtrStackInnerLoop[dimIdxSubLoop - 1];
goto lbl_next_depth_inner_loop;
lbl_return_to_caller_inner_loop:
dimIdxSubLoop--;
--countInnerLoop[dimIdxSubLoop];
if (countInnerLoop[dimIdxSubLoop] == 0)
{
break;
}
indicesInnerLoop[dimIdxSubLoop] += arrayStep[dimIdxSubLoop];
srcPtrStackInnerLoop[dimIdxSubLoop] +=
srcBufferStrideBytes[dimIdxSubLoop];
}
}
end_inner_loop:
if (dimIdxSubLoop > 0)
goto lbl_return_to_caller_inner_loop;
}
else
{
// This level of loop loops over blocks
indicesOuterLoop[dimIdx] = arrayStartIdx[dimIdx];
tileIndices[dimIdx] = indicesOuterLoop[dimIdx] / m_anBlockSize[dimIdx];
while (true)
{
dimIdx++;
srcPtrStackOuterLoop[dimIdx] = srcPtrStackOuterLoop[dimIdx - 1];
goto lbl_next_depth;
lbl_return_to_caller:
dimIdx--;
if (count[dimIdx] == 1 || arrayStep[dimIdx] == 0)
break;
size_t nIncr;
if (static_cast<GUInt64>(arrayStep[dimIdx]) < m_anBlockSize[dimIdx])
{
// Compute index at next block boundary
auto newIdx =
indicesOuterLoop[dimIdx] +
(m_anBlockSize[dimIdx] -
(indicesOuterLoop[dimIdx] % m_anBlockSize[dimIdx]));
// And round up compared to arrayStartIdx, arrayStep
nIncr = static_cast<size_t>((newIdx - indicesOuterLoop[dimIdx] +
arrayStep[dimIdx] - 1) /
arrayStep[dimIdx]);
}
else
{
nIncr = 1;
}
indicesOuterLoop[dimIdx] += nIncr * arrayStep[dimIdx];
if (indicesOuterLoop[dimIdx] >
arrayStartIdx[dimIdx] + (count[dimIdx] - 1) * arrayStep[dimIdx])
break;
srcPtrStackOuterLoop[dimIdx] +=
bufferStride[dimIdx] *
static_cast<GPtrDiff_t>(nIncr * nBufferDTSize);
tileIndices[dimIdx] =
indicesOuterLoop[dimIdx] / m_anBlockSize[dimIdx];
}
}
if (dimIdx > 0)
goto lbl_return_to_caller;
return true;
}
/************************************************************************/
/* ParseDtype() */
/************************************************************************/
static size_t GetAlignment(const CPLJSONObject &obj)
{
if (obj.GetType() == CPLJSONObject::Type::String)
{
const auto str = obj.ToString();
if (str.size() < 3)
return 1;
const char chType = str[1];
const int nBytes = atoi(str.c_str() + 2);
if (chType == 'S')
return sizeof(char *);
if (chType == 'c' && nBytes == 8)
return sizeof(float);
if (chType == 'c' && nBytes == 16)
return sizeof(double);
return nBytes;
}
else if (obj.GetType() == CPLJSONObject::Type::Array)
{
const auto oArray = obj.ToArray();
size_t nAlignment = 1;
for (const auto &oElt : oArray)
{
const auto oEltArray = oElt.ToArray();
if (!oEltArray.IsValid() || oEltArray.Size() != 2 ||
oEltArray[0].GetType() != CPLJSONObject::Type::String)
{
return 1;
}
nAlignment = std::max(nAlignment, GetAlignment(oEltArray[1]));
if (nAlignment == sizeof(void *))
break;
}
return nAlignment;
}
return 1;
}
static GDALExtendedDataType ParseDtype(bool isZarrV2, const CPLJSONObject &obj,
std::vector<DtypeElt> &elts)
{
const auto AlignOffsetOn = [](size_t offset, size_t alignment)
{ return offset + (alignment - (offset % alignment)) % alignment; };
do
{
if (obj.GetType() == CPLJSONObject::Type::String)
{
const auto str = obj.ToString();
char chEndianness = 0;
char chType;
int nBytes;
DtypeElt elt;
if (isZarrV2)
{
if (str.size() < 3)
break;
chEndianness = str[0];
chType = str[1];
nBytes = atoi(str.c_str() + 2);
}
else
{
if (str.size() < 2)
break;
if (str == "bool")
{
chType = 'b';
nBytes = 1;
}
else if (str == "u1" || str == "i1")
{
chType = str[0];
nBytes = 1;
}
else
{
if (str.size() < 3)
break;
chEndianness = str[0];
chType = str[1];
nBytes = atoi(str.c_str() + 2);
}
}
if (nBytes <= 0 || nBytes >= 1000)
break;
elt.needByteSwapping = false;
if ((nBytes > 1 && chType != 'S') || chType == 'U')
{
if (chEndianness == '<')
elt.needByteSwapping = (CPL_IS_LSB == 0);
else if (chEndianness == '>')
elt.needByteSwapping = (CPL_IS_LSB != 0);
}
GDALDataType eDT;
if (!elts.empty())
{
elt.nativeOffset =
elts.back().nativeOffset + elts.back().nativeSize;
}
elt.nativeSize = nBytes;
if (chType == 'b' && nBytes == 1) // boolean
{
elt.nativeType = DtypeElt::NativeType::BOOLEAN;
eDT = GDT_Byte;
}
else if (chType == 'u' && nBytes == 1)
{
elt.nativeType = DtypeElt::NativeType::UNSIGNED_INT;
eDT = GDT_Byte;
}
else if (chType == 'i' && nBytes == 1)
{
elt.nativeType = DtypeElt::NativeType::SIGNED_INT;
elt.gdalTypeIsApproxOfNative = true;
eDT = GDT_Int16;
}
else if (chType == 'i' && nBytes == 2)
{
elt.nativeType = DtypeElt::NativeType::SIGNED_INT;
eDT = GDT_Int16;
}
else if (chType == 'i' && nBytes == 4)
{
elt.nativeType = DtypeElt::NativeType::SIGNED_INT;
eDT = GDT_Int32;
}
else if (chType == 'i' && nBytes == 8)
{
elt.nativeType = DtypeElt::NativeType::SIGNED_INT;
eDT = GDT_Int64;
}
else if (chType == 'u' && nBytes == 2)
{
elt.nativeType = DtypeElt::NativeType::UNSIGNED_INT;
eDT = GDT_UInt16;
}
else if (chType == 'u' && nBytes == 4)
{
elt.nativeType = DtypeElt::NativeType::UNSIGNED_INT;
eDT = GDT_UInt32;
}
else if (chType == 'u' && nBytes == 8)
{
elt.nativeType = DtypeElt::NativeType::UNSIGNED_INT;
eDT = GDT_UInt64;
}
else if (chType == 'f' && nBytes == 2)
{
elt.nativeType = DtypeElt::NativeType::IEEEFP;
elt.gdalTypeIsApproxOfNative = true;
eDT = GDT_Float32;
}
else if (chType == 'f' && nBytes == 4)
{
elt.nativeType = DtypeElt::NativeType::IEEEFP;
eDT = GDT_Float32;
}
else if (chType == 'f' && nBytes == 8)
{
elt.nativeType = DtypeElt::NativeType::IEEEFP;
eDT = GDT_Float64;
}
else if (chType == 'c' && nBytes == 8)
{
elt.nativeType = DtypeElt::NativeType::COMPLEX_IEEEFP;
eDT = GDT_CFloat32;
}
else if (chType == 'c' && nBytes == 16)
{
elt.nativeType = DtypeElt::NativeType::COMPLEX_IEEEFP;
eDT = GDT_CFloat64;
}
else if (chType == 'S')
{
elt.nativeType = DtypeElt::NativeType::STRING_ASCII;
elt.gdalType = GDALExtendedDataType::CreateString(nBytes);
elt.gdalSize = elt.gdalType.GetSize();
elts.emplace_back(elt);
return GDALExtendedDataType::CreateString(nBytes);
}
else if (chType == 'U')
{
elt.nativeType = DtypeElt::NativeType::STRING_UNICODE;
// the dtype declaration is number of UCS4 characters. Store it
// as bytes
elt.nativeSize *= 4;
// We can really map UCS4 size to UTF-8
elt.gdalType = GDALExtendedDataType::CreateString();
elt.gdalSize = elt.gdalType.GetSize();
elts.emplace_back(elt);
return GDALExtendedDataType::CreateString();
}
else
break;
elt.gdalType = GDALExtendedDataType::Create(eDT);
elt.gdalSize = elt.gdalType.GetSize();
elts.emplace_back(elt);
return GDALExtendedDataType::Create(eDT);
}
else if (isZarrV2 && obj.GetType() == CPLJSONObject::Type::Array)
{
bool error = false;
const auto oArray = obj.ToArray();
std::vector<std::unique_ptr<GDALEDTComponent>> comps;
size_t offset = 0;
size_t alignmentMax = 1;
for (const auto &oElt : oArray)
{
const auto oEltArray = oElt.ToArray();
if (!oEltArray.IsValid() || oEltArray.Size() != 2 ||
oEltArray[0].GetType() != CPLJSONObject::Type::String)
{
error = true;
break;
}
GDALExtendedDataType subDT =
ParseDtype(isZarrV2, oEltArray[1], elts);
if (subDT.GetClass() == GEDTC_NUMERIC &&
subDT.GetNumericDataType() == GDT_Unknown)
{
error = true;
break;
}
const std::string osName = oEltArray[0].ToString();
// Add padding for alignment
const size_t alignmentSub = GetAlignment(oEltArray[1]);
assert(alignmentSub);
alignmentMax = std::max(alignmentMax, alignmentSub);
offset = AlignOffsetOn(offset, alignmentSub);
comps.emplace_back(std::unique_ptr<GDALEDTComponent>(
new GDALEDTComponent(osName, offset, subDT)));
offset += subDT.GetSize();
}
if (error)
break;
size_t nTotalSize = offset;
nTotalSize = AlignOffsetOn(nTotalSize, alignmentMax);
return GDALExtendedDataType::Create(obj.ToString(), nTotalSize,
std::move(comps));
}
} while (false);
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid or unsupported format for dtype: %s",
obj.ToString().c_str());
return GDALExtendedDataType::Create(GDT_Unknown);
}
static void SetGDALOffset(const GDALExtendedDataType &dt,
const size_t nBaseOffset, std::vector<DtypeElt> &elts,
size_t &iCurElt)
{
if (dt.GetClass() == GEDTC_COMPOUND)
{
const auto &comps = dt.GetComponents();
for (const auto &comp : comps)
{
const size_t nBaseOffsetSub = nBaseOffset + comp->GetOffset();
SetGDALOffset(comp->GetType(), nBaseOffsetSub, elts, iCurElt);
}
}
else
{
elts[iCurElt].gdalOffset = nBaseOffset;
iCurElt++;
}
}
/************************************************************************/
/* ZarrGroupBase::LoadArray() */
/************************************************************************/
std::shared_ptr<ZarrArray>
ZarrGroupBase::LoadArray(const std::string &osArrayName,
const std::string &osZarrayFilename,
const CPLJSONObject &oRoot, bool bLoadedFromZMetadata,
const CPLJSONObject &oAttributesIn,
std::set<std::string> &oSetFilenamesInLoading) const
{
// Prevent too deep or recursive array loading
if (oSetFilenamesInLoading.find(osZarrayFilename) !=
oSetFilenamesInLoading.end())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt at recursively loading %s", osZarrayFilename.c_str());
return nullptr;
}
if (oSetFilenamesInLoading.size() == 32)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Too deep call stack in LoadArray()");
return nullptr;
}
struct SetFilenameAdder
{
std::set<std::string> &m_oSetFilenames;
std::string m_osFilename;
SetFilenameAdder(std::set<std::string> &oSetFilenamesIn,
const std::string &osFilename)
: m_oSetFilenames(oSetFilenamesIn), m_osFilename(osFilename)
{
m_oSetFilenames.insert(osFilename);
}
~SetFilenameAdder()
{
m_oSetFilenames.erase(m_osFilename);
}
};
// Add osZarrayFilename to oSetFilenamesInLoading during the scope
// of this function call.
SetFilenameAdder filenameAdder(oSetFilenamesInLoading, osZarrayFilename);
const bool isZarrV2 = dynamic_cast<const ZarrGroupV2 *>(this) != nullptr;
if (isZarrV2)
{
const auto osFormat = oRoot["zarr_format"].ToString();
if (osFormat != "2")
{
CPLError(CE_Failure, CPLE_NotSupported,
"Invalid value for zarr_format");
return nullptr;
}
}
bool bFortranOrder = false;
const char *orderKey = isZarrV2 ? "order" : "chunk_memory_layout";
const auto osOrder = oRoot[orderKey].ToString();
if (osOrder == "C")
{
// ok
}
else if (osOrder == "F")
{
bFortranOrder = true;
}
else
{
CPLError(CE_Failure, CPLE_NotSupported, "Invalid value for %s",
orderKey);
return nullptr;
}
const auto oShape = oRoot["shape"].ToArray();
if (!oShape.IsValid())
{
CPLError(CE_Failure, CPLE_AppDefined, "shape missing or not an array");
return nullptr;
}
const char *chunksKey = isZarrV2 ? "chunks" : "chunk_grid/chunk_shape";
const auto oChunks = oRoot[chunksKey].ToArray();
if (!oChunks.IsValid())
{
CPLError(CE_Failure, CPLE_AppDefined, "%s missing or not an array",
chunksKey);
return nullptr;
}
if (oShape.Size() != oChunks.Size())
{
CPLError(CE_Failure, CPLE_AppDefined,
"shape and chunks arrays are of different size");
return nullptr;
}
CPLJSONObject oAttributes(oAttributesIn);
if (!bLoadedFromZMetadata && isZarrV2)
{
CPLJSONDocument oDoc;
const std::string osZattrsFilename(CPLFormFilename(
CPLGetDirname(osZarrayFilename.c_str()), ".zattrs", nullptr));
CPLErrorHandlerPusher quietError(CPLQuietErrorHandler);
CPLErrorStateBackuper errorStateBackuper;
if (oDoc.Load(osZattrsFilename))
{
oAttributes = oDoc.GetRoot();
}
}
else if (!isZarrV2)
{
oAttributes = oRoot["attributes"];
}
// Deep-clone of oAttributes
{
CPLJSONDocument oTmpDoc;
oTmpDoc.SetRoot(oAttributes);
CPL_IGNORE_RET_VAL(oTmpDoc.LoadMemory(oTmpDoc.SaveAsString()));
oAttributes = oTmpDoc.GetRoot();
}
const auto crs = oAttributes[CRS_ATTRIBUTE_NAME];
std::shared_ptr<OGRSpatialReference> poSRS;
if (crs.GetType() == CPLJSONObject::Type::Object)
{
for (const char *key : {"url", "wkt", "projjson"})
{
const auto item = crs[key];
if (item.IsValid())
{
poSRS = std::make_shared<OGRSpatialReference>();
poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (poSRS->SetFromUserInput(
item.ToString().c_str(),
OGRSpatialReference::
SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
OGRERR_NONE)
{
oAttributes.Delete(CRS_ATTRIBUTE_NAME);
break;
}
poSRS.reset();
}
}
}
const auto unit = oAttributes[CF_UNITS];
std::string osUnit;
if (unit.GetType() == CPLJSONObject::Type::String)
{
osUnit = unit.ToString();
oAttributes.Delete(CF_UNITS);
}
bool bHasOffset = false;
double dfOffset = 0.0;
const auto offset = oAttributes[CF_ADD_OFFSET];
const auto offsetType = offset.GetType();
if (offsetType == CPLJSONObject::Type::Integer ||
offsetType == CPLJSONObject::Type::Long ||
offsetType == CPLJSONObject::Type::Double)
{
dfOffset = offset.ToDouble();
bHasOffset = true;
oAttributes.Delete(CF_ADD_OFFSET);
}
bool bHasScale = false;
double dfScale = 1.0;
const auto scale = oAttributes[CF_SCALE_FACTOR];
const auto scaleType = scale.GetType();
if (scaleType == CPLJSONObject::Type::Integer ||
scaleType == CPLJSONObject::Type::Long ||
scaleType == CPLJSONObject::Type::Double)
{
dfScale = scale.ToDouble();
bHasScale = true;
oAttributes.Delete(CF_SCALE_FACTOR);
}
std::vector<std::shared_ptr<GDALDimension>> aoDims;
for (int i = 0; i < oShape.Size(); ++i)
{
const auto nSize = static_cast<GUInt64>(oShape[i].ToLong());
if (nSize == 0)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid content for shape");
return nullptr;
}
aoDims.emplace_back(std::make_shared<GDALDimension>(
std::string(), CPLSPrintf("dim%d", i), std::string(), std::string(),
nSize));
}
const auto GetDimensionTypeDirection =
[&oAttributes, &osUnit](std::string &osType, std::string &osDirection)
{
const auto oStdName = oAttributes[CF_STD_NAME];
if (oStdName.GetType() == CPLJSONObject::Type::String)
{
const auto osStdName = oStdName.ToString();
if (osStdName == CF_PROJ_X_COORD ||
osStdName == CF_LONGITUDE_STD_NAME)
{
osType = GDAL_DIM_TYPE_HORIZONTAL_X;
oAttributes.Delete(CF_STD_NAME);
if (osUnit == CF_DEGREES_EAST)
{
osDirection = "EAST";
}
}
else if (osStdName == CF_PROJ_Y_COORD ||
osStdName == CF_LATITUDE_STD_NAME)
{
osType = GDAL_DIM_TYPE_HORIZONTAL_Y;
oAttributes.Delete(CF_STD_NAME);
if (osUnit == CF_DEGREES_NORTH)
{
osDirection = "NORTH";
}
}
else if (osStdName == "time")
{
osType = GDAL_DIM_TYPE_TEMPORAL;
oAttributes.Delete(CF_STD_NAME);
}
}
const auto osAxis = oAttributes[CF_AXIS].ToString();
if (osAxis == "Z")
{
osType = GDAL_DIM_TYPE_VERTICAL;
const auto osPositive = oAttributes["positive"].ToString();
if (osPositive == "up")
{
osDirection = "UP";
oAttributes.Delete("positive");
}
else if (osPositive == "down")
{
osDirection = "DOWN";
oAttributes.Delete("positive");
}
oAttributes.Delete(CF_AXIS);
}
};
// XArray extension
const auto arrayDimensionsObj = oAttributes["_ARRAY_DIMENSIONS"];
const auto FindDimension =
[this, &aoDims, &GetDimensionTypeDirection, bLoadedFromZMetadata,
&osArrayName, &osZarrayFilename, &oSetFilenamesInLoading,
isZarrV2](const std::string &osDimName,
std::shared_ptr<GDALDimension> &poDim, int i)
{
auto oIter = m_oMapDimensions.find(osDimName);
if (oIter != m_oMapDimensions.end())
{
if (oIter->second->GetSize() == poDim->GetSize())
{
poDim = oIter->second;
return true;
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Size of _ARRAY_DIMENSIONS[%d] different "
"from the one of shape",
i);
return false;
}
}
// Try to load the indexing variable.
// If loading from zmetadata, we should have normally
// already loaded the dimension variables, unless they
// are in a upper level.
if (bLoadedFromZMetadata && osArrayName != osDimName &&
m_oMapMDArrays.find(osDimName) == m_oMapMDArrays.end())
{
auto poParent = m_poParent.lock();
while (poParent != nullptr)
{
oIter = poParent->m_oMapDimensions.find(osDimName);
if (oIter != poParent->m_oMapDimensions.end() &&
oIter->second->GetSize() == poDim->GetSize())
{
poDim = oIter->second;
return true;
}
poParent = poParent->m_poParent.lock();
}
}
// Not loading from zmetadata, and not in m_oMapMDArrays,
// then stat() the indexing variable.
else if (!bLoadedFromZMetadata && osArrayName != osDimName &&
m_oMapMDArrays.find(osDimName) == m_oMapMDArrays.end())
{
std::string osDirName = m_osDirectoryName;
while (true)
{
const std::string osArrayFilenameDim =
isZarrV2
? CPLFormFilename(CPLFormFilename(osDirName.c_str(),
osDimName.c_str(),
nullptr),
".zarray", nullptr)
: CPLFormFilename(
CPLGetDirname(osZarrayFilename.c_str()),
(osDimName + ".array.json").c_str(), nullptr);
VSIStatBufL sStat;
if (VSIStatL(osArrayFilenameDim.c_str(), &sStat) == 0)
{
CPLJSONDocument oDoc;
if (oDoc.Load(osArrayFilenameDim))
{
LoadArray(osDimName, osArrayFilenameDim, oDoc.GetRoot(),
false, CPLJSONObject(),
oSetFilenamesInLoading);
}
}
else
{
// Recurse to upper level for datasets such as
// /vsis3/hrrrzarr/sfc/20210809/20210809_00z_anl.zarr/0.1_sigma_level/HAIL_max_fcst/0.1_sigma_level/HAIL_max_fcst
const std::string osDirNameNew =
CPLGetPath(osDirName.c_str());
if (!osDirNameNew.empty() && osDirNameNew != osDirName)
{
osDirName = osDirNameNew;
continue;
}
}
break;
}
}
oIter = m_oMapDimensions.find(osDimName);
if (oIter != m_oMapDimensions.end() &&
oIter->second->GetSize() == poDim->GetSize())
{
poDim = oIter->second;
return true;
}
std::string osType;
std::string osDirection;
if (aoDims.size() == 1 && osArrayName == osDimName)
{
GetDimensionTypeDirection(osType, osDirection);
}
auto poDimLocal = std::make_shared<GDALDimensionWeakIndexingVar>(
GetFullName(), osDimName, osType, osDirection, poDim->GetSize());
m_oMapDimensions[osDimName] = poDimLocal;
poDim = poDimLocal;
return true;
};
if (arrayDimensionsObj.GetType() == CPLJSONObject::Type::Array)
{
const auto arrayDims = arrayDimensionsObj.ToArray();
if (arrayDims.Size() == oShape.Size())
{
bool ok = true;
for (int i = 0; i < oShape.Size(); ++i)
{
if (arrayDims[i].GetType() == CPLJSONObject::Type::String)
{
const auto osDimName = arrayDims[i].ToString();
ok &= FindDimension(osDimName, aoDims[i], i);
}
}
if (ok)
{
oAttributes.Delete("_ARRAY_DIMENSIONS");
}
}
else
{
CPLError(
CE_Warning, CPLE_AppDefined,
"Size of _ARRAY_DIMENSIONS different from the one of shape");
}
}
// _NCZARR_ARRAY extension
const auto nczarrArrayDimrefs = oRoot["_NCZARR_ARRAY"]["dimrefs"].ToArray();
if (nczarrArrayDimrefs.IsValid())
{
const auto arrayDims = nczarrArrayDimrefs.ToArray();
if (arrayDims.Size() == oShape.Size())
{
auto poRG = m_pSelf.lock();
CPLAssert(poRG != nullptr);
while (true)
{
auto poNewRG = poRG->m_poParent.lock();
if (poNewRG == nullptr)
break;
poRG = poNewRG;
}
for (int i = 0; i < oShape.Size(); ++i)
{
if (arrayDims[i].GetType() == CPLJSONObject::Type::String)
{
const auto osDimFullpath = arrayDims[i].ToString();
auto poDim = poRG->OpenDimensionFromFullname(osDimFullpath);
if (poDim == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot find NCZarr dimension %s",
osDimFullpath.c_str());
}
else if (poDim->GetSize() != aoDims[i]->GetSize())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Inconsistency in size between NCZarr "
"dimension %s and regular dimension",
osDimFullpath.c_str());
}
else
{
aoDims[i] = poDim;
// If this is an indexing variable, then fetch the
// dimension type and direction, and patch the dimension
const std::string osArrayFullname =
(GetFullName() != "/" ? GetFullName()
: std::string()) +
'/' + osArrayName;
if (aoDims.size() == 1 &&
osArrayFullname == poDim->GetFullName())
{
std::string osType;
std::string osDirection;
GetDimensionTypeDirection(osType, osDirection);
std::string osDimParent = osDimFullpath;
const auto nPos = osDimParent.rfind('/');
if (nPos != std::string::npos)
{
if (nPos == 0)
osDimParent = '/';
else
osDimParent.resize(nPos);
auto poDimParentGroup =
dynamic_cast<ZarrGroupBase *>(
poRG->OpenGroupFromFullname(osDimParent)
.get());
if (poDimParentGroup)
{
auto poDimLocal = std::make_shared<
GDALDimensionWeakIndexingVar>(
poDimParentGroup->GetFullName(),
poDim->GetName(), osType, osDirection,
poDim->GetSize());
aoDims[i] = poDimLocal;
poDimParentGroup
->m_oMapDimensions[poDim->GetName()] =
poDimLocal;
}
}
}
}
}
}
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Size of _NCZARR_ARRAY.dimrefs different from the one of "
"shape");
}
}
const char *dtypeKey = isZarrV2 ? "dtype" : "data_type";
auto oDtype = oRoot[dtypeKey];
if (!oDtype.IsValid())
{
CPLError(CE_Failure, CPLE_NotSupported, "%s missing", dtypeKey);
return nullptr;
}
if (!isZarrV2 && oDtype["fallback"].IsValid())
oDtype = oDtype["fallback"];
std::vector<DtypeElt> aoDtypeElts;
const auto oType = ParseDtype(isZarrV2, oDtype, aoDtypeElts);
if (oType.GetClass() == GEDTC_NUMERIC &&
oType.GetNumericDataType() == GDT_Unknown)
return nullptr;
size_t iCurElt = 0;
SetGDALOffset(oType, 0, aoDtypeElts, iCurElt);
std::vector<GUInt64> anBlockSize;
size_t nBlockSize = oType.GetSize();
for (const auto &item : oChunks)
{
const auto nSize = static_cast<GUInt64>(item.ToLong());
if (nSize == 0)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid content for chunks");
return nullptr;
}
if (nBlockSize > std::numeric_limits<size_t>::max() / nSize)
{
CPLError(CE_Failure, CPLE_AppDefined, "Too large chunks");
return nullptr;
}
nBlockSize *= static_cast<size_t>(nSize);
anBlockSize.emplace_back(nSize);
}
std::string osDimSeparator;
if (isZarrV2)
{
osDimSeparator = oRoot["dimension_separator"].ToString();
if (osDimSeparator.empty())
osDimSeparator = ".";
}
else
{
osDimSeparator = oRoot["chunk_grid/separator"].ToString();
if (osDimSeparator.empty())
osDimSeparator = "/";
}
std::vector<GByte> abyNoData;
struct NoDataFreer
{
std::vector<GByte> &m_abyNodata;
const GDALExtendedDataType &m_oType;
NoDataFreer(std::vector<GByte> &abyNoDataIn,
const GDALExtendedDataType &oTypeIn)
: m_abyNodata(abyNoDataIn), m_oType(oTypeIn)
{
}
~NoDataFreer()
{
if (!m_abyNodata.empty())
m_oType.FreeDynamicMemory(&m_abyNodata[0]);
}
};
NoDataFreer NoDataFreer(abyNoData, oType);
auto oFillValue = oRoot["fill_value"];
auto eFillValueType = oFillValue.GetType();
// Normally arrays are not supported, but that's what NCZarr 4.8.0 outputs
if (eFillValueType == CPLJSONObject::Type::Array &&
oFillValue.ToArray().Size() == 1)
{
oFillValue = oFillValue.ToArray()[0];
eFillValueType = oFillValue.GetType();
}
if (!oFillValue.IsValid())
{
// fill_value is normally required but some implementations
// are lacking it: https://github.com/Unidata/netcdf-c/issues/2059
CPLError(CE_Warning, CPLE_AppDefined, "fill_value missing");
}
else if (eFillValueType == CPLJSONObject::Type::Null)
{
// Nothing to do
}
else if (eFillValueType == CPLJSONObject::Type::String)
{
const auto osFillValue = oFillValue.ToString();
if (oType.GetClass() == GEDTC_NUMERIC &&
CPLGetValueType(osFillValue.c_str()) != CPL_VALUE_STRING)
{
abyNoData.resize(oType.GetSize());
// Be tolerant with numeric values serialized as strings.
if (oType.GetNumericDataType() == GDT_Int64)
{
const int64_t nVal = static_cast<int64_t>(
std::strtoll(osFillValue.c_str(), nullptr, 10));
GDALCopyWords(&nVal, GDT_Int64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
else if (oType.GetNumericDataType() == GDT_UInt64)
{
const uint64_t nVal = static_cast<uint64_t>(
std::strtoull(osFillValue.c_str(), nullptr, 10));
GDALCopyWords(&nVal, GDT_UInt64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
else
{
const double dfNoDataValue = CPLAtof(osFillValue.c_str());
GDALCopyWords(&dfNoDataValue, GDT_Float64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
}
else if (oType.GetClass() == GEDTC_NUMERIC)
{
double dfNoDataValue;
if (osFillValue == "NaN")
{
dfNoDataValue = std::numeric_limits<double>::quiet_NaN();
}
else if (osFillValue == "Infinity")
{
dfNoDataValue = std::numeric_limits<double>::infinity();
}
else if (osFillValue == "-Infinity")
{
dfNoDataValue = -std::numeric_limits<double>::infinity();
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid fill_value");
return nullptr;
}
if (oType.GetNumericDataType() == GDT_Float32)
{
const float fNoDataValue = static_cast<float>(dfNoDataValue);
abyNoData.resize(sizeof(fNoDataValue));
memcpy(&abyNoData[0], &fNoDataValue, sizeof(fNoDataValue));
}
else if (oType.GetNumericDataType() == GDT_Float64)
{
abyNoData.resize(sizeof(dfNoDataValue));
memcpy(&abyNoData[0], &dfNoDataValue, sizeof(dfNoDataValue));
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid fill_value");
return nullptr;
}
}
else if (oType.GetClass() == GEDTC_STRING)
{
// zarr.open('unicode_be.zarr', mode = 'w', shape=(1,), dtype =
// '>U1', compressor = None) oddly generates "fill_value": "0"
if (osFillValue != "0")
{
std::vector<GByte> abyNativeFillValue(osFillValue.size() + 1);
memcpy(&abyNativeFillValue[0], osFillValue.data(),
osFillValue.size());
int nBytes = CPLBase64DecodeInPlace(&abyNativeFillValue[0]);
abyNativeFillValue.resize(nBytes + 1);
abyNativeFillValue[nBytes] = 0;
abyNoData.resize(oType.GetSize());
char *pDstStr = CPLStrdup(
reinterpret_cast<const char *>(&abyNativeFillValue[0]));
char **pDstPtr = reinterpret_cast<char **>(&abyNoData[0]);
memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
}
}
else
{
std::vector<GByte> abyNativeFillValue(osFillValue.size() + 1);
memcpy(&abyNativeFillValue[0], osFillValue.data(),
osFillValue.size());
int nBytes = CPLBase64DecodeInPlace(&abyNativeFillValue[0]);
abyNativeFillValue.resize(nBytes);
if (abyNativeFillValue.size() !=
aoDtypeElts.back().nativeOffset + aoDtypeElts.back().nativeSize)
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid fill_value");
return nullptr;
}
abyNoData.resize(oType.GetSize());
DecodeSourceElt(aoDtypeElts, abyNativeFillValue.data(),
&abyNoData[0]);
}
}
else if (eFillValueType == CPLJSONObject::Type::Boolean ||
eFillValueType == CPLJSONObject::Type::Integer ||
eFillValueType == CPLJSONObject::Type::Long ||
eFillValueType == CPLJSONObject::Type::Double)
{
if (oType.GetClass() == GEDTC_NUMERIC)
{
const double dfNoDataValue = oFillValue.ToDouble();
if (oType.GetNumericDataType() == GDT_Int64)
{
const int64_t nNoDataValue =
static_cast<int64_t>(oFillValue.ToLong());
abyNoData.resize(oType.GetSize());
GDALCopyWords(&nNoDataValue, GDT_Int64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
else if (oType.GetNumericDataType() == GDT_UInt64 &&
/* we can't really deal with nodata value between */
/* int64::max and uint64::max due to json-c limitations */
dfNoDataValue >= 0)
{
const int64_t nNoDataValue =
static_cast<int64_t>(oFillValue.ToLong());
abyNoData.resize(oType.GetSize());
GDALCopyWords(&nNoDataValue, GDT_Int64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
else
{
abyNoData.resize(oType.GetSize());
GDALCopyWords(&dfNoDataValue, GDT_Float64, 0, &abyNoData[0],
oType.GetNumericDataType(), 0, 1);
}
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid fill_value");
return nullptr;
}
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid fill_value");
return nullptr;
}
const CPLCompressor *psCompressor = nullptr;
const CPLCompressor *psDecompressor = nullptr;
const auto oCompressor = oRoot["compressor"];
std::string osDecompressorId("NONE");
if (isZarrV2)
{
if (!oCompressor.IsValid())
{
CPLError(CE_Failure, CPLE_AppDefined, "compressor missing");
return nullptr;
}
if (oCompressor.GetType() == CPLJSONObject::Type::Null)
{
// nothing to do
}
else if (oCompressor.GetType() == CPLJSONObject::Type::Object)
{
osDecompressorId = oCompressor["id"].ToString();
if (osDecompressorId.empty())
{
CPLError(CE_Failure, CPLE_AppDefined, "Missing compressor id");
return nullptr;
}
psCompressor = CPLGetCompressor(osDecompressorId.c_str());
psDecompressor = CPLGetDecompressor(osDecompressorId.c_str());
if (psCompressor == nullptr || psDecompressor == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Decompressor %s not handled",
osDecompressorId.c_str());
return nullptr;
}
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid compressor");
return nullptr;
}
}
else if (oCompressor.IsValid())
{
const auto oCodec = oCompressor["codec"];
if (oCodec.GetType() == CPLJSONObject::Type::String)
{
const auto osCodec = oCodec.ToString();
// See https://github.com/zarr-developers/zarr-specs/pull/119
// We accept the plural form, but singular is the official one.
for (const char *key : {"https://purl.org/zarr/spec/codec/",
"https://purl.org/zarr/spec/codecs/"})
{
if (osCodec.find(key) == 0)
{
auto osCodecName = osCodec.substr(strlen(key));
auto posSlash = osCodecName.find('/');
if (posSlash != std::string::npos)
{
osDecompressorId = osCodecName.substr(0, posSlash);
psCompressor =
CPLGetCompressor(osDecompressorId.c_str());
psDecompressor =
CPLGetDecompressor(osDecompressorId.c_str());
}
break;
}
}
if (psCompressor == nullptr || psDecompressor == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Decompressor %s not handled", osCodec.c_str());
return nullptr;
}
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid compressor");
return nullptr;
}
}
CPLJSONArray oFiltersArray;
if (isZarrV2)
{
const auto oFilters = oRoot["filters"];
if (!oFilters.IsValid())
{
CPLError(CE_Failure, CPLE_AppDefined, "filters missing");
return nullptr;
}
if (oFilters.GetType() == CPLJSONObject::Type::Null)
{
}
else if (oFilters.GetType() == CPLJSONObject::Type::Array)
{
oFiltersArray = oFilters.ToArray();
for (const auto &oFilter : oFiltersArray)
{
const auto osFilterId = oFilter["id"].ToString();
if (osFilterId.empty())
{
CPLError(CE_Failure, CPLE_AppDefined, "Missing filter id");
return nullptr;
}
const auto psFilterCompressor =
CPLGetCompressor(osFilterId.c_str());
const auto psFilterDecompressor =
CPLGetDecompressor(osFilterId.c_str());
if (psFilterCompressor == nullptr ||
psFilterDecompressor == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Filter %s not handled", osFilterId.c_str());
return nullptr;
}
}
}
else
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid filters");
return nullptr;
}
}
auto poArray = ZarrArray::Create(m_poSharedResource, GetFullName(),
osArrayName, aoDims, oType, aoDtypeElts,
anBlockSize, bFortranOrder);
if (!poArray)
return nullptr;
poArray->SetUpdatable(m_bUpdatable); // must be set before SetAttributes()
poArray->SetFilename(osZarrayFilename);
poArray->SetDimSeparator(osDimSeparator);
if (isZarrV2)
poArray->SetCompressorJsonV2(oCompressor);
poArray->SetCompressorDecompressor(osDecompressorId, psCompressor,
psDecompressor);
poArray->SetFilters(oFiltersArray);
if (!abyNoData.empty())
{
poArray->RegisterNoDataValue(abyNoData.data());
}
poArray->SetSRS(poSRS);
poArray->SetAttributes(oAttributes);
poArray->SetRootDirectoryName(m_osDirectoryName);
poArray->SetVersion(isZarrV2 ? 2 : 3);
poArray->SetDtype(oDtype);
poArray->RegisterUnit(osUnit);
if (bHasOffset)
poArray->RegisterOffset(dfOffset);
if (bHasScale)
poArray->RegisterScale(dfScale);
RegisterArray(poArray);
// If this is an indexing variable, attach it to the dimension.
if (aoDims.size() == 1 && aoDims[0]->GetName() == poArray->GetName())
{
auto oIter = m_oMapDimensions.find(poArray->GetName());
if (oIter != m_oMapDimensions.end())
{
oIter->second->SetIndexingVariable(poArray);
}
}
if (CPLTestBool(m_poSharedResource->GetOpenOptions().FetchNameValueDef(
"CACHE_TILE_PRESENCE", "NO")))
{
poArray->CacheTilePresence();
}
return poArray;
}
/************************************************************************/
/* ZarrArray::OpenTilePresenceCache() */
/************************************************************************/
std::shared_ptr<GDALMDArray>
ZarrArray::OpenTilePresenceCache(bool bCanCreate) const
{
if (m_bHasTriedCacheTilePresenceArray)
return m_poCacheTilePresenceArray;
m_bHasTriedCacheTilePresenceArray = true;
if (m_nTotalTileCount == 1)
return nullptr;
std::string osCacheFilename;
auto poRGCache = GetCacheRootGroup(bCanCreate, osCacheFilename);
if (!poRGCache)
return nullptr;
const std::string osTilePresenceArrayName(MassageName(GetFullName()) +
"_tile_presence");
auto poTilePresenceArray = poRGCache->OpenMDArray(osTilePresenceArrayName);
const auto eByteDT = GDALExtendedDataType::Create(GDT_Byte);
if (poTilePresenceArray)
{
bool ok = true;
const auto apoDimsCache = poTilePresenceArray->GetDimensions();
if (poTilePresenceArray->GetDataType() != eByteDT ||
apoDimsCache.size() != m_aoDims.size())
{
ok = false;
}
else
{
for (size_t i = 0; i < m_aoDims.size(); i++)
{
const auto nExpectedDimSize =
(m_aoDims[i]->GetSize() + m_anBlockSize[i] - 1) /
m_anBlockSize[i];
if (apoDimsCache[i]->GetSize() != nExpectedDimSize)
{
ok = false;
break;
}
}
}
if (!ok)
{
CPLError(CE_Failure, CPLE_NotSupported,
"Array %s in %s has not expected characteristics",
osTilePresenceArrayName.c_str(), osCacheFilename.c_str());
return nullptr;
}
if (!poTilePresenceArray->GetAttribute("filling_status") && !bCanCreate)
{
CPLDebug(ZARR_DEBUG_KEY,
"Cache tile presence array for %s found, but filling not "
"finished",
GetFullName().c_str());
return nullptr;
}
CPLDebug(ZARR_DEBUG_KEY, "Using cache tile presence for %s",
GetFullName().c_str());
}
else if (bCanCreate)
{
int idxDim = 0;
std::string osBlockSize;
std::vector<std::shared_ptr<GDALDimension>> apoNewDims;
for (const auto &poDim : m_aoDims)
{
auto poNewDim = poRGCache->CreateDimension(
osTilePresenceArrayName + '_' + std::to_string(idxDim),
std::string(), std::string(),
(poDim->GetSize() + m_anBlockSize[idxDim] - 1) /
m_anBlockSize[idxDim]);
if (!poNewDim)
return nullptr;
apoNewDims.emplace_back(poNewDim);
if (!osBlockSize.empty())
osBlockSize += ',';
constexpr GUInt64 BLOCKSIZE = 256;
osBlockSize +=
std::to_string(std::min(poNewDim->GetSize(), BLOCKSIZE));
idxDim++;
}
CPLStringList aosOptionsTilePresence;
aosOptionsTilePresence.SetNameValue("BLOCKSIZE", osBlockSize.c_str());
poTilePresenceArray =
poRGCache->CreateMDArray(osTilePresenceArrayName, apoNewDims,
eByteDT, aosOptionsTilePresence.List());
if (!poTilePresenceArray)
{
CPLError(CE_Failure, CPLE_NotSupported, "Cannot create %s in %s",
osTilePresenceArrayName.c_str(), osCacheFilename.c_str());
return nullptr;
}
poTilePresenceArray->SetNoDataValue(0);
}
else
{
return nullptr;
}
m_poCacheTilePresenceArray = poTilePresenceArray;
return poTilePresenceArray;
}
/************************************************************************/
/* ZarrArray::CacheTilePresence() */
/************************************************************************/
bool ZarrArray::CacheTilePresence()
{
if (m_nTotalTileCount == 1)
return true;
const std::string osDirectoryName = [this]()
{
if (m_nVersion == 2)
return std::string(CPLGetDirname(m_osFilename.c_str()));
std::string osTmp = m_osRootDirectoryName + "/data/root";
if (GetFullName() != "/")
osTmp += GetFullName();
return osTmp;
}();
struct DirCloser
{
DirCloser(const DirCloser &) = delete;
DirCloser &operator=(const DirCloser &) = delete;
VSIDIR *m_psDir;
explicit DirCloser(VSIDIR *psDir) : m_psDir(psDir)
{
}
~DirCloser()
{
VSICloseDir(m_psDir);
}
};
auto psDir = VSIOpenDir(osDirectoryName.c_str(), -1, nullptr);
if (!psDir)
return false;
DirCloser dirCloser(psDir);
auto poTilePresenceArray = OpenTilePresenceCache(true);
if (!poTilePresenceArray)
{
return false;
}
if (poTilePresenceArray->GetAttribute("filling_status"))
{
CPLDebug(ZARR_DEBUG_KEY,
"CacheTilePresence(): %s already filled. Nothing to do",
poTilePresenceArray->GetName().c_str());
return true;
}
std::vector<GUInt64> anTileIdx(m_aoDims.size());
const std::vector<size_t> anCount(m_aoDims.size(), 1);
const std::vector<GInt64> anArrayStep(m_aoDims.size(), 0);
const std::vector<GPtrDiff_t> anBufferStride(m_aoDims.size(), 0);
const auto apoDimsCache = poTilePresenceArray->GetDimensions();
const auto eByteDT = GDALExtendedDataType::Create(GDT_Byte);
CPLDebug(ZARR_DEBUG_KEY,
"CacheTilePresence(): Iterating over %s to find which tiles are "
"present...",
osDirectoryName.c_str());
uint64_t nCounter = 0;
while (const VSIDIREntry *psEntry = VSIGetNextDirEntry(psDir))
{
if (!VSI_ISDIR(psEntry->nMode))
{
int nOff = 0;
if (m_nVersion == 3)
{
if (psEntry->pszName[0] != 'c')
continue;
nOff = 1;
}
const CPLStringList aosTokens(CSLTokenizeString2(
psEntry->pszName + nOff, m_osDimSeparator.c_str(), 0));
if (aosTokens.size() == static_cast<int>(m_aoDims.size()))
{
// Get tile indices from filename
bool unexpectedIndex = false;
for (int i = 0; i < aosTokens.size(); ++i)
{
if (CPLGetValueType(aosTokens[i]) != CPL_VALUE_INTEGER)
{
unexpectedIndex = true;
}
anTileIdx[i] =
static_cast<GUInt64>(CPLAtoGIntBig(aosTokens[i]));
if (anTileIdx[i] >= apoDimsCache[i]->GetSize())
{
unexpectedIndex = true;
}
}
if (unexpectedIndex)
{
continue;
}
nCounter++;
if ((nCounter % 1000) == 0)
{
CPLDebug(ZARR_DEBUG_KEY,
"CacheTilePresence(): Listing in progress "
"(last examined %s, at least %.02f %% completed)",
psEntry->pszName,
100.0 * double(nCounter) /
double(m_nTotalTileCount));
}
constexpr GByte byOne = 1;
// CPLDebugOnly(ZARR_DEBUG_KEY, "Marking %s has present",
// psEntry->pszName);
if (!poTilePresenceArray->Write(
anTileIdx.data(), anCount.data(), anArrayStep.data(),
anBufferStride.data(), eByteDT, &byOne))
{
return false;
}
}
}
}
CPLDebug(ZARR_DEBUG_KEY, "CacheTilePresence(): finished");
// Write filling_status attribute
auto poAttr = poTilePresenceArray->CreateAttribute(
"filling_status", {}, GDALExtendedDataType::CreateString(), nullptr);
if (poAttr)
{
if (nCounter == 0)
poAttr->Write("no_tile_present");
else if (nCounter == m_nTotalTileCount)
poAttr->Write("all_tiles_present");
else
poAttr->Write("some_tiles_missing");
}
// Force closing
m_poCacheTilePresenceArray = nullptr;
m_bHasTriedCacheTilePresenceArray = false;
return true;
}
/************************************************************************/
/* ZarrArray::CreateAttribute() */
/************************************************************************/
std::shared_ptr<GDALAttribute> ZarrArray::CreateAttribute(
const std::string &osName, const std::vector<GUInt64> &anDimensions,
const GDALExtendedDataType &oDataType, CSLConstList papszOptions)
{
if (!m_bUpdatable)
{
CPLError(CE_Failure, CPLE_NotSupported,
"Dataset not open in update mode");
return nullptr;
}
if (anDimensions.size() >= 2)
{
CPLError(CE_Failure, CPLE_NotSupported,
"Cannot create attributes of dimension >= 2");
return nullptr;
}
return m_oAttrGroup.CreateAttribute(osName, anDimensions, oDataType,
papszOptions);
}
/************************************************************************/
/* ZarrArray::SetSpatialRef() */
/************************************************************************/
bool ZarrArray::SetSpatialRef(const OGRSpatialReference *poSRS)
{
if (!m_bUpdatable)
{
return GDALPamMDArray::SetSpatialRef(poSRS);
}
m_poSRS.reset();
if (poSRS)
m_poSRS.reset(poSRS->Clone());
m_bSRSModified = true;
return true;
}
/************************************************************************/
/* ZarrArray::SetUnit() */
/************************************************************************/
bool ZarrArray::SetUnit(const std::string &osUnit)
{
if (!m_bUpdatable)
{
CPLError(CE_Failure, CPLE_NotSupported,
"Dataset not open in update mode");
return false;
}
m_osUnit = osUnit;
m_bUnitModified = true;
return true;
}
/************************************************************************/
/* ZarrArray::GetOffset() */
/************************************************************************/
double ZarrArray::GetOffset(bool *pbHasOffset,
GDALDataType *peStorageType) const
{
if (pbHasOffset)
*pbHasOffset = m_bHasOffset;
if (peStorageType)
*peStorageType = GDT_Unknown;
return m_dfOffset;
}
/************************************************************************/
/* ZarrArray::GetScale() */
/************************************************************************/
double ZarrArray::GetScale(bool *pbHasScale, GDALDataType *peStorageType) const
{
if (pbHasScale)
*pbHasScale = m_bHasScale;
if (peStorageType)
*peStorageType = GDT_Unknown;
return m_dfScale;
}
/************************************************************************/
/* ZarrArray::SetOffset() */
/************************************************************************/
bool ZarrArray::SetOffset(double dfOffset, GDALDataType /* eStorageType */)
{
m_dfOffset = dfOffset;
m_bHasOffset = true;
m_bOffsetModified = true;
return true;
}
/************************************************************************/
/* ZarrArray::SetScale() */
/************************************************************************/
bool ZarrArray::SetScale(double dfScale, GDALDataType /* eStorageType */)
{
m_dfScale = dfScale;
m_bHasScale = true;
m_bScaleModified = true;
return true;
}
/************************************************************************/
/* GetCoordinateVariables() */
/************************************************************************/
std::vector<std::shared_ptr<GDALMDArray>>
ZarrArray::GetCoordinateVariables() const
{
std::vector<std::shared_ptr<GDALMDArray>> ret;
const auto poCoordinates = GetAttribute("coordinates");
if (poCoordinates &&
poCoordinates->GetDataType().GetClass() == GEDTC_STRING &&
poCoordinates->GetDimensionCount() == 0)
{
const char *pszCoordinates = poCoordinates->ReadAsString();
if (pszCoordinates)
{
auto poGroup = m_poGroupWeak.lock();
if (!poGroup)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot access coordinate variables of %s has "
"belonging group has gone out of scope",
GetName().c_str());
}
else
{
const CPLStringList aosNames(
CSLTokenizeString2(pszCoordinates, " ", 0));
for (int i = 0; i < aosNames.size(); i++)
{
auto poCoordinateVar = poGroup->OpenMDArray(aosNames[i]);
if (poCoordinateVar)
{
ret.emplace_back(poCoordinateVar);
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Cannot find variable corresponding to "
"coordinate %s",
aosNames[i]);
}
}
}
}
}
return ret;
}
|