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 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325
|
// basisu_tool.cpp
// Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.
// 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.
#if _MSC_VER
// For sprintf(), strcpy()
#define _CRT_SECURE_NO_WARNINGS (1)
#endif
#include "transcoder/basisu.h"
#include "transcoder/basisu_transcoder_internal.h"
#include "encoder/basisu_enc.h"
#include "encoder/basisu_etc.h"
#include "encoder/basisu_gpu_texture.h"
#include "encoder/basisu_frontend.h"
#include "encoder/basisu_backend.h"
#include "encoder/basisu_comp.h"
#include "transcoder/basisu_transcoder.h"
#include "encoder/basisu_ssim.h"
#include "encoder/basisu_opencl.h"
#define MINIZ_HEADER_FILE_ONLY
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#include "encoder/basisu_miniz.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
// Set BASISU_CATCH_EXCEPTIONS if you want exceptions to crash the app, otherwise main() catches them.
#ifndef BASISU_CATCH_EXCEPTIONS
#define BASISU_CATCH_EXCEPTIONS 0
#endif
using namespace basisu;
using namespace buminiz;
#define BASISU_TOOL_VERSION "1.50.0"
// Define to lower the -test and -test_hdr tolerances
//#define USE_TIGHTER_TEST_TOLERANCES
// Only enable to verify SAN is working.
//#define FORCE_SAN_FAILURE
enum tool_mode
{
cDefault,
cCompress,
cValidate,
cInfo,
cUnpack,
cCompare,
cHDRCompare,
cVersion,
cBench,
cCompSize,
cTestLDR,
cTestHDR,
cCLBench,
cSplitImage,
cCombineImages,
cTonemapImage
};
static void print_usage()
{
printf("\nUsage: basisu filename [filename ...] <options>\n");
puts("\n"
"The default mode is compression of one or more .PNG/.BMP/.TGA/.JPG/.QOI/.DDS/.EXR/.HDR files to a LDR or HDR .KTX2 file. Alternate modes:\n"
" -unpack: Use transcoder to unpack a .basis/.KTX2 file to one or more .KTX/.PNG files\n"
" -validate: Validate and display information about a .basis/.KTX2 file\n"
" -info: Display high-level information about a .basis/.KTX2 file\n"
" -compare: Compare two LDR PNG/BMP/TGA/JPG/QOI images specified with -file, output PSNR and SSIM statistics and RGB/A delta images\n"
" -compare_hdr: Compare two HDR .EXR/.HDR images specified with -file, output PSNR statistics and RGB delta images\n"
" -tonemap: Tonemap an HDR or EXR image to PNG at multiple exposures, use -file to specify filename\n"
" -version: Print version and exit\n"
"\n"
"Notes:\n"
"\nUnless an explicit mode is specified, if one or more files have the .basis or .KTX2 extension this tool defaults to unpack mode.\n"
"\nBy default, the compressor assumes the input is in the sRGB colorspace (like photos/albedo textures).\n"
"If the input is NOT sRGB (like a normal map), be sure to specify -linear for less artifacts. Depending on the content type, some experimentation may be needed.\n"
"\n"
"The TinyEXR library is used to read .EXR images. This library does not support all .EXR compression methods. For unsupported images, you can use ImageMagick to convert them to uncompressed .EXR.\n"
"\n"
"For .DDS source files: Mipmapped or not mipmapped 2D textures (but not cubemaps) are supported. Only uncompressed 32-bit RGBA/BGRA, half float RGBA, or float RGBA .DDS files are supported. In -tex_array mode, if a .DDS file is specified, all source files must be in .DDS format.\n"
"\n"
"Filenames prefixed with a @ symbol are read as filename listing files. Listing text files specify which actual filenames to process (one filename per line).\n"
"\n"
"Options:\n"
" -hdr: Encode input as UASTC HDR (automatic if any input file has the .EXR or .HDR extension, or if any .DDS file is HDR).\n"
" -fastest: Set UASTC LDR and HDR to fastest but lowest quality encoding mode (same as -uastc_level 0)\n"
" -slower: Set UASTC LDR and HDR to slower but a higher quality encoding mode (same as -uastc_level 3)\n"
" -opencl: Enable OpenCL usage (currently only accelerates ETC1S encoding)\n"
" -opencl_serialize: Serialize all calls to the OpenCL driver (to work around buggy drivers, only useful with -parallel)\n"
" -parallel: Compress multiple textures simumtanously (one per thread), instead of one at a time. Compatible with OpenCL mode. This is much faster, but in OpenCL mode the driver is pushed harder, and the CLI output will be jumbled.\n"
" -ktx2: Write .KTX2 files (the default). By default, UASTC LDR/HDR files will be compressed using Zstandard unless -ktx2_no_zstandard is specified.\n"
" -basis: Write .basis files instead of .KTX2 files (the previous default).\n"
" -file filename.png/bmp/tga/jpg/qoi: Input image filename, multiple images are OK, use -file X for each input filename (prefixing input filenames with -file is optional)\n"
" -alpha_file filename.png/bmp/tga/jpg/qoi: Input alpha image filename, multiple images are OK, use -file X for each input filename (must be paired with -file), images converted to REC709 grayscale and used as input alpha\n"
" -multifile_printf: printf() format strint to use to compose multiple filenames\n"
" -multifile_first: The index of the first file to process, default is 0 (must specify -multifile_printf and -multifile_num)\n"
" -multifile_num: The total number of files to process.\n"
" -q X: Set ETC1S quality level, 1-255, default is 128, lower=better compression/lower quality/faster, higher=less compression/higher quality/slower, default is 128. For even higher quality, use -max_endpoints/-max_selectors.\n"
" -linear: Use linear colorspace metrics (instead of the default sRGB or scaled RGB for HDR), and by default linear (not sRGB) mipmap filtering.\n"
" -output_file filename: Output .basis/.KTX2 filename\n"
" -output_path: Output .basis/.KTX2 files to specified directory.\n"
" -debug or -verbose: Enable codec debug print to stdout (slightly slower).\n"
" -debug_images: Enable codec debug images (much slower).\n"
" -stats: Compute and display image quality metrics (slightly to much slower).\n"
" -tex_type <2d, 2darray, 3d, video, cubemap>: Set Basis file header's texture type field. Cubemap arrays require multiples of 6 images, in X+, X-, Y+, Y-, Z+, Z- order, each image must be the same resolutions.\n"
" 2d=arbitrary 2D images, 2darray=2D array, 3D=volume texture slices, video=video frames, cubemap=array of faces. For 2darray/3d/cubemaps/video, each source image's dimensions and # of mipmap levels must be the same.\n"
" For video, the .basis file will be written with the first frame being an I-Frame, and subsequent frames being P-Frames (using conditional replenishment). Playback must always occur in order from first to last image.\n"
" -cubemap: same as -tex_type cubemap\n"
" -individual: Process input images individually and output multiple .basis/.KTX2 files (not as a texture array - this is now the default as of v1.16)\n"
" -tex_array: Process input images as a single texture array and write a single .basis/.KTX2 file (the former default before v1.16)\n"
" -comp_level X: Set ETC1S encoding speed vs. quality tradeoff. Range is 0-6, default is 1. Higher values=MUCH slower, but slightly higher quality. Higher levels intended for videos. Use -q first!\n"
" -fuzz_testing: Use with -validate: Disables CRC16 validation of file contents before transcoding\n"
"\nUASTC options:\n"
" -uastc: Enable UASTC LDR texture mode, instead of the default ETC1S mode. Significantly higher texture quality, but larger files. (Note that UASTC .basis files must be losslessly compressed by the user.)\n"
" -uastc_level: Set UASTC LDR/HDR encoding level. LDR Range is [0,4], default is 2, higher=slower but higher quality. 0=fastest/lowest quality, 3=slowest practical option, 4=impractically slow/highest achievable quality\n"
" UASTC HDR range is [0,4] - higher=slower but higher quality. HDR default=1.\n"
" -uastc_rdo_l X: Enable UASTC LDR RDO post-processing and set UASTC RDO quality scalar (lambda) to X. Lower values=higher quality/larger LZ\n"
" compressed files, higher values=lower quality/smaller LZ compressed files. Good range to try is [.25-10].\n"
" Note: Previous versons used the -uastc_rdo_q option, which was removed because the RDO algorithm was changed.\n"
" -uastc_rdo_d X: Set UASTC LDR RDO dictionary size in bytes. Default is 4096, max is 65536. Lower values=faster, but less compression.\n"
" -uastc_rdo_b X: Set UASTC LDR RDO max smooth block error scale. Range is [1,300]. Default is 10.0, 1.0=disabled. Larger values suppress more artifacts (and allocate more bits) on smooth blocks.\n"
" -uastc_rdo_s X: Set UASTC LDR RDO max smooth block standard deviation. Range is [.01,65536]. Default is 18.0. Larger values expand the range of blocks considered smooth.\n"
" -uastc_rdo_f: Don't favor simpler UASTC LDR modes in RDO mode.\n"
" -uastc_rdo_m: Disable RDO multithreading (slightly higher compression, deterministic).\n"
"\n"
"HDR specific options:\n"
" -uastc_level X: Sets the UASTC HDR compressor's level. Valid range is [0,4] - higher=slower but higher quality. HDR default=1.\n"
" Level 0=fastest/lowest quality, 3=highest practical setting, 4=exhaustive\n"
" -hdr_ldr_no_srgb_to_linear: If specified, LDR images will NOT be converted to normalized linear light (via a sRGB->Linear conversion) before compressing as HDR.\n"
" -hdr_uber_mode: Allow the encoder to try varying the selectors more for slightly higher quality. This may negatively impact BC6H quality, however.\n"
" -hdr_favor_astc: By default the HDR encoder tries to strike a balance or even slightly favor BC6H quality. If this option is specified, ASTC HDR quality is favored instead.\n"
"\n"
"More options:\n"
" -test: Run an automated LDR ETC1S/UASTC encoding and transcoding test. Returns EXIT_FAILURE if any failures\n"
" -test_hdr: Run an automated UASTC HDR encoding and transcoding test. Returns EXIT_FAILURE if any failures\n"
" -test_dir: Optional directory of test files. Defaults to \"../test_files\".\n"
" -max_endpoints X: Manually set the max number of color endpoint clusters from 1-16128, use instead of -q\n"
" -max_selectors X: Manually set the max number of color selector clusters from 1-16128, use instead of -q\n"
" -y_flip: Flip input images vertically before compression\n"
" -normal_map: Tunes codec parameters for better quality on normal maps (linear colorspace metrics, linear mipmap filtering, no selector RDO, no sRGB)\n"
" -no_alpha: Always output non-alpha basis files, even if one or more inputs has alpha\n"
" -force_alpha: Always output alpha basis files, even if no inputs has alpha\n"
" -separate_rg_to_color_alpha: Separate input R and G channels to RGB and A (for tangent space XY normal maps)\n"
" -swizzle rgba: Specify swizzle for the 4 input color channels using r, g, b and a (the -separate_rg_to_color_alpha flag is equivalent to rrrg)\n"
" -renorm: Renormalize each input image before any further processing/compression\n"
" -no_multithreading: Disable multithreading\n"
" -max_threads X: Use at most X threads total when multithreading is enabled (this includes the main thread)\n"
" -no_ktx: Disable KTX writing when unpacking (faster, less output files)\n"
" -ktx_only: Only write KTX files when unpacking (faster, less output files)\n"
" -write_out: Write 3dfx OUT files when unpacking FXT1 textures\n"
" -format_only: Only unpack the specified format, by its numeric code.\n"
" -etc1_only: Only unpack to ETC1, skipping the other texture formats during -unpack\n"
" -disable_hierarchical_endpoint_codebooks: Disable hierarchical endpoint codebook usage, slower but higher quality on some compression levels\n"
" -compare_ssim: Compute and display SSIM of image comparison (slow)\n"
" -compare_plot: Display histogram plots in -compare mode\n"
" -bench: UASTC benchmark mode, for development only\n"
" -resample X Y: Resample all input textures to XxY pixels using a box filter\n"
" -resample_factor X: Resample all input textures by scale factor X using a box filter\n"
" -no_sse: Forbid all SSE instruction set usage\n"
" -validate_etc1s: Validate internal ETC1S compressor's data structures during compression (slower, intended for development).\n"
" -ktx2_animdata_duration X: Set KTX2animData duration field to integer value X (only valid/useful for -tex_type video, default is 1)\n"
" -ktx2_animdata_timescale X: Set KTX2animData timescale field to integer value X (only valid/useful for -tex_type video, default is 15)\n"
" -ktx2_animdata_loopcount X: Set KTX2animData loopcount field to integer value X (only valid/useful for -tex_type video, default is 0)\n"
" -framerate X: Set framerate in .basis header to X/frames sec.\n"
" -ktx2_no_zstandard: Don't compress UASTC texture data using Zstandard -- store it uncompressed instead.\n"
" -ktx2_zstandard_level X: Set ZStandard compression level to X (see Zstandard documentation, default level is 6)\n"
"\n"
"Mipmap generation options:\n"
" -mipmap: Generate mipmaps for each source image\n"
" -mip_srgb: Convert image to linear before filtering, then back to sRGB\n"
" -mip_linear: Keep image in linear light during mipmap filtering (i.e. do not convert to/from sRGB for filtering purposes)\n"
" -mip_scale X: Set mipmap filter kernel's scale, lower=sharper, higher=more blurry, default is 1.0\n"
" -mip_filter X: Set mipmap filter kernel, default is kaiser, filters: box, tent, bell, blackman, catmullrom, mitchell, etc.\n"
" -mip_renorm: Renormalize normal map to unit length vectors after filtering\n"
" -mip_clamp: Use clamp addressing on borders, instead of wrapping\n"
" -mip_fast: Use faster mipmap generation (resample from previous mip, not always first/largest mip level). The default (as of 1/2021)\n"
" -mip_slow: Always resample each mipmap level starting from the largest mipmap. Higher quality, but slower. Opposite of -mip_fast. Was the prior default before 1/2021.\n"
" -mip_smallest X: Set smallest pixel dimension for generated mipmaps, default is 1 pixel\n"
"By default, textures will be converted from sRGB to linear light before mipmap filtering, then back to sRGB (for the RGB color channels) unless -linear is specified.\n"
"You can override this behavior with -mip_srgb/-mip_linear.\n"
"\n"
"Backend endpoint/selector RDO codec options:\n"
" -no_selector_rdo: Disable backend's selector rate distortion optimizations (slightly faster, less noisy output, but lower quality per output bit)\n"
" -selector_rdo_thresh X: Set selector RDO quality threshold, default is 1.25, lower is higher quality but less quality per output bit (try 1.0-3.0)\n"
" -no_endpoint_rdo: Disable backend's endpoint rate distortion optimizations (slightly faster, less noisy output, but lower quality per output bit)\n"
" -endpoint_rdo_thresh X: Set endpoint RDO quality threshold, default is 1.5, lower is higher quality but less quality per output bit (try 1.0-3.0)\n"
"\n"
"Set various fields in the Basis file header:\n"
" -userdata0 X: Set 32-bit userdata0 field in Basis file header to X (X is a signed 32-bit int)\n"
" -userdata1 X: Set 32-bit userdata1 field in Basis file header to X (X is a signed 32-bit int)\n"
"\n"
"Example LDR command lines:\n"
" basisu x.png : Compress sRGB image x.png to x.ktx2 using default settings (multiple filenames OK, use -tex_array if you want a tex array vs. multiple output files)\n"
" basisu -basis x.qoi : Compress sRGB image x.qoi to x.basis (supports 24-bit or 32-bit .QOI files)\n"
" basisu x.ktx2 : Unpack x.basis to PNG/KTX files (multiple filenames OK)\n"
" basisu x.basis : Unpack x.basis to PNG/KTX files (multiple filenames OK)\n"
" basisu -uastc x.png -uastc_rdo_l 2.0 -ktx2 -stats : Compress to a UASTC .KTX2 file with RDO (rate distortion optimization) to reduce .KTX2 compressed file size\n"
" basisu -file x.png -mipmap -y_flip : Compress a mipmapped x.ktx2 file from an sRGB image named x.png, Y flip each source image\n"
" basisu -validate -file x.basis : Validate x.basis (check header, check file CRC's, attempt to transcode all slices)\n"
" basisu -unpack -file x.basis : Validates, transcodes and unpacks x.basis to mipmapped .KTX and RGB/A .PNG files (transcodes to all supported GPU texture formats)\n"
" basisu -q 255 -file x.png -mipmap -debug -stats : Compress sRGB x.png to x.ktx2 at quality level 255 with compressor debug output/statistics\n"
" basisu -linear -max_endpoints 16128 -max_selectors 16128 -file x.png : Compress non-sRGB x.png to x.ktx2 using the largest supported manually specified codebook sizes\n"
" basisu -basis -comp_level 2 -max_selectors 8192 -max_endpoints 8192 -tex_type video -framerate 20 -multifile_printf \"x%02u.png\" -multifile_first 1 -multifile_count 20 : Compress a 20 sRGB source image video sequence (x01.png, x02.png, x03.png, etc.) to x01.basis\n"
"\n"
"Example HDR command lines:\n"
" basisu x.exr : Compress a HDR .EXR image to a UASTC HDR .KTX2 file.\n"
" basisu x.hdr -uastc_level 0 : Compress a HDR .hdr image to a UASTC HDR .KTX2 file, fastest encoding but lowest quality\n"
" basisu -hdr x.png : Compress a LDR .PNG image to UASTC HDR (image is converted from sRGB to linear light first, use -hdr_ldr_no_srgb_to_linear to disable)\n"
" basisu x.hdr -uastc_level 3 : Compress a HDR .hdr image to UASTC HDR at higher quality (-uastc_level 4 is highest quality, but very slow encoding)\n"
" basisu x.hdr -uastc_level 3 -mipmap -basis -stats -debug -debug_images : Compress a HDR .hdr image to a UASTC HDR, .basis output file, at higher quality, generate mipmaps, output statistics and debug information, and write tone mapped debug images\n"
" basisu x.hdr -stats -hdr_favor_astc -hdr_uber_mode -uastc_level 4 : Highest achievable ASTC HDR quality (very slow encoding, BC6H quality is traded off)\n"
"\n"
"Video notes: For video use, it's recommended to encode on a machine with many cores. Use -comp_level 2 or higher for better codebook\n"
"generation, specify very large codebooks using -max_endpoints and -max_selectors, and reduce the default endpoint RDO threshold\n"
"(-endpoint_rdo_thresh) to around 1.25. Videos may have mipmaps and alpha channels. Videos must always be played back by the transcoder\n"
"in first to last image order.\n"
"Video files currently use I-Frames on the first image, and P-Frames using conditional replenishment on subsequent frames.\n"
"\nETC1S Compression level (-comp_level X) details. This controls the ETC1S speed vs. quality trandeoff. (Use -q to control the quality vs. compressed size tradeoff.):\n"
" Level 0: Fastest, but has marginal quality and can be brittle on complex images. Avg. Y dB: 35.45\n"
" Level 1: Hierarchical codebook searching, faster ETC1S encoding. 36.87 dB, ~1.4x slower vs. level 0. (This is the default setting.)\n"
" Level 2: Use this or higher for video. Hierarchical codebook searching. 36.87 dB, ~1.4x slower vs. level 0. (This is the v1.12's default setting.)\n"
" Level 3: Full codebook searching. 37.13 dB, ~1.8x slower vs. level 0. (Equivalent the the initial release's default settings.)\n"
" Level 4: Hierarchical codebook searching, codebook k-means iterations. 37.15 dB, ~4x slower vs. level 0\n"
" Level 5: Full codebook searching, codebook k-means iterations. 37.41 dB, ~5.5x slower vs. level 0.\n"
" Level 6: Full codebook searching, twice as many codebook k-means iterations, best ETC1 endpoint opt. 37.43 dB, ~12x slower vs. level 0\n"
);
}
static bool load_listing_file(const std::string &f, basisu::vector<std::string> &filenames)
{
std::string filename(f);
filename.erase(0, 1);
FILE *pFile = nullptr;
#ifdef _WIN32
fopen_s(&pFile, filename.c_str(), "r");
#else
pFile = fopen(filename.c_str(), "r");
#endif
if (!pFile)
{
error_printf("Failed opening listing file: \"%s\"\n", filename.c_str());
return false;
}
uint32_t total_filenames = 0;
for ( ; ; )
{
char buf[3072];
buf[0] = '\0';
char *p = fgets(buf, sizeof(buf), pFile);
if (!p)
{
if (ferror(pFile))
{
error_printf("Failed reading from listing file: \"%s\"\n", filename.c_str());
fclose(pFile);
return false;
}
else
break;
}
std::string read_filename(p);
while (read_filename.size())
{
if (read_filename[0] == ' ')
read_filename.erase(0, 1);
else
break;
}
while (read_filename.size())
{
const char c = read_filename.back();
if ((c == ' ') || (c == '\n') || (c == '\r'))
read_filename.erase(read_filename.size() - 1, 1);
else
break;
}
if (read_filename.size())
{
filenames.push_back(read_filename);
total_filenames++;
}
}
fclose(pFile);
printf("Successfully read %u filenames(s) from listing file \"%s\"\n", total_filenames, filename.c_str());
return true;
}
class command_line_params
{
BASISU_NO_EQUALS_OR_COPY_CONSTRUCT(command_line_params);
public:
command_line_params() :
m_mode(cDefault),
m_ktx2_mode(true),
m_ktx2_zstandard(true),
m_ktx2_zstandard_level(6),
m_ktx2_animdata_duration(1),
m_ktx2_animdata_timescale(15),
m_ktx2_animdata_loopcount(0),
m_format_only(-1),
m_multifile_first(0),
m_multifile_num(0),
m_max_threads(1024), // surely this is high enough
m_individual(true),
m_no_ktx(false),
m_ktx_only(false),
m_write_out(false),
m_etc1_only(false),
m_fuzz_testing(false),
m_compare_ssim(false),
m_compare_plot(false),
m_parallel_compression(false)
{
m_comp_params.m_compression_level = basisu::maximum<int>(0, BASISU_DEFAULT_COMPRESSION_LEVEL - 1);
m_comp_params.m_uastc_hdr_options.set_quality_level(astc_hdr_codec_options::cDefaultLevel);
m_test_file_dir = "../test_files";
}
bool parse(int arg_c, const char **arg_v)
{
int arg_index = 1;
while (arg_index < arg_c)
{
const char *pArg = arg_v[arg_index];
const int num_remaining_args = arg_c - (arg_index + 1);
int arg_count = 1;
#define REMAINING_ARGS_CHECK(n) if (num_remaining_args < (n)) { error_printf("Error: Expected %u values to follow %s!\n", n, pArg); return false; }
if ((strcasecmp(pArg, "-help") == 0) || (strcasecmp(pArg, "--help") == 0))
{
print_usage();
exit(EXIT_SUCCESS);
}
else if (strcasecmp(pArg, "-ktx2") == 0)
{
m_ktx2_mode = true;
}
else if (strcasecmp(pArg, "-basis") == 0)
{
m_ktx2_mode = false;
}
else if (strcasecmp(pArg, "-ktx2_no_zstandard") == 0)
{
m_ktx2_zstandard = false;
}
else if (strcasecmp(pArg, "-ktx2_zstandard_level") == 0)
{
REMAINING_ARGS_CHECK(1);
m_ktx2_zstandard_level = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-ktx2_animdata_duration") == 0)
{
REMAINING_ARGS_CHECK(1);
m_ktx2_animdata_duration = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-ktx2_animdata_timescale") == 0)
{
REMAINING_ARGS_CHECK(1);
m_ktx2_animdata_timescale = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-ktx2_animdata_loopcount") == 0)
{
REMAINING_ARGS_CHECK(1);
m_ktx2_animdata_loopcount = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-ldr") == 0)
{
}
else if (strcasecmp(pArg, "-compress") == 0)
m_mode = cCompress;
else if (strcasecmp(pArg, "-compare") == 0)
m_mode = cCompare;
else if ((strcasecmp(pArg, "-hdr_compare") == 0) || (strcasecmp(pArg, "-compare_hdr") == 0))
m_mode = cHDRCompare;
else if (strcasecmp(pArg, "-split") == 0)
m_mode = cSplitImage;
else if (strcasecmp(pArg, "-combine") == 0)
m_mode = cCombineImages;
else if (strcasecmp(pArg, "-tonemap") == 0)
m_mode = cTonemapImage;
else if (strcasecmp(pArg, "-unpack") == 0)
m_mode = cUnpack;
else if (strcasecmp(pArg, "-validate") == 0)
m_mode = cValidate;
else if (strcasecmp(pArg, "-info") == 0)
m_mode = cInfo;
else if ((strcasecmp(pArg, "-version") == 0) || (strcasecmp(pArg, "--version") == 0))
m_mode = cVersion;
else if (strcasecmp(pArg, "-compare_ssim") == 0)
m_compare_ssim = true;
else if (strcasecmp(pArg, "-compare_plot") == 0)
m_compare_plot = true;
else if (strcasecmp(pArg, "-bench") == 0)
m_mode = cBench;
else if (strcasecmp(pArg, "-comp_size") == 0)
m_mode = cCompSize;
else if (strcasecmp(pArg, "-hdr_ldr_no_srgb_to_linear") == 0)
m_comp_params.m_hdr_ldr_srgb_to_linear_conversion = false;
else if (strcasecmp(pArg, "-hdr_uber_mode") == 0)
m_comp_params.m_uastc_hdr_options.m_allow_uber_mode = true;
else if (strcasecmp(pArg, "-hdr_favor_astc") == 0)
m_comp_params.m_hdr_favor_astc = true;
else if ((strcasecmp(pArg, "-test") == 0) || (strcasecmp(pArg, "-test_ldr") == 0))
m_mode = cTestLDR;
else if (strcasecmp(pArg, "-test_hdr") == 0)
m_mode = cTestHDR;
else if (strcasecmp(pArg, "-clbench") == 0)
m_mode = cCLBench;
else if (strcasecmp(pArg, "-test_dir") == 0)
{
REMAINING_ARGS_CHECK(1);
m_test_file_dir = std::string(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-no_sse") == 0)
{
#if BASISU_SUPPORT_SSE
g_cpu_supports_sse41 = false;
#endif
}
else if (strcasecmp(pArg, "-no_status_output") == 0)
{
m_comp_params.m_status_output = false;
}
else if (strcasecmp(pArg, "-file") == 0)
{
REMAINING_ARGS_CHECK(1);
m_input_filenames.push_back(std::string(arg_v[arg_index + 1]));
arg_count++;
}
else if (strcasecmp(pArg, "-alpha_file") == 0)
{
REMAINING_ARGS_CHECK(1);
m_input_alpha_filenames.push_back(std::string(arg_v[arg_index + 1]));
arg_count++;
}
else if (strcasecmp(pArg, "-multifile_printf") == 0)
{
REMAINING_ARGS_CHECK(1);
m_multifile_printf = std::string(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-multifile_first") == 0)
{
REMAINING_ARGS_CHECK(1);
m_multifile_first = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-multifile_num") == 0)
{
REMAINING_ARGS_CHECK(1);
m_multifile_num = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-uastc") == 0)
m_comp_params.m_uastc = true;
else if (strcasecmp(pArg, "-fastest") == 0)
{
m_comp_params.m_pack_uastc_flags &= ~cPackUASTCLevelMask;
m_comp_params.m_pack_uastc_flags |= cPackUASTCLevelFastest;
m_comp_params.m_uastc_hdr_options.set_quality_level(0);
}
else if (strcasecmp(pArg, "-slower") == 0)
{
m_comp_params.m_pack_uastc_flags &= ~cPackUASTCLevelMask;
m_comp_params.m_pack_uastc_flags |= cPackUASTCLevelSlower;
m_comp_params.m_uastc_hdr_options.set_quality_level(3);
}
else if (strcasecmp(pArg, "-uastc_level") == 0)
{
REMAINING_ARGS_CHECK(1);
int uastc_level = atoi(arg_v[arg_index + 1]);
uastc_level = clamp<int>(uastc_level, 0, TOTAL_PACK_UASTC_LEVELS - 1);
static_assert(TOTAL_PACK_UASTC_LEVELS == 5, "TOTAL_PACK_UASTC_LEVELS==5");
static const uint32_t s_level_flags[TOTAL_PACK_UASTC_LEVELS] = { cPackUASTCLevelFastest, cPackUASTCLevelFaster, cPackUASTCLevelDefault, cPackUASTCLevelSlower, cPackUASTCLevelVerySlow };
m_comp_params.m_pack_uastc_flags &= ~cPackUASTCLevelMask;
m_comp_params.m_pack_uastc_flags |= s_level_flags[uastc_level];
m_comp_params.m_uastc_hdr_options.set_quality_level(uastc_level);
arg_count++;
}
else if (strcasecmp(pArg, "-resample") == 0)
{
REMAINING_ARGS_CHECK(2);
m_comp_params.m_resample_width = atoi(arg_v[arg_index + 1]);
m_comp_params.m_resample_height = atoi(arg_v[arg_index + 2]);
arg_count += 2;
}
else if (strcasecmp(pArg, "-resample_factor") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_resample_factor = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-uastc_rdo_l") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_rdo_uastc_quality_scalar = (float)atof(arg_v[arg_index + 1]);
m_comp_params.m_rdo_uastc = true;
arg_count++;
}
else if (strcasecmp(pArg, "-uastc_rdo_d") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_rdo_uastc_dict_size = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-uastc_rdo_b") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_rdo_uastc_max_smooth_block_error_scale = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-uastc_rdo_s") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_rdo_uastc_smooth_block_max_std_dev = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-uastc_rdo_f") == 0)
m_comp_params.m_rdo_uastc_favor_simpler_modes_in_rdo_mode = false;
else if (strcasecmp(pArg, "-uastc_rdo_m") == 0)
m_comp_params.m_rdo_uastc_multithreading = false;
else if (strcasecmp(pArg, "-linear") == 0)
m_comp_params.m_perceptual = false;
else if (strcasecmp(pArg, "-srgb") == 0)
m_comp_params.m_perceptual = true;
else if (strcasecmp(pArg, "-q") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_quality_level = clamp<int>(atoi(arg_v[arg_index + 1]), BASISU_QUALITY_MIN, BASISU_QUALITY_MAX);
arg_count++;
}
else if (strcasecmp(pArg, "-output_file") == 0)
{
REMAINING_ARGS_CHECK(1);
m_output_filename = arg_v[arg_index + 1];
arg_count++;
}
else if (strcasecmp(pArg, "-output_path") == 0)
{
REMAINING_ARGS_CHECK(1);
m_output_path = arg_v[arg_index + 1];
arg_count++;
}
else if ((strcasecmp(pArg, "-debug") == 0) || (strcasecmp(pArg, "-verbose") == 0))
{
m_comp_params.m_debug = true;
enable_debug_printf(true);
}
else if (strcasecmp(pArg, "-validate_etc1s") == 0)
{
m_comp_params.m_validate_etc1s = true;
}
else if (strcasecmp(pArg, "-validate_output") == 0)
{
m_comp_params.m_validate_output_data = true;
}
else if (strcasecmp(pArg, "-debug_images") == 0)
m_comp_params.m_debug_images = true;
else if (strcasecmp(pArg, "-stats") == 0)
m_comp_params.m_compute_stats = true;
else if (strcasecmp(pArg, "-gen_global_codebooks") == 0)
{
// TODO
}
else if (strcasecmp(pArg, "-use_global_codebooks") == 0)
{
REMAINING_ARGS_CHECK(1);
m_etc1s_use_global_codebooks_file = arg_v[arg_index + 1];
arg_count++;
}
else if (strcasecmp(pArg, "-comp_level") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_compression_level = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-max_endpoints") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_max_endpoint_clusters = clamp<int>(atoi(arg_v[arg_index + 1]), 1, BASISU_MAX_ENDPOINT_CLUSTERS);
arg_count++;
}
else if (strcasecmp(pArg, "-max_selectors") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_max_selector_clusters = clamp<int>(atoi(arg_v[arg_index + 1]), 1, BASISU_MAX_SELECTOR_CLUSTERS);
arg_count++;
}
else if (strcasecmp(pArg, "-y_flip") == 0)
m_comp_params.m_y_flip = true;
else if (strcasecmp(pArg, "-normal_map") == 0)
{
m_comp_params.m_perceptual = false;
m_comp_params.m_mip_srgb = false;
m_comp_params.m_no_selector_rdo = true;
m_comp_params.m_no_endpoint_rdo = true;
}
else if (strcasecmp(pArg, "-no_alpha") == 0)
m_comp_params.m_check_for_alpha = false;
else if (strcasecmp(pArg, "-force_alpha") == 0)
m_comp_params.m_force_alpha = true;
else if ((strcasecmp(pArg, "-separate_rg_to_color_alpha") == 0) ||
(strcasecmp(pArg, "-seperate_rg_to_color_alpha") == 0)) // was mispelled for a while - whoops!
{
m_comp_params.m_swizzle[0] = 0;
m_comp_params.m_swizzle[1] = 0;
m_comp_params.m_swizzle[2] = 0;
m_comp_params.m_swizzle[3] = 1;
}
else if (strcasecmp(pArg, "-swizzle") == 0)
{
REMAINING_ARGS_CHECK(1);
const char *swizzle = arg_v[arg_index + 1];
if (strlen(swizzle) != 4)
{
error_printf("Swizzle requires exactly 4 characters\n");
return false;
}
for (int i=0; i<4; ++i)
{
if (swizzle[i] == 'r')
m_comp_params.m_swizzle[i] = 0;
else if (swizzle[i] == 'g')
m_comp_params.m_swizzle[i] = 1;
else if (swizzle[i] == 'b')
m_comp_params.m_swizzle[i] = 2;
else if (swizzle[i] == 'a')
m_comp_params.m_swizzle[i] = 3;
else
{
error_printf("Swizzle must be one of [rgba]");
return false;
}
}
arg_count++;
}
else if (strcasecmp(pArg, "-renorm") == 0)
m_comp_params.m_renormalize = true;
else if ((strcasecmp(pArg, "-no_multithreading") == 0) || (strcasecmp(pArg, "-no_threading") == 0))
{
m_comp_params.m_multithreading = false;
}
else if (strcasecmp(pArg, "-parallel") == 0)
{
m_parallel_compression = true;
}
else if (strcasecmp(pArg, "-max_threads") == 0)
{
REMAINING_ARGS_CHECK(1);
m_max_threads = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-mipmap") == 0)
m_comp_params.m_mip_gen = true;
else if (strcasecmp(pArg, "-no_ktx") == 0)
m_no_ktx = true;
else if (strcasecmp(pArg, "-ktx_only") == 0)
m_ktx_only = true;
else if (strcasecmp(pArg, "-write_out") == 0)
m_write_out = true;
else if (strcasecmp(pArg, "-format_only") == 0)
{
REMAINING_ARGS_CHECK(1);
m_format_only = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-etc1_only") == 0)
{
m_etc1_only = true;
m_format_only = (int)basist::transcoder_texture_format::cTFETC1_RGB;
}
else if (strcasecmp(pArg, "-disable_hierarchical_endpoint_codebooks") == 0)
m_comp_params.m_disable_hierarchical_endpoint_codebooks = true;
else if (strcasecmp(pArg, "-hdr") == 0)
{
m_comp_params.m_hdr = true;
m_comp_params.m_uastc = true;
}
else if (strcasecmp(pArg, "-opencl") == 0)
{
m_comp_params.m_use_opencl = true;
}
else if (strcasecmp(pArg, "-opencl_serialize") == 0)
{
}
else if (strcasecmp(pArg, "-mip_scale") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_mip_scale = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-mip_filter") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_mip_filter = arg_v[arg_index + 1];
// TODO: Check filter
arg_count++;
}
else if (strcasecmp(pArg, "-mip_renorm") == 0)
m_comp_params.m_mip_renormalize = true;
else if (strcasecmp(pArg, "-mip_clamp") == 0)
m_comp_params.m_mip_wrapping = false;
else if (strcasecmp(pArg, "-mip_fast") == 0)
m_comp_params.m_mip_fast = true;
else if (strcasecmp(pArg, "-mip_slow") == 0)
m_comp_params.m_mip_fast = false;
else if (strcasecmp(pArg, "-mip_smallest") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_mip_smallest_dimension = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-mip_srgb") == 0)
m_comp_params.m_mip_srgb = true;
else if (strcasecmp(pArg, "-mip_linear") == 0)
m_comp_params.m_mip_srgb = false;
else if (strcasecmp(pArg, "-no_selector_rdo") == 0)
m_comp_params.m_no_selector_rdo = true;
else if (strcasecmp(pArg, "-selector_rdo_thresh") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_selector_rdo_thresh = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-no_endpoint_rdo") == 0)
m_comp_params.m_no_endpoint_rdo = true;
else if (strcasecmp(pArg, "-endpoint_rdo_thresh") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_endpoint_rdo_thresh = (float)atof(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-userdata0") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_userdata0 = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-userdata1") == 0)
{
REMAINING_ARGS_CHECK(1);
m_comp_params.m_userdata1 = atoi(arg_v[arg_index + 1]);
arg_count++;
}
else if (strcasecmp(pArg, "-framerate") == 0)
{
REMAINING_ARGS_CHECK(1);
double fps = atof(arg_v[arg_index + 1]);
double us_per_frame = 0;
if (fps > 0)
us_per_frame = 1000000.0f / fps;
m_comp_params.m_us_per_frame = clamp<int>(static_cast<int>(us_per_frame + .5f), 0, basist::cBASISMaxUSPerFrame);
arg_count++;
}
else if (strcasecmp(pArg, "-cubemap") == 0)
{
m_comp_params.m_tex_type = basist::cBASISTexTypeCubemapArray;
m_individual = false;
}
else if (strcasecmp(pArg, "-tex_type") == 0)
{
REMAINING_ARGS_CHECK(1);
const char* pType = arg_v[arg_index + 1];
if (strcasecmp(pType, "2d") == 0)
m_comp_params.m_tex_type = basist::cBASISTexType2D;
else if (strcasecmp(pType, "2darray") == 0)
{
m_comp_params.m_tex_type = basist::cBASISTexType2DArray;
m_individual = false;
}
else if (strcasecmp(pType, "3d") == 0)
{
m_comp_params.m_tex_type = basist::cBASISTexTypeVolume;
m_individual = false;
}
else if (strcasecmp(pType, "cubemap") == 0)
{
m_comp_params.m_tex_type = basist::cBASISTexTypeCubemapArray;
m_individual = false;
}
else if (strcasecmp(pType, "video") == 0)
{
m_comp_params.m_tex_type = basist::cBASISTexTypeVideoFrames;
m_individual = false;
}
else
{
error_printf("Invalid texture type: %s\n", pType);
return false;
}
arg_count++;
}
else if (strcasecmp(pArg, "-individual") == 0)
m_individual = true;
else if ((strcasecmp(pArg, "-tex_array") == 0) || (strcasecmp(pArg, "-texarray") == 0))
m_individual = false;
else if (strcasecmp(pArg, "-fuzz_testing") == 0)
m_fuzz_testing = true;
else if (strcasecmp(pArg, "-csv_file") == 0)
{
REMAINING_ARGS_CHECK(1);
m_csv_file = arg_v[arg_index + 1];
m_comp_params.m_compute_stats = true;
arg_count++;
}
else if (pArg[0] == '-')
{
error_printf("Unrecognized command line option: %s\n", pArg);
return false;
}
else
{
// Let's assume it's a source filename, so globbing works
//error_printf("Unrecognized command line option: %s\n", pArg);
m_input_filenames.push_back(pArg);
}
arg_index += arg_count;
}
if (m_comp_params.m_quality_level != -1)
{
m_comp_params.m_max_endpoint_clusters = 0;
m_comp_params.m_max_selector_clusters = 0;
}
else if ((!m_comp_params.m_max_endpoint_clusters) || (!m_comp_params.m_max_selector_clusters))
{
m_comp_params.m_max_endpoint_clusters = 0;
m_comp_params.m_max_selector_clusters = 0;
m_comp_params.m_quality_level = 128;
}
if (!m_comp_params.m_mip_srgb.was_changed())
{
// They didn't specify what colorspace to do mipmap filtering in, so choose sRGB if they've specified that the texture is sRGB.
if (m_comp_params.m_perceptual)
m_comp_params.m_mip_srgb = true;
else
m_comp_params.m_mip_srgb = false;
}
return true;
}
bool process_listing_files()
{
basisu::vector<std::string> new_input_filenames;
for (uint32_t i = 0; i < m_input_filenames.size(); i++)
{
if (m_input_filenames[i][0] == '@')
{
if (!load_listing_file(m_input_filenames[i], new_input_filenames))
return false;
}
else
new_input_filenames.push_back(m_input_filenames[i]);
}
new_input_filenames.swap(m_input_filenames);
basisu::vector<std::string> new_input_alpha_filenames;
for (uint32_t i = 0; i < m_input_alpha_filenames.size(); i++)
{
if (m_input_alpha_filenames[i][0] == '@')
{
if (!load_listing_file(m_input_alpha_filenames[i], new_input_alpha_filenames))
return false;
}
else
new_input_alpha_filenames.push_back(m_input_alpha_filenames[i]);
}
new_input_alpha_filenames.swap(m_input_alpha_filenames);
return true;
}
basis_compressor_params m_comp_params;
tool_mode m_mode;
bool m_ktx2_mode;
bool m_ktx2_zstandard;
int m_ktx2_zstandard_level;
uint32_t m_ktx2_animdata_duration;
uint32_t m_ktx2_animdata_timescale;
uint32_t m_ktx2_animdata_loopcount;
basisu::vector<std::string> m_input_filenames;
basisu::vector<std::string> m_input_alpha_filenames;
std::string m_output_filename;
std::string m_output_path;
int m_format_only;
std::string m_multifile_printf;
uint32_t m_multifile_first;
uint32_t m_multifile_num;
std::string m_csv_file;
std::string m_etc1s_use_global_codebooks_file;
std::string m_test_file_dir;
uint32_t m_max_threads;
bool m_individual;
bool m_no_ktx;
bool m_ktx_only;
bool m_write_out;
bool m_etc1_only;
bool m_fuzz_testing;
bool m_compare_ssim;
bool m_compare_plot;
bool m_parallel_compression;
};
static bool expand_multifile(command_line_params &opts)
{
if (!opts.m_multifile_printf.size())
return true;
if (!opts.m_multifile_num)
{
error_printf("-multifile_printf specified, but not -multifile_num\n");
return false;
}
std::string fmt(opts.m_multifile_printf);
// Workaround for MSVC debugger issues. Questionable to leave in here.
size_t x = fmt.find_first_of('!');
if (x != std::string::npos)
fmt[x] = '%';
if (string_find_right(fmt, '%') == -1)
{
error_printf("Must include C-style printf() format character '%%' in -multifile_printf string\n");
return false;
}
for (uint32_t i = opts.m_multifile_first; i < opts.m_multifile_first + opts.m_multifile_num; i++)
{
char buf[1024];
#ifdef _WIN32
sprintf_s(buf, sizeof(buf), fmt.c_str(), i);
#else
snprintf(buf, sizeof(buf), fmt.c_str(), i);
#endif
if (buf[0])
opts.m_input_filenames.push_back(buf);
}
return true;
}
struct basis_data
{
basis_data() :
m_transcoder()
{
}
uint8_vec m_file_data;
basist::basisu_transcoder m_transcoder;
};
static basis_data *load_basis_file(const char *pInput_filename, bool force_etc1s)
{
basis_data* p = new basis_data;
uint8_vec &basis_data = p->m_file_data;
if (!basisu::read_file_to_vec(pInput_filename, basis_data))
{
error_printf("Failed reading file \"%s\"\n", pInput_filename);
delete p;
return nullptr;
}
printf("Input file \"%s\"\n", pInput_filename);
if (!basis_data.size())
{
error_printf("File is empty!\n");
delete p;
return nullptr;
}
if (basis_data.size() > UINT32_MAX)
{
error_printf("File is too large!\n");
delete p;
return nullptr;
}
if (force_etc1s)
{
if (p->m_transcoder.get_tex_format((const void*)&p->m_file_data[0], (uint32_t)p->m_file_data.size()) != basist::basis_tex_format::cETC1S)
{
error_printf("Global codebook file must be in ETC1S format!\n");
delete p;
return nullptr;
}
}
if (!p->m_transcoder.start_transcoding(&basis_data[0], (uint32_t)basis_data.size()))
{
error_printf("start_transcoding() failed!\n");
delete p;
return nullptr;
}
return p;
}
static bool compress_mode(command_line_params &opts)
{
uint32_t num_threads = 1;
if (opts.m_comp_params.m_multithreading)
{
// We use std::thread::hardware_concurrency() as a hint to determine the default # of threads to put into a pool.
num_threads = std::thread::hardware_concurrency();
if (num_threads < 1)
num_threads = 1;
if (num_threads > opts.m_max_threads)
num_threads = opts.m_max_threads;
}
job_pool compressor_jpool(opts.m_parallel_compression ? 1 : num_threads);
if (!opts.m_parallel_compression)
opts.m_comp_params.m_pJob_pool = &compressor_jpool;
if (!expand_multifile(opts))
{
error_printf("-multifile expansion failed!\n");
return false;
}
if (!opts.m_input_filenames.size())
{
error_printf("No input files to process!\n");
return false;
}
basis_data* pGlobal_codebook_data = nullptr;
if (opts.m_etc1s_use_global_codebooks_file.size())
{
pGlobal_codebook_data = load_basis_file(opts.m_etc1s_use_global_codebooks_file.c_str(), true);
if (!pGlobal_codebook_data)
return false;
printf("Loaded global codebooks from .basis file \"%s\"\n", opts.m_etc1s_use_global_codebooks_file.c_str());
}
basis_compressor_params ¶ms = opts.m_comp_params;
if (opts.m_ktx2_mode)
{
params.m_create_ktx2_file = true;
if (opts.m_ktx2_zstandard)
params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD;
else
params.m_ktx2_uastc_supercompression = basist::KTX2_SS_NONE;
params.m_ktx2_srgb_transfer_func = opts.m_comp_params.m_perceptual;
if (params.m_tex_type == basist::basis_texture_type::cBASISTexTypeVideoFrames)
{
// Create KTXanimData key value entry
// TODO: Move this to basisu_comp.h
basist::ktx2_transcoder::key_value kv;
const char* pAD = "KTXanimData";
kv.m_key.resize(strlen(pAD) + 1);
strcpy((char*)kv.m_key.data(), pAD);
basist::ktx2_animdata ad;
ad.m_duration = opts.m_ktx2_animdata_duration;
ad.m_timescale = opts.m_ktx2_animdata_timescale;
ad.m_loopcount = opts.m_ktx2_animdata_loopcount;
kv.m_value.resize(sizeof(ad));
memcpy(kv.m_value.data(), &ad, sizeof(ad));
params.m_ktx2_key_values.push_back(kv);
}
// TODO- expose this to command line.
params.m_ktx2_zstd_supercompression_level = opts.m_ktx2_zstandard_level;
}
params.m_read_source_images = true;
params.m_write_output_basis_or_ktx2_files = true;
params.m_pGlobal_codebooks = pGlobal_codebook_data ? &pGlobal_codebook_data->m_transcoder.get_lowlevel_etc1s_decoder() : nullptr;
FILE *pCSV_file = nullptr;
if (opts.m_csv_file.size())
{
//pCSV_file = fopen_safe(opts.m_csv_file.c_str(), "a");
pCSV_file = fopen_safe(opts.m_csv_file.c_str(), "w");
if (!pCSV_file)
{
error_printf("Failed opening CVS file \"%s\"\n", opts.m_csv_file.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
fprintf(pCSV_file, "Filename, Size, Slices, Width, Height, HasAlpha, BitsPerTexel, Slice0RGBAvgPSNR, Slice0RGBAAvgPSNR, Slice0Luma709PSNR, Slice0BestETC1SLuma709PSNR, Q, CL, Time, RGBAvgPSNRMin, RGBAvgPSNRAvg, AAvgPSNRMin, AAvgPSNRAvg, Luma709PSNRMin, Luma709PSNRAvg\n");
}
printf("Processing %u total file(s)\n", (uint32_t)opts.m_input_filenames.size());
interval_timer all_tm;
all_tm.start();
basisu::vector<basis_compressor_params> comp_params_vec;
const size_t total_files = (opts.m_individual ? opts.m_input_filenames.size() : 1U);
bool result = true;
if ((opts.m_individual) && (opts.m_output_filename.size()))
{
if (total_files > 1)
{
error_printf("-output_file specified in individual mode, but multiple input files have been specified which would cause the output file to be written multiple times.\n");
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
}
uint32_t total_successes = 0, total_failures = 0;
for (size_t file_index = 0; file_index < total_files; file_index++)
{
if (opts.m_individual)
{
params.m_source_filenames.resize(1);
params.m_source_filenames[0] = opts.m_input_filenames[file_index];
if (file_index < opts.m_input_alpha_filenames.size())
{
params.m_source_alpha_filenames.resize(1);
params.m_source_alpha_filenames[0] = opts.m_input_alpha_filenames[file_index];
if (params.m_status_output)
printf("Processing source file \"%s\", alpha file \"%s\"\n", params.m_source_filenames[0].c_str(), params.m_source_alpha_filenames[0].c_str());
}
else
{
params.m_source_alpha_filenames.resize(0);
if (params.m_status_output)
printf("Processing source file \"%s\"\n", params.m_source_filenames[0].c_str());
}
}
else
{
params.m_source_filenames = opts.m_input_filenames;
params.m_source_alpha_filenames = opts.m_input_alpha_filenames;
}
if (opts.m_output_filename.size())
params.m_out_filename = opts.m_output_filename;
else
{
std::string filename;
string_get_filename(opts.m_input_filenames[file_index].c_str(), filename);
string_remove_extension(filename);
if (opts.m_ktx2_mode)
filename += ".ktx2";
else
filename += ".basis";
if (opts.m_output_path.size())
string_combine_path(filename, opts.m_output_path.c_str(), filename.c_str());
params.m_out_filename = filename;
}
if (opts.m_parallel_compression)
{
comp_params_vec.push_back(params);
}
else
{
basis_compressor c;
if (!c.init(opts.m_comp_params))
{
error_printf("basis_compressor::init() failed!\n");
if (pCSV_file)
{
fclose(pCSV_file);
pCSV_file = nullptr;
}
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
interval_timer tm;
tm.start();
basis_compressor::error_code ec = c.process();
tm.stop();
if (ec == basis_compressor::cECSuccess)
{
total_successes++;
if (params.m_status_output)
{
printf("Compression succeeded to file \"%s\" size %u bytes in %3.3f secs\n", params.m_out_filename.c_str(),
opts.m_ktx2_mode ? c.get_output_ktx2_file().size() : c.get_output_basis_file().size(),
tm.get_elapsed_secs());
}
}
else
{
total_failures++;
result = false;
if (!params.m_status_output)
{
error_printf("Compression failed on file \"%s\"\n", params.m_out_filename.c_str());
}
bool exit_flag = true;
switch (ec)
{
case basis_compressor::cECFailedReadingSourceImages:
{
error_printf("Compressor failed reading a source image!\n");
if (opts.m_individual)
exit_flag = false;
break;
}
case basis_compressor::cECFailedValidating:
error_printf("Compressor failed 2darray/cubemap/video validation checks!\n");
break;
case basis_compressor::cECFailedEncodeUASTC:
error_printf("Compressor UASTC encode failed!\n");
break;
case basis_compressor::cECFailedFrontEnd:
error_printf("Compressor frontend stage failed!\n");
break;
case basis_compressor::cECFailedFontendExtract:
error_printf("Compressor frontend data extraction failed!\n");
break;
case basis_compressor::cECFailedBackend:
error_printf("Compressor backend stage failed!\n");
break;
case basis_compressor::cECFailedCreateBasisFile:
error_printf("Compressor failed creating Basis file data!\n");
break;
case basis_compressor::cECFailedWritingOutput:
error_printf("Compressor failed writing to output Basis file!\n");
break;
case basis_compressor::cECFailedUASTCRDOPostProcess:
error_printf("Compressor failed during the UASTC post process step!\n");
break;
case basis_compressor::cECFailedCreateKTX2File:
error_printf("Compressor failed creating KTX2 file data!\n");
break;
default:
error_printf("basis_compress::process() failed!\n");
break;
}
if (exit_flag)
{
if (pCSV_file)
{
fclose(pCSV_file);
pCSV_file = nullptr;
}
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
}
if ((pCSV_file) && (c.get_stats().size()))
{
if (c.get_stats().size())
{
float rgb_avg_psnr_min = 1e+9f, rgb_avg_psnr_avg = 0.0f;
float a_avg_psnr_min = 1e+9f, a_avg_psnr_avg = 0.0f;
float luma_709_psnr_min = 1e+9f, luma_709_psnr_avg = 0.0f;
for (size_t slice_index = 0; slice_index < c.get_stats().size(); slice_index++)
{
rgb_avg_psnr_min = basisu::minimum(rgb_avg_psnr_min, c.get_stats()[slice_index].m_basis_rgb_avg_psnr);
rgb_avg_psnr_avg += c.get_stats()[slice_index].m_basis_rgb_avg_psnr;
a_avg_psnr_min = basisu::minimum(a_avg_psnr_min, c.get_stats()[slice_index].m_basis_a_avg_psnr);
a_avg_psnr_avg += c.get_stats()[slice_index].m_basis_a_avg_psnr;
luma_709_psnr_min = basisu::minimum(luma_709_psnr_min, c.get_stats()[slice_index].m_basis_luma_709_psnr);
luma_709_psnr_avg += c.get_stats()[slice_index].m_basis_luma_709_psnr;
}
rgb_avg_psnr_avg /= c.get_stats().size();
a_avg_psnr_avg /= c.get_stats().size();
luma_709_psnr_avg /= c.get_stats().size();
fprintf(pCSV_file, "\"%s\", %u, %u, %u, %u, %u, %f, %f, %f, %f, %f, %u, %u, %f, %f, %f, %f, %f, %f, %f\n",
params.m_out_filename.c_str(),
c.get_basis_file_size(),
(uint32_t)c.get_stats().size(),
c.get_stats()[0].m_width, c.get_stats()[0].m_height, (uint32_t)c.get_any_source_image_has_alpha(),
c.get_basis_bits_per_texel(),
c.get_stats()[0].m_basis_rgb_avg_psnr,
c.get_stats()[0].m_basis_rgba_avg_psnr,
c.get_stats()[0].m_basis_luma_709_psnr,
c.get_stats()[0].m_best_etc1s_luma_709_psnr,
params.m_quality_level, (int)params.m_compression_level, tm.get_elapsed_secs(),
rgb_avg_psnr_min, rgb_avg_psnr_avg,
a_avg_psnr_min, a_avg_psnr_avg,
luma_709_psnr_min, luma_709_psnr_avg);
fflush(pCSV_file);
}
}
//if ((opts.m_individual) && (params.m_status_output))
// printf("\n");
} // if (opts.m_parallel_compression)
} // file_index
if (opts.m_parallel_compression)
{
basisu::vector<parallel_results> results;
bool any_failed = basis_parallel_compress(
num_threads,
comp_params_vec,
results);
BASISU_NOTE_UNUSED(any_failed);
for (uint32_t i = 0; i < comp_params_vec.size(); i++)
{
if (results[i].m_error_code != basis_compressor::cECSuccess)
{
result = false;
total_failures++;
error_printf("File %u (first source image: \"%s\", output file: \"%s\") failed with error code %i!\n", i,
comp_params_vec[i].m_source_filenames[0].c_str(),
comp_params_vec[i].m_out_filename.c_str(),
(int)results[i].m_error_code);
}
else
{
total_successes++;
}
}
} // if (opts.m_parallel_compression)
printf("Total successes: %u failures: %u\n", total_successes, total_failures);
all_tm.stop();
if (total_files > 1)
printf("Total compression time: %3.3f secs\n", all_tm.get_elapsed_secs());
if (pCSV_file)
{
fclose(pCSV_file);
pCSV_file = nullptr;
}
delete pGlobal_codebook_data;
pGlobal_codebook_data = nullptr;
return result;
}
static bool unpack_and_validate_ktx2_file(
uint32_t file_index,
const std::string& base_filename,
uint8_vec& ktx2_file_data,
command_line_params& opts,
FILE* pCSV_file,
basis_data* pGlobal_codebook_data,
uint32_t& total_unpack_warnings,
uint32_t& total_pvrtc_nonpow2_warnings)
{
// TODO
(void)pCSV_file;
(void)file_index;
const bool validate_flag = (opts.m_mode == cValidate);
basist::ktx2_transcoder dec;
if (!dec.init(ktx2_file_data.data(), ktx2_file_data.size()))
{
error_printf("ktx2_transcoder::init() failed! File either uses an unsupported feature, is invalid, was corrupted, or this is a bug.\n");
return false;
}
if (!dec.start_transcoding())
{
error_printf("ktx2_transcoder::start_transcoding() failed! File either uses an unsupported feature, is invalid, was corrupted, or this is a bug.\n");
return false;
}
printf("Resolution: %ux%u\n", dec.get_width(), dec.get_height());
printf("Mipmap Levels: %u\n", dec.get_levels());
printf("Texture Array Size (layers): %u\n", dec.get_layers());
printf("Total Faces: %u (%s)\n", dec.get_faces(), (dec.get_faces() == 6) ? "CUBEMAP" : "2D");
printf("Is Texture Video: %u\n", dec.is_video());
const bool is_etc1s = (dec.get_format() == basist::basis_tex_format::cETC1S);
const char* pFmt_str = "ETC1S";
if (dec.get_format() == basist::basis_tex_format::cUASTC4x4)
pFmt_str = "UASTC";
else if (dec.get_format() == basist::basis_tex_format::cUASTC_HDR_4x4)
pFmt_str = "UASTC_HDR";
printf("Supercompression Format: %s\n", pFmt_str);
printf("Supercompression Scheme: ");
switch (dec.get_header().m_supercompression_scheme)
{
case basist::KTX2_SS_NONE: printf("NONE\n"); break;
case basist::KTX2_SS_BASISLZ: printf("BASISLZ\n"); break;
case basist::KTX2_SS_ZSTANDARD: printf("ZSTANDARD\n"); break;
default:
error_printf("Invalid/unknown/unsupported\n");
return false;
}
printf("Has Alpha: %u\n", (uint32_t)dec.get_has_alpha());
printf("\nKTX2 header vk_format: 0x%X (decimal %u)\n", (uint32_t)dec.get_header().m_vk_format, (uint32_t)dec.get_header().m_vk_format);
printf("\nData Format Descriptor (DFD):\n");
printf("DFD length in bytes: %u\n", dec.get_dfd().size());
printf("DFD color model: %u\n", dec.get_dfd_color_model());
printf("DFD color primaries: %u (%s)\n", dec.get_dfd_color_primaries(), basist::ktx2_get_df_color_primaries_str(dec.get_dfd_color_primaries()));
printf("DFD transfer func: %u (%s)\n", dec.get_dfd_transfer_func(),
(dec.get_dfd_transfer_func() == basist::KTX2_KHR_DF_TRANSFER_LINEAR) ? "LINEAR" : ((dec.get_dfd_transfer_func() == basist::KTX2_KHR_DF_TRANSFER_SRGB) ? "SRGB" : "?"));
printf("DFD flags: %u\n", dec.get_dfd_flags());
printf("DFD samples: %u\n", dec.get_dfd_total_samples());
if (is_etc1s)
{
printf("DFD chan0: %s\n", basist::ktx2_get_etc1s_df_channel_id_str(dec.get_dfd_channel_id0()));
if (dec.get_dfd_total_samples() == 2)
printf("DFD chan1: %s\n", basist::ktx2_get_etc1s_df_channel_id_str(dec.get_dfd_channel_id1()));
}
else
printf("DFD chan0: %s\n", basist::ktx2_get_uastc_df_channel_id_str(dec.get_dfd_channel_id0()));
printf("DFD hex values:\n");
for (uint32_t i = 0; i < dec.get_dfd().size(); i++)
{
printf("0x%X", dec.get_dfd()[i]);
if ((i + 1) != dec.get_dfd().size())
printf(",");
if ((i & 3) == 3)
printf("\n");
}
printf("\n");
printf("Total key values: %u\n", dec.get_key_values().size());
for (uint32_t i = 0; i < dec.get_key_values().size(); i++)
{
printf("%u. Key: \"%s\", Value length in bytes: %u", i, (const char*)dec.get_key_values()[i].m_key.data(), dec.get_key_values()[i].m_value.size());
if (dec.get_key_values()[i].m_value.size() > 256)
continue;
bool is_ascii = true;
for (uint32_t j = 0; j < dec.get_key_values()[i].m_value.size(); j++)
{
uint8_t c = dec.get_key_values()[i].m_value[j];
if (!(
((c >= ' ') && (c < 0x80)) ||
((j == dec.get_key_values()[i].m_value.size() - 1) && (!c))
))
{
is_ascii = false;
break;
}
}
if (is_ascii)
{
uint8_vec s(dec.get_key_values()[i].m_value);
s.push_back(0);
printf(" Value String: \"%s\"", (const char *)s.data());
}
else
{
printf(" Value Bytes: ");
for (uint32_t j = 0; j < dec.get_key_values()[i].m_value.size(); j++)
{
if (j)
printf(",");
printf("0x%X", dec.get_key_values()[i].m_value[j]);
}
}
printf("\n");
}
if (is_etc1s)
{
printf("ETC1S header:\n");
printf("Endpoint Count: %u, Selector Count: %u, Endpoint Length: %u, Selector Length: %u, Tables Length: %u, Extended Length: %u\n",
(uint32_t)dec.get_etc1s_header().m_endpoint_count, (uint32_t)dec.get_etc1s_header().m_selector_count,
(uint32_t)dec.get_etc1s_header().m_endpoints_byte_length, (uint32_t)dec.get_etc1s_header().m_selectors_byte_length,
(uint32_t)dec.get_etc1s_header().m_tables_byte_length, (uint32_t)dec.get_etc1s_header().m_extended_byte_length);
printf("Total ETC1S image descs: %u\n", dec.get_etc1s_image_descs().size());
for (uint32_t i = 0; i < dec.get_etc1s_image_descs().size(); i++)
{
printf("%u. Flags: 0x%X, RGB Ofs: %u Len: %u, Alpha Ofs: %u, Len: %u\n", i,
(uint32_t)dec.get_etc1s_image_descs()[i].m_image_flags,
(uint32_t)dec.get_etc1s_image_descs()[i].m_rgb_slice_byte_offset, (uint32_t)dec.get_etc1s_image_descs()[i].m_rgb_slice_byte_length,
(uint32_t)dec.get_etc1s_image_descs()[i].m_alpha_slice_byte_offset, (uint32_t)dec.get_etc1s_image_descs()[i].m_alpha_slice_byte_length);
}
}
printf("Levels:\n");
for (uint32_t i = 0; i < dec.get_levels(); i++)
{
printf("%u. Offset: %llu, Length: %llu, Uncompressed Length: %llu\n",
i, (long long unsigned int)dec.get_level_index()[i].m_byte_offset,
(long long unsigned int)dec.get_level_index()[i].m_byte_length,
(long long unsigned int)dec.get_level_index()[i].m_uncompressed_byte_length);
}
if (opts.m_mode == cInfo)
{
return true;
}
// gpu_images[format][face][layer][level]
basisu::vector< gpu_image_vec > gpu_images[(int)basist::transcoder_texture_format::cTFTotalTextureFormats][6];
int first_format = 0;
int last_format = (int)basist::transcoder_texture_format::cTFTotalTextureFormats;
if (opts.m_format_only > -1)
{
first_format = opts.m_format_only;
last_format = first_format + 1;
}
const uint32_t total_layers = maximum<uint32_t>(1, dec.get_layers());
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
basist::transcoder_texture_format tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (basist::basis_transcoder_format_is_uncompressed(tex_fmt))
continue;
if (!basis_is_format_supported(tex_fmt, dec.get_format()))
continue;
if (tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
for (uint32_t face_index = 0; face_index < dec.get_faces(); face_index++)
{
gpu_images[(int)tex_fmt][face_index].resize(total_layers);
for (uint32_t layer_index = 0; layer_index < total_layers; layer_index++)
gpu_images[(int)tex_fmt][face_index][layer_index].resize(dec.get_levels());
}
}
// Now transcode the file to all supported texture formats and save mipmapped KTX/DDS files
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (basist::basis_transcoder_format_is_uncompressed(transcoder_tex_fmt))
continue;
if (!basis_is_format_supported(transcoder_tex_fmt, dec.get_format()))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
for (uint32_t level_index = 0; level_index < dec.get_levels(); level_index++)
{
for (uint32_t layer_index = 0; layer_index < total_layers; layer_index++)
{
for (uint32_t face_index = 0; face_index < dec.get_faces(); face_index++)
{
basist::ktx2_image_level_info level_info;
if (!dec.get_image_level_info(level_info, level_index, layer_index, face_index))
{
error_printf("Failed retrieving image level information (%u %u %u)!\n", layer_index, level_index, face_index);
return false;
}
if ((transcoder_tex_fmt == basist::transcoder_texture_format::cTFPVRTC1_4_RGB) || (transcoder_tex_fmt == basist::transcoder_texture_format::cTFPVRTC1_4_RGBA))
{
if (!is_pow2(level_info.m_width) || !is_pow2(level_info.m_height))
{
total_pvrtc_nonpow2_warnings++;
printf("Warning: Will not transcode image %u level %u res %ux%u to PVRTC1 (one or more dimension is not a power of 2)\n", layer_index, level_index, level_info.m_width, level_info.m_height);
// Can't transcode this image level to PVRTC because it's not a pow2 (we're going to support transcoding non-pow2 to the next larger pow2 soon)
continue;
}
}
basisu::texture_format tex_fmt = basis_get_basisu_texture_format(transcoder_tex_fmt);
gpu_image& gi = gpu_images[(int)transcoder_tex_fmt][face_index][layer_index][level_index];
gi.init(tex_fmt, level_info.m_orig_width, level_info.m_orig_height);
// Fill the buffer with psuedo-random bytes, to help more visibly detect cases where the transcoder fails to write to part of the output.
fill_buffer_with_random_bytes(gi.get_ptr(), gi.get_size_in_bytes());
uint32_t decode_flags = 0;
if (!dec.transcode_image_level(level_index, layer_index, face_index, gi.get_ptr(), gi.get_total_blocks(), transcoder_tex_fmt, decode_flags))
{
error_printf("Failed transcoding image level (%u %u %u %u)!\n", layer_index, level_index, face_index, format_iter);
return false;
}
printf("Transcode of layer %u level %u face %u res %ux%u format %s succeeded\n", layer_index, level_index, face_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt));
}
} // format_iter
} // level_index
} // image_info
// Return if we're just validating that transcoding succeeds
if (validate_flag)
return true;
// Now write KTX/DDS files and unpack them to individual PNG's/EXR's
const bool is_cubemap = (dec.get_faces() > 1);
const bool is_array = (total_layers > 1);
const bool is_cubemap_array = is_cubemap && is_array;
const bool is_mipmapped = dec.get_levels() > 1;
BASISU_NOTE_UNUSED(is_cubemap_array);
BASISU_NOTE_UNUSED(is_mipmapped);
// The maximum Direct3D array size is 2048.
const uint32_t MAX_DDS_TEXARRAY_SIZE = 2048;
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
const basisu::texture_format tex_fmt = basis_get_basisu_texture_format(transcoder_tex_fmt);
if (basist::basis_transcoder_format_is_uncompressed(transcoder_tex_fmt))
continue;
if (!basis_is_format_supported(transcoder_tex_fmt, dec.get_format()))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
// TODO: Could write DDS texture arrays.
// No KTX tool that we know of supports cubemap arrays, so write individual cubemap files for each layer.
if ((!opts.m_no_ktx) && (is_cubemap))
{
// Write a separate compressed texture file for each layer in a texarray.
for (uint32_t layer_index = 0; layer_index < total_layers; layer_index++)
{
basisu::vector<gpu_image_vec> cubemap;
for (uint32_t face_index = 0; face_index < 6; face_index++)
cubemap.push_back(gpu_images[format_iter][face_index][layer_index]);
{
std::string ktx_filename(base_filename + string_format("_transcoded_cubemap_%s_layer_%u.ktx", basist::basis_get_format_name(transcoder_tex_fmt), layer_index));
if (!write_compressed_texture_file(ktx_filename.c_str(), cubemap, true, true))
{
error_printf("Failed writing KTX file \"%s\"!\n", ktx_filename.c_str());
return false;
}
printf("Wrote KTX cubemap file \"%s\"\n", ktx_filename.c_str());
}
if (does_dds_support_format(cubemap[0][0].get_format()))
{
std::string dds_filename(base_filename + string_format("_transcoded_cubemap_%s_layer_%u.dds", basist::basis_get_format_name(transcoder_tex_fmt), layer_index));
if (!write_compressed_texture_file(dds_filename.c_str(), cubemap, true, true))
{
error_printf("Failed writing DDS file \"%s\"!\n", dds_filename.c_str());
return false;
}
printf("Wrote DDS cubemap file \"%s\"\n", dds_filename.c_str());
}
} // layer_index
}
// For texture arrays, let's be adventurous and write a DDS texture array file. RenderDoc and DDSView (DirectXTex) can view them. (Only RenderDoc allows viewing them entirely.)
if ((!opts.m_no_ktx) && (is_array) && (total_layers <= MAX_DDS_TEXARRAY_SIZE))
{
if (does_dds_support_format(tex_fmt))
{
basisu::vector<gpu_image_vec> tex_array;
for (uint32_t layer_index = 0; layer_index < total_layers; layer_index++)
for (uint32_t face_index = 0; face_index < dec.get_faces(); face_index++)
tex_array.push_back(gpu_images[format_iter][face_index][layer_index]);
std::string dds_filename(base_filename + string_format("_transcoded_array_%s.dds", basist::basis_get_format_name(transcoder_tex_fmt)));
if (!write_compressed_texture_file(dds_filename.c_str(), tex_array, is_cubemap, true))
{
error_printf("Failed writing DDS file \"%s\"!\n", dds_filename.c_str());
return false;
}
printf("Wrote DDS texture array file \"%s\"\n", dds_filename.c_str());
}
}
// Now unpack each layer and face individually and write KTX/DDS/PNG/EXR files for each
for (uint32_t layer_index = 0; layer_index < total_layers; layer_index++)
{
for (uint32_t face_index = 0; face_index < dec.get_faces(); face_index++)
{
gpu_image_vec& gi = gpu_images[format_iter][face_index][layer_index];
if (!gi.size())
continue;
uint32_t level;
for (level = 0; level < gi.size(); level++)
if (!gi[level].get_total_blocks())
break;
if (level < gi.size())
continue;
// Write separate compressed KTX/DDS textures with mipmap levels for each individual texarray layer and face.
if (!opts.m_no_ktx)
{
// Write KTX
{
std::string ktx_filename;
if (is_cubemap)
ktx_filename = base_filename + string_format("_transcoded_%s_face_%u_layer_%04u.ktx", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
else
ktx_filename = base_filename + string_format("_transcoded_%s_layer_%04u.ktx", basist::basis_get_format_name(transcoder_tex_fmt), layer_index);
if (!write_compressed_texture_file(ktx_filename.c_str(), gi, true))
{
error_printf("Failed writing KTX file \"%s\"!\n", ktx_filename.c_str());
return false;
}
printf("Wrote KTX file \"%s\"\n", ktx_filename.c_str());
}
// Write DDS if it supports this texture format
if (does_dds_support_format(gi[0].get_format()))
{
std::string dds_filename;
if (is_cubemap)
dds_filename = base_filename + string_format("_transcoded_%s_face_%u_layer_%04u.dds", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
else
dds_filename = base_filename + string_format("_transcoded_%s_layer_%04u.dds", basist::basis_get_format_name(transcoder_tex_fmt), layer_index);
if (!write_compressed_texture_file(dds_filename.c_str(), gi, true))
{
error_printf("Failed writing DDS file \"%s\"!\n", dds_filename.c_str());
return false;
}
printf("Wrote DDS file \"%s\"\n", dds_filename.c_str());
}
}
// Now unpack and save PNG/EXR files
for (uint32_t level_index = 0; level_index < gi.size(); level_index++)
{
basist::ktx2_image_level_info level_info;
if (!dec.get_image_level_info(level_info, level_index, layer_index, face_index))
{
error_printf("Failed retrieving image level information (%u %u %u)!\n", layer_index, level_index, face_index);
return false;
}
if (basist::basis_transcoder_format_is_hdr(transcoder_tex_fmt))
{
imagef u;
if (!gi[level_index].unpack_hdr(u))
{
printf("Warning: Failed unpacking HDR GPU texture data (%u %u %u %u). Unpacking as much as possible.\n", format_iter, layer_index, level_index, face_index);
total_unpack_warnings++;
}
if (!opts.m_ktx_only)
{
std::string rgb_filename;
if (gi.size() > 1)
rgb_filename = base_filename + string_format("_hdr_unpacked_rgb_%s_level_%u_face_%u_layer_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), level_index, face_index, layer_index);
else
rgb_filename = base_filename + string_format("_hdr_unpacked_rgb_%s_face_%u_layer_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
if (!write_exr(rgb_filename.c_str(), u, 3, 0))
{
error_printf("Failed writing to EXR file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote EXR file \"%s\"\n", rgb_filename.c_str());
}
}
else
{
image u;
if (!gi[level_index].unpack(u))
{
printf("Warning: Failed unpacking GPU texture data (%u %u %u %u). Unpacking as much as possible.\n", format_iter, layer_index, level_index, face_index);
total_unpack_warnings++;
}
//u.crop(level_info.m_orig_width, level_info.m_orig_height);
bool write_png = true;
// Save PNG (ignoring alpha)
if ((!opts.m_ktx_only) && (write_png))
{
std::string rgb_filename;
if (gi.size() > 1)
rgb_filename = base_filename + string_format("_unpacked_rgb_%s_level_%u_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, face_index, layer_index);
else
rgb_filename = base_filename + string_format("_unpacked_rgb_%s_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
if (!save_png(rgb_filename, u, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
}
// Save .OUT
if ((transcoder_tex_fmt == basist::transcoder_texture_format::cTFFXT1_RGB) && (opts.m_write_out))
{
std::string out_filename;
if (gi.size() > 1)
out_filename = base_filename + string_format("_unpacked_rgb_%s_level_%u_face_%u_layer_%04u.out", basist::basis_get_format_name(transcoder_tex_fmt), level_index, face_index, layer_index);
else
out_filename = base_filename + string_format("_unpacked_rgb_%s_face_%u_layer_%04u.out", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
if (!write_3dfx_out_file(out_filename.c_str(), gi[level_index]))
{
error_printf("Failed writing to OUT file \"%s\"\n", out_filename.c_str());
return false;
}
printf("Wrote .OUT file \"%s\"\n", out_filename.c_str());
}
// Save alpha
if (basis_transcoder_format_has_alpha(transcoder_tex_fmt) && (!opts.m_ktx_only) && (write_png))
{
std::string a_filename;
if (gi.size() > 1)
a_filename = base_filename + string_format("_unpacked_a_%s_level_%u_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, face_index, layer_index);
else
a_filename = base_filename + string_format("_unpacked_a_%s_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
if (!save_png(a_filename, u, cImageSaveGrayscale, 3))
{
error_printf("Failed writing to PNG file \"%s\"\n", a_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", a_filename.c_str());
std::string rgba_filename;
if (gi.size() > 1)
rgba_filename = base_filename + string_format("_unpacked_rgba_%s_level_%u_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, face_index, layer_index);
else
rgba_filename = base_filename + string_format("_unpacked_rgba_%s_face_%u_layer_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), face_index, layer_index);
if (!save_png(rgba_filename, u))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgba_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", rgba_filename.c_str());
}
} // is_hdr
} // level_index
} // face_index
} // layer_index
} // format_iter
// TODO: transcode to unpacked texture formats, like we do for .basis. As this is mostly a transcode test, supporting this with .basis seems fine.
return true;
}
static bool unpack_and_validate_basis_file(
uint32_t file_index,
const std::string &base_filename,
uint8_vec &basis_file_data,
command_line_params& opts,
FILE *pCSV_file,
basis_data* pGlobal_codebook_data,
uint32_t &total_unpack_warnings,
uint32_t &total_pvrtc_nonpow2_warnings)
{
const bool validate_flag = (opts.m_mode == cValidate);
basist::basisu_transcoder dec;
if (pGlobal_codebook_data)
{
dec.set_global_codebooks(&pGlobal_codebook_data->m_transcoder.get_lowlevel_etc1s_decoder());
}
if (!opts.m_fuzz_testing)
{
// Skip the full validation, which CRC16's the entire file.
// Validate the file - note this isn't necessary for transcoding
if (!dec.validate_file_checksums(&basis_file_data[0], (uint32_t)basis_file_data.size(), true))
{
error_printf("File version is unsupported, or file failed one or more CRC checks!\n");
return false;
}
}
printf("File version and CRC checks succeeded\n");
basist::basisu_file_info fileinfo;
if (!dec.get_file_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), fileinfo))
{
error_printf("Failed retrieving Basis file information!\n");
return false;
}
assert(fileinfo.m_total_images == fileinfo.m_image_mipmap_levels.size());
assert(fileinfo.m_total_images == dec.get_total_images(&basis_file_data[0], (uint32_t)basis_file_data.size()));
printf("File info:\n");
printf(" Version: %X\n", fileinfo.m_version);
printf(" Total header size: %u\n", fileinfo.m_total_header_size);
printf(" Total selectors: %u\n", fileinfo.m_total_selectors);
printf(" Selector codebook size: %u\n", fileinfo.m_selector_codebook_size);
printf(" Total endpoints: %u\n", fileinfo.m_total_endpoints);
printf(" Endpoint codebook size: %u\n", fileinfo.m_endpoint_codebook_size);
printf(" Tables size: %u\n", fileinfo.m_tables_size);
printf(" Slices size: %u\n", fileinfo.m_slices_size);
const bool is_hdr = (fileinfo.m_tex_format == basist::basis_tex_format::cUASTC_HDR_4x4);
printf(" Texture format: %s\n", is_hdr ? "UASTC_HDR" : ((fileinfo.m_tex_format == basist::basis_tex_format::cUASTC4x4) ? "UASTC" : "ETC1S"));
printf(" Texture type: %s\n", basist::basis_get_texture_type_name(fileinfo.m_tex_type));
printf(" us per frame: %u (%f fps)\n", fileinfo.m_us_per_frame, fileinfo.m_us_per_frame ? (1.0f / ((float)fileinfo.m_us_per_frame / 1000000.0f)) : 0.0f);
printf(" Total slices: %u\n", (uint32_t)fileinfo.m_slice_info.size());
printf(" Total images: %i\n", fileinfo.m_total_images);
printf(" Y Flipped: %u, Has alpha slices: %u\n", fileinfo.m_y_flipped, fileinfo.m_has_alpha_slices);
printf(" userdata0: 0x%X userdata1: 0x%X\n", fileinfo.m_userdata0, fileinfo.m_userdata1);
printf(" Per-image mipmap levels: ");
for (uint32_t i = 0; i < fileinfo.m_total_images; i++)
printf("%u ", fileinfo.m_image_mipmap_levels[i]);
printf("\n");
uint32_t total_texels = 0;
printf("\nImage info:\n");
for (uint32_t i = 0; i < fileinfo.m_total_images; i++)
{
basist::basisu_image_info ii;
if (!dec.get_image_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), ii, i))
{
error_printf("get_image_info() failed!\n");
return false;
}
printf("Image %u: MipLevels: %u OrigDim: %ux%u, BlockDim: %ux%u, FirstSlice: %u, HasAlpha: %u\n", i, ii.m_total_levels, ii.m_orig_width, ii.m_orig_height,
ii.m_num_blocks_x, ii.m_num_blocks_y, ii.m_first_slice_index, (uint32_t)ii.m_alpha_flag);
total_texels += ii.m_width * ii.m_height;
}
printf("\nSlice info:\n");
for (uint32_t i = 0; i < fileinfo.m_slice_info.size(); i++)
{
const basist::basisu_slice_info& sliceinfo = fileinfo.m_slice_info[i];
printf("%u: OrigWidthHeight: %ux%u, BlockDim: %ux%u, TotalBlocks: %u, Compressed size: %u, Image: %u, Level: %u, UnpackedCRC16: 0x%X, alpha: %u, iframe: %i\n",
i,
sliceinfo.m_orig_width, sliceinfo.m_orig_height,
sliceinfo.m_num_blocks_x, sliceinfo.m_num_blocks_y,
sliceinfo.m_total_blocks,
sliceinfo.m_compressed_size,
sliceinfo.m_image_index, sliceinfo.m_level_index,
sliceinfo.m_unpacked_slice_crc16,
(uint32_t)sliceinfo.m_alpha_flag,
(uint32_t)sliceinfo.m_iframe_flag);
}
printf("\n");
size_t comp_size = 0;
void* pComp_data = tdefl_compress_mem_to_heap(&basis_file_data[0], basis_file_data.size(), &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
mz_free(pComp_data);
const float basis_bits_per_texel = basis_file_data.size() * 8.0f / total_texels;
const float comp_bits_per_texel = comp_size * 8.0f / total_texels;
printf("Original size: %u, bits per texel: %3.3f\nCompressed size (Deflate): %u, bits per texel: %3.3f\n", (uint32_t)basis_file_data.size(), basis_bits_per_texel, (uint32_t)comp_size, comp_bits_per_texel);
if (opts.m_mode == cInfo)
{
return true;
}
if ((fileinfo.m_etc1s) && (fileinfo.m_selector_codebook_size == 0) && (fileinfo.m_endpoint_codebook_size == 0))
{
// File is ETC1S and uses global codebooks - make sure we loaded one
if (!pGlobal_codebook_data)
{
error_printf("ETC1S file uses global codebooks, but none were loaded (see the -use_global_codebooks option)\n");
return false;
}
if ((pGlobal_codebook_data->m_transcoder.get_lowlevel_etc1s_decoder().get_endpoints().size() != fileinfo.m_total_endpoints) ||
(pGlobal_codebook_data->m_transcoder.get_lowlevel_etc1s_decoder().get_selectors().size() != fileinfo.m_total_selectors))
{
error_printf("Supplied global codebook is not compatible with this file\n");
return false;
}
}
interval_timer tm;
tm.start();
if (!dec.start_transcoding(&basis_file_data[0], (uint32_t)basis_file_data.size()))
{
error_printf("start_transcoding() failed!\n");
return false;
}
const double start_transcoding_time_ms = tm.get_elapsed_ms();
printf("start_transcoding time: %3.3f ms\n", start_transcoding_time_ms);
basisu::vector< gpu_image_vec > gpu_images[(int)basist::transcoder_texture_format::cTFTotalTextureFormats];
double total_format_transcoding_time_ms[(int)basist::transcoder_texture_format::cTFTotalTextureFormats];
clear_obj(total_format_transcoding_time_ms);
int first_format = 0;
int last_format = (int)basist::transcoder_texture_format::cTFTotalTextureFormats;
if (opts.m_format_only > -1)
{
first_format = opts.m_format_only;
last_format = first_format + 1;
}
if ((pCSV_file) && (file_index == 0))
{
std::string desc;
desc = "filename,basis_bitrate,comp_bitrate,images,levels,slices,start_transcoding_time,";
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (!basis_is_format_supported(transcoder_tex_fmt, fileinfo.m_tex_format))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
desc += std::string(basis_get_format_name(transcoder_tex_fmt));
if (format_iter != last_format - 1)
desc += ",";
}
fprintf(pCSV_file, "%s\n", desc.c_str());
}
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
basist::transcoder_texture_format tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (basist::basis_transcoder_format_is_uncompressed(tex_fmt))
continue;
if (!basis_is_format_supported(tex_fmt, fileinfo.m_tex_format))
continue;
if (tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
gpu_images[(int)tex_fmt].resize(fileinfo.m_total_images);
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
gpu_images[(int)tex_fmt][image_index].resize(fileinfo.m_image_mipmap_levels[image_index]);
}
// Now transcode the file to all supported texture formats and save mipmapped KTX files
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (basist::basis_transcoder_format_is_uncompressed(transcoder_tex_fmt))
continue;
if (!basis_is_format_supported(transcoder_tex_fmt, fileinfo.m_tex_format))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
if ((transcoder_tex_fmt == basist::transcoder_texture_format::cTFPVRTC1_4_RGB) || (transcoder_tex_fmt == basist::transcoder_texture_format::cTFPVRTC1_4_RGBA))
{
if (!is_pow2(level_info.m_width) || !is_pow2(level_info.m_height))
{
total_pvrtc_nonpow2_warnings++;
printf("Warning: Will not transcode image %u level %u res %ux%u to PVRTC1 (one or more dimension is not a power of 2)\n", image_index, level_index, level_info.m_width, level_info.m_height);
// Can't transcode this image level to PVRTC because it's not a pow2 (we're going to support transcoding non-pow2 to the next larger pow2 soon)
continue;
}
}
basisu::texture_format tex_fmt = basis_get_basisu_texture_format(transcoder_tex_fmt);
gpu_image& gi = gpu_images[(int)transcoder_tex_fmt][image_index][level_index];
gi.init(tex_fmt, level_info.m_orig_width, level_info.m_orig_height);
// Fill the buffer with psuedo-random bytes, to help more visibly detect cases where the transcoder fails to write to part of the output.
fill_buffer_with_random_bytes(gi.get_ptr(), gi.get_size_in_bytes());
uint32_t decode_flags = 0;
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index, gi.get_ptr(), gi.get_total_blocks(), transcoder_tex_fmt, decode_flags))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, format_iter);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[format_iter] += total_transcode_time;
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
} // format_iter
} // level_index
} // image_info
// Upack UASTC files seperately, to validate we can transcode slices to UASTC and unpack them to pixels.
// This is a special path because UASTC is not yet a valid transcoder_texture_format, but a lower-level block_format.
if (fileinfo.m_tex_format == basist::basis_tex_format::cUASTC4x4)
{
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
gpu_image gi;
gi.init(basisu::texture_format::cUASTC4x4, level_info.m_orig_width, level_info.m_orig_height);
// Fill the buffer with psuedo-random bytes, to help more visibly detect cases where the transcoder fails to write to part of the output.
fill_buffer_with_random_bytes(gi.get_ptr(), gi.get_size_in_bytes());
//uint32_t decode_flags = 0;
tm.start();
if (!dec.transcode_slice(
&basis_file_data[0], (uint32_t)basis_file_data.size(),
level_info.m_first_slice_index, gi.get_ptr(), gi.get_total_blocks(), basist::block_format::cUASTC_4x4, gi.get_bytes_per_block()))
{
error_printf("Failed transcoding image level (%u %u) to UASTC!\n", image_index, level_index);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
printf("Transcode of image %u level %u res %ux%u format UASTC_4x4 succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
image u;
if (!gi.unpack(u))
{
error_printf("Warning: Failed unpacking GPU texture data (%u %u) to UASTC. \n", image_index, level_index);
return false;
}
//u.crop(level_info.m_orig_width, level_info.m_orig_height);
std::string rgb_filename;
if (fileinfo.m_image_mipmap_levels[image_index] > 1)
rgb_filename = base_filename + string_format("_unpacked_rgb_UASTC_4x4_%u_%04u.png", level_index, image_index);
else
rgb_filename = base_filename + string_format("_unpacked_rgb_UASTC_4x4_%04u.png", image_index);
if (!save_png(rgb_filename, u, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
std::string alpha_filename;
if (fileinfo.m_image_mipmap_levels[image_index] > 1)
alpha_filename = base_filename + string_format("_unpacked_a_UASTC_4x4_%u_%04u.png", level_index, image_index);
else
alpha_filename = base_filename + string_format("_unpacked_a_UASTC_4x4_%04u.png", image_index);
if (!save_png(alpha_filename, u, cImageSaveGrayscale, 3))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote PNG file \"%s\"\n", alpha_filename.c_str());
}
}
}
}
if (!validate_flag)
{
// Now write KTX files and unpack them to individual PNG's/EXR's
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (basist::basis_transcoder_format_is_uncompressed(transcoder_tex_fmt))
continue;
if (!basis_is_format_supported(transcoder_tex_fmt, fileinfo.m_tex_format))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
if ((!opts.m_no_ktx) && (fileinfo.m_tex_type == basist::cBASISTexTypeCubemapArray))
{
// No KTX tool that we know of supports cubemap arrays, so write individual cubemap files.
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index += 6)
{
basisu::vector<gpu_image_vec> cubemap;
for (uint32_t i = 0; i < 6; i++)
cubemap.push_back(gpu_images[format_iter][image_index + i]);
{
std::string ktx_filename(base_filename + string_format("_transcoded_cubemap_%s_%u.ktx", basist::basis_get_format_name(transcoder_tex_fmt), image_index / 6));
if (!write_compressed_texture_file(ktx_filename.c_str(), cubemap, true, true))
{
error_printf("Failed writing KTX file \"%s\"!\n", ktx_filename.c_str());
return false;
}
printf("Wrote KTX file \"%s\"\n", ktx_filename.c_str());
}
if (does_dds_support_format(cubemap[0][0].get_format()))
{
std::string dds_filename(base_filename + string_format("_transcoded_cubemap_%s_%u.dds", basist::basis_get_format_name(transcoder_tex_fmt), image_index / 6));
if (!write_compressed_texture_file(dds_filename.c_str(), cubemap, true, true))
{
error_printf("Failed writing DDS file \"%s\"!\n", dds_filename.c_str());
return false;
}
printf("Wrote DDS file \"%s\"\n", dds_filename.c_str());
}
}
}
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
gpu_image_vec& gi = gpu_images[format_iter][image_index];
if (!gi.size())
continue;
uint32_t level;
for (level = 0; level < gi.size(); level++)
if (!gi[level].get_total_blocks())
break;
if (level < gi.size())
continue;
if ((!opts.m_no_ktx) && (fileinfo.m_tex_type != basist::cBASISTexTypeCubemapArray))
{
{
std::string ktx_filename(base_filename + string_format("_transcoded_%s_%04u.ktx", basist::basis_get_format_name(transcoder_tex_fmt), image_index));
if (!write_compressed_texture_file(ktx_filename.c_str(), gi, true))
{
error_printf("Failed writing KTX file \"%s\"!\n", ktx_filename.c_str());
return false;
}
printf("Wrote KTX file \"%s\"\n", ktx_filename.c_str());
}
if (does_dds_support_format(gi[0].get_format()))
{
std::string dds_filename(base_filename + string_format("_transcoded_%s_%04u.dds", basist::basis_get_format_name(transcoder_tex_fmt), image_index));
if (!write_compressed_texture_file(dds_filename.c_str(), gi, true))
{
error_printf("Failed writing DDS file \"%s\"!\n", dds_filename.c_str());
return false;
}
printf("Wrote DDS file \"%s\"\n", dds_filename.c_str());
}
}
for (uint32_t level_index = 0; level_index < gi.size(); level_index++)
{
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
if (basist::basis_transcoder_format_is_hdr(transcoder_tex_fmt))
{
imagef u;
if (!gi[level_index].unpack_hdr(u))
{
printf("Warning: Failed unpacking GPU texture data (%u %u %u). Unpacking as much as possible.\n", format_iter, image_index, level_index);
total_unpack_warnings++;
}
if (!opts.m_ktx_only)
{
std::string rgb_filename;
if (gi.size() > 1)
rgb_filename = base_filename + string_format("_hdr_unpacked_rgb_%s_%u_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index);
else
rgb_filename = base_filename + string_format("_hdr_unpacked_rgb_%s_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), image_index);
if (!write_exr(rgb_filename.c_str(), u, 3, 0))
{
error_printf("Failed writing to EXR file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote EXR file \"%s\"\n", rgb_filename.c_str());
}
}
else
{
image u;
if (!gi[level_index].unpack(u))
{
printf("Warning: Failed unpacking GPU texture data (%u %u %u). Unpacking as much as possible.\n", format_iter, image_index, level_index);
total_unpack_warnings++;
}
//u.crop(level_info.m_orig_width, level_info.m_orig_height);
bool write_png = true;
if ((!opts.m_ktx_only) && (write_png))
{
std::string rgb_filename;
if (gi.size() > 1)
rgb_filename = base_filename + string_format("_unpacked_rgb_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index);
else
rgb_filename = base_filename + string_format("_unpacked_rgb_%s_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), image_index);
if (!save_png(rgb_filename, u, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
}
if ((transcoder_tex_fmt == basist::transcoder_texture_format::cTFFXT1_RGB) && (opts.m_write_out))
{
std::string out_filename;
if (gi.size() > 1)
out_filename = base_filename + string_format("_unpacked_rgb_%s_%u_%04u.out", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index);
else
out_filename = base_filename + string_format("_unpacked_rgb_%s_%04u.out", basist::basis_get_format_name(transcoder_tex_fmt), image_index);
if (!write_3dfx_out_file(out_filename.c_str(), gi[level_index]))
{
error_printf("Failed writing to OUT file \"%s\"\n", out_filename.c_str());
return false;
}
printf("Wrote .OUT file \"%s\"\n", out_filename.c_str());
}
if (basis_transcoder_format_has_alpha(transcoder_tex_fmt) && (!opts.m_ktx_only) && (write_png))
{
std::string a_filename;
if (gi.size() > 1)
a_filename = base_filename + string_format("_unpacked_a_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index);
else
a_filename = base_filename + string_format("_unpacked_a_%s_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), image_index);
if (!save_png(a_filename, u, cImageSaveGrayscale, 3))
{
error_printf("Failed writing to PNG file \"%s\"\n", a_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", a_filename.c_str());
std::string rgba_filename;
if (gi.size() > 1)
rgba_filename = base_filename + string_format("_unpacked_rgba_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index);
else
rgba_filename = base_filename + string_format("_unpacked_rgba_%s_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), image_index);
if (!save_png(rgba_filename, u))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgba_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", rgba_filename.c_str());
}
} // is_hdr
} // level_index
} // image_index
} // format_iter
} // if (!validate_flag)
uint32_t max_mipmap_levels = 0;
//if (!opts.m_etc1_only)
if ((opts.m_format_only == -1) && (!validate_flag))
{
if (is_hdr)
{
// Now unpack to RGBA_HALF using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGBA_HALF;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
const uint32_t total_pixels = level_info.m_orig_width * level_info.m_orig_height;
basisu::vector<basist::half_float> half_img(total_pixels * 4);
fill_buffer_with_random_bytes(&half_img[0], half_img.size_in_bytes());
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index,
half_img.get_ptr(), total_pixels, transcoder_tex_fmt, 0, level_info.m_orig_width, nullptr, level_info.m_orig_height))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
// TODO: HDR alpha support
imagef float_img(level_info.m_orig_width, level_info.m_orig_height);
for (uint32_t y = 0; y < level_info.m_orig_height; y++)
for (uint32_t x = 0; x < level_info.m_orig_width; x++)
for (uint32_t c = 0; c < 4; c++)
float_img(x, y)[c] = basist::half_to_float(half_img[(x + y * level_info.m_orig_width) * 4 + c]);
std::string rgb_filename(base_filename + string_format("_hdr_unpacked_rgba_%s_%u_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!write_exr(rgb_filename.c_str(), float_img, 3, 0))
{
error_printf("Failed writing to EXR file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote EXR file \"%s\"\n", rgb_filename.c_str());
}
} // level_index
} // image_index
// Now unpack to RGB_HALF using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGB_HALF;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
const uint32_t total_pixels = level_info.m_orig_width * level_info.m_orig_height;
basisu::vector<basist::half_float> half_img(total_pixels * 3);
fill_buffer_with_random_bytes(&half_img[0], half_img.size_in_bytes());
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index,
half_img.get_ptr(), total_pixels, transcoder_tex_fmt, 0, level_info.m_orig_width, nullptr, level_info.m_orig_height))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
// TODO: HDR alpha support
imagef float_img(level_info.m_orig_width, level_info.m_orig_height);
for (uint32_t y = 0; y < level_info.m_orig_height; y++)
for (uint32_t x = 0; x < level_info.m_orig_width; x++)
for (uint32_t c = 0; c < 3; c++)
float_img(x, y)[c] = basist::half_to_float(half_img[(x + y * level_info.m_orig_width) * 3 + c]);
std::string rgb_filename(base_filename + string_format("_hdr_unpacked_rgb_%s_%u_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!write_exr(rgb_filename.c_str(), float_img, 3, 0))
{
error_printf("Failed writing to EXR file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote EXR file \"%s\"\n", rgb_filename.c_str());
}
} // level_index
} // image_index
// Now unpack to RGB_9E5 using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGB_9E5;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
const uint32_t total_pixels = level_info.m_orig_width * level_info.m_orig_height;
basisu::vector<uint32_t> rgb9e5_img(total_pixels);
fill_buffer_with_random_bytes(&rgb9e5_img[0], rgb9e5_img.size_in_bytes());
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index,
rgb9e5_img.get_ptr(), total_pixels, transcoder_tex_fmt, 0, level_info.m_orig_width, nullptr, level_info.m_orig_height))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
// TODO: Write KTX or DDS
imagef float_img(level_info.m_orig_width, level_info.m_orig_height);
for (uint32_t y = 0; y < level_info.m_orig_height; y++)
for (uint32_t x = 0; x < level_info.m_orig_width; x++)
astc_helpers::unpack_rgb9e5(rgb9e5_img[x + y * level_info.m_orig_width], float_img(x, y)[0], float_img(x, y)[1], float_img(x, y)[2]);
std::string rgb_filename(base_filename + string_format("_hdr_unpacked_rgb_%s_%u_%04u.exr", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!write_exr(rgb_filename.c_str(), float_img, 3, 0))
{
error_printf("Failed writing to EXR file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote EXR file \"%s\"\n", rgb_filename.c_str());
}
} // level_index
} // image_index
}
else
{
// Now unpack to RGBA using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGBA32;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
image img(level_info.m_orig_width, level_info.m_orig_height);
fill_buffer_with_random_bytes(&img(0, 0), img.get_total_pixels() * sizeof(uint32_t));
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index, &img(0, 0).r, img.get_total_pixels(), transcoder_tex_fmt, 0, img.get_pitch(), nullptr, img.get_height()))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
std::string rgb_filename(base_filename + string_format("_unpacked_rgb_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!save_png(rgb_filename, img, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
std::string a_filename(base_filename + string_format("_unpacked_a_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!save_png(a_filename, img, cImageSaveGrayscale, 3))
{
error_printf("Failed writing to PNG file \"%s\"\n", a_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", a_filename.c_str());
}
} // level_index
} // image_index
// Now unpack to RGB565 using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGB565;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
basisu::vector<uint16_t> packed_img(level_info.m_orig_width * level_info.m_orig_height);
fill_buffer_with_random_bytes(&packed_img[0], packed_img.size() * sizeof(uint16_t));
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index, &packed_img[0], (uint32_t)packed_img.size(), transcoder_tex_fmt, 0, level_info.m_orig_width, nullptr, level_info.m_orig_height))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
image img(level_info.m_orig_width, level_info.m_orig_height);
for (uint32_t y = 0; y < level_info.m_orig_height; y++)
{
for (uint32_t x = 0; x < level_info.m_orig_width; x++)
{
const uint16_t p = packed_img[x + y * level_info.m_orig_width];
uint32_t r = p >> 11, g = (p >> 5) & 63, b = p & 31;
r = (r << 3) | (r >> 2);
g = (g << 2) | (g >> 4);
b = (b << 3) | (b >> 2);
img(x, y).set(r, g, b, 255);
}
}
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
std::string rgb_filename(base_filename + string_format("_unpacked_rgb_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!save_png(rgb_filename, img, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
}
} // level_index
} // image_index
// Now unpack to RGBA4444 using the transcoder itself to do the unpacking to raster images
for (uint32_t image_index = 0; image_index < fileinfo.m_total_images; image_index++)
{
for (uint32_t level_index = 0; level_index < fileinfo.m_image_mipmap_levels[image_index]; level_index++)
{
max_mipmap_levels = basisu::maximum(max_mipmap_levels, fileinfo.m_image_mipmap_levels[image_index]);
const basist::transcoder_texture_format transcoder_tex_fmt = basist::transcoder_texture_format::cTFRGBA4444;
basist::basisu_image_level_info level_info;
if (!dec.get_image_level_info(&basis_file_data[0], (uint32_t)basis_file_data.size(), level_info, image_index, level_index))
{
error_printf("Failed retrieving image level information (%u %u)!\n", image_index, level_index);
return false;
}
basisu::vector<uint16_t> packed_img(level_info.m_orig_width * level_info.m_orig_height);
fill_buffer_with_random_bytes(&packed_img[0], packed_img.size() * sizeof(uint16_t));
tm.start();
if (!dec.transcode_image_level(&basis_file_data[0], (uint32_t)basis_file_data.size(), image_index, level_index, &packed_img[0], (uint32_t)packed_img.size(), transcoder_tex_fmt, 0, level_info.m_orig_width, nullptr, level_info.m_orig_height))
{
error_printf("Failed transcoding image level (%u %u %u)!\n", image_index, level_index, transcoder_tex_fmt);
return false;
}
double total_transcode_time = tm.get_elapsed_ms();
total_format_transcoding_time_ms[(int)transcoder_tex_fmt] += total_transcode_time;
image img(level_info.m_orig_width, level_info.m_orig_height);
for (uint32_t y = 0; y < level_info.m_orig_height; y++)
{
for (uint32_t x = 0; x < level_info.m_orig_width; x++)
{
const uint16_t p = packed_img[x + y * level_info.m_orig_width];
uint32_t r = p >> 12, g = (p >> 8) & 15, b = (p >> 4) & 15, a = p & 15;
r = (r << 4) | r;
g = (g << 4) | g;
b = (b << 4) | b;
a = (a << 4) | a;
img(x, y).set(r, g, b, a);
}
}
printf("Transcode of image %u level %u res %ux%u format %s succeeded in %3.3f ms\n", image_index, level_index, level_info.m_orig_width, level_info.m_orig_height, basist::basis_get_format_name(transcoder_tex_fmt), total_transcode_time);
if ((!validate_flag) && (!opts.m_ktx_only))
{
std::string rgb_filename(base_filename + string_format("_unpacked_rgb_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!save_png(rgb_filename, img, cImageSaveIgnoreAlpha))
{
error_printf("Failed writing to PNG file \"%s\"\n", rgb_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", rgb_filename.c_str());
std::string a_filename(base_filename + string_format("_unpacked_a_%s_%u_%04u.png", basist::basis_get_format_name(transcoder_tex_fmt), level_index, image_index));
if (!save_png(a_filename, img, cImageSaveGrayscale, 3))
{
error_printf("Failed writing to PNG file \"%s\"\n", a_filename.c_str());
return false;
}
printf("Wrote PNG file \"%s\"\n", a_filename.c_str());
}
} // level_index
} // image_index
} // is_hdr
} // if ((opts.m_format_only == -1) && (!validate_flag))
if (pCSV_file)
{
fprintf(pCSV_file, "%s, %3.3f, %3.3f, %u, %u, %u, %3.3f, ",
base_filename.c_str(),
basis_bits_per_texel,
comp_bits_per_texel,
fileinfo.m_total_images,
max_mipmap_levels,
(uint32_t)fileinfo.m_slice_info.size(),
start_transcoding_time_ms);
for (int format_iter = first_format; format_iter < last_format; format_iter++)
{
const basist::transcoder_texture_format transcoder_tex_fmt = static_cast<basist::transcoder_texture_format>(format_iter);
if (!basis_is_format_supported(transcoder_tex_fmt, fileinfo.m_tex_format))
continue;
if (transcoder_tex_fmt == basist::transcoder_texture_format::cTFBC7_ALT)
continue;
fprintf(pCSV_file, "%3.3f", total_format_transcoding_time_ms[format_iter]);
if (format_iter != (last_format - 1))
fprintf(pCSV_file, ",");
}
fprintf(pCSV_file, "\n");
}
return true;
}
static bool unpack_and_validate_mode(command_line_params &opts)
{
interval_timer tm;
tm.start();
//const bool validate_flag = (opts.m_mode == cValidate);
basis_data* pGlobal_codebook_data = nullptr;
if (opts.m_etc1s_use_global_codebooks_file.size())
{
pGlobal_codebook_data = load_basis_file(opts.m_etc1s_use_global_codebooks_file.c_str(), true);
if (!pGlobal_codebook_data)
{
error_printf("Failed loading global codebook data from file \"%s\"\n", opts.m_etc1s_use_global_codebooks_file.c_str());
return false;
}
printf("Loaded global codebooks from file \"%s\"\n", opts.m_etc1s_use_global_codebooks_file.c_str());
}
if (!opts.m_input_filenames.size())
{
error_printf("No input files to process!\n");
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
FILE* pCSV_file = nullptr;
if ((opts.m_csv_file.size()) && (opts.m_mode == cValidate))
{
pCSV_file = fopen_safe(opts.m_csv_file.c_str(), "w");
if (!pCSV_file)
{
error_printf("Failed opening CVS file \"%s\"\n", opts.m_csv_file.c_str());
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
//fprintf(pCSV_file, "Filename, Size, Slices, Width, Height, HasAlpha, BitsPerTexel, Slice0RGBAvgPSNR, Slice0RGBAAvgPSNR, Slice0Luma709PSNR, Slice0BestETC1SLuma709PSNR, Q, CL, Time, RGBAvgPSNRMin, RGBAvgPSNRAvg, AAvgPSNRMin, AAvgPSNRAvg, Luma709PSNRMin, Luma709PSNRAvg\n");
}
uint32_t total_unpack_warnings = 0;
uint32_t total_pvrtc_nonpow2_warnings = 0;
for (uint32_t file_index = 0; file_index < opts.m_input_filenames.size(); file_index++)
{
const char* pInput_filename = opts.m_input_filenames[file_index].c_str();
std::string base_filename;
string_split_path(pInput_filename, nullptr, nullptr, &base_filename, nullptr);
uint8_vec file_data;
if (!basisu::read_file_to_vec(pInput_filename, file_data))
{
error_printf("Failed reading file \"%s\"\n", pInput_filename);
if (pCSV_file) fclose(pCSV_file);
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
if (!file_data.size())
{
error_printf("File is empty!\n");
if (pCSV_file) fclose(pCSV_file);
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
if (file_data.size() > UINT32_MAX)
{
error_printf("File is too large!\n");
if (pCSV_file) fclose(pCSV_file);
delete pGlobal_codebook_data; pGlobal_codebook_data = nullptr;
return false;
}
bool is_ktx2 = false;
if (file_data.size() >= sizeof(basist::g_ktx2_file_identifier))
{
is_ktx2 = (memcmp(file_data.data(), basist::g_ktx2_file_identifier, sizeof(basist::g_ktx2_file_identifier)) == 0);
}
printf("Input file \"%s\", KTX2: %u\n", pInput_filename, is_ktx2);
bool status;
if (is_ktx2)
{
status = unpack_and_validate_ktx2_file(
file_index,
base_filename,
file_data,
opts,
pCSV_file,
pGlobal_codebook_data,
total_unpack_warnings,
total_pvrtc_nonpow2_warnings);
}
else
{
status = unpack_and_validate_basis_file(
file_index,
base_filename,
file_data,
opts,
pCSV_file,
pGlobal_codebook_data,
total_unpack_warnings,
total_pvrtc_nonpow2_warnings);
}
if (!status)
{
if (pCSV_file)
fclose(pCSV_file);
delete pGlobal_codebook_data;
pGlobal_codebook_data = nullptr;
return false;
}
} // file_index
if (total_pvrtc_nonpow2_warnings)
printf("Warning: %u images could not be transcoded to PVRTC1 because one or both dimensions were not a power of 2\n", total_pvrtc_nonpow2_warnings);
if (total_unpack_warnings)
printf("ATTENTION: %u total images had invalid GPU texture data!\n", total_unpack_warnings);
else
printf("Success\n");
debug_printf("Elapsed time: %3.3f secs\n", tm.get_elapsed_secs());
if (pCSV_file)
{
fclose(pCSV_file);
pCSV_file = nullptr;
}
delete pGlobal_codebook_data;
pGlobal_codebook_data = nullptr;
return true;
}
static bool hdr_compare_mode(command_line_params& opts)
{
if (opts.m_input_filenames.size() != 2)
{
error_printf("Must specify two PNG filenames using -file\n");
return false;
}
imagef a, b;
if (!load_image_hdr(opts.m_input_filenames[0].c_str(), a))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[0].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u\n", opts.m_input_filenames[0].c_str(), a.get_width(), a.get_height());
if (!load_image_hdr(opts.m_input_filenames[1].c_str(), b))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[1].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u\n", opts.m_input_filenames[1].c_str(), b.get_width(), b.get_height());
if ((a.get_width() != b.get_width()) || (a.get_height() != b.get_height()))
{
printf("Images don't have the same dimensions - cropping input images to smallest common dimensions\n");
uint32_t w = minimum(a.get_width(), b.get_width());
uint32_t h = minimum(a.get_height(), b.get_height());
a.crop(w, h);
b.crop(w, h);
}
printf("Comparison image res: %ux%u\n", a.get_width(), a.get_height());
image_metrics im;
im.calc_half(a, b, 0, 1, true);
im.print("R ");
im.calc_half(a, b, 1, 1, true);
im.print("G ");
im.calc_half(a, b, 2, 1, true);
im.print("B ");
im.calc_half(a, b, 0, 3, true);
im.print("RGB ");
return true;
}
static bool compare_mode(command_line_params &opts)
{
if (opts.m_input_filenames.size() != 2)
{
error_printf("Must specify two PNG filenames using -file\n");
return false;
}
std::string ext0(string_get_extension(opts.m_input_filenames[0]));
if ((strcasecmp(ext0.c_str(), "exr") == 0) || (strcasecmp(ext0.c_str(), "hdr") == 0))
{
error_printf("Can't compare HDR image files with this option. Use -hdr_compare instead.\n");
return false;
}
std::string ext1(string_get_extension(opts.m_input_filenames[1]));
if ((strcasecmp(ext1.c_str(), "exr") == 0) || (strcasecmp(ext1.c_str(), "hdr") == 0))
{
error_printf("Can't compare HDR image files with this option. Use -hdr_compare instead.\n");
return false;
}
image a, b;
if (!load_image(opts.m_input_filenames[0].c_str(), a))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[0].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u, has alpha: %u\n", opts.m_input_filenames[0].c_str(), a.get_width(), a.get_height(), a.has_alpha());
if (!load_image(opts.m_input_filenames[1].c_str(), b))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[1].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u, has alpha: %u\n", opts.m_input_filenames[1].c_str(), b.get_width(), b.get_height(), b.has_alpha());
if ((a.get_width() != b.get_width()) || (a.get_height() != b.get_height()))
{
printf("Images don't have the same dimensions - cropping input images to smallest common dimensions\n");
uint32_t w = minimum(a.get_width(), b.get_width());
uint32_t h = minimum(a.get_height(), b.get_height());
a.crop(w, h);
b.crop(w, h);
}
printf("Comparison image res: %ux%u\n", a.get_width(), a.get_height());
image_metrics im;
im.calc(a, b, 0, 3);
im.print("RGB ");
im.calc(a, b, 0, 4);
im.print("RGBA ");
im.calc(a, b, 0, 1);
im.print("R ");
im.calc(a, b, 1, 1);
im.print("G ");
im.calc(a, b, 2, 1);
im.print("B ");
im.calc(a, b, 3, 1);
im.print("A ");
im.calc(a, b, 0, 0);
im.print("Y 709 " );
im.calc(a, b, 0, 0, true, true);
im.print("Y 601 " );
if (opts.m_compare_ssim)
{
vec4F s_rgb(compute_ssim(a, b, false, false));
printf("R SSIM: %f\n", s_rgb[0]);
printf("G SSIM: %f\n", s_rgb[1]);
printf("B SSIM: %f\n", s_rgb[2]);
printf("RGB Avg SSIM: %f\n", (s_rgb[0] + s_rgb[1] + s_rgb[2]) / 3.0f);
printf("A SSIM: %f\n", s_rgb[3]);
vec4F s_y_709(compute_ssim(a, b, true, false));
printf("Y 709 SSIM: %f\n", s_y_709[0]);
vec4F s_y_601(compute_ssim(a, b, true, true));
printf("Y 601 SSIM: %f\n", s_y_601[0]);
}
image delta_img(a.get_width(), a.get_height());
const int X = 2;
for (uint32_t y = 0; y < a.get_height(); y++)
{
for (uint32_t x = 0; x < a.get_width(); x++)
{
color_rgba &d = delta_img(x, y);
for (int c = 0; c < 4; c++)
d[c] = (uint8_t)clamp<int>((a(x, y)[c] - b(x, y)[c]) * X + 128, 0, 255);
} // x
} // y
save_png("a_rgb.png", a, cImageSaveIgnoreAlpha);
save_png("a_alpha.png", a, cImageSaveGrayscale, 3);
printf("Wrote a_rgb.png and a_alpha.png\n");
save_png("b_rgb.png", b, cImageSaveIgnoreAlpha);
save_png("b_alpha.png", b, cImageSaveGrayscale, 3);
printf("Wrote b_rgb.png and b_alpha.png\n");
save_png("delta_img_rgb.png", delta_img, cImageSaveIgnoreAlpha);
printf("Wrote delta_img_rgb.png\n");
save_png("delta_img_a.png", delta_img, cImageSaveGrayscale, 3);
printf("Wrote delta_img_a.png\n");
if (opts.m_compare_plot)
{
uint32_t bins[5][512];
clear_obj(bins);
running_stat delta_stats[5];
basisu::rand rm;
double avg[5];
clear_obj(avg);
for (uint32_t y = 0; y < a.get_height(); y++)
{
for (uint32_t x = 0; x < a.get_width(); x++)
{
//color_rgba& d = delta_img(x, y);
for (int c = 0; c < 4; c++)
{
int delta = a(x, y)[c] - b(x, y)[c];
//delta = clamp<int>((int)std::round(rm.gaussian(70.0f, 10.0f)), -255, 255);
bins[c][delta + 256]++;
delta_stats[c].push(delta);
avg[c] += delta;
}
int y_delta = a(x, y).get_709_luma() - b(x, y).get_709_luma();
bins[4][y_delta + 256]++;
delta_stats[4].push(y_delta);
avg[4] += y_delta;
} // x
} // y
for (uint32_t i = 0; i <= 4; i++)
avg[i] /= a.get_total_pixels();
printf("\n");
//bins[2][256+-255] = 100000;
//bins[2][256-56] = 50000;
const uint32_t X_SIZE = 128, Y_SIZE = 40;
for (uint32_t c = 0; c <= 4; c++)
{
std::vector<uint8_t> plot[Y_SIZE + 1];
for (uint32_t i = 0; i < Y_SIZE; i++)
{
plot[i].resize(X_SIZE + 2);
memset(plot[i].data(), ' ', X_SIZE + 1);
}
uint32_t max_val = 0;
int max_val_bin_index = 0;
int lowest_bin_index = INT_MAX, highest_bin_index = INT_MIN;
double avg_val = 0;
double total_val = 0;
running_stat bin_stats;
for (int y = -255; y <= 255; y++)
{
uint32_t val = bins[c][256 + y];
if (!val)
continue;
bin_stats.push(y);
total_val += (double)val;
lowest_bin_index = minimum(lowest_bin_index, y);
highest_bin_index = maximum(highest_bin_index, y);
if (val > max_val)
{
max_val = val;
max_val_bin_index = y;
}
avg_val += y * (double)val;
}
avg_val /= total_val;
int lo_limit = -(int)X_SIZE / 2;
int hi_limit = X_SIZE / 2;
for (int x = lo_limit; x <= hi_limit; x++)
{
uint32_t total = 0;
if (x == lo_limit)
{
for (int i = -255; i <= lo_limit; i++)
total += bins[c][256 + i];
}
else if (x == hi_limit)
{
for (int i = hi_limit; i <= 255; i++)
total += bins[c][256 + i];
}
else
{
total = bins[c][256 + x];
}
uint32_t height = max_val ? (total * Y_SIZE + max_val - 1) / max_val : 0;
if (height)
{
for (uint32_t y = (Y_SIZE - 1) - (height - 1); y <= (Y_SIZE - 1); y++)
plot[y][x + X_SIZE / 2] = '*';
}
}
printf("%c delta histogram: total samples: %5.0f, max bin value: %u index: %i (%3.3f%% of total), range %i [%i,%i], weighted mean: %f\n", "RGBAY"[c], total_val, max_val, max_val_bin_index, max_val * 100.0f / total_val, highest_bin_index - lowest_bin_index + 1, lowest_bin_index, highest_bin_index, avg_val);
printf("bin mean: %f, bin std deviation: %f, non-zero bins: %u\n", bin_stats.get_mean(), bin_stats.get_std_dev(), bin_stats.get_num());
printf("delta mean: %f, delta std deviation: %f\n", delta_stats[c].get_mean(), delta_stats[c].get_std_dev());
printf("\n");
for (uint32_t y = 0; y < Y_SIZE; y++)
printf("%s\n", (char*)plot[y].data());
char tics[1024];
tics[0] = '\0';
char tics2[1024];
tics2[0] = '\0';
for (int x = 0; x <= (int)X_SIZE; x++)
{
char buf[64];
if (x == X_SIZE / 2)
{
while ((int)strlen(tics) < x)
strcat(tics, ".");
while ((int)strlen(tics2) < x)
strcat(tics2, " ");
sprintf(buf, "0");
strcat(tics, buf);
}
else if (((x & 7) == 0) || (x == X_SIZE))
{
while ((int)strlen(tics) < x)
strcat(tics, ".");
while ((int)strlen(tics2) < x)
strcat(tics2, " ");
int v = (x - (int)X_SIZE / 2);
sprintf(buf, "%i", v / 10);
strcat(tics, buf);
if (v < 0)
{
if (-v < 10)
sprintf(buf, "%i", v % 10);
else
sprintf(buf, " %i", -v % 10);
}
else
sprintf(buf, "%i", v % 10);
strcat(tics2, buf);
}
else
{
while ((int)strlen(tics) < x)
strcat(tics, ".");
}
}
printf("%s\n", tics);
printf("%s\n", tics2);
printf("\n");
}
} // display_plot
return true;
}
static bool split_image_mode(command_line_params& opts)
{
if (opts.m_input_filenames.size() != 1)
{
error_printf("Must specify one image filename using -file\n");
return false;
}
image a;
if (!load_image(opts.m_input_filenames[0].c_str(), a))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[0].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u, has alpha: %u\n", opts.m_input_filenames[0].c_str(), a.get_width(), a.get_height(), a.has_alpha());
if (!save_png("split_rgb.png", a, cImageSaveIgnoreAlpha))
{
fprintf(stderr, "Failed writing file split_rgb.png\n");
return false;
}
printf("Wrote file split_rgb.png\n");
for (uint32_t i = 0; i < 4; i++)
{
char buf[256];
snprintf(buf, sizeof(buf), "split_%c.png", "RGBA"[i]);
if (!save_png(buf, a, cImageSaveGrayscale, i))
{
fprintf(stderr, "Failed writing file %s\n", buf);
return false;
}
printf("Wrote file %s\n", buf);
}
return true;
}
static bool combine_images_mode(command_line_params& opts)
{
if (opts.m_input_filenames.size() != 2)
{
error_printf("Must specify two image filename using -file\n");
return false;
}
image a, b;
if (!load_image(opts.m_input_filenames[0].c_str(), a))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[0].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u, has alpha: %u\n", opts.m_input_filenames[0].c_str(), a.get_width(), a.get_height(), a.has_alpha());
if (!load_image(opts.m_input_filenames[1].c_str(), b))
{
error_printf("Failed loading image from file \"%s\"!\n", opts.m_input_filenames[1].c_str());
return false;
}
printf("Loaded \"%s\", %ux%u, has alpha: %u\n", opts.m_input_filenames[1].c_str(), b.get_width(), b.get_height(), b.has_alpha());
const uint32_t width = minimum(a.get_width(), b.get_width());
const uint32_t height = minimum(b.get_height(), b.get_height());
image combined_img(width, height);
for (uint32_t y = 0; y < height; y++)
{
for (uint32_t x = 0; x < width; x++)
{
combined_img(x, y) = a(x, y);
combined_img(x, y).a = b(x, y).g;
}
}
const char* pOutput_filename = "combined.png";
if (opts.m_output_filename.size())
pOutput_filename = opts.m_output_filename.c_str();
if (!save_png(pOutput_filename, combined_img))
{
fprintf(stderr, "Failed writing file %s\n", pOutput_filename);
return false;
}
printf("Wrote file %s\n", pOutput_filename);
return true;
}
static bool tonemap_image_mode(command_line_params& opts)
{
if (opts.m_input_filenames.size() != 1)
{
error_printf("Must specify one LDR image filename using -file\n");
return false;
}
imagef hdr_img;
if (!load_image_hdr(opts.m_input_filenames[0].c_str(), hdr_img, opts.m_comp_params.m_hdr_ldr_srgb_to_linear_conversion))
{
error_printf("Failed loading LDR image from file \"%s\"!\n", opts.m_input_filenames[0].c_str());
return false;
}
hdr_img.clean_astc_hdr_pixels(1e+30f);
const uint32_t width = hdr_img.get_width(), height = hdr_img.get_height();
printf("Loaded \"%s\", %ux%u\n", opts.m_input_filenames[0].c_str(), width, height);
std::string output_filename;
string_get_filename(opts.m_input_filenames[0].c_str(), output_filename);
string_remove_extension(output_filename);
if (!output_filename.size())
output_filename = "tonemapped";
if (opts.m_output_path.size())
string_combine_path(output_filename, opts.m_output_path.c_str(), output_filename.c_str());
const char* pBasename = output_filename.c_str();
image srgb_img(width, height);
for (uint32_t y = 0; y < height; y++)
{
for (uint32_t x = 0; x < width; x++)
{
vec4F p(hdr_img(x, y));
p[0] = clamp(p[0], 0.0f, 1.0f);
p[1] = clamp(p[1], 0.0f, 1.0f);
p[2] = clamp(p[2], 0.0f, 1.0f);
int rc = (int)std::round(linear_to_srgb(p[0]) * 255.0f);
int gc = (int)std::round(linear_to_srgb(p[1]) * 255.0f);
int bc = (int)std::round(linear_to_srgb(p[2]) * 255.0f);
srgb_img.set_clipped(x, y, color_rgba(rc, gc, bc, 255));
}
}
{
const std::string filename(string_format("%s_linear_clamped_to_srgb.png", pBasename));
save_png(filename.c_str(), srgb_img);
printf("Wrote .PNG file %s\n", filename.c_str());
}
{
const std::string filename(string_format("%s_compressive_tonemapped.png", pBasename));
image compressive_tonemapped_img;
bool status = tonemap_image_compressive(compressive_tonemapped_img, hdr_img);
if (!status)
{
error_printf("tonemap_image_compressive() failed (invalid half-float input)\n");
}
else
{
save_png(filename.c_str(), compressive_tonemapped_img);
printf("Wrote .PNG file %s\n", filename.c_str());
}
}
image tonemapped_img;
for (int e = -5; e <= 5; e++)
{
const float scale = powf(2.0f, (float)e);
tonemap_image_reinhard(tonemapped_img, hdr_img, scale);
std::string filename(string_format("%s_reinhard_tonemapped_scale_%f.png", pBasename, scale));
save_png(filename.c_str(), tonemapped_img, cImageSaveIgnoreAlpha);
printf("Wrote .PNG file %s\n", filename.c_str());
}
return true;
}
//#include "encoder/3rdparty/android_astc_decomp.h"
//#include "encoder/basisu_pvrtc1_4.h"
static bool bench_mode(command_line_params& opts)
{
BASISU_NOTE_UNUSED(opts);
error_printf("Unsupported\n");
return false;
#if 0
#if 0
ispc::bc7e_compress_block_init();
ispc::bc7e_compress_block_params pack_params;
memset(&pack_params, 0, sizeof(pack_params));
ispc::bc7e_compress_block_params_init_slow(&pack_params, false);
#endif
const uint32_t JOB_POOL_SIZE = 7;
job_pool jpool(JOB_POOL_SIZE);
float total_uastc_psnr = 0, total_uastc_a_psnr = 0, total_uastc_rgba_psnr = 0;
float total_rdo_uastc_psnr = 0, total_rdo_uastc_a_psnr = 0, total_rdo_uastc_rgba_psnr = 0;
float total_uastc2_psnr = 0, total_uastc2_a_psnr = 0, total_uastc2_rgba_psnr = 0;
float total_bc7_psnr = 0, total_bc7_a_psnr = 0, total_bc7_rgba_psnr = 0;
float total_rdo_bc7_psnr = 0, total_rdo_bc7_a_psnr = 0, total_rdo_bc7_rgba_psnr = 0;
float total_obc1_psnr = 0;
float total_obc1_2_psnr = 0;
float total_obc1_psnr_sq = 0;
float total_obc1_2_psnr_sq = 0;
float total_bc1_psnr = 0;
float total_bc1_psnr_sq = 0;
//float total_obc7_psnr = 0, total_obc7_rgba_psnr = 0;
//float total_obc7_a_psnr = 0;
//float total_oastc_psnr = 0, total_oastc_rgba_psnr = 0;
float total_bc7enc_psnr = 0, total_bc7enc_rgba_psnr = 0, total_bc7enc_a_psnr = 0;
//float total_oastc_a_psnr = 0;
float total_etc1_psnr = 0;
float total_etc1_y_psnr = 0;
float total_etc1_g_psnr = 0;
float total_etc2_psnr = 0, total_etc2_rgba_psnr = 0;
float total_etc2_a_psnr = 0;
float total_bc3_psnr = 0, total_bc3_rgba_psnr = 0;
float total_bc3_a_psnr = 0;
float total_eac_r11_psnr = 0;
float total_eac_rg11_psnr = 0;
float total_pvrtc1_rgb_psnr = 0, total_pvrtc1_rgba_psnr = 0;
float total_pvrtc1_a_psnr = 0;
uint32_t total_images = 0;
uint32_t total_a_images = 0;
uint32_t total_pvrtc1_images = 0;
uint64_t overall_mode_hist[basist::TOTAL_UASTC_MODES];
memset(overall_mode_hist, 0, sizeof(overall_mode_hist));
std::mutex mode_hist_mutex;
uint32_t etc1_hint_hist[32];
memset(etc1_hint_hist, 0, sizeof(etc1_hint_hist));
srand(1023);
uint32_t first_image = 96;
uint32_t last_image = 96; //34
if (opts.m_input_filenames.size() >= 1)
{
first_image = 1;
last_image = 1;
}
const bool perceptual = false;
const bool force_la = false;
interval_timer otm;
otm.start();
//const uint32_t flags = cPackUASTCLevelFastest;// | cPackUASTCETC1DisableFlipAndIndividual;// Slower;
//const uint32_t flags = cPackUASTCLevelFaster;
//const uint32_t flags = cPackUASTCLevelVerySlow;
const uint32_t flags = cPackUASTCLevelDefault;
uint32_t etc1_inten_hist[8] = { 0,0,0,0,0,0,0,0 };
uint32_t etc1_flip_hist[2] = { 0, 0 };
uint32_t etc1_diff_hist[2] = { 0, 0 };
double overall_total_enc_time = 0;
double overall_total_bench_time = 0;
double overall_total_bench2_time = 0;
uint64_t overall_blocks = 0;
//bc7enc_compress_block_params bc7enc_p;
//bc7enc_compress_block_params_init(&bc7enc_p);
//bc7enc_compress_block_params_init_linear_weights(&bc7enc_p);
//bc7enc_p.m_uber_level = 3;
uint64_t total_comp_size = 0;
uint64_t total_raw_size = 0;
uint64_t total_rdo_comp_size = 0;
uint64_t total_rdo_raw_size = 0;
uint64_t total_comp_blocks = 0;
for (uint32_t image_index = first_image; image_index <= last_image; image_index++)
{
uint64_t mode_hist[basist::TOTAL_UASTC_MODES];
memset(mode_hist, 0, sizeof(mode_hist));
char buf[1024];
if (opts.m_input_filenames.size() >= 1)
strcpy(buf, opts.m_input_filenames[0].c_str());
else
sprintf(buf, "c:/dev/test_images/photo_png/kodim%02u.png", image_index);
printf("Image: %s\n", buf);
image img;
if (!load_image(buf, img))
return 0;
if (opts.m_input_filenames.size() == 2)
{
image alpha_img;
if (!load_image(opts.m_input_filenames[1].c_str(), alpha_img))
return 0;
printf("Alpha image: %s, %ux%u\n", opts.m_input_filenames[1].c_str(), alpha_img.get_width(), alpha_img.get_height());
for (uint32_t x = 0; x < alpha_img.get_width(); x++)
for (uint32_t y = 0; y < alpha_img.get_height(); y++)
{
if (x < img.get_width() && y < img.get_height())
img(x, y)[3] = (uint8_t)alpha_img(x, y).get_709_luma();
}
}
if (force_la)
{
for (uint32_t x = 0; x < img.get_width(); x++)
{
for (uint32_t y = 0; y < img.get_height(); y++)
{
const color_rgba& c = img(x, y);
img(x, y).set(c.r, c.r, c.r, c.g);
}
}
}
// HACK HACK
//if (!img.has_alpha())
// continue;
// HACK HACK
//img.crop(1024, 1024);
const uint32_t num_blocks_x = img.get_block_width(4);
const uint32_t num_blocks_y = img.get_block_height(4);
const uint32_t total_blocks = num_blocks_x * num_blocks_y;
const bool img_has_alpha = img.has_alpha();
img.crop_dup_borders(num_blocks_x * 4, num_blocks_y * 4);
printf("%ux%u, has alpha: %u\n", img.get_width(), img.get_height(), img_has_alpha);
image uastc_img(num_blocks_x * 4, num_blocks_y * 4);
image rdo_uastc_img(num_blocks_x * 4, num_blocks_y * 4);
image uastc2_img(num_blocks_x * 4, num_blocks_y * 4);
image opt_bc1_img(num_blocks_x * 4, num_blocks_y * 4);
image opt_bc1_2_img(num_blocks_x * 4, num_blocks_y * 4);
image bc1_img(num_blocks_x * 4, num_blocks_y * 4);
image bc3_img(num_blocks_x * 4, num_blocks_y * 4);
image eac_r11_img(num_blocks_x * 4, num_blocks_y * 4);
image eac_rg11_img(num_blocks_x * 4, num_blocks_y * 4);
image bc7_img(num_blocks_x * 4, num_blocks_y * 4);
image rdo_bc7_img(num_blocks_x * 4, num_blocks_y * 4);
image opt_bc7_img(num_blocks_x * 4, num_blocks_y * 4);
image etc1_img(num_blocks_x * 4, num_blocks_y * 4);
image etc1_g_img(num_blocks_x * 4, num_blocks_y * 4);
image etc2_img(num_blocks_x * 4, num_blocks_y * 4);
image part_img(num_blocks_x * 4, num_blocks_y * 4);
image opt_astc_img(num_blocks_x * 4, num_blocks_y * 4);
image bc7enc_img(num_blocks_x * 4, num_blocks_y * 4);
uint32_t total_bc1_hint0s = 0;
uint32_t total_bc1_hint1s = 0;
uint32_t total_bc1_hint01s = 0;
double total_enc_time = 0;
double total_bench_time = 0;
double total_bench2_time = 0;
basisu::vector<basist::uastc_block> ublocks(total_blocks);
#if 0
astc_enc_settings astc_settings;
//if (img_has_alpha)
GetProfile_astc_alpha_slow(&astc_settings, 4, 4);
//else
// GetProfile_astc_fast(&astc_settings, 4, 4);
#endif
#if 0
//#pragma omp parallel for
for (int by = 0; by < (int)num_blocks_y; by++)
{
// Process 64 blocks at a time, for efficient SIMD processing.
// Ideally, N >= 8 (or more) and (N % 8) == 0.
const int N = 64;
for (uint32_t bx = 0; bx < num_blocks_x; bx += N)
{
const uint32_t num_blocks_to_process = basisu::minimum<uint32_t>(num_blocks_x - bx, N);
color_rgba pixels[16 * N];
#if 0
// BC7E
// Extract num_blocks_to_process 4x4 pixel blocks from the source image and put them into the pixels[] array.
for (uint32_t b = 0; b < num_blocks_to_process; b++)
img.extract_block_clamped(pixels + b * 16, (bx + b) * 4, by * 4, 4, 4);
// Compress the blocks to BC7.
// Note: If you've used Intel's ispc_texcomp, the input pixels are different. BC7E requires a pointer to an array of 16 pixels for each block.
basist::bc7_block packed_blocks[N];
ispc::bc7e_compress_blocks(num_blocks_to_process, (uint64_t*)packed_blocks, reinterpret_cast<const uint32_t*>(pixels), &pack_params);
for (uint32_t i = 0; i < num_blocks_to_process; i++)
{
color_rgba decoded_block[4][4];
//detexDecompressBlockBPTC((uint8_t *)&packed_blocks[i], 0xFF, 0, (uint8_t *)&decoded_block[0][0]);
unpack_block(texture_format::cBC7, &packed_blocks[i], &decoded_block[0][0]);
opt_bc7_img.set_block_clipped(&decoded_block[0][0], (bx + i) * 4, by * 4, 4, 4);
}
#endif
#if 0
// ispc_texcomp
color_rgba raster_pixels[(N * 4) * 4];
const uint32_t raster_width = num_blocks_to_process * 4;
const uint32_t raster_height = 4;
rgba_surface surf;
surf.ptr = &raster_pixels[0].r;
surf.width = raster_width;
surf.height = 4;
surf.stride = raster_width * 4;
for (uint32_t b = 0; b < num_blocks_to_process; b++)
for (uint32_t y = 0; y < 4; y++)
for (uint32_t x = 0; x < 4; x++)
raster_pixels[y * raster_width + b * 4 + x] = pixels[b * 16 + y * 4 + x];
uint8_t astc_blocks[16 * N];
CompressBlocksASTC(&surf, astc_blocks, &astc_settings);
for (uint32_t i = 0; i < num_blocks_to_process; i++)
{
color_rgba decoded_astc_block[4][4];
basisu_astc::astc::decompress((uint8_t*)decoded_astc_block, (uint8_t*)&astc_blocks[i * 16], false, 4, 4);
opt_astc_img.set_block_clipped(&decoded_astc_block[0][0], (bx + i) * 4, by * 4, 4, 4);
}
#endif
}
}
#endif
const uint32_t N = 128;
for (uint32_t block_index_iter = 0; block_index_iter < total_blocks; block_index_iter += N)
{
const uint32_t first_index = block_index_iter;
const uint32_t last_index = minimum<uint32_t>(total_blocks, block_index_iter + N);
jpool.add_job([first_index, last_index, &img, num_blocks_x, num_blocks_y,
&opt_bc1_img, &opt_bc1_2_img, &mode_hist, &overall_mode_hist, &uastc_img, &uastc2_img, &bc7_img, &part_img, &mode_hist_mutex, &bc1_img, &etc1_img, &etc1_g_img, &etc2_img, &etc1_hint_hist, &perceptual,
&total_bc1_hint0s, &total_bc1_hint1s, &total_bc1_hint01s, &bc3_img, &total_enc_time, &eac_r11_img, &eac_rg11_img, &ublocks, &flags, &etc1_inten_hist, &etc1_flip_hist, &etc1_diff_hist, &total_bench_time, &total_bench2_time,
//&bc7enc_p, &bc7enc_img] {
&bc7enc_img] {
BASISU_NOTE_UNUSED(num_blocks_y);
BASISU_NOTE_UNUSED(perceptual);
BASISU_NOTE_UNUSED(flags);
for (uint32_t block_index = first_index; block_index < last_index; block_index++)
{
const uint32_t block_x = block_index % num_blocks_x;
const uint32_t block_y = block_index / num_blocks_x;
//uint32_t block_x = 170;
//uint32_t block_y = 167;
// HACK HACK
//if ((block_x == 77) && (block_y == 54))
// printf("!");
color_rgba block[4][4];
img.extract_block_clamped(&block[0][0], block_x * 4, block_y * 4, 4, 4);
uint8_t bc7_block[16];
//bc7enc_compress_block(bc7_block, block, &bc7enc_p);
color_rgba decoded_bc7enc_blk[4][4];
unpack_block(texture_format::cBC7, &bc7_block, &decoded_bc7enc_blk[0][0]);
bc7enc_img.set_block_clipped(&decoded_bc7enc_blk[0][0], block_x * 4, block_y * 4, 4, 4);
// Pack near-optimal BC1
// stb_dxt BC1 encoder
uint8_t bc1_block[8];
interval_timer btm;
btm.start();
//stb_compress_dxt_block(bc1_block, (uint8_t*)&block[0][0], 0, STB_DXT_HIGHQUAL);
basist::encode_bc1(bc1_block, (uint8_t*)&block[0][0], 0);// basist::cEncodeBC1HighQuality);
double total_b_time = btm.get_elapsed_secs();
{
std::lock_guard<std::mutex> lck(mode_hist_mutex);
total_bench_time += total_b_time;
}
color_rgba block_bc1[4][4];
unpack_block(texture_format::cBC1, bc1_block, &block_bc1[0][0]);
opt_bc1_img.set_block_clipped(&block_bc1[0][0], block_x * 4, block_y * 4, 4, 4);
//uint64_t e1 = 0;
//for (uint32_t i = 0; i < 16; i++)
// e1 += color_distance(((color_rgba*)block_bc1)[i], ((color_rgba*)block)[i], false);
// My BC1 encoder
uint8_t bc1_block_2[8];
color_rgba block_bc1_2[4][4];
btm.start();
basist::encode_bc1_alt(bc1_block_2, (uint8_t*)&block[0][0], basist::cEncodeBC1HighQuality);
double total_b2_time = btm.get_elapsed_secs();
{
std::lock_guard<std::mutex> lck(mode_hist_mutex);
total_bench2_time += total_b2_time;
}
unpack_block(texture_format::cBC1, bc1_block_2, &block_bc1_2[0][0]);
//uint64_t e2 = 0;
//for (uint32_t i = 0; i < 16; i++)
// e2 += color_distance(((color_rgba *)block_bc1_2)[i], ((color_rgba*)block)[i], false);
opt_bc1_2_img.set_block_clipped(&block_bc1_2[0][0], block_x * 4, block_y * 4, 4, 4);
// Encode to UASTC
basist::uastc_block encoded_uastc_blk;
interval_timer tm;
tm.start();
encode_uastc(&block[0][0].r, encoded_uastc_blk, flags);
double total_time = tm.get_elapsed_secs();
{
std::lock_guard<std::mutex> lck(mode_hist_mutex);
total_enc_time += total_time;
}
ublocks[block_x + block_y * num_blocks_x] = encoded_uastc_blk;
#if 0
for (uint32_t i = 0; i < 16; i++)
printf("0x%X,", encoded_uastc_blk.m_bytes[i]);
printf("\n");
#endif
// Unpack UASTC
basist::unpacked_uastc_block unpacked_uastc_blk;
unpack_uastc(encoded_uastc_blk, unpacked_uastc_blk, false);
color_rgba unpacked_uastc_block_pixels[4][4];
bool success = basist::unpack_uastc(unpacked_uastc_blk, (basist::color32*) & unpacked_uastc_block_pixels[0][0], false);
(void)success;
assert(success);
uastc_img.set_block_clipped(&unpacked_uastc_block_pixels[0][0], block_x * 4, block_y * 4, 4, 4);
const uint32_t best_mode = unpacked_uastc_blk.m_mode;
{
std::lock_guard<std::mutex> lck(mode_hist_mutex);
assert(best_mode < basist::TOTAL_UASTC_MODES);
if (best_mode < basist::TOTAL_UASTC_MODES)
{
mode_hist[best_mode]++;
overall_mode_hist[best_mode]++;
}
if (basist::g_uastc_mode_has_etc1_bias[best_mode])
etc1_hint_hist[unpacked_uastc_blk.m_etc1_bias]++;
total_bc1_hint0s += unpacked_uastc_blk.m_bc1_hint0;
total_bc1_hint1s += unpacked_uastc_blk.m_bc1_hint1;
total_bc1_hint01s += (unpacked_uastc_blk.m_bc1_hint0 || unpacked_uastc_blk.m_bc1_hint1);
etc1_inten_hist[unpacked_uastc_blk.m_etc1_inten0]++;
etc1_inten_hist[unpacked_uastc_blk.m_etc1_inten1]++;
etc1_flip_hist[unpacked_uastc_blk.m_etc1_flip]++;
etc1_diff_hist[unpacked_uastc_blk.m_etc1_diff]++;
}
// Transcode to BC1
color_rgba tblock_bc1[4][4];
uint8_t tbc1_block[8];
transcode_uastc_to_bc1(encoded_uastc_blk, tbc1_block, false);
unpack_block(texture_format::cBC1, tbc1_block, &tblock_bc1[0][0]);
bc1_img.set_block_clipped(&tblock_bc1[0][0], block_x * 4, block_y * 4, 4, 4);
// Transcode to BC7
basist::bc7_optimization_results best_bc7_results;
transcode_uastc_to_bc7(unpacked_uastc_blk, best_bc7_results);
{
basist::bc7_block bc7_data;
encode_bc7_block(&bc7_data, &best_bc7_results);
color_rgba decoded_bc7_blk[4][4];
unpack_block(texture_format::cBC7, &bc7_data, &decoded_bc7_blk[0][0]);
bc7_img.set_block_clipped(&decoded_bc7_blk[0][0], block_x * 4, block_y * 4, 4, 4);
// Compute partition visualization image
for (uint32_t y = 0; y < 4; y++)
{
for (uint32_t x = 0; x < 4; x++)
{
uint32_t part = 0;
switch (best_bc7_results.m_mode)
{
case 1:
case 3:
case 7:
part = basist::g_bc7_partition2[best_bc7_results.m_partition * 16 + x + y * 4];
break;
case 0:
case 2:
part = basist::g_bc7_partition3[best_bc7_results.m_partition * 16 + x + y * 4];
break;
}
color_rgba c(0, 255, 0, 255);
if (part == 1)
c.set(255, 0, 0, 255);
else if (part == 2)
c.set(0, 0, 255, 255);
part_img.set_clipped(block_x * 4 + x, block_y * 4 + y, c);
}
}
}
bool high_quality = false;
// Transcode UASTC->BC3
uint8_t ublock_bc3[16];
transcode_uastc_to_bc3(encoded_uastc_blk, ublock_bc3, high_quality);
color_rgba ublock_bc3_unpacked[4][4];
unpack_block(texture_format::cBC3, &ublock_bc3, &ublock_bc3_unpacked[0][0]);
bc3_img.set_block_clipped(&ublock_bc3_unpacked[0][0], block_x * 4, block_y * 4, 4, 4);
// Transcode UASTC->R11
uint8_t ublock_eac_r11[8];
transcode_uastc_to_etc2_eac_r11(encoded_uastc_blk, ublock_eac_r11, high_quality, 0);
color_rgba ublock_eac_r11_unpacked[4][4];
for (uint32_t y = 0; y < 4; y++)
for (uint32_t x = 0; x < 4; x++)
ublock_eac_r11_unpacked[y][x].set(0, 0, 0, 255);
unpack_block(texture_format::cETC2_R11_EAC, &ublock_eac_r11, &ublock_eac_r11_unpacked[0][0]);
eac_r11_img.set_block_clipped(&ublock_eac_r11_unpacked[0][0], block_x * 4, block_y * 4, 4, 4);
// Transcode UASTC->RG11
uint8_t ublock_eac_rg11[16];
transcode_uastc_to_etc2_eac_rg11(encoded_uastc_blk, ublock_eac_rg11, high_quality, 0, 1);
color_rgba ublock_eac_rg11_unpacked[4][4];
for (uint32_t y = 0; y < 4; y++)
for (uint32_t x = 0; x < 4; x++)
ublock_eac_rg11_unpacked[y][x].set(0, 0, 0, 255);
unpack_block(texture_format::cETC2_RG11_EAC, &ublock_eac_rg11, &ublock_eac_rg11_unpacked[0][0]);
eac_rg11_img.set_block_clipped(&ublock_eac_rg11_unpacked[0][0], block_x * 4, block_y * 4, 4, 4);
// ETC1
etc_block unpacked_etc1;
transcode_uastc_to_etc1(encoded_uastc_blk, &unpacked_etc1);
color_rgba unpacked_etc1_block[16];
unpack_etc1(unpacked_etc1, unpacked_etc1_block);
etc1_img.set_block_clipped(unpacked_etc1_block, block_x * 4, block_y * 4, 4, 4);
// ETC1 Y
etc_block unpacked_etc1_g;
transcode_uastc_to_etc1(encoded_uastc_blk, &unpacked_etc1_g, 1);
color_rgba unpacked_etc1_g_block[16];
unpack_etc1(unpacked_etc1_g, unpacked_etc1_g_block);
etc1_g_img.set_block_clipped(unpacked_etc1_g_block, block_x * 4, block_y * 4, 4, 4);
// ETC2
etc2_rgba_block unpacked_etc2;
transcode_uastc_to_etc2_rgba(encoded_uastc_blk, &unpacked_etc2);
color_rgba unpacked_etc2_block[16];
unpack_block(texture_format::cETC2_RGBA, &unpacked_etc2, unpacked_etc2_block);
etc2_img.set_block_clipped(unpacked_etc2_block, block_x * 4, block_y * 4, 4, 4);
// UASTC->ASTC
uint32_t tastc_data[4];
transcode_uastc_to_astc(encoded_uastc_blk, tastc_data);
color_rgba decoded_tastc_block[4][4];
clear_obj(decoded_tastc_block);
//basisu_astc::astc::decompress((uint8_t*)decoded_tastc_block, (uint8_t*)&tastc_data, false, 4, 4);
uastc2_img.set_block_clipped(&decoded_tastc_block[0][0], block_x * 4, block_y * 4, 4, 4);
for (uint32_t y = 0; y < 4; y++)
{
for (uint32_t x = 0; x < 4; x++)
{
if (decoded_tastc_block[y][x] != unpacked_uastc_block_pixels[y][x])
{
printf("UASTC!=ASTC!\n");
}
}
}
} // block_index
});
} // block_index_iter
jpool.wait_for_all();
{
size_t comp_size = 0;
void* pComp_data = tdefl_compress_mem_to_heap(&ublocks[0], ublocks.size() * 16, &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
size_t decomp_size;
void* pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, comp_size, &decomp_size, 0);
if ((decomp_size != ublocks.size() * 16) || (memcmp(pDecomp_data, &ublocks[0], decomp_size) != 0))
{
printf("Compression or decompression failed!\n");
exit(1);
}
mz_free(pComp_data);
mz_free(pDecomp_data);
printf("Pre-RDO UASTC size: %u, compressed size: %u, %3.2f bits/texel\n",
(uint32_t)ublocks.size() * 16,
(uint32_t)comp_size,
comp_size * 8.0f / img.get_total_pixels());
total_comp_size += comp_size;
total_raw_size += ublocks.size() * 16;
}
basisu::vector<color_rgba> orig_block_pixels(ublocks.size() * 16);
for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
img.extract_block_clamped(&orig_block_pixels[(block_x + block_y * num_blocks_x) * 16], block_x * 4, block_y * 4, 4, 4);
// HACK HACK
const uint32_t max_rdo_jobs = 4;
char rdo_fname[256];
FILE* pFile = nullptr;
for (uint32_t try_index = 0; try_index < 100; try_index++)
{
sprintf(rdo_fname, "rdo_%02u_%u.csv", image_index, try_index);
pFile = fopen(rdo_fname, "rb");
if (pFile)
{
fclose(pFile);
continue;
}
pFile = fopen(rdo_fname, "w");
if (!pFile)
printf("Cannot open CSV file %s\n", rdo_fname);
else
{
printf("Opened CSV file %s\n", rdo_fname);
break;
}
}
for (float q = .2f; q <= 10.0f; q += (q >= 1.0f ? .5f : .1f))
{
printf("Q: %f\n", q);
uastc_rdo_params p;
p.m_lambda = q;
p.m_max_allowed_rms_increase_ratio = 10.0f;
p.m_skip_block_rms_thresh = 8.0f;
bool rdo_status = uastc_rdo((uint32_t)ublocks.size(), &ublocks[0], &orig_block_pixels[0], p, flags, &jpool, max_rdo_jobs);
if (!rdo_status)
{
printf("uastc_rdo() failed!\n");
return false;
}
for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
{
for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
{
const basist::uastc_block& blk = ublocks[block_x + block_y * num_blocks_x];
color_rgba unpacked_block[4][4];
if (!basist::unpack_uastc(blk, (basist::color32*)unpacked_block, false))
{
printf("Block unpack failed!\n");
exit(1);
}
rdo_uastc_img.set_block_clipped(&unpacked_block[0][0], block_x * 4, block_y * 4, 4, 4);
basist::bc7_optimization_results best_bc7_results;
transcode_uastc_to_bc7(blk, best_bc7_results);
basist::bc7_block bc7_data;
encode_bc7_block(&bc7_data, &best_bc7_results);
color_rgba decoded_bc7_blk[4][4];
unpack_block(texture_format::cBC7, &bc7_data, &decoded_bc7_blk[0][0]);
rdo_bc7_img.set_block_clipped(&decoded_bc7_blk[0][0], block_x * 4, block_y * 4, 4, 4);
}
}
image_metrics em;
em.calc(img, rdo_uastc_img, 0, 3);
em.print("RDOUASTC RGB ");
size_t comp_size = 0;
void* pComp_data = tdefl_compress_mem_to_heap(&ublocks[0], ublocks.size() * 16, &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
size_t decomp_size;
void* pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, comp_size, &decomp_size, 0);
if ((decomp_size != ublocks.size() * 16) || (memcmp(pDecomp_data, &ublocks[0], decomp_size) != 0))
{
printf("Compression or decompression failed!\n");
exit(1);
}
mz_free(pComp_data);
mz_free(pDecomp_data);
printf("RDO UASTC size: %u, compressed size: %u, %3.2f bits/texel\n",
(uint32_t)ublocks.size() * 16,
(uint32_t)comp_size,
comp_size * 8.0f / img.get_total_pixels());
if (pFile)
fprintf(pFile, "%f, %f, %f\n", q, comp_size * 8.0f / img.get_total_pixels(), em.m_psnr);
}
if (pFile)
fclose(pFile);
{
size_t comp_size = 0;
void* pComp_data = tdefl_compress_mem_to_heap(&ublocks[0], ublocks.size() * 16, &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
size_t decomp_size;
void* pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, comp_size, &decomp_size, 0);
if ((decomp_size != ublocks.size() * 16) || (memcmp(pDecomp_data, &ublocks[0], decomp_size) != 0))
{
printf("Compression or decompression failed!\n");
exit(1);
}
mz_free(pComp_data);
mz_free(pDecomp_data);
printf("RDO UASTC size: %u, compressed size: %u, %3.2f bits/texel\n",
(uint32_t)ublocks.size() * 16,
(uint32_t)comp_size,
comp_size * 8.0f / img.get_total_pixels());
total_rdo_comp_size += comp_size;
total_rdo_raw_size += ublocks.size() * 16;
total_comp_blocks += ublocks.size();
}
printf("Total blocks: %u\n", total_blocks);
printf("Total BC1 hint 0's: %u %3.1f%%\n", total_bc1_hint0s, total_bc1_hint0s * 100.0f / total_blocks);
printf("Total BC1 hint 1's: %u %3.1f%%\n", total_bc1_hint1s, total_bc1_hint1s * 100.0f / total_blocks);
printf("Total BC1 hint 01's: %u %3.1f%%\n", total_bc1_hint01s, total_bc1_hint01s * 100.0f / total_blocks);
printf("Total enc time per block: %f us\n", total_enc_time / total_blocks * 1000000.0f);
printf("Total bench time per block: %f us\n", total_bench_time / total_blocks * 1000000.0f);
printf("Total bench2 time per block: %f us\n", total_bench2_time / total_blocks * 1000000.0f);
overall_total_enc_time += total_enc_time;
overall_total_bench_time += total_bench_time;
overall_total_bench2_time += total_bench2_time;
overall_blocks += total_blocks;
printf("ETC1 inten hist: %u %u %u %u %u %u %u %u\n", etc1_inten_hist[0], etc1_inten_hist[1], etc1_inten_hist[2], etc1_inten_hist[3],
etc1_inten_hist[4], etc1_inten_hist[5], etc1_inten_hist[6], etc1_inten_hist[7]);
printf("ETC1 flip hist: %u %u\n", etc1_flip_hist[0], etc1_flip_hist[1]);
printf("ETC1 diff hist: %u %u\n", etc1_diff_hist[0], etc1_diff_hist[1]);
printf("UASTC mode histogram:\n");
uint64_t total_hist = 0;
for (uint32_t i = 0; i < basist::TOTAL_UASTC_MODES; i++)
total_hist += mode_hist[i];
for (uint32_t i = 0; i < basist::TOTAL_UASTC_MODES; i++)
printf("%u: %u %3.2f%%\n", i, (uint32_t)mode_hist[i], mode_hist[i] * 100.0f / total_hist);
char fn[256];
#if 0
for (uint32_t y = 0; y < img.get_height(); y++)
for (uint32_t x = 0; x < img.get_width(); x++)
{
//static inline uint8_t to_5(uint32_t v) { ; }
color_rgba &c = img(x, y);
for (uint32_t i = 0; i < 3; i++)
{
const uint32_t limit = (i == 1) ? 63 : 31;
uint32_t v = c[i];
v = v * limit + 128; v = (uint8_t)((v + (v >> 8)) >> 8);
v = (v * 255 + (limit / 2)) / limit;
c[i] = (uint8_t)v;
}
}
#endif
sprintf(fn, "orig_%02u.png", image_index);
save_png(fn, img, cImageSaveIgnoreAlpha);
sprintf(fn, "orig_a_%02u.png", image_index);
save_png(fn, img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_uastc_%02u.png", image_index);
save_png(fn, uastc_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_uastc_a_%02u.png", image_index);
save_png(fn, uastc_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_rdo_uastc_%02u.png", image_index);
save_png(fn, rdo_uastc_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_rdo_uastc_a_%02u.png", image_index);
save_png(fn, rdo_uastc_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_uastc2_%02u.png", image_index);
save_png(fn, uastc2_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_bc7_%02u.png", image_index);
save_png(fn, bc7_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_bc7_a_%02u.png", image_index);
save_png(fn, bc7_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_rdo_bc7_%02u.png", image_index);
save_png(fn, rdo_bc7_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_rdo_bc7_a_%02u.png", image_index);
save_png(fn, rdo_bc7_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_opt_bc7_%02u.png", image_index);
save_png(fn, opt_bc7_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_opt_bc7_a_%02u.png", image_index);
save_png(fn, opt_bc7_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_opt_astc_%02u.png", image_index);
save_png(fn, opt_astc_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_opt_astc_a_%02u.png", image_index);
save_png(fn, opt_astc_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_bc7enc_%02u.png", image_index);
save_png(fn, bc7enc_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_bc7enc_a_%02u.png", image_index);
save_png(fn, bc7enc_img, cImageSaveGrayscale, 3);
sprintf(fn, "unpacked_opt_bc1_%02u.png", image_index);
save_png(fn, opt_bc1_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_opt_bc1_2_%02u.png", image_index);
save_png(fn, opt_bc1_2_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_tbc1_%02u.png", image_index);
save_png(fn, bc1_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_bc3_%02u.png", image_index);
save_png(fn, bc3_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_eac_r11_%02u.png", image_index);
save_png(fn, eac_r11_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_eac_rg11_%02u.png", image_index);
save_png(fn, eac_rg11_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_bc3_a_%02u.png", image_index);
save_png(fn, bc3_img, cImageSaveGrayscale, 3);
sprintf(fn, "part_vis_%02u.png", image_index);
save_png(fn, part_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_etc1_%02u.png", image_index);
save_png(fn, etc1_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_etc1_g_%02u.png", image_index);
save_png(fn, etc1_g_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_etc2_%02u.png", image_index);
save_png(fn, etc2_img, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_etc2_a_%02u.png", image_index);
save_png(fn, etc2_img, cImageSaveGrayscale, 3);
image_metrics em;
// UASTC
em.calc(img, uastc_img, 0, 3);
em.print("UASTC RGB ");
total_uastc_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, uastc_img, 3, 1);
em.print("UASTC A ");
if (img_has_alpha)
total_uastc_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, uastc_img, 0, 4);
em.print("UASTC RGBA ");
total_uastc_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// RDO UASTC
em.calc(img, rdo_uastc_img, 0, 3);
em.print("RDOUASTC RGB ");
total_rdo_uastc_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, rdo_uastc_img, 3, 1);
em.print("RDOUASTC A ");
if (img_has_alpha)
total_rdo_uastc_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, rdo_uastc_img, 0, 4);
em.print("RDOUASTC RGBA ");
total_rdo_uastc_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// UASTC2
em.calc(img, uastc2_img, 0, 3);
em.print("UASTC2 RGB ");
total_uastc2_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, uastc2_img, 3, 1);
em.print("UASTC2 A ");
if (img_has_alpha)
total_uastc2_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, uastc2_img, 0, 4);
em.print("UASTC2 RGBA ");
total_uastc2_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// BC7
em.calc(img, bc7_img, 0, 3);
em.print("BC7 RGB ");
total_bc7_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc7_img, 3, 1);
em.print("BC7 A ");
if (img_has_alpha)
total_bc7_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc7_img, 0, 4);
em.print("BC7 RGBA ");
total_bc7_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// RDO BC7
em.calc(img, rdo_bc7_img, 0, 3);
em.print("RDOBC7 RGB ");
total_rdo_bc7_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, rdo_bc7_img, 3, 1);
em.print("RDOBC7 A ");
if (img_has_alpha)
total_rdo_bc7_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, rdo_bc7_img, 0, 4);
em.print("RDOBC7 RGBA ");
total_rdo_bc7_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
#if 0
// OBC7
em.calc(img, opt_bc7_img, 0, 3);
em.print("OBC7 RGB ");
total_obc7_psnr += basisu::minimum(99.0f, em.m_psnr);
em.calc(img, opt_bc7_img, 3, 1);
em.print("OBC7 A ");
if (img_has_alpha)
total_obc7_a_psnr += basisu::minimum(99.0f, em.m_psnr);
em.calc(img, opt_bc7_img, 0, 4);
em.print("OBC7 RGBA ");
total_obc7_rgba_psnr += basisu::minimum(99.0f, em.m_psnr);
// OASTC
em.calc(img, opt_astc_img, 0, 3);
em.print("OASTC RGB ");
total_oastc_psnr += basisu::minimum(99.0f, em.m_psnr);
em.calc(img, opt_astc_img, 3, 1);
em.print("OASTC A ");
if (img_has_alpha)
total_oastc_a_psnr += basisu::minimum(99.0f, em.m_psnr);
em.calc(img, opt_astc_img, 0, 4);
em.print("OASTC RGBA ");
total_oastc_rgba_psnr += basisu::minimum(99.0f, em.m_psnr);
#endif
// bc7enc
em.calc(img, bc7enc_img, 0, 3);
em.print("BC7ENC RGB ");
total_bc7enc_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc7enc_img, 3, 1);
em.print("BC7ENC A ");
if (img_has_alpha)
total_bc7enc_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc7enc_img, 0, 4);
em.print("BC7ENC RGBA ");
total_bc7enc_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
#if 1
// OBC1
em.calc(img, opt_bc1_img, 0, 3);
em.print("OBC1 RGB ");
total_obc1_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
total_obc1_psnr_sq += (float)(basisu::minimum<double>(99.0f, em.m_psnr) * basisu::minimum<double>(99.0f, em.m_psnr));
#endif
em.calc(img, opt_bc1_2_img, 0, 3);
em.print("OBC1 2 RGB ");
total_obc1_2_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
total_obc1_2_psnr_sq += (float)(basisu::minimum<double>(99.0f, em.m_psnr) * basisu::minimum<double>(99.0f, em.m_psnr));
em.calc(img, bc1_img, 0, 3);
em.print("BC1 RGB ");
total_bc1_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
total_bc1_psnr_sq += (float)(basisu::minimum<double>(99.0f, em.m_psnr) * basisu::minimum<double>(99.0f, em.m_psnr));
// ETC1
em.calc(img, etc1_img, 0, 3);
em.print("ETC1 RGB ");
total_etc1_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, etc1_img, 0, 0);
em.print("ETC1 Y ");
total_etc1_y_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// ETC1
em.calc(img, etc1_g_img, 1, 1);
em.print("ETC1 G ");
total_etc1_g_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// ETC2
em.calc(img, etc2_img, 0, 3);
em.print("ETC2 RGB ");
total_etc2_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, etc2_img, 3, 1);
em.print("ETC2 A ");
if (img_has_alpha)
total_etc2_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, etc2_img, 0, 4);
em.print("ETC2 RGBA ");
total_etc2_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// BC3
em.calc(img, bc3_img, 0, 3);
em.print("BC3 RGB ");
total_bc3_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc3_img, 3, 1);
em.print("BC3 A ");
if (img_has_alpha)
total_bc3_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, bc3_img, 0, 4);
em.print("BC3 RGBA ");
total_bc3_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// EAC R11
em.calc(img, eac_r11_img, 0, 1);
em.print("EAC R11 ");
total_eac_r11_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
// EAC RG11
em.calc(img, eac_rg11_img, 0, 2);
em.print("EAC RG11 ");
total_eac_rg11_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
const uint32_t width = num_blocks_x * 4;
const uint32_t height = num_blocks_y * 4;
if (is_pow2(width) && is_pow2(height))
{
pvrtc4_image pi(width, height);
transcode_uastc_to_pvrtc1_4_rgba(&ublocks[0], pi.get_blocks().get_ptr(), num_blocks_x, num_blocks_y, false);
pi.deswizzle();
//pi.map_all_pixels(img, perceptual, false);
image pi_unpacked;
pi.unpack_all_pixels(pi_unpacked);
#if 0
sprintf(fn, "unpacked_pvrtc1_rgb_before_%02u.png", image_index);
save_png(fn, pi_unpacked, cImageSaveIgnoreAlpha);
em.calc(img, pi_unpacked, 0, 3);
em.print("PVRTC1 RGB Before ");
for (uint32_t pass = 0; pass < 1; pass++)
{
for (uint32_t by = 0; by < num_blocks_y; by++)
{
for (uint32_t bx = 0; bx < num_blocks_x; bx++)
{
pi.local_endpoint_optimization_opaque(bx, by, img, perceptual, false);
}
}
}
//pi.map_all_pixels(img, perceptual, false);
pi.unpack_all_pixels(pi_unpacked);
#endif
sprintf(fn, "unpacked_pvrtc1_%02u.png", image_index);
save_png(fn, pi_unpacked, cImageSaveIgnoreAlpha);
sprintf(fn, "unpacked_pvrtc1_a_%02u.png", image_index);
save_png(fn, pi_unpacked, cImageSaveGrayscale, 3);
em.calc(img, pi_unpacked, 0, 3);
em.print("PVRTC1 After RGB ");
total_pvrtc1_rgb_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, pi_unpacked, 3, 1);
em.print("PVRTC1 After A ");
total_pvrtc1_a_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
em.calc(img, pi_unpacked, 0, 4);
em.print("PVRTC1 After RGBA ");
total_pvrtc1_rgba_psnr += (float)basisu::minimum<double>(99.0f, em.m_psnr);
total_pvrtc1_images++;
}
printf("ETC1 hint histogram:\n");
for (uint32_t i = 0; i < 32; i++)
printf("%u ", etc1_hint_hist[i]);
printf("\n");
total_images++;
if (img_has_alpha)
total_a_images++;
} // image_index
printf("Total time: %f secs\n", otm.get_elapsed_secs());
printf("Total Non-RDO UASTC size: %llu, compressed size: %llu, %3.2f bits/texel\n",
(unsigned long long)total_raw_size,
(unsigned long long)total_comp_size,
total_comp_size * 8.0f / (total_comp_blocks * 16));
printf("Total RDO UASTC size: %llu, compressed size: %llu, %3.2f bits/texel\n",
(unsigned long long)total_rdo_raw_size,
(unsigned long long)total_rdo_comp_size,
total_rdo_comp_size * 8.0f / (total_comp_blocks * 16));
printf("Overall enc time per block: %f us\n", overall_total_enc_time / overall_blocks * 1000000.0f);
printf("Overall bench time per block: %f us\n", overall_total_bench_time / overall_blocks * 1000000.0f);
printf("Overall bench2 time per block: %f us\n", overall_total_bench2_time / overall_blocks * 1000000.0f);
printf("Overall ASTC mode histogram:\n");
uint64_t total_hist = 0;
for (uint32_t i = 0; i < basist::TOTAL_UASTC_MODES; i++)
total_hist += overall_mode_hist[i];
for (uint32_t i = 0; i < basist::TOTAL_UASTC_MODES; i++)
printf("%u: %u %3.2f%%\n", i, (uint32_t)overall_mode_hist[i], overall_mode_hist[i] * 100.0f / total_hist);
printf("Total images: %u, total images with alpha: %u, total PVRTC1 images: %u\n", total_images, total_a_images, total_pvrtc1_images);
if (!total_a_images)
total_a_images = 1;
printf("Avg UASTC RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_uastc_psnr / total_images, total_uastc_a_psnr / total_a_images, total_uastc_rgba_psnr / total_images);
printf("Avg UASTC2 RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_uastc2_psnr / total_images, total_uastc2_a_psnr / total_a_images, total_uastc2_rgba_psnr / total_images);
printf("Avg RDO UASTC RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_rdo_uastc_psnr / total_images, total_rdo_uastc_a_psnr / total_a_images, total_rdo_uastc_rgba_psnr / total_images);
printf("Avg BC7 RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_bc7_psnr / total_images, total_bc7_a_psnr / total_a_images, total_bc7_rgba_psnr / total_images);
printf("Avg RDO BC7 RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_rdo_bc7_psnr / total_images, total_rdo_bc7_a_psnr / total_a_images, total_rdo_bc7_rgba_psnr / total_images);
//printf("Avg Opt BC7 RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_obc7_psnr / total_images, total_obc7_a_psnr / total_a_images, total_obc7_rgba_psnr / total_images);
//printf("Avg Opt ASTC RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_oastc_psnr / total_images, total_oastc_a_psnr / total_a_images, total_oastc_rgba_psnr / total_images);
printf("Avg BC7ENC RGB PSNR: %f, A PSNR: %f, RGBA PSNR: %f\n", total_bc7enc_psnr / total_images, total_bc7enc_a_psnr / total_a_images, total_bc7enc_rgba_psnr / total_images);
printf("Avg Opt BC1 PSNR: %f, std dev: %f\n", total_obc1_psnr / total_images, sqrtf(basisu::maximum(0.0f, (total_obc1_psnr_sq / total_images) - (total_obc1_psnr / total_images) * (total_obc1_psnr / total_images))));
printf("Avg Opt BC1 2 PSNR: %f, std dev: %f\n", total_obc1_2_psnr / total_images, sqrtf(basisu::maximum(0.0f, (total_obc1_2_psnr_sq / total_images) - (total_obc1_2_psnr / total_images) * (total_obc1_2_psnr / total_images))));
printf("Avg BC1 PSNR: %f, std dev: %f\n", total_bc1_psnr / total_images, sqrtf(basisu::maximum(0.0f, (total_bc1_psnr_sq / total_images) - (total_bc1_psnr / total_images) * (total_bc1_psnr / total_images))));
printf("Avg ETC1 RGB PSNR: %f\n", total_etc1_psnr / total_images);
printf("Avg ETC1 Y PSNR: %f\n", total_etc1_y_psnr / total_images);
printf("Avg ETC1 G PSNR: %f\n", total_etc1_g_psnr / total_images);
printf("Avg ETC2 RGB PSNR: %f\n", total_etc2_psnr / total_images);
printf("Avg ETC2 A PSNR: %f\n", total_etc2_a_psnr / total_a_images);
printf("Avg ETC2 RGBA PSNR: %f\n", total_etc2_rgba_psnr / total_images);
printf("Avg BC3 RGB PSNR: %f\n", total_bc3_psnr / total_images);
printf("Avg BC3 A PSNR: %f\n", total_bc3_a_psnr / total_a_images);
printf("Avg BC3 RGBA PSNR: %f\n", total_bc3_rgba_psnr / total_images);
printf("Avg EAC R11 PSNR: %f\n", total_eac_r11_psnr / total_images);
printf("Avg EAC RG11 PSNR: %f\n", total_eac_rg11_psnr / total_images);
if (total_pvrtc1_images)
{
printf("Avg PVRTC1 RGB PSNR: %f\n", total_pvrtc1_rgb_psnr / total_pvrtc1_images);
printf("Avg PVRTC1 A PSNR: %f\n", total_pvrtc1_a_psnr / total_pvrtc1_images);
printf("Avg PVRTC1 RGBA PSNR: %f\n", total_pvrtc1_rgba_psnr / total_pvrtc1_images);
}
return true;
#endif
}
static uint32_t compute_miniz_compressed_size(const char* pFilename, uint32_t &orig_size)
{
orig_size = 0;
uint8_vec buf;
if (!read_file_to_vec(pFilename, buf))
return 0;
if (!buf.size())
return 0;
orig_size = buf.size();
size_t comp_size = 0;
void* pComp_data = tdefl_compress_mem_to_heap(&buf[0], buf.size(), &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
mz_free(pComp_data);
return (uint32_t)comp_size;
}
static bool compsize_mode(command_line_params& opts)
{
if (opts.m_input_filenames.size() != 1)
{
error_printf("Must specify a filename using -file\n");
return false;
}
uint32_t orig_size;
uint32_t comp_size = compute_miniz_compressed_size(opts.m_input_filenames[0].c_str(), orig_size);
printf("Original file size: %u bytes\n", orig_size);
printf("miniz compressed size: %u bytes\n", comp_size);
return true;
}
const struct test_file
{
const char* m_pFilename;
uint32_t m_etc1s_size;
float m_etc1s_psnr;
float m_uastc_psnr;
uint32_t m_etc1s_128_size;
float m_etc1s_128_psnr;
} g_test_files[] =
{
{ "black_1x1.png", 189, 100.0f, 100.0f, 189, 100.0f },
{ "kodim01.png", 30993, 27.40f, 44.14f, 58354, 30.356064f },
{ "kodim02.png", 28529, 32.20f, 41.06f, 51411, 34.713940f },
{ "kodim03.png", 23411, 32.57f, 44.87f, 49282, 36.709675f },
{ "kodim04.png", 28256, 31.76f, 43.02f, 57003, 34.864861f },
{ "kodim05.png", 32646, 25.94f, 40.28f, 65731, 29.935091f },
{ "kodim06.png", 27336, 28.66f, 44.57f, 54963, 32.294220f },
{ "kodim07.png", 26618, 31.51f, 43.94f, 53352, 35.576595f },
{ "kodim08.png", 31133, 25.28f, 41.15f, 63347, 29.509914f },
{ "kodim09.png", 24777, 32.05f, 45.85f, 51355, 35.985966f },
{ "kodim10.png", 27247, 32.20f, 45.77f, 54291, 36.395000f },
{ "kodim11.png", 26579, 29.22f, 43.68f, 55491, 33.468971f },
{ "kodim12.png", 25102, 32.96f, 46.77f, 51465, 36.722233f },
{ "kodim13.png", 31604, 24.25f, 41.25f, 62629, 27.588623f },
{ "kodim14.png", 31162, 27.81f, 39.65f, 62866, 31.206463f },
{ "kodim15.png", 25528, 31.26f, 42.87f, 53343, 35.026314f },
{ "kodim16.png", 26894, 32.21f, 47.78f, 51325, 35.555458f },
{ "kodim17.png", 29334, 31.40f, 45.66f, 55630, 35.909283f },
{ "kodim18.png", 30929, 27.46f, 41.54f, 62421, 31.348171f },
{ "kodim19.png", 27889, 29.69f, 44.95f, 55055, 33.613987f },
{ "kodim20.png", 21104, 31.30f, 45.31f, 47136, 35.759407f },
{ "kodim21.png", 25943, 28.53f, 44.45f, 54768, 32.415817f },
{ "kodim22.png", 29277, 29.85f, 42.63f, 60889, 33.495415f },
{ "kodim23.png", 23550, 31.69f, 45.11f, 53774, 36.223492f },
{ "kodim24.png", 29613, 26.75f, 40.61f, 59014, 31.522869f },
{ "white_1x1.png", 189, 100.0f, 100.0f, 189, 100.000000f },
{ "wikipedia.png", 38961, 24.10f, 30.47f, 69558, 27.630802f },
{ "alpha0.png", 766, 100.0f, 56.16f, 747, 100.000000f }
};
const uint32_t TOTAL_TEST_FILES = sizeof(g_test_files) / sizeof(g_test_files[0]);
static bool test_mode_ldr(command_line_params& opts)
{
uint32_t total_mismatches = 0;
// TODO: Record min/max/avgs
// TODO: Add another ETC1S quality level
// Minor differences in how floating point code is optimized can result in slightly different generated files.
#ifdef USE_TIGHTER_TEST_TOLERANCES
const float ETC1S_PSNR_THRESHOLD = .125f;
const float UASTC_PSNR_THRESHOLD = .125f;
#else
const float ETC1S_PSNR_THRESHOLD = .3f;
const float UASTC_PSNR_THRESHOLD = .3f;
#endif
const float ETC1S_FILESIZE_THRESHOLD = .045f;
for (uint32_t i = 0; i < TOTAL_TEST_FILES; i++)
{
std::string filename(opts.m_test_file_dir);
if (filename.size())
{
filename.push_back('/');
}
filename += std::string(g_test_files[i].m_pFilename);
basisu::vector<image> source_images(1);
image& source_image = source_images[0];
if (!load_png(filename.c_str(), source_image))
{
error_printf("Failed loading test image \"%s\"\n", filename.c_str());
return false;
}
printf("Loaded file \"%s\", dimemsions %ux%u has alpha: %u\n", filename.c_str(), source_image.get_width(), source_image.get_height(), source_image.has_alpha());
image_stats stats;
uint32_t flags_and_quality;
float uastc_rdo_quality = 0.0f;
size_t data_size = 0;
// Test ETC1S
flags_and_quality = (opts.m_comp_params.m_multithreading ? cFlagThreaded : 0) | cFlagPrintStats | cFlagPrintStatus;
{
printf("**** Testing ETC1S non-OpenCL level 1\n");
// Level 1
void* pData = basis_compress(source_images, flags_and_quality, uastc_rdo_quality, &data_size, &stats);
if (!pData)
{
error_printf("basis_compress() failed!\n");
return false;
}
basis_free_data(pData);
printf("ETC1S level 1 Size: %u, PSNR: %f\n", (uint32_t)data_size, stats.m_basis_rgba_avg_psnr);
float file_size_ratio = fabs((data_size / (float)g_test_files[i].m_etc1s_size) - 1.0f);
if (file_size_ratio > ETC1S_FILESIZE_THRESHOLD)
{
error_printf("Expected ETC1S file size was %u, but got %u instead!\n", g_test_files[i].m_etc1s_size, (uint32_t)data_size);
total_mismatches++;
}
if (fabs(stats.m_basis_rgba_avg_psnr - g_test_files[i].m_etc1s_psnr) > ETC1S_PSNR_THRESHOLD)
{
error_printf("Expected ETC1S RGBA Avg PSNR was %f, but got %f instead!\n", g_test_files[i].m_etc1s_psnr, stats.m_basis_rgba_avg_psnr);
total_mismatches++;
}
}
{
printf("**** Testing ETC1S non-OpenCL level 128\n");
// Test ETC1S level 128
flags_and_quality |= 128;
void* pData = basis_compress(source_images, flags_and_quality, uastc_rdo_quality, &data_size, &stats);
if (!pData)
{
error_printf("basis_compress() failed!\n");
return false;
}
basis_free_data(pData);
printf("ETC1S level 128 Size: %u, PSNR: %f\n", (uint32_t)data_size, stats.m_basis_rgba_avg_psnr);
float file_size_ratio = fabs((data_size / (float)g_test_files[i].m_etc1s_128_size) - 1.0f);
if (file_size_ratio > ETC1S_FILESIZE_THRESHOLD)
{
error_printf("Expected ETC1S file size was %u, but got %u instead!\n", g_test_files[i].m_etc1s_128_size, (uint32_t)data_size);
total_mismatches++;
}
if (fabs(stats.m_basis_rgba_avg_psnr - g_test_files[i].m_etc1s_128_psnr) > ETC1S_PSNR_THRESHOLD)
{
error_printf("Expected ETC1S RGBA Avg PSNR was %f, but got %f instead!\n", g_test_files[i].m_etc1s_128_psnr, stats.m_basis_rgba_avg_psnr);
total_mismatches++;
}
}
if (opencl_is_available())
{
printf("**** Testing ETC1S OpenCL level 1\n");
// Test ETC1S OpenCL level 1
flags_and_quality = (opts.m_comp_params.m_multithreading ? cFlagThreaded : 0) | cFlagUseOpenCL | cFlagPrintStats | cFlagPrintStatus;
void *pData = basis_compress(source_images, flags_and_quality, uastc_rdo_quality, &data_size, &stats);
if (!pData)
{
error_printf("basis_compress() failed!\n");
return false;
}
basis_free_data(pData);
printf("ETC1S+OpenCL Size: %u, PSNR: %f\n", (uint32_t)data_size, stats.m_basis_rgba_avg_psnr);
float file_size_ratio = fabs((data_size / (float)g_test_files[i].m_etc1s_size) - 1.0f);
if (file_size_ratio > .04f)
{
error_printf("Expected ETC1S+OpenCL file size was %u, but got %u instead!\n", g_test_files[i].m_etc1s_size, (uint32_t)data_size);
total_mismatches++;
}
if (g_test_files[i].m_etc1s_psnr == 100.0f)
{
// TODO
if (stats.m_basis_rgba_avg_psnr < 69.0f)
{
error_printf("Expected ETC1S+OpenCL RGBA Avg PSNR was %f, but got %f instead!\n", g_test_files[i].m_etc1s_psnr, stats.m_basis_rgba_avg_psnr);
total_mismatches++;
}
}
else if (fabs(stats.m_basis_rgba_avg_psnr - g_test_files[i].m_etc1s_psnr) > .2f)
{
error_printf("Expected ETC1S+OpenCL RGBA Avg PSNR was %f, but got %f instead!\n", g_test_files[i].m_etc1s_psnr, stats.m_basis_rgba_avg_psnr);
total_mismatches++;
}
}
// Test UASTC
{
printf("**** Testing UASTC\n");
flags_and_quality = (opts.m_comp_params.m_multithreading ? cFlagThreaded : 0) | cFlagUASTC | cFlagPrintStats | cFlagPrintStatus;
void* pData = basis_compress(source_images, flags_and_quality, uastc_rdo_quality, &data_size, &stats);
if (!pData)
{
error_printf("basis_compress() failed!\n");
return false;
}
basis_free_data(pData);
printf("UASTC Size: %u, PSNR: %f\n", (uint32_t)data_size, stats.m_basis_rgba_avg_psnr);
if (fabs(stats.m_basis_rgba_avg_psnr - g_test_files[i].m_uastc_psnr) > UASTC_PSNR_THRESHOLD)
{
error_printf("Expected UASTC RGBA Avg PSNR was %f, but got %f instead!\n", g_test_files[i].m_etc1s_psnr, stats.m_basis_rgba_avg_psnr);
total_mismatches++;
}
}
}
printf("Total LDR mismatches: %u\n", total_mismatches);
bool result = true;
if (total_mismatches)
{
error_printf("LDR test FAILED\n");
result = false;
}
else
{
printf("LDR test succeeded\n");
}
return result;
}
const struct hdr_test_file
{
const char* m_pFilename;
float m_level_psnr_astc[5];
float m_level_psnr_bc6h[5];
} g_hdr_test_files[] =
{
{ "black_1x1.png", { 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f }, { 1000.0f, 1000.0f, 1000.0f, 1000.0f, 1000.0f } },
{ "atrium.exr", { 58.387924f, 58.976650f, 59.000862f, 58.951488f, 58.898571f }, { 58.103821f, 58.900017f, 58.910744f, 58.876980f, 58.810989f } },
{ "backyard.exr", { 63.704613f, 63.453190f, 63.600426f, 63.626850f, 63.938366f }, { 62.911961f, 63.353348f, 63.501392f, 63.533562f, 63.823147f } },
{ "Desk.exr", { 50.020317f, 50.580063f, 50.937798f, 51.024494f, 51.315540f }, { 49.944633f, 50.565235f, 50.914314f, 50.999512f, 51.293797f } },
{ "atrium.exr", { 58.387924f, 58.976650f, 59.000862f, 58.951488f, 58.898571f }, { 58.103821f, 58.900017f, 58.910744f, 58.876980f, 58.810989f } },
{ "yucca.exr", { 53.481602f, 53.905769f, 53.954353f, 54.074474f, 54.139977f }, { 53.437008f, 53.883400f, 53.929897f, 54.050571f, 54.117466f } },
{ "tough.png", { 39.680382f, 43.291210f, 43.637939f, 44.180916f, 46.030712f }, { 39.703949f, 43.255989f, 43.590729f, 44.132393f, 46.033344f } },
{ "kodim03.png", { 51.031773f, 51.275902f, 51.300705f, 51.338562f, 51.355114f }, { 50.982365f, 51.251923f, 51.275295f, 51.315796f, 51.332462f } },
{ "kodim18.png", { 48.362595f, 48.638092f, 48.610493f, 48.618176f, 48.520008f }, { 48.319820f, 48.635593f, 48.609116f, 48.621853f, 48.520535f } },
{ "kodim23.png", { 49.796471f, 50.144829f, 50.171085f, 50.325180f, 50.366810f }, { 49.779743f, 50.119869f, 50.147041f, 50.299568f, 50.341846f } }
};
const uint32_t TOTAL_HDR_TEST_FILES = sizeof(g_hdr_test_files) / sizeof(g_hdr_test_files[0]);
static bool test_mode_hdr(command_line_params& opts)
{
BASISU_ASSUME(astc_hdr_codec_options::cMaxLevel == 4);
uint32_t total_mismatches = 0;
#ifdef USE_TIGHTER_TEST_TOLERANCES
// The PSNR's above were created with a MSVC compiled executable, x64. Hopefully this is not too low a threshold.
const float PSNR_THRESHOLD = .125f;
#else
// Minor differences in how floating point code is optimized can result in slightly different generated files.
const float PSNR_THRESHOLD = .3f;
#endif
double highest_delta = 0.0f;
for (uint32_t i = 0; i < TOTAL_HDR_TEST_FILES; i++)
{
std::string filename(opts.m_test_file_dir);
if (filename.size())
{
filename.push_back('/');
}
filename += std::string(g_hdr_test_files[i].m_pFilename);
basisu::vector<imagef> source_imagesf(1);
imagef& source_image = source_imagesf[0];
if (!load_image_hdr(filename.c_str(), source_image))
{
error_printf("Failed loading test image \"%s\"\n", filename.c_str());
return false;
}
printf("Loaded file \"%s\", dimemsions %ux%u\n", filename.c_str(), source_image.get_width(), source_image.get_height());
for (uint32_t uastc_hdr_level = 0; uastc_hdr_level <= 4; uastc_hdr_level++)
{
image_stats stats;
uint32_t flags_and_quality;
size_t data_size = 0;
printf("**** Testing UASTC HDR Level %u\n", uastc_hdr_level);
flags_and_quality = (opts.m_comp_params.m_multithreading ? cFlagThreaded : 0) | cFlagUASTC;// | cFlagPrintStats | cFlagPrintStatus;
flags_and_quality |= cFlagHDRLDRImageSRGBToLinearConversion;
flags_and_quality |= uastc_hdr_level;
void* pData = basis_compress(source_imagesf, flags_and_quality, &data_size, &stats);
if (!pData)
{
error_printf("basis_compress() failed!\n");
return false;
}
basis_free_data(pData);
double delta1, delta2;
printf("ASTC PSNR: %f (expected %f, delta %f), BC6H PSNR: %f (expected %f, delta %f)\n",
stats.m_basis_rgb_avg_psnr, g_hdr_test_files[i].m_level_psnr_astc[uastc_hdr_level], delta1 = fabs(stats.m_basis_rgb_avg_psnr - g_hdr_test_files[i].m_level_psnr_astc[uastc_hdr_level]),
stats.m_basis_rgb_avg_bc6h_psnr, g_hdr_test_files[i].m_level_psnr_bc6h[uastc_hdr_level], delta2 = fabs(stats.m_basis_rgb_avg_bc6h_psnr - g_hdr_test_files[i].m_level_psnr_bc6h[uastc_hdr_level]));
highest_delta = maximum(highest_delta, delta1);
highest_delta = maximum(highest_delta, delta2);
if (fabs(stats.m_basis_rgb_avg_psnr - g_hdr_test_files[i].m_level_psnr_astc[uastc_hdr_level]) > PSNR_THRESHOLD)
{
error_printf("Expected UASTC HDR RGB Avg PSNR was %f, but got %f instead!\n", g_hdr_test_files[i].m_level_psnr_astc[uastc_hdr_level], stats.m_basis_rgb_avg_psnr);
total_mismatches++;
}
if (fabs(stats.m_basis_rgb_avg_bc6h_psnr - g_hdr_test_files[i].m_level_psnr_bc6h[uastc_hdr_level]) > PSNR_THRESHOLD)
{
error_printf("Expected UASTC->BC6H HDR RGB Avg PSNR was %f, but got %f instead!\n", g_hdr_test_files[i].m_level_psnr_bc6h[uastc_hdr_level], stats.m_basis_rgb_avg_bc6h_psnr);
total_mismatches++;
}
}
}
printf("Total HDR mismatches: %u\n", total_mismatches);
printf("Highest delta: %f\n", highest_delta);
bool result = true;
if (total_mismatches)
{
error_printf("HDR test FAILED\n");
result = false;
}
else
{
printf("HDR test succeeded\n");
}
return result;
}
static bool clbench_mode(command_line_params& opts)
{
BASISU_NOTE_UNUSED(opts);
bool opencl_failed = false;
bool use_cl = basis_benchmark_etc1s_opencl(&opencl_failed);
if (use_cl)
printf("OpenCL ETC1S encoding is faster on this machine\n");
else
{
if (opencl_failed)
printf("OpenCL failed!\n");
printf("CPU ETC1S encoding is faster on this machine\n");
}
return true;
}
#ifdef FORCE_SAN_FAILURE
static void force_san_failure()
{
// Purposely do things that should trigger the address sanitizer
int arr[5] = { 0, 1, 2, 3, 4 };
printf("Out of bounds element: %d\n", arr[10]);
//uint8_t* p = (uint8_t *)malloc(10);
//p[10] = 99;
//uint8_t* p = (uint8_t *)malloc(10);
//free(p);
//p[0] = 99;
}
#endif // FORCE_SAN_FAILURE
static int main_internal(int argc, const char **argv)
{
printf("Basis Universal LDR/HDR GPU Texture Compression and Transcoding System v" BASISU_TOOL_VERSION "\nCopyright (C) 2019-2024 Binomial LLC, All rights reserved\n");
#ifdef FORCE_SAN_FAILURE
force_san_failure();
#endif
//interval_timer tm;
//tm.start();
// See if OpenCL support has been disabled. We don't want to parse the command line until the lib is initialized
bool use_opencl = false;
bool opencl_force_serialization = false;
for (int i = 1; i < argc; i++)
{
if ((strcmp(argv[i], "-opencl") == 0) || (strcmp(argv[i], "-clbench") == 0))
use_opencl = true;
if (strcmp(argv[i], "-opencl_serialize") == 0)
opencl_force_serialization = true;
}
#ifndef BASISU_SUPPORT_OPENCL
if (use_opencl)
{
fprintf(stderr, "WARNING: -opencl specified, but OpenCL support was not enabled at compile time! With cmake, use -D OPENCL=1. Falling back to CPU compression.\n");
}
#endif
basisu_encoder_init(use_opencl, opencl_force_serialization);
//printf("Encoder and transcoder libraries initialized in %3.3f ms\n", tm.get_elapsed_ms());
if (argc == 1)
{
print_usage();
return EXIT_FAILURE;
}
command_line_params opts;
if (!opts.parse(argc, argv))
{
//print_usage();
return EXIT_FAILURE;
}
#if BASISU_SUPPORT_SSE
printf("Using SSE 4.1: %u, Multithreading: %u, Zstandard support: %u, OpenCL: %u\n", g_cpu_supports_sse41, (uint32_t)opts.m_comp_params.m_multithreading, basist::basisu_transcoder_supports_ktx2_zstd(), opencl_is_available());
#else
printf("No SSE, Multithreading: %u, Zstandard support: %u, OpenCL: %u\n", (uint32_t)opts.m_comp_params.m_multithreading, basist::basisu_transcoder_supports_ktx2_zstd(), opencl_is_available());
#endif
if (!opts.process_listing_files())
return EXIT_FAILURE;
if (opts.m_mode == cDefault)
{
for (size_t i = 0; i < opts.m_input_filenames.size(); i++)
{
std::string ext(string_get_extension(opts.m_input_filenames[i]));
if ((strcasecmp(ext.c_str(), "basis") == 0) || (strcasecmp(ext.c_str(), "ktx") == 0) || (strcasecmp(ext.c_str(), "ktx2") == 0))
{
// If they haven't specified any modes, and they give us a .basis file, then assume they want to unpack it.
opts.m_mode = cUnpack;
break;
}
}
}
bool status = false;
switch (opts.m_mode)
{
case cDefault:
case cCompress:
status = compress_mode(opts);
break;
case cValidate:
case cInfo:
case cUnpack:
status = unpack_and_validate_mode(opts);
break;
case cCompare:
status = compare_mode(opts);
break;
case cHDRCompare:
status = hdr_compare_mode(opts);
break;
case cVersion:
status = true; // We printed the version at the beginning of main_internal
break;
case cBench:
status = bench_mode(opts);
break;
case cCompSize:
status = compsize_mode(opts);
break;
case cTestLDR:
status = test_mode_ldr(opts);
break;
case cTestHDR:
status = test_mode_hdr(opts);
break;
case cCLBench:
status = clbench_mode(opts);
break;
case cSplitImage:
status = split_image_mode(opts);
break;
case cCombineImages:
status = combine_images_mode(opts);
break;
case cTonemapImage:
status = tonemap_image_mode(opts);
break;
default:
assert(0);
break;
}
return status ? EXIT_SUCCESS : EXIT_FAILURE;
}
int main(int argc, const char** argv)
{
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
#if defined(DEBUG) || defined(_DEBUG)
printf("DEBUG build\n");
#endif
#ifdef __SANITIZE_ADDRESS__
printf("Address sanitizer enabled\n");
#endif
int status = EXIT_FAILURE;
#if BASISU_CATCH_EXCEPTIONS
try
{
status = main_internal(argc, argv);
}
catch (const std::exception &exc)
{
fprintf(stderr, "Fatal error: Caught exception \"%s\"\n", exc.what());
}
catch (...)
{
fprintf(stderr, "Fatal error: Uncaught exception!\n");
}
#else
status = main_internal(argc, argv);
#endif
return status;
}
|