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
|
// SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2011-2024 Arm Limited
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
// ----------------------------------------------------------------------------
/**
* @brief Functions for codec library front-end.
*/
#include "astcenc.h"
#include "astcenccli_internal.h"
#if defined(_WIN32)
#include <io.h>
#define isatty _isatty
#else
#include <unistd.h>
#endif
#include <cassert>
#include <cstring>
#include <functional>
#include <string>
#include <sstream>
#include <vector>
#include <memory>
/* ============================================================================
Data structure definitions
============================================================================ */
typedef unsigned int astcenc_operation;
struct mode_entry
{
const char* opt;
astcenc_operation operation;
astcenc_profile decode_mode;
};
/* ============================================================================
Constants and literals
============================================================================ */
/** @brief Stage bit indicating we need to load a compressed image. */
static const unsigned int ASTCENC_STAGE_LD_COMP = 1 << 0;
/** @brief Stage bit indicating we need to store a compressed image. */
static const unsigned int ASTCENC_STAGE_ST_COMP = 1 << 1;
/** @brief Stage bit indicating we need to load an uncompressed image. */
static const unsigned int ASTCENC_STAGE_LD_NCOMP = 1 << 2;
/** @brief Stage bit indicating we need to store an uncompressed image. */
static const unsigned int ASTCENC_STAGE_ST_NCOMP = 1 << 3;
/** @brief Stage bit indicating we need compress an image. */
static const unsigned int ASTCENC_STAGE_COMPRESS = 1 << 4;
/** @brief Stage bit indicating we need to decompress an image. */
static const unsigned int ASTCENC_STAGE_DECOMPRESS = 1 << 5;
/** @brief Stage bit indicating we need to compare an image with the original input. */
static const unsigned int ASTCENC_STAGE_COMPARE = 1 << 6;
/** @brief Operation indicating an unknown request (should never happen). */
static const astcenc_operation ASTCENC_OP_UNKNOWN = 0;
/** @brief Operation indicating the user wants to print long-form help text and version info. */
static const astcenc_operation ASTCENC_OP_HELP = 1 << 7;
/** @brief Operation indicating the user wants to print short-form help text and version info. */
static const astcenc_operation ASTCENC_OP_VERSION = 1 << 8;
/** @brief Operation indicating the user wants to compress and store an image. */
static const astcenc_operation ASTCENC_OP_COMPRESS =
ASTCENC_STAGE_LD_NCOMP |
ASTCENC_STAGE_COMPRESS |
ASTCENC_STAGE_ST_COMP;
/** @brief Operation indicating the user wants to decompress and store an image. */
static const astcenc_operation ASTCENC_OP_DECOMPRESS =
ASTCENC_STAGE_LD_COMP |
ASTCENC_STAGE_DECOMPRESS |
ASTCENC_STAGE_ST_NCOMP;
/** @brief Operation indicating the user wants to test a compression setting on an image. */
static const astcenc_operation ASTCENC_OP_TEST =
ASTCENC_STAGE_LD_NCOMP |
ASTCENC_STAGE_COMPRESS |
ASTCENC_STAGE_DECOMPRESS |
ASTCENC_STAGE_COMPARE |
ASTCENC_STAGE_ST_NCOMP;
/**
* @brief Image preprocesing tasks prior to encoding.
*/
enum astcenc_preprocess
{
/** @brief No image preprocessing. */
ASTCENC_PP_NONE = 0,
/** @brief Normal vector unit-length normalization. */
ASTCENC_PP_NORMALIZE,
/** @brief Color data alpha premultiplication. */
ASTCENC_PP_PREMULTIPLY
};
/** @brief Decode table for command line operation modes. */
static const mode_entry modes[] {
{"-cl", ASTCENC_OP_COMPRESS, ASTCENC_PRF_LDR},
{"-dl", ASTCENC_OP_DECOMPRESS, ASTCENC_PRF_LDR},
{"-tl", ASTCENC_OP_TEST, ASTCENC_PRF_LDR},
{"-cs", ASTCENC_OP_COMPRESS, ASTCENC_PRF_LDR_SRGB},
{"-ds", ASTCENC_OP_DECOMPRESS, ASTCENC_PRF_LDR_SRGB},
{"-ts", ASTCENC_OP_TEST, ASTCENC_PRF_LDR_SRGB},
{"-ch", ASTCENC_OP_COMPRESS, ASTCENC_PRF_HDR_RGB_LDR_A},
{"-dh", ASTCENC_OP_DECOMPRESS, ASTCENC_PRF_HDR_RGB_LDR_A},
{"-th", ASTCENC_OP_TEST, ASTCENC_PRF_HDR_RGB_LDR_A},
{"-cH", ASTCENC_OP_COMPRESS, ASTCENC_PRF_HDR},
{"-dH", ASTCENC_OP_DECOMPRESS, ASTCENC_PRF_HDR},
{"-tH", ASTCENC_OP_TEST, ASTCENC_PRF_HDR},
{"-h", ASTCENC_OP_HELP, ASTCENC_PRF_HDR},
{"-help", ASTCENC_OP_HELP, ASTCENC_PRF_HDR},
{"-v", ASTCENC_OP_VERSION, ASTCENC_PRF_HDR},
{"-version", ASTCENC_OP_VERSION, ASTCENC_PRF_HDR}
};
/**
* @brief Compression workload definition for worker threads.
*/
struct compression_workload
{
astcenc_context* context;
astcenc_image* image;
astcenc_swizzle swizzle;
uint8_t* data_out;
size_t data_len;
astcenc_error error;
};
/**
* @brief Decompression workload definition for worker threads.
*/
struct decompression_workload
{
astcenc_context* context;
uint8_t* data;
size_t data_len;
astcenc_image* image_out;
astcenc_swizzle swizzle;
astcenc_error error;
};
/**
* @brief Callback emitting a progress bar
*/
extern "C" void progress_emitter(
float value
) {
const unsigned int bar_size = 25;
unsigned int parts = static_cast<int>(value / 4.0f);
char buffer[bar_size + 3];
buffer[0] = '[';
for (unsigned int i = 0; i < parts; i++)
{
buffer[i + 1] = '=';
}
for (unsigned int i = parts; i < bar_size; i++)
{
buffer[i + 1] = ' ';
}
buffer[bar_size + 1] = ']';
buffer[bar_size + 2] = '\0';
printf(" Progress: %s %03.1f%%\r", buffer, static_cast<double>(value));
fflush(stdout);
}
/**
* @brief Test if a string argument is a well formed float.
*/
static bool is_float(
std::string target
) {
float test;
std::istringstream stream(target);
// Leading whitespace is an error
stream >> std::noskipws >> test;
// Ensure entire no remaining string in addition to parse failure
return stream.eof() && !stream.fail();
}
/**
* @brief Test if a string ends with a given suffix.
*/
static bool ends_with(
const std::string& str,
const std::string& suffix
) {
return (str.size() >= suffix.size()) &&
(0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix));
}
/**
* @brief Runner callback function for a compression worker thread.
*
* @param thread_count The number of threads in the worker pool.
* @param thread_id The index of this thread in the worker pool.
* @param payload The parameters for this thread.
*/
static void compression_workload_runner(
int thread_count,
int thread_id,
void* payload
) {
(void)thread_count;
char name[16] { 0 };
std::snprintf(name, 16, "astc workc %d", thread_id);
set_thread_name(name);
compression_workload* work = static_cast<compression_workload*>(payload);
astcenc_error error = astcenc_compress_image(
work->context, work->image, &work->swizzle,
work->data_out, work->data_len, thread_id);
// This is a racy update, so which error gets returned is a random, but it
// will reliably report an error if an error occurs
if (error != ASTCENC_SUCCESS)
{
work->error = error;
}
}
/**
* @brief Runner callback function for a decompression worker thread.
*
* @param thread_count The number of threads in the worker pool.
* @param thread_id The index of this thread in the worker pool.
* @param payload The parameters for this thread.
*/
static void decompression_workload_runner(
int thread_count,
int thread_id,
void* payload
) {
(void)thread_count;
char name[16] { 0 };
std::snprintf(name, 16, "astc workd %d", thread_id);
set_thread_name(name);
decompression_workload* work = static_cast<decompression_workload*>(payload);
astcenc_error error = astcenc_decompress_image(
work->context, work->data, work->data_len,
work->image_out, &work->swizzle, thread_id);
// This is a racy update, so which error gets returned is a random, but it
// will reliably report an error if an error occurs
if (error != ASTCENC_SUCCESS)
{
work->error = error;
}
}
/**
* @brief Utility to generate a slice file name from a pattern.
*
* Convert "foo/bar.png" in to "foo/bar_<slice>.png"
*
* @param basename The base pattern; must contain a file extension.
* @param index The slice index.
* @param error Set to true on success, false on error (no extension found).
*
* @return The slice file name.
*/
static std::string get_slice_filename(
const std::string& basename,
unsigned int index,
bool& error
) {
size_t sep = basename.find_last_of('.');
if (sep == std::string::npos)
{
error = true;
return "";
}
std::string base = basename.substr(0, sep);
std::string ext = basename.substr(sep);
std::string name = base + "_" + std::to_string(index) + ext;
error = false;
return name;
}
/**
* @brief Load a non-astc image file from memory.
*
* @param filename The file to load, or a pattern for array loads.
* @param dim_z The number of slices to load.
* @param y_flip Should this image be Y flipped?
* @param[out] is_hdr Is the loaded image HDR?
* @param[out] component_count The number of components in the loaded image.
*
* @return The astc image file, or nullptr on error.
*/
static astcenc_image* load_uncomp_file(
const char* filename,
unsigned int dim_z,
bool y_flip,
bool& is_hdr,
unsigned int& component_count
) {
astcenc_image *image = nullptr;
// For a 2D image just load the image directly
if (dim_z == 1)
{
image = load_ncimage(filename, y_flip, is_hdr, component_count);
}
else
{
bool slice_is_hdr;
unsigned int slice_component_count;
astcenc_image* slice = nullptr;
std::vector<astcenc_image*> slices;
// For a 3D image load an array of slices
for (unsigned int image_index = 0; image_index < dim_z; image_index++)
{
bool error;
std::string slice_name = get_slice_filename(filename, image_index, error);
if (error)
{
print_error("ERROR: Image pattern does not contain file extension: %s\n", filename);
break;
}
slice = load_ncimage(slice_name.c_str(), y_flip,
slice_is_hdr, slice_component_count);
if (!slice)
{
break;
}
slices.push_back(slice);
// Check it is not a 3D image
if (slice->dim_z != 1)
{
print_error("ERROR: Image arrays do not support 3D sources: %s\n", slice_name.c_str());
break;
}
// Check slices are consistent with each other
if (image_index != 0)
{
if ((is_hdr != slice_is_hdr) || (component_count != slice_component_count))
{
print_error("ERROR: Image array[0] and [%d] are different formats\n", image_index);
break;
}
if ((slices[0]->dim_x != slice->dim_x) ||
(slices[0]->dim_y != slice->dim_y) ||
(slices[0]->dim_z != slice->dim_z))
{
print_error("ERROR: Image array[0] and [%d] are different dimensions\n", image_index);
break;
}
}
else
{
is_hdr = slice_is_hdr;
component_count = slice_component_count;
}
}
// If all slices loaded correctly then repack them into a single image
if (slices.size() == dim_z)
{
unsigned int dim_x = slices[0]->dim_x;
unsigned int dim_y = slices[0]->dim_y;
int bitness = is_hdr ? 16 : 8;
int slice_size = dim_x * dim_y;
image = alloc_image(bitness, dim_x, dim_y, dim_z);
// Combine 2D source images into one 3D image
for (unsigned int z = 0; z < dim_z; z++)
{
if (image->data_type == ASTCENC_TYPE_U8)
{
uint8_t* data8 = static_cast<uint8_t*>(image->data[z]);
uint8_t* data8src = static_cast<uint8_t*>(slices[z]->data[0]);
size_t copy_size = slice_size * 4 * sizeof(uint8_t);
memcpy(data8, data8src, copy_size);
}
else if (image->data_type == ASTCENC_TYPE_F16)
{
uint16_t* data16 = static_cast<uint16_t*>(image->data[z]);
uint16_t* data16src = static_cast<uint16_t*>(slices[z]->data[0]);
size_t copy_size = slice_size * 4 * sizeof(uint16_t);
memcpy(data16, data16src, copy_size);
}
else // if (image->data_type == ASTCENC_TYPE_F32)
{
assert(image->data_type == ASTCENC_TYPE_F32);
float* data32 = static_cast<float*>(image->data[z]);
float* data32src = static_cast<float*>(slices[z]->data[0]);
size_t copy_size = slice_size * 4 * sizeof(float);
memcpy(data32, data32src, copy_size);
}
}
}
for (auto &i : slices)
{
free_image(i);
}
}
return image;
}
/**
* @brief Parse the command line.
*
* @param argc Command line argument count.
* @param[in] argv Command line argument vector.
* @param[out] operation Codec operation mode.
* @param[out] profile Codec color profile.
*
* @return 0 if everything is okay, 1 if there is some error
*/
static int parse_commandline_options(
int argc,
char **argv,
astcenc_operation& operation,
astcenc_profile& profile
) {
assert(argc >= 2); (void)argc;
profile = ASTCENC_PRF_LDR;
operation = ASTCENC_OP_UNKNOWN;
int modes_count = sizeof(modes) / sizeof(modes[0]);
for (int i = 0; i < modes_count; i++)
{
if (!strcmp(modes[i].opt, argv[1]))
{
operation = modes[i].operation;
profile = modes[i].decode_mode;
break;
}
}
if (operation == ASTCENC_OP_UNKNOWN)
{
print_error("ERROR: Unrecognized operation '%s'\n", argv[1]);
return 1;
}
return 0;
}
/**
* @brief Initialize the astcenc_config
*
* @param argc Command line argument count.
* @param[in] argv Command line argument vector.
* @param operation Codec operation mode.
* @param[out] profile Codec color profile.
* @param comp_image Compressed image if a decompress operation.
* @param[out] preprocess Image preprocess operation.
* @param[out] config Codec configuration.
*
* @return 0 if everything is okay, 1 if there is some error
*/
static int init_astcenc_config(
int argc,
char **argv,
astcenc_profile profile,
astcenc_operation operation,
astc_compressed_image& comp_image,
astcenc_preprocess& preprocess,
astcenc_config& config
) {
unsigned int block_x = 0;
unsigned int block_y = 0;
unsigned int block_z = 1;
// For decode the block size is set by the incoming image.
if (operation == ASTCENC_OP_DECOMPRESS)
{
block_x = comp_image.block_x;
block_y = comp_image.block_y;
block_z = comp_image.block_z;
}
float quality = 0.0f;
preprocess = ASTCENC_PP_NONE;
// parse the command line's encoding options.
int argidx = 4;
if (operation & ASTCENC_STAGE_COMPRESS)
{
// Read and decode block size
if (argc < 5)
{
print_error("ERROR: Block size must be specified\n");
return 1;
}
int cnt2D, cnt3D;
int dimensions = sscanf(argv[4], "%ux%u%nx%u%n",
&block_x, &block_y, &cnt2D, &block_z, &cnt3D);
// Character after the last match should be a NUL
if (!(((dimensions == 2) && !argv[4][cnt2D]) || ((dimensions == 3) && !argv[4][cnt3D])))
{
print_error("ERROR: Block size '%s' is invalid\n", argv[4]);
return 1;
}
// Read and decode search quality
if (argc < 6)
{
print_error("ERROR: Search quality level must be specified\n");
return 1;
}
if (!strcmp(argv[5], "-fastest"))
{
quality = ASTCENC_PRE_FASTEST;
}
else if (!strcmp(argv[5], "-fast"))
{
quality = ASTCENC_PRE_FAST;
}
else if (!strcmp(argv[5], "-medium"))
{
quality = ASTCENC_PRE_MEDIUM;
}
else if (!strcmp(argv[5], "-thorough"))
{
quality = ASTCENC_PRE_THOROUGH;
}
else if (!strcmp(argv[5], "-verythorough"))
{
quality = ASTCENC_PRE_VERYTHOROUGH;
}
else if (!strcmp(argv[5], "-exhaustive"))
{
quality = ASTCENC_PRE_EXHAUSTIVE;
}
else if (is_float(argv[5]))
{
quality = static_cast<float>(atof(argv[5]));
}
else
{
print_error("ERROR: Search quality/preset '%s' is invalid\n", argv[5]);
return 1;
}
argidx = 6;
}
unsigned int flags = 0;
// Gather the flags that we need
while (argidx < argc)
{
if (!strcmp(argv[argidx], "-a"))
{
// Skip over the data value for now
argidx++;
flags |= ASTCENC_FLG_USE_ALPHA_WEIGHT;
}
else if (!strcmp(argv[argidx], "-normal"))
{
flags |= ASTCENC_FLG_MAP_NORMAL;
}
else if (!strcmp(argv[argidx], "-decode_unorm8"))
{
flags |= ASTCENC_FLG_USE_DECODE_UNORM8;
}
else if (!strcmp(argv[argidx], "-rgbm"))
{
// Skip over the data value for now
argidx++;
flags |= ASTCENC_FLG_MAP_RGBM;
}
else if (!strcmp(argv[argidx], "-perceptual"))
{
flags |= ASTCENC_FLG_USE_PERCEPTUAL;
}
else if (!strcmp(argv[argidx], "-pp-normalize"))
{
if (preprocess != ASTCENC_PP_NONE)
{
print_error("ERROR: Only a single image preprocess can be used\n");
return 1;
}
preprocess = ASTCENC_PP_NORMALIZE;
}
else if (!strcmp(argv[argidx], "-pp-premultiply"))
{
if (preprocess != ASTCENC_PP_NONE)
{
print_error("ERROR: Only a single image preprocess can be used\n");
return 1;
}
preprocess = ASTCENC_PP_PREMULTIPLY;
}
argidx ++;
}
#if defined(ASTCENC_DECOMPRESS_ONLY)
flags |= ASTCENC_FLG_DECOMPRESS_ONLY;
#else
// Decompression can skip some memory allocation, but need full tables
if (operation == ASTCENC_OP_DECOMPRESS)
{
flags |= ASTCENC_FLG_DECOMPRESS_ONLY;
}
// Compression and test passes can skip some decimation initialization
// as we know we are decompressing images that were compressed using the
// same settings and heuristics ...
else
{
flags |= ASTCENC_FLG_SELF_DECOMPRESS_ONLY;
}
#endif
astcenc_error status = astcenc_config_init(profile, block_x, block_y, block_z,
quality, flags, &config);
if (status == ASTCENC_ERR_BAD_BLOCK_SIZE)
{
print_error("ERROR: Block size '%s' is invalid\n", argv[4]);
return 1;
}
else if (status == ASTCENC_ERR_BAD_DECODE_MODE)
{
print_error("ERROR: Decode_unorm8 is not supported by HDR profiles\n", argv[4]);
return 1;
}
else if (status == ASTCENC_ERR_BAD_CPU_FLOAT)
{
print_error("ERROR: astcenc must not be compiled with -ffast-math\n");
return 1;
}
else if (status != ASTCENC_SUCCESS)
{
print_error("ERROR: Init config failed with %s\n", astcenc_get_error_string(status));
return 1;
}
return 0;
}
/**
* @brief Edit the astcenc_config
*
* @param argc Command line argument count.
* @param[in] argv Command line argument vector.
* @param operation Codec operation.
* @param[out] cli_config Command line config.
* @param[in,out] config Codec configuration.
*
* @return 0 if everything is OK, 1 if there is some error
*/
static int edit_astcenc_config(
int argc,
char **argv,
const astcenc_operation operation,
cli_config_options& cli_config,
astcenc_config& config
) {
int argidx = (operation & ASTCENC_STAGE_COMPRESS) ? 6 : 4;
while (argidx < argc)
{
if (!strcmp(argv[argidx], "-silent"))
{
argidx++;
cli_config.silentmode = 1;
}
else if (!strcmp(argv[argidx], "-cw"))
{
argidx += 5;
if (argidx > argc)
{
print_error("ERROR: -cw switch with less than 4 arguments\n");
return 1;
}
config.cw_r_weight = static_cast<float>(atof(argv[argidx - 4]));
config.cw_g_weight = static_cast<float>(atof(argv[argidx - 3]));
config.cw_b_weight = static_cast<float>(atof(argv[argidx - 2]));
config.cw_a_weight = static_cast<float>(atof(argv[argidx - 1]));
}
else if (!strcmp(argv[argidx], "-a"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -a switch with no argument\n");
return 1;
}
config.a_scale_radius = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-esw"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -esw switch with no argument\n");
return 1;
}
if (strlen(argv[argidx - 1]) != 4)
{
print_error("ERROR: -esw pattern does not contain 4 characters\n");
return 1;
}
astcenc_swz swizzle_components[4];
for (int i = 0; i < 4; i++)
{
switch (argv[argidx - 1][i])
{
case 'r':
swizzle_components[i] = ASTCENC_SWZ_R;
break;
case 'g':
swizzle_components[i] = ASTCENC_SWZ_G;
break;
case 'b':
swizzle_components[i] = ASTCENC_SWZ_B;
break;
case 'a':
swizzle_components[i] = ASTCENC_SWZ_A;
break;
case '0':
swizzle_components[i] = ASTCENC_SWZ_0;
break;
case '1':
swizzle_components[i] = ASTCENC_SWZ_1;
break;
default:
print_error("ERROR: -esw component '%c' is not valid\n", argv[argidx - 1][i]);
return 1;
}
}
cli_config.swz_encode.r = swizzle_components[0];
cli_config.swz_encode.g = swizzle_components[1];
cli_config.swz_encode.b = swizzle_components[2];
cli_config.swz_encode.a = swizzle_components[3];
}
else if (!strcmp(argv[argidx], "-ssw"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -ssw switch with no argument\n");
return 1;
}
size_t char_count = strlen(argv[argidx - 1]);
if (char_count == 0)
{
print_error("ERROR: -ssw pattern contains no characters\n");
return 1;
}
if (char_count > 4)
{
print_error("ERROR: -ssw pattern contains more than 4 characters\n");
return 1;
}
bool found_r = false;
bool found_g = false;
bool found_b = false;
bool found_a = false;
for (size_t i = 0; i < char_count; i++)
{
switch (argv[argidx - 1][i])
{
case 'r':
found_r = true;
break;
case 'g':
found_g = true;
break;
case 'b':
found_b = true;
break;
case 'a':
found_a = true;
break;
default:
print_error("ERROR: -ssw component '%c' is not valid\n", argv[argidx - 1][i]);
return 1;
}
}
config.cw_r_weight = found_r ? 1.0f : 0.0f;
config.cw_g_weight = found_g ? 1.0f : 0.0f;
config.cw_b_weight = found_b ? 1.0f : 0.0f;
config.cw_a_weight = found_a ? 1.0f : 0.0f;
}
else if (!strcmp(argv[argidx], "-dsw"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -dsw switch with no argument\n");
return 1;
}
if (strlen(argv[argidx - 1]) != 4)
{
print_error("ERROR: -dsw switch does not contain 4 characters\n");
return 1;
}
astcenc_swz swizzle_components[4];
for (int i = 0; i < 4; i++)
{
switch (argv[argidx - 1][i])
{
case 'r':
swizzle_components[i] = ASTCENC_SWZ_R;
break;
case 'g':
swizzle_components[i] = ASTCENC_SWZ_G;
break;
case 'b':
swizzle_components[i] = ASTCENC_SWZ_B;
break;
case 'a':
swizzle_components[i] = ASTCENC_SWZ_A;
break;
case '0':
swizzle_components[i] = ASTCENC_SWZ_0;
break;
case '1':
swizzle_components[i] = ASTCENC_SWZ_1;
break;
case 'z':
swizzle_components[i] = ASTCENC_SWZ_Z;
break;
default:
print_error("ERROR: ERROR: -dsw component '%c' is not valid\n", argv[argidx - 1][i]);
return 1;
}
}
cli_config.swz_decode.r = swizzle_components[0];
cli_config.swz_decode.g = swizzle_components[1];
cli_config.swz_decode.b = swizzle_components[2];
cli_config.swz_decode.a = swizzle_components[3];
}
// presets begin here
else if (!strcmp(argv[argidx], "-normal"))
{
argidx++;
cli_config.swz_encode.r = ASTCENC_SWZ_R;
cli_config.swz_encode.g = ASTCENC_SWZ_R;
cli_config.swz_encode.b = ASTCENC_SWZ_R;
cli_config.swz_encode.a = ASTCENC_SWZ_G;
cli_config.swz_decode.r = ASTCENC_SWZ_R;
cli_config.swz_decode.g = ASTCENC_SWZ_A;
cli_config.swz_decode.b = ASTCENC_SWZ_Z;
cli_config.swz_decode.a = ASTCENC_SWZ_1;
}
else if (!strcmp(argv[argidx], "-rgbm"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -rgbm switch with no argument\n");
return 1;
}
config.rgbm_m_scale = static_cast<float>(atof(argv[argidx - 1]));
config.cw_a_weight = 2.0f * config.rgbm_m_scale;
}
else if (!strcmp(argv[argidx], "-decode_unorm8"))
{
argidx++;
}
else if (!strcmp(argv[argidx], "-perceptual"))
{
argidx++;
}
else if (!strcmp(argv[argidx], "-pp-normalize"))
{
argidx++;
}
else if (!strcmp(argv[argidx], "-pp-premultiply"))
{
argidx++;
}
else if (!strcmp(argv[argidx], "-blockmodelimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -blockmodelimit switch with no argument\n");
return 1;
}
config.tune_block_mode_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-partitioncountlimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -partitioncountlimit switch with no argument\n");
return 1;
}
config.tune_partition_count_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-2partitionindexlimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -2partitionindexlimit switch with no argument\n");
return 1;
}
config.tune_2partition_index_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-3partitionindexlimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -3partitionindexlimit switch with no argument\n");
return 1;
}
config.tune_3partition_index_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-4partitionindexlimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -4partitionindexlimit switch with no argument\n");
return 1;
}
config.tune_4partition_index_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-2partitioncandidatelimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -2partitioncandidatelimit switch with no argument\n");
return 1;
}
config.tune_2partitioning_candidate_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-3partitioncandidatelimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -3partitioncandidatelimit switch with no argument\n");
return 1;
}
config.tune_3partitioning_candidate_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-4partitioncandidatelimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -4partitioncandidatelimit switch with no argument\n");
return 1;
}
config.tune_4partitioning_candidate_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-dblimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -dblimit switch with no argument\n");
return 1;
}
if ((config.profile == ASTCENC_PRF_LDR) || (config.profile == ASTCENC_PRF_LDR_SRGB))
{
config.tune_db_limit = static_cast<float>(atof(argv[argidx - 1]));
}
}
else if (!strcmp(argv[argidx], "-2partitionlimitfactor"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -2partitionlimitfactor switch with no argument\n");
return 1;
}
config.tune_2partition_early_out_limit_factor = static_cast<float>(atof(argv[argidx - 1]));
}
else if (!strcmp(argv[argidx], "-3partitionlimitfactor"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -3partitionlimitfactor switch with no argument\n");
return 1;
}
config.tune_3partition_early_out_limit_factor = static_cast<float>(atof(argv[argidx - 1]));
}
else if (!strcmp(argv[argidx], "-2planelimitcorrelation"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -2planelimitcorrelation switch with no argument\n");
return 1;
}
config.tune_2plane_early_out_limit_correlation = static_cast<float>(atof(argv[argidx - 1]));
}
else if (!strcmp(argv[argidx], "-refinementlimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -refinementlimit switch with no argument\n");
return 1;
}
config.tune_refinement_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-candidatelimit"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -candidatelimit switch with no argument\n");
return 1;
}
config.tune_candidate_limit = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-j"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -j switch with no argument\n");
return 1;
}
cli_config.thread_count = atoi(argv[argidx - 1]);
}
else if (!strcmp(argv[argidx], "-repeats"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -repeats switch with no argument\n");
return 1;
}
cli_config.repeat_count = atoi(argv[argidx - 1]);
if (cli_config.repeat_count <= 0)
{
print_error("ERROR: -repeats value must be at least one\n");
return 1;
}
}
else if (!strcmp(argv[argidx], "-yflip"))
{
argidx++;
cli_config.y_flip = 1;
}
else if (!strcmp(argv[argidx], "-mpsnr"))
{
argidx += 3;
if (argidx > argc)
{
print_error("ERROR: -mpsnr switch with less than 2 arguments\n");
return 1;
}
cli_config.low_fstop = atoi(argv[argidx - 2]);
cli_config.high_fstop = atoi(argv[argidx - 1]);
if (cli_config.high_fstop < cli_config.low_fstop)
{
print_error("ERROR: -mpsnr switch <low> is greater than the <high>\n");
return 1;
}
}
// Option: Encode a 3D image from a sequence of 2D images.
else if (!strcmp(argv[argidx], "-zdim"))
{
// Only supports compressing
if (!(operation & ASTCENC_STAGE_COMPRESS))
{
print_error("ERROR: -zdim switch is only valid for compression\n");
return 1;
}
// Image depth must be specified.
if (argidx + 2 > argc)
{
print_error("ERROR: -zdim switch with no argument\n");
return 1;
}
argidx++;
// Read array size (image depth).
if (!sscanf(argv[argidx], "%u", &cli_config.array_size) || cli_config.array_size == 0)
{
print_error("ERROR: -zdim size '%s' is invalid\n", argv[argidx]);
return 1;
}
if ((cli_config.array_size > 1) && (config.block_z == 1))
{
print_error("ERROR: -zdim with 3D input data for a 2D output format\n");
return 1;
}
argidx++;
}
#if defined(ASTCENC_DIAGNOSTICS)
else if (!strcmp(argv[argidx], "-dtrace"))
{
argidx += 2;
if (argidx > argc)
{
print_error("ERROR: -dtrace switch with no argument\n");
return 1;
}
config.trace_file_path = argv[argidx - 1];
}
#endif
else if (!strcmp(argv[argidx], "-dimage"))
{
argidx += 1;
cli_config.diagnostic_images = true;
}
else // check others as well
{
print_error("ERROR: Argument '%s' not recognized\n", argv[argidx]);
return 1;
}
}
if (cli_config.thread_count <= 0)
{
cli_config.thread_count = get_cpu_count();
}
#if defined(ASTCENC_DIAGNOSTICS)
// Force single threaded for diagnostic builds
cli_config.thread_count = 1;
if (!config.trace_file_path)
{
print_error("ERROR: Diagnostics builds must set -dtrace\n");
return 1;
}
#endif
return 0;
}
/**
* @brief Print the config settings in a human readable form.
*
* @param[in] cli_config Command line config.
* @param[in] config Codec configuration.
*/
static void print_astcenc_config(
const cli_config_options& cli_config,
const astcenc_config& config
) {
// Print all encoding settings unless specifically told otherwise
if (!cli_config.silentmode)
{
printf("Compressor settings\n");
printf("===================\n\n");
switch (config.profile)
{
case ASTCENC_PRF_LDR:
printf(" Color profile: LDR linear\n");
break;
case ASTCENC_PRF_LDR_SRGB:
printf(" Color profile: LDR sRGB\n");
break;
case ASTCENC_PRF_HDR_RGB_LDR_A:
printf(" Color profile: HDR RGB + LDR A\n");
break;
case ASTCENC_PRF_HDR:
printf(" Color profile: HDR RGBA\n");
break;
}
if (config.block_z == 1)
{
printf(" Block size: %ux%u\n", config.block_x, config.block_y);
}
else
{
printf(" Block size: %ux%ux%u\n", config.block_x, config.block_y, config.block_z);
}
printf(" Bitrate: %3.2f bpp\n", 128.0 / (config.block_x * config.block_y * config.block_z));
printf(" RGB alpha scale weight: %d\n", (config.flags & ASTCENC_FLG_USE_ALPHA_WEIGHT));
if ((config.flags & ASTCENC_FLG_USE_ALPHA_WEIGHT))
{
printf(" Radius RGB alpha scale: %u texels\n", config.a_scale_radius);
}
printf(" R component weight: %g\n", static_cast<double>(config.cw_r_weight));
printf(" G component weight: %g\n", static_cast<double>(config.cw_g_weight));
printf(" B component weight: %g\n", static_cast<double>(config.cw_b_weight));
printf(" A component weight: %g\n", static_cast<double>(config.cw_a_weight));
printf(" Partition cutoff: %u partitions\n", config.tune_partition_count_limit);
printf(" 2 partition index cutoff: %u partition ids\n", config.tune_2partition_index_limit);
printf(" 3 partition index cutoff: %u partition ids\n", config.tune_3partition_index_limit);
printf(" 4 partition index cutoff: %u partition ids\n", config.tune_4partition_index_limit);
printf(" PSNR cutoff: %g dB\n", static_cast<double>(config.tune_db_limit));
printf(" 3 partition cutoff: %g\n", static_cast<double>(config.tune_2partition_early_out_limit_factor));
printf(" 4 partition cutoff: %g\n", static_cast<double>(config.tune_3partition_early_out_limit_factor));
printf(" 2 plane correlation cutoff: %g\n", static_cast<double>(config.tune_2plane_early_out_limit_correlation));
printf(" Block mode centile cutoff: %g%%\n", static_cast<double>(config.tune_block_mode_limit));
printf(" Candidate cutoff: %u candidates\n", config.tune_candidate_limit);
printf(" Refinement cutoff: %u iterations\n", config.tune_refinement_limit);
printf(" Compressor thread count: %d\n", cli_config.thread_count);
printf("\n");
}
}
/**
* @brief Get the value of a single pixel in an image.
*
* Note, this implementation is not particularly optimal as it puts format
* checks in the inner-most loop. For the CLI preprocess passes this is deemed
* acceptable as these are not performance critical paths.
*
* @param[in] img The output image.
* @param x The pixel x coordinate.
* @param y The pixel y coordinate.
* @param z The pixel z coordinate.
*
* @return pixel The pixel color value to write.
*/
static vfloat4 image_get_pixel(
const astcenc_image& img,
unsigned int x,
unsigned int y,
unsigned int z
) {
// We should never escape bounds
assert(x < img.dim_x);
assert(y < img.dim_y);
assert(z < img.dim_z);
if (img.data_type == ASTCENC_TYPE_U8)
{
uint8_t* data = static_cast<uint8_t*>(img.data[z]);
float r = data[(4 * img.dim_x * y) + (4 * x )] / 255.0f;
float g = data[(4 * img.dim_x * y) + (4 * x + 1)] / 255.0f;
float b = data[(4 * img.dim_x * y) + (4 * x + 2)] / 255.0f;
float a = data[(4 * img.dim_x * y) + (4 * x + 3)] / 255.0f;
return vfloat4(r, g, b, a);
}
else if (img.data_type == ASTCENC_TYPE_F16)
{
uint16_t* data = static_cast<uint16_t*>(img.data[z]);
vint4 colori(
data[(4 * img.dim_x * y) + (4 * x )],
data[(4 * img.dim_x * y) + (4 * x + 1)],
data[(4 * img.dim_x * y) + (4 * x + 2)],
data[(4 * img.dim_x * y) + (4 * x + 3)]
);
return float16_to_float(colori);
}
else // if (img.data_type == ASTCENC_TYPE_F32)
{
assert(img.data_type == ASTCENC_TYPE_F32);
float* data = static_cast<float*>(img.data[z]);
return vfloat4(
data[(4 * img.dim_x * y) + (4 * x )],
data[(4 * img.dim_x * y) + (4 * x + 1)],
data[(4 * img.dim_x * y) + (4 * x + 2)],
data[(4 * img.dim_x * y) + (4 * x + 3)]
);
}
}
/**
* @brief Set the value of a single pixel in an image.
*
* @param[out] img The output image; must use F32 texture components.
* @param x The pixel x coordinate.
* @param y The pixel y coordinate.
* @param z The pixel z coordinate.
* @param pixel The pixel color value to write.
*/
static void image_set_pixel(
astcenc_image& img,
unsigned int x,
unsigned int y,
unsigned int z,
vfloat4 pixel
) {
// We should never escape bounds
assert(x < img.dim_x);
assert(y < img.dim_y);
assert(z < img.dim_z);
assert(img.data_type == ASTCENC_TYPE_F32);
float* data = static_cast<float*>(img.data[z]);
data[(4 * img.dim_x * y) + (4 * x )] = pixel.lane<0>();
data[(4 * img.dim_x * y) + (4 * x + 1)] = pixel.lane<1>();
data[(4 * img.dim_x * y) + (4 * x + 2)] = pixel.lane<2>();
data[(4 * img.dim_x * y) + (4 * x + 3)] = pixel.lane<3>();
}
/**
* @brief Set the value of a single pixel in an image.
*
* @param[out] img The output image; must use F32 texture components.
* @param x The pixel x coordinate.
* @param y The pixel y coordinate.
* @param pixel The pixel color value to write.
*/
static void image_set_pixel_u8(
astcenc_image& img,
size_t x,
size_t y,
vint4 pixel
) {
// We should never escape bounds
assert(x < img.dim_x);
assert(y < img.dim_y);
assert(img.data_type == ASTCENC_TYPE_U8);
uint8_t* data = static_cast<uint8_t*>(img.data[0]);
pack_and_store_low_bytes(pixel, data + (4 * img.dim_x * y) + (4 * x));
}
/**
* @brief Create a copy of @c input with forced unit-length normal vectors.
*
* It is assumed that all normal vectors are stored in the RGB components, and
* stored in a packed unsigned range of [0,1] which must be unpacked prior
* normalization. Data must then be repacked into this form for handing over to
* the core codec.
*
* @param[in] input The input image.
* @param[out] output The output image, must use F32 components.
*/
static void image_preprocess_normalize(
const astcenc_image& input,
astcenc_image& output
) {
for (unsigned int z = 0; z < input.dim_z; z++)
{
for (unsigned int y = 0; y < input.dim_y; y++)
{
for (unsigned int x = 0; x < input.dim_x; x++)
{
vfloat4 pixel = image_get_pixel(input, x, y, z);
// Stash alpha component and zero
float a = pixel.lane<3>();
pixel.set_lane<3>(0.0f);
// Decode [0,1] normals to [-1,1]
pixel.set_lane<0>((pixel.lane<0>() * 2.0f) - 1.0f);
pixel.set_lane<1>((pixel.lane<1>() * 2.0f) - 1.0f);
pixel.set_lane<2>((pixel.lane<2>() * 2.0f) - 1.0f);
// Normalize pixel and restore alpha
pixel = normalize(pixel);
pixel.set_lane<3>(a);
// Encode [-1,1] normals to [0,1]
pixel.set_lane<0>((pixel.lane<0>() + 1.0f) / 2.0f);
pixel.set_lane<1>((pixel.lane<1>() + 1.0f) / 2.0f);
pixel.set_lane<2>((pixel.lane<2>() + 1.0f) / 2.0f);
image_set_pixel(output, x, y, z, pixel);
}
}
}
}
/**
* @brief Linearize an sRGB value.
*
* @return The linearized value.
*/
static float srgb_to_linear(
float a
) {
if (a <= 0.04045f)
{
return a * (1.0f / 12.92f);
}
return powf((a + 0.055f) * (1.0f / 1.055f), 2.4f);
}
/**
* @brief sRGB gamma-encode a linear value.
*
* @return The gamma encoded value.
*/
static float linear_to_srgb(
float a
) {
if (a <= 0.0031308f)
{
return a * 12.92f;
}
return 1.055f * powf(a, 1.0f / 2.4f) - 0.055f;
}
/**
* @brief Create a copy of @c input with premultiplied color data.
*
* If we are compressing sRGB data we linearize the data prior to
* premultiplication and re-gamma-encode afterwards.
*
* @param[in] input The input image.
* @param[out] output The output image, must use F32 components.
* @param profile The encoding profile.
*/
static void image_preprocess_premultiply(
const astcenc_image& input,
astcenc_image& output,
astcenc_profile profile
) {
for (unsigned int z = 0; z < input.dim_z; z++)
{
for (unsigned int y = 0; y < input.dim_y; y++)
{
for (unsigned int x = 0; x < input.dim_x; x++)
{
vfloat4 pixel = image_get_pixel(input, x, y, z);
// Linearize sRGB
if (profile == ASTCENC_PRF_LDR_SRGB)
{
pixel.set_lane<0>(srgb_to_linear(pixel.lane<0>()));
pixel.set_lane<1>(srgb_to_linear(pixel.lane<1>()));
pixel.set_lane<2>(srgb_to_linear(pixel.lane<2>()));
}
// Premultiply pixel in linear-space
pixel.set_lane<0>(pixel.lane<0>() * pixel.lane<3>());
pixel.set_lane<1>(pixel.lane<1>() * pixel.lane<3>());
pixel.set_lane<2>(pixel.lane<2>() * pixel.lane<3>());
// Gamma-encode sRGB
if (profile == ASTCENC_PRF_LDR_SRGB)
{
pixel.set_lane<0>(linear_to_srgb(pixel.lane<0>()));
pixel.set_lane<1>(linear_to_srgb(pixel.lane<1>()));
pixel.set_lane<2>(linear_to_srgb(pixel.lane<2>()));
}
image_set_pixel(output, x, y, z, pixel);
}
}
}
}
/**
* @brief Populate a single diagnostic image showing aspects of the encoding.
*
* @param context The context to use.
* @param image The compressed image to analyze.
* @param diag_image The output visualization image to populate.
* @param texel_func The per-texel callback used to determine output color.
*/
static void print_diagnostic_image(
astcenc_context* context,
const astc_compressed_image& image,
astcenc_image& diag_image,
std::function<vint4(astcenc_block_info&, size_t, size_t)> texel_func
) {
size_t block_cols = (image.dim_x + image.block_x - 1) / image.block_x;
size_t block_rows = (image.dim_y + image.block_y - 1) / image.block_y;
uint8_t* data = image.data;
for (size_t block_y = 0; block_y < block_rows; block_y++)
{
for (size_t block_x = 0; block_x < block_cols; block_x++)
{
astcenc_block_info block_info;
astcenc_get_block_info(context, data, &block_info);
data += 16;
size_t start_row = block_y * image.block_y;
size_t start_col = block_x * image.block_x;
size_t end_row = astc::min(start_row + image.block_y, static_cast<size_t>(image.dim_y));
size_t end_col = astc::min(start_col + image.block_x, static_cast<size_t>(image.dim_x));
for (size_t texel_y = start_row; texel_y < end_row; texel_y++)
{
for (size_t texel_x = start_col; texel_x < end_col; texel_x++)
{
vint4 color = texel_func(block_info, texel_x - start_col, texel_y - start_row);
image_set_pixel_u8(diag_image, texel_x, texel_y, color);
}
}
}
}
}
/**
* @brief Print a set of diagnostic images showing aspects of the encoding.
*
* @param context The context to use.
* @param image The compressed image to analyze.
* @param output_file The output file name to use as a stem for new names.
*/
static void print_diagnostic_images(
astcenc_context* context,
const astc_compressed_image& image,
const std::string& output_file
) {
if (image.dim_z != 1)
{
return;
}
// Try to find a file extension we know about
size_t index = output_file.find_last_of(".");
std::string stem = output_file;
if (index != std::string::npos)
{
stem = stem.substr(0, index);
}
auto diag_image = alloc_image(8, image.dim_x, image.dim_y, image.dim_z);
// ---- ---- ---- ---- Partitioning ---- ---- ---- ----
auto partition_func = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
const vint4 colors[] {
vint4( 0, 0, 0, 255),
vint4(255, 0, 0, 255),
vint4( 0, 255, 0, 255),
vint4( 0, 0, 255, 255),
vint4(255, 255, 255, 255)
};
size_t texel_index = texel_y * info.block_x + texel_x;
int partition { 0 };
if (!info.is_constant_block)
{
partition = info.partition_assignment[texel_index] + 1;
}
return colors[partition];
};
print_diagnostic_image(context, image, *diag_image, partition_func);
std::string fname = stem + "_diag_partitioning.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Weight planes ---- ---- ---- ----
auto texel_func1 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
const vint4 colors[] {
vint4( 0, 0, 0, 255),
vint4(255, 0, 0, 255),
vint4( 0, 255, 0, 255),
vint4( 0, 0, 255, 255),
vint4(255, 255, 255, 255)
};
int component { 0 };
if (info.is_dual_plane_block)
{
component = info.dual_plane_component + 1;
}
return colors[component];
};
print_diagnostic_image(context, image, *diag_image, texel_func1);
fname = stem + "_diag_weight_plane2.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Weight density ---- ---- ---- ----
auto texel_func2 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
float density = 0.0f;
if (!info.is_constant_block)
{
float texel_count = static_cast<float>(info.block_x * info.block_y);
float weight_count = static_cast<float>(info.weight_x * info.weight_y);
density = weight_count / texel_count;
}
int densityi = static_cast<int>(255.0f * density);
return vint4(densityi, densityi, densityi, 255);
};
print_diagnostic_image(context, image, *diag_image, texel_func2);
fname = stem + "_diag_weight_density.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Weight quant ---- ---- ---- ----
auto texel_func3 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
int quant { 0 };
if (!info.is_constant_block)
{
quant = info.weight_level_count - 1;
}
return vint4(quant, quant, quant, 255);
};
print_diagnostic_image(context, image, *diag_image, texel_func3);
fname = stem + "_diag_weight_quant.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Color quant ---- ---- ---- ----
auto texel_func4 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
int quant { 0 };
if (!info.is_constant_block)
{
quant = info.color_level_count - 1;
}
return vint4(quant, quant, quant, 255);
};
print_diagnostic_image(context, image, *diag_image, texel_func4);
fname = stem + "_diag_color_quant.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Color endpoint mode: Index ---- ---- ---- ----
auto texel_func5 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
size_t texel_index = texel_y * info.block_x + texel_x;
int cem { 255 };
if (!info.is_constant_block)
{
uint8_t partition = info.partition_assignment[texel_index];
cem = info.color_endpoint_modes[partition] * 16;
}
return vint4(cem, cem, cem, 255);
};
print_diagnostic_image(context, image, *diag_image, texel_func5);
fname = stem + "_diag_cem_index.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Color endpoint mode: Components ---- ---- ---- ----
auto texel_func6 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
const vint4 colors[] {
vint4( 0, 0, 0, 255),
vint4(255, 0, 0, 255),
vint4( 0, 255, 0, 255),
vint4( 0, 0, 255, 255),
vint4(255, 255, 255, 255)
};
size_t texel_index = texel_y * info.block_x + texel_x;
int components { 0 };
if (!info.is_constant_block)
{
uint8_t partition = info.partition_assignment[texel_index];
uint8_t cem = info.color_endpoint_modes[partition];
switch (cem)
{
case 0:
case 1:
case 2:
case 3:
components = 1;
break;
case 4:
case 5:
components = 2;
break;
case 6:
case 7:
case 8:
case 9:
case 11:
components = 3;
break;
default:
components = 4;
break;
}
}
return colors[components];
};
print_diagnostic_image(context, image, *diag_image, texel_func6);
fname = stem + "_diag_cem_components.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Color endpoint mode: Style ---- ---- ---- ----
auto texel_func7 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
const vint4 colors[] {
vint4( 0, 0, 0, 255),
vint4(255, 0, 0, 255),
vint4( 0, 255, 0, 255),
vint4( 0, 0, 255, 255),
};
size_t texel_index = texel_y * info.block_x + texel_x;
int style { 0 };
if (!info.is_constant_block)
{
uint8_t partition = info.partition_assignment[texel_index];
uint8_t cem = info.color_endpoint_modes[partition];
switch (cem)
{
// Direct - two absolute endpoints
case 0:
case 1:
case 2:
case 3:
case 4:
case 8:
case 11:
case 12:
case 14:
case 15:
style = 1;
break;
// Offset - one absolute plus delta
case 5:
case 9:
case 13:
style = 2;
break;
// Scale - one absolute plus scale
case 6:
case 7:
case 10:
style = 3;
break;
// Shouldn't happen ...
default:
style = 0;
break;
}
}
return colors[style];
};
print_diagnostic_image(context, image, *diag_image, texel_func7);
fname = stem + "_diag_cem_style.png";
store_ncimage(diag_image, fname.c_str(), false);
// ---- ---- ---- ---- Color endpoint mode: Style ---- ---- ---- ----
auto texel_func8 = [](astcenc_block_info& info, size_t texel_x, size_t texel_y) {
(void)texel_x;
(void)texel_y;
size_t texel_index = texel_y * info.block_x + texel_x;
int style { 0 };
if (!info.is_constant_block)
{
uint8_t partition = info.partition_assignment[texel_index];
uint8_t cem = info.color_endpoint_modes[partition];
switch (cem)
{
// LDR blocks
case 0:
case 1:
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
case 12:
case 13:
style = 128;
break;
// HDR blocks
default:
style = 155;
break;
}
}
return vint4(style, style, style, 255);
};
print_diagnostic_image(context, image, *diag_image, texel_func8);
fname = stem + "_diag_cem_hdr.png";
store_ncimage(diag_image, fname.c_str(), false);
free_image(diag_image);
}
/**
* @brief The main entry point.
*
* @param argc The number of arguments.
* @param argv The vector of arguments.
*
* @return 0 on success, non-zero otherwise.
*/
int astcenc_main(
int argc,
char **argv
) {
set_thread_name("astc main");
double start_time = get_time();
if (argc < 2)
{
astcenc_print_shorthelp();
return 0;
}
astcenc_operation operation;
astcenc_profile profile;
int error = parse_commandline_options(argc, argv, operation, profile);
if (error)
{
return 1;
}
switch (operation)
{
case ASTCENC_OP_HELP:
astcenc_print_longhelp();
return 0;
case ASTCENC_OP_VERSION:
astcenc_print_header();
return 0;
default:
break;
}
std::string input_filename = argc >= 3 ? argv[2] : "";
std::string output_filename = argc >= 4 ? argv[3] : "";
if (input_filename.empty())
{
print_error("ERROR: Input file not specified\n");
return 1;
}
if (output_filename.empty())
{
print_error("ERROR: Output file not specified\n");
return 1;
}
// TODO: Handle RAII resources so they get freed when out of scope
// Load the compressed input file if needed
// This has to come first, as the block size is in the file header
astc_compressed_image image_comp {};
if (operation & ASTCENC_STAGE_LD_COMP)
{
if (ends_with(input_filename, ".astc"))
{
error = load_cimage(input_filename.c_str(), image_comp);
if (error)
{
return 1;
}
}
else if (ends_with(input_filename, ".ktx"))
{
bool is_srgb;
error = load_ktx_compressed_image(input_filename.c_str(), is_srgb, image_comp);
if (error)
{
return 1;
}
if (is_srgb && (profile != ASTCENC_PRF_LDR_SRGB))
{
printf("WARNING: Input file is sRGB, but decompressing as linear\n");
}
if (!is_srgb && (profile == ASTCENC_PRF_LDR_SRGB))
{
printf("WARNING: Input file is linear, but decompressing as sRGB\n");
}
}
else
{
print_error("ERROR: Unknown compressed input file type\n");
return 1;
}
}
astcenc_config config {};
astcenc_preprocess preprocess;
error = init_astcenc_config(argc, argv, profile, operation, image_comp, preprocess, config);
if (error)
{
return 1;
}
// Initialize cli_config_options with default values
cli_config_options cli_config { 0, 1, 1, false, false, false, -10, 10,
{ ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A },
{ ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A } };
error = edit_astcenc_config(argc, argv, operation, cli_config, config);
if (error)
{
return 1;
}
// Enable progress callback if not in silent mode and using a terminal
#if defined(_WIN32)
int stdoutfno = _fileno(stdout);
#else
int stdoutfno = STDOUT_FILENO;
#endif
if ((!cli_config.silentmode) && isatty(stdoutfno))
{
config.progress_callback = progress_emitter;
}
astcenc_image* image_uncomp_in = nullptr ;
unsigned int image_uncomp_in_component_count = 0;
bool image_uncomp_in_is_hdr = false;
astcenc_image* image_decomp_out = nullptr;
// Determine decompression output bitness, if limited by file type
int out_bitness = 0;
if (operation & ASTCENC_STAGE_DECOMPRESS)
{
out_bitness = get_output_filename_enforced_bitness(output_filename.c_str());
if (out_bitness == 0)
{
bool is_hdr = (config.profile == ASTCENC_PRF_HDR) ||
(config.profile == ASTCENC_PRF_HDR_RGB_LDR_A);
out_bitness = is_hdr ? 16 : 8;
}
// If decompressed output is unorm8 then force the decode_unorm8 heuristics for compression
if (out_bitness == 8)
{
config.flags |= ASTCENC_FLG_USE_DECODE_UNORM8;
}
}
// TODO: Handle RAII resources so they get freed when out of scope
astcenc_error codec_status;
astcenc_context* codec_context;
// Preflight - check we have valid extensions for storing a file
if (operation & ASTCENC_STAGE_ST_NCOMP)
{
int bitness = get_output_filename_enforced_bitness(output_filename.c_str());
if (bitness < 0)
{
const char *eptr = strrchr(output_filename.c_str(), '.');
eptr = eptr ? eptr : "";
print_error("ERROR: Unknown uncompressed output file type '%s'\n", eptr);
return 1;
}
}
if (operation & ASTCENC_STAGE_ST_COMP)
{
#if defined(_WIN32)
bool is_null = output_filename == "NUL" || output_filename == "nul";
#else
bool is_null = output_filename == "/dev/null";
#endif
if (!(is_null || ends_with(output_filename, ".astc") || ends_with(output_filename, ".ktx")))
{
const char *eptr = strrchr(output_filename.c_str(), '.');
eptr = eptr ? eptr : "";
print_error("ERROR: Unknown compressed output file type '%s'\n", eptr);
return 1;
}
}
codec_status = astcenc_context_alloc(&config, cli_config.thread_count, &codec_context);
if (codec_status != ASTCENC_SUCCESS)
{
print_error("ERROR: Codec context alloc failed: %s\n", astcenc_get_error_string(codec_status));
return 1;
}
// Load the uncompressed input file if needed
if (operation & ASTCENC_STAGE_LD_NCOMP)
{
image_uncomp_in = load_uncomp_file(
input_filename.c_str(), cli_config.array_size, cli_config.y_flip,
image_uncomp_in_is_hdr, image_uncomp_in_component_count);
if (!image_uncomp_in)
{
print_error("ERROR: Failed to load uncompressed image file\n");
return 1;
}
if (preprocess != ASTCENC_PP_NONE)
{
// Allocate a float image so we can avoid additional quantization,
// as e.g. premultiplication can result in fractional color values
astcenc_image* image_pp = alloc_image(32,
image_uncomp_in->dim_x,
image_uncomp_in->dim_y,
image_uncomp_in->dim_z);
if (!image_pp)
{
print_error("ERROR: Failed to allocate preprocessed image\n");
return 1;
}
if (preprocess == ASTCENC_PP_NORMALIZE)
{
image_preprocess_normalize(*image_uncomp_in, *image_pp);
}
if (preprocess == ASTCENC_PP_PREMULTIPLY)
{
image_preprocess_premultiply(*image_uncomp_in, *image_pp,
config.profile);
}
// Delete the original as we no longer need it
free_image(image_uncomp_in);
image_uncomp_in = image_pp;
}
if (!cli_config.silentmode)
{
printf("Source image\n");
printf("============\n\n");
printf(" Source: %s\n", input_filename.c_str());
printf(" Color profile: %s\n", image_uncomp_in_is_hdr ? "HDR" : "LDR");
if (image_uncomp_in->dim_z > 1)
{
printf(" Dimensions: 3D, %ux%ux%u\n",
image_uncomp_in->dim_x, image_uncomp_in->dim_y, image_uncomp_in->dim_z);
}
else
{
printf(" Dimensions: 2D, %ux%u\n",
image_uncomp_in->dim_x, image_uncomp_in->dim_y);
}
printf(" Components: %d\n\n", image_uncomp_in_component_count);
}
}
double image_size = 0.0;
if (image_uncomp_in)
{
image_size = static_cast<double>(image_uncomp_in->dim_x) *
static_cast<double>(image_uncomp_in->dim_y) *
static_cast<double>(image_uncomp_in->dim_z);
}
else
{
image_size = static_cast<double>(image_comp.dim_x) *
static_cast<double>(image_comp.dim_y) *
static_cast<double>(image_comp.dim_z);
}
// Compress an image
double best_compression_time = 100000.0;
double total_compression_time = 0.0;
if (operation & ASTCENC_STAGE_COMPRESS)
{
print_astcenc_config(cli_config, config);
unsigned int blocks_x = (image_uncomp_in->dim_x + config.block_x - 1) / config.block_x;
unsigned int blocks_y = (image_uncomp_in->dim_y + config.block_y - 1) / config.block_y;
unsigned int blocks_z = (image_uncomp_in->dim_z + config.block_z - 1) / config.block_z;
size_t buffer_size = blocks_x * blocks_y * blocks_z * 16;
uint8_t* buffer = new uint8_t[buffer_size];
compression_workload work;
work.context = codec_context;
work.image = image_uncomp_in;
work.swizzle = cli_config.swz_encode;
work.data_out = buffer;
work.data_len = buffer_size;
work.error = ASTCENC_SUCCESS;
// Only launch worker threads for multi-threaded use - it makes basic
// single-threaded profiling and debugging a little less convoluted
double start_compression_time = get_time();
for (unsigned int i = 0; i < cli_config.repeat_count; i++)
{
if (config.progress_callback)
{
printf("Compression\n");
printf("===========\n");
printf("\n");
}
double start_iter_time = get_time();
if (cli_config.thread_count > 1)
{
launch_threads("Compression", cli_config.thread_count, compression_workload_runner, &work);
}
else
{
work.error = astcenc_compress_image(
work.context, work.image, &work.swizzle,
work.data_out, work.data_len, 0);
}
astcenc_compress_reset(codec_context);
if (config.progress_callback)
{
printf("\n\n");
}
double iter_time = get_time() - start_iter_time;
best_compression_time = astc::min(iter_time, best_compression_time);
}
total_compression_time = get_time() - start_compression_time;
if (work.error != ASTCENC_SUCCESS)
{
print_error("ERROR: Codec compress failed: %s\n", astcenc_get_error_string(work.error));
return 1;
}
image_comp.block_x = config.block_x;
image_comp.block_y = config.block_y;
image_comp.block_z = config.block_z;
image_comp.dim_x = image_uncomp_in->dim_x;
image_comp.dim_y = image_uncomp_in->dim_y;
image_comp.dim_z = image_uncomp_in->dim_z;
image_comp.data = buffer;
image_comp.data_len = buffer_size;
}
// Decompress an image
double best_decompression_time = 100000.0;
double total_decompression_time = 0.0;
if (operation & ASTCENC_STAGE_DECOMPRESS)
{
image_decomp_out = alloc_image(
out_bitness, image_comp.dim_x, image_comp.dim_y, image_comp.dim_z);
decompression_workload work;
work.context = codec_context;
work.data = image_comp.data;
work.data_len = image_comp.data_len;
work.image_out = image_decomp_out;
work.swizzle = cli_config.swz_decode;
work.error = ASTCENC_SUCCESS;
// Only launch worker threads for multi-threaded use - it makes basic
// single-threaded profiling and debugging a little less convoluted
double start_decompression_time = get_time();
for (unsigned int i = 0; i < cli_config.repeat_count; i++)
{
double start_iter_time = get_time();
if (cli_config.thread_count > 1)
{
launch_threads("Decompression", cli_config.thread_count, decompression_workload_runner, &work);
}
else
{
work.error = astcenc_decompress_image(
work.context, work.data, work.data_len,
work.image_out, &work.swizzle, 0);
}
astcenc_decompress_reset(codec_context);
double iter_time = get_time() - start_iter_time;
best_decompression_time = astc::min(iter_time, best_decompression_time);
}
total_decompression_time = get_time() - start_decompression_time;
if (work.error != ASTCENC_SUCCESS)
{
print_error("ERROR: Codec decompress failed: %s\n", astcenc_get_error_string(codec_status));
return 1;
}
}
#if defined(_WIN32)
bool is_null = output_filename == "NUL" || output_filename == "nul";
#else
bool is_null = output_filename == "/dev/null";
#endif
// Print metrics in comparison mode
if (operation & ASTCENC_STAGE_COMPARE)
{
bool is_normal_map = config.flags & ASTCENC_FLG_MAP_NORMAL;
compute_error_metrics(
image_uncomp_in_is_hdr, is_normal_map, image_uncomp_in_component_count,
image_uncomp_in, image_decomp_out, cli_config.low_fstop, cli_config.high_fstop);
}
// Store compressed image
if (operation & ASTCENC_STAGE_ST_COMP)
{
if (ends_with(output_filename, ".astc"))
{
error = store_cimage(image_comp, output_filename.c_str());
if (error)
{
print_error("ERROR: Failed to store compressed image\n");
return 1;
}
}
else if (ends_with(output_filename, ".ktx"))
{
bool srgb = profile == ASTCENC_PRF_LDR_SRGB;
error = store_ktx_compressed_image(image_comp, output_filename.c_str(), srgb);
if (error)
{
print_error("ERROR: Failed to store compressed image\n");
return 1;
}
}
else
{
if (!is_null)
{
print_error("ERROR: Unknown compressed output file type\n");
return 1;
}
}
}
// Store decompressed image
if (operation & ASTCENC_STAGE_ST_NCOMP)
{
if (!is_null)
{
bool store_result = store_ncimage(image_decomp_out, output_filename.c_str(),
cli_config.y_flip);
if (!store_result)
{
print_error("ERROR: Failed to write output image %s\n", output_filename.c_str());
return 1;
}
}
}
// Store diagnostic images
if (cli_config.diagnostic_images && !is_null)
{
print_diagnostic_images(codec_context, image_comp, output_filename);
}
free_image(image_uncomp_in);
free_image(image_decomp_out);
astcenc_context_free(codec_context);
delete[] image_comp.data;
if ((operation & ASTCENC_STAGE_COMPARE) || (!cli_config.silentmode))
{
double end_time = get_time();
double repeats = static_cast<double>(cli_config.repeat_count);
double avg_compression_time = total_compression_time / repeats;
double avg_decompression_time = total_decompression_time / repeats;
double total_time = (end_time - start_time) - ((repeats - 1.0) * avg_compression_time) - ((repeats - 1.0) * avg_decompression_time);
printf("Performance metrics\n");
printf("===================\n\n");
printf(" Total time: %8.4f s\n", total_time);
if (operation & ASTCENC_STAGE_COMPRESS)
{
double compression_rate = image_size / (best_compression_time * 1000000.0);
printf(" Coding time: %8.4f s\n", best_compression_time);
printf(" Coding rate: %8.4f MT/s\n", compression_rate);
}
if (operation & ASTCENC_STAGE_DECOMPRESS)
{
double decompression_rate = image_size / (best_decompression_time * 1000000.0);
printf(" Decoding time: %8.4f s\n", best_decompression_time);
printf(" Decoding rate: %8.4f MT/s\n", decompression_rate);
}
}
return 0;
}
|