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 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424
|
/* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of
* the image data through additional options listed below
*
* Original code:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* Additions (c) Richard Nolde 2006-2010
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
* HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
* ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*
* Some portions of the current code are derived from tiffcp, primarily in
* the areas of lowlevel reading and writing of TAGS, scanlines and tiles though
* some of the original functions have been extended to support arbitrary bit
* depths. These functions are presented at the top of this file.
*
* Add support for the options below to extract sections of image(s)
* and to modify the whole image or selected portions of each image by
* rotations, mirroring, and colorscale/colormap inversion of selected
* types of TIFF images when appropriate. Some color model dependent
* functions are restricted to bilevel or 8 bit per sample data.
* See the man page for the full explanations.
*
* New Options:
* -h Display the syntax guide.
* -v Report the version and last build date for tiffcrop and libtiff.
* -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1
* Specify a series of coordinates to define rectangular
* regions by the top left and lower right corners.
* -e c|d|i|m|s export mode for images and selections from input images
* combined All images and selections are written to a single file (default)
* with multiple selections from one image combined into a single image
* divided All images and selections are written to a single file
* with each selection from one image written to a new image
* image Each input image is written to a new file (numeric filename sequence)
* with multiple selections from the image combined into one image
* multiple Each input image is written to a new file (numeric filename sequence)
* with each selection from the image written to a new image
* separated Individual selections from each image are written to separate files
* -U units [in, cm, px ] inches, centimeters or pixels
* -H # Set horizontal resolution of output images to #
* -V # Set vertical resolution of output images to #
* -J # Horizontal margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -K # Vertical margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -X # Horizontal dimension of region to extract expressed in current
* units
* -Y # Vertical dimension of region to extract expressed in current
* units
* -O orient Orientation for output image, portrait, landscape, auto
* -P page Page size for output image segments, eg letter, legal, tabloid,
* etc.
* -S cols:rows Divide the image into equal sized segments using cols across
* and rows down
* -E t|l|r|b Edge to use as origin
* -m #,#,#,# Margins from edges for selection: top, left, bottom, right
* (commas separated)
* -Z #:#,#:# Zones of the image designated as zone X of Y,
* eg 1:3 would be first of three equal portions measured
* from reference edge
* -N odd|even|#,#-#,#|last
* Select sequences and/or ranges of images within file
* to process. The words odd or even may be used to specify
* all odd or even numbered images the word last may be used
* in place of a number in the sequence to indicate the final
* image in the file without knowing how many images there are.
* -R # Rotate image or crop selection by 90,180,or 270 degrees
* clockwise
* -F h|v Flip (mirror) image or crop selection horizontally
* or vertically
* -I [black|white|data|both]
* Invert color space, eg dark to light for bilevel and grayscale images
* If argument is white or black, set the PHOTOMETRIC_INTERPRETATION
* tag to MinIsBlack or MinIsWhite without altering the image data
* If the argument is data or both, the image data are modified:
* both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,
* data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag
* -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N
* Dump raw data for input and/or output images to individual files
* in raw (binary) format or text (ASCII) representing binary data
* as strings of 1s and 0s. The filename arguments are used as stems
* from which individual files are created for each image. Text format
* includes annotations for image parameters and scanline info. Level
* selects which functions dump data, with higher numbers selecting
* lower level, scanline level routines. Debug reports a limited set
* of messages to monitor progess without enabling dump logs.
*/
static char tiffcrop_version_id[] = "2.4.1";
static char tiffcrop_rev_date[] = "03-03-2010";
#include "tif_config.h"
#include "tiffiop.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
# include <inttypes.h>
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif
#ifndef HAVE_GETOPT
extern int getopt(int argc, char * const argv[], const char *optstring);
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffio.h"
#if defined(VMS)
# define unlink delete
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#define TIFF_UINT32_MAX 0xFFFFFFFFU
#define TRUE 1
#define FALSE 0
#ifndef TIFFhowmany
#define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y)))
#define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
#endif
/*
* Definitions and data structures required to support cropping and image
* manipulations.
*/
#define EDGE_TOP 1
#define EDGE_LEFT 2
#define EDGE_BOTTOM 3
#define EDGE_RIGHT 4
#define EDGE_CENTER 5
#define MIRROR_HORIZ 1
#define MIRROR_VERT 2
#define MIRROR_BOTH 3
#define ROTATECW_90 8
#define ROTATECW_180 16
#define ROTATECW_270 32
#define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270)
#define CROP_NONE 0
#define CROP_MARGINS 1
#define CROP_WIDTH 2
#define CROP_LENGTH 4
#define CROP_ZONES 8
#define CROP_REGIONS 16
#define CROP_ROTATE 32
#define CROP_MIRROR 64
#define CROP_INVERT 128
/* Modes for writing out images and selections */
#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
#define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */
#define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */
#define FILE_PER_SELECTION 4 /* One file per selection */
#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
#define STRIP 1
#define TILE 2
#define MAX_REGIONS 8 /* number of regions to extract from a single page */
#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
#define MAX_SECTIONS 32 /* number of sections per page to write to output */
#define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */
#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
#define DUMP_NONE 0
#define DUMP_TEXT 1
#define DUMP_RAW 2
#define TIFF_DIR_MAX 65534
/* Some conversion subroutines require image buffers, which are at least 3 bytes
* larger than the necessary size for the image itself. */
#define NUM_BUFF_OVERSIZE_BYTES 3
/* Offsets into buffer for margins and fixed width and length segments */
struct offset {
uint32 tmargin;
uint32 lmargin;
uint32 bmargin;
uint32 rmargin;
uint32 crop_width;
uint32 crop_length;
uint32 startx;
uint32 endx;
uint32 starty;
uint32 endy;
};
/* Description of a zone within the image. Position 1 of 3 zones would be
* the first third of the image. These are computed after margins and
* width/length requests are applied so that you can extract multiple
* zones from within a larger region for OCR or barcode recognition.
*/
struct buffinfo {
size_t size; /* size of this buffer */
unsigned char *buffer; /* address of the allocated buffer */
};
struct zone {
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
};
struct pageseg {
uint32 x1; /* index of left edge */
uint32 x2; /* index of right edge */
uint32 y1; /* index of top edge */
uint32 y2; /* index of bottom edge */
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
uint32 buffsize; /* size of buffer needed to hold the cropped zone */
};
struct coordpairs {
double X1; /* index of left edge in current units */
double X2; /* index of right edge in current units */
double Y1; /* index of top edge in current units */
double Y2; /* index of bottom edge in current units */
};
struct region {
uint32 x1; /* pixel offset of left edge */
uint32 x2; /* pixel offset of right edge */
uint32 y1; /* pixel offset of top edge */
uint32 y2; /* picel offset of bottom edge */
uint32 width; /* width in pixels */
uint32 length; /* length in pixels */
uint32 buffsize; /* size of buffer needed to hold the cropped region */
};
/* Cropping parameters from command line and image data
* Note: This should be renamed to proc_opts and expanded to include all current globals
* if possible, but each function that accesses global variables will have to be redone.
*/
struct crop_mask {
double width; /* Selection width for master crop region in requested units */
double length; /* Selection length for master crop region in requesed units */
double margins[4]; /* Top, left, bottom, right margins */
float xres; /* Horizontal resolution read from image*/
float yres; /* Vertical resolution read from image */
uint32 combined_width; /* Width of combined cropped zones */
uint32 combined_length; /* Length of combined cropped zones */
uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */
uint16 img_mode; /* Composite or separate images created from zones or regions */
uint16 exp_mode; /* Export input images or selections to one or more files */
uint16 crop_mode; /* Crop options to be applied */
uint16 res_unit; /* Resolution unit for margins and selections */
uint16 edge_ref; /* Reference edge for sections extraction and combination */
uint16 rotation; /* Clockwise rotation of the extracted region or image */
uint16 mirror; /* Mirror extracted region or image horizontally or vertically */
uint16 invert; /* Invert the color map of image or region */
uint16 photometric; /* Status of photometric interpretation for inverted image */
uint16 selections; /* Number of regions or zones selected */
uint16 regions; /* Number of regions delimited by corner coordinates */
struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
uint16 zones; /* Number of zones delimited by Ordinal:Total requested */
struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */
};
#define MAX_PAPERNAMES 49
#define MAX_PAPERNAME_LENGTH 15
#define DEFAULT_RESUNIT RESUNIT_INCH
#define DEFAULT_PAGE_HEIGHT 14.0
#define DEFAULT_PAGE_WIDTH 8.5
#define DEFAULT_RESOLUTION 300
#define DEFAULT_PAPER_SIZE "legal"
#define ORIENTATION_NONE 0
#define ORIENTATION_PORTRAIT 1
#define ORIENTATION_LANDSCAPE 2
#define ORIENTATION_SEASCAPE 4
#define ORIENTATION_AUTO 16
#define PAGE_MODE_NONE 0
#define PAGE_MODE_RESOLUTION 1
#define PAGE_MODE_PAPERSIZE 2
#define PAGE_MODE_MARGINS 4
#define PAGE_MODE_ROWSCOLS 8
#define INVERT_DATA_ONLY 10
#define INVERT_DATA_AND_TAG 11
struct paperdef {
char name[MAX_PAPERNAME_LENGTH];
double width;
double length;
double asratio;
};
/* European page sizes corrected from update sent by
* thomas . jarosch @ intra2net . com on 5/7/2010
* Paper Size Width Length Aspect Ratio */
const struct paperdef PaperTable[MAX_PAPERNAMES] = {
{"default", 8.500, 14.000, 0.607},
{"pa4", 8.264, 11.000, 0.751},
{"letter", 8.500, 11.000, 0.773},
{"legal", 8.500, 14.000, 0.607},
{"half-letter", 8.500, 5.514, 1.542},
{"executive", 7.264, 10.528, 0.690},
{"tabloid", 11.000, 17.000, 0.647},
{"11x17", 11.000, 17.000, 0.647},
{"ledger", 17.000, 11.000, 1.545},
{"archa", 9.000, 12.000, 0.750},
{"archb", 12.000, 18.000, 0.667},
{"archc", 18.000, 24.000, 0.750},
{"archd", 24.000, 36.000, 0.667},
{"arche", 36.000, 48.000, 0.750},
{"csheet", 17.000, 22.000, 0.773},
{"dsheet", 22.000, 34.000, 0.647},
{"esheet", 34.000, 44.000, 0.773},
{"superb", 11.708, 17.042, 0.687},
{"commercial", 4.139, 9.528, 0.434},
{"monarch", 3.889, 7.528, 0.517},
{"envelope-dl", 4.333, 8.681, 0.499},
{"envelope-c5", 6.389, 9.028, 0.708},
{"europostcard", 4.139, 5.833, 0.710},
{"a0", 33.110, 46.811, 0.707},
{"a1", 23.386, 33.110, 0.706},
{"a2", 16.535, 23.386, 0.707},
{"a3", 11.693, 16.535, 0.707},
{"a4", 8.268, 11.693, 0.707},
{"a5", 5.827, 8.268, 0.705},
{"a6", 4.134, 5.827, 0.709},
{"a7", 2.913, 4.134, 0.705},
{"a8", 2.047, 2.913, 0.703},
{"a9", 1.457, 2.047, 0.712},
{"a10", 1.024, 1.457, 0.703},
{"b0", 39.370, 55.669, 0.707},
{"b1", 27.835, 39.370, 0.707},
{"b2", 19.685, 27.835, 0.707},
{"b3", 13.898, 19.685, 0.706},
{"b4", 9.843, 13.898, 0.708},
{"b5", 6.929, 9.843, 0.704},
{"b6", 4.921, 6.929, 0.710},
{"c0", 36.102, 51.063, 0.707},
{"c1", 25.512, 36.102, 0.707},
{"c2", 18.031, 25.512, 0.707},
{"c3", 12.756, 18.031, 0.707},
{"c4", 9.016, 12.756, 0.707},
{"c5", 6.378, 9.016, 0.707},
{"c6", 4.488, 6.378, 0.704},
{"", 0.000, 0.000, 1.000}
};
/* Structure to define input image parameters */
struct image_data {
float xres;
float yres;
uint32 width;
uint32 length;
uint16 res_unit;
uint16 bps;
uint16 spp;
uint16 planar;
uint16 photometric;
uint16 orientation;
uint16 compression;
uint16 adjustments;
};
/* Structure to define the output image modifiers */
struct pagedef {
char name[16];
double width; /* width in pixels */
double length; /* length in pixels */
double hmargin; /* margins to subtract from width of sections */
double vmargin; /* margins to subtract from height of sections */
double hres; /* horizontal resolution for output */
double vres; /* vertical resolution for output */
uint32 mode; /* bitmask of modifiers to page format */
uint16 res_unit; /* resolution unit for output image */
unsigned int rows; /* number of section rows */
unsigned int cols; /* number of section cols */
unsigned int orient; /* portrait, landscape, seascape, auto */
};
struct dump_opts {
int debug;
int format;
int level;
char mode[4];
char infilename[PATH_MAX + 1];
char outfilename[PATH_MAX + 1];
FILE *infile;
FILE *outfile;
};
/* globals */
static int outtiled = -1;
static uint32 tilewidth = 0;
static uint32 tilelength = 0;
static uint16 config = 0;
static uint16 compression = 0;
static uint16 predictor = 0;
static uint16 fillorder = 0;
static uint32 rowsperstrip = 0;
static uint32 g3opts = 0;
static int ignore = FALSE; /* if true, ignore read errors */
static uint32 defg3opts = (uint32) -1;
static int quality = 100; /* JPEG quality */
/* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */
static int jpegcolormode = JPEGCOLORMODE_RGB;
static uint16 defcompression = (uint16) -1;
static uint16 defpredictor = (uint16) -1;
static int pageNum = 0;
static int little_endian = 1;
/* Functions adapted from tiffcp with additions or significant modifications */
static int readContigStripsIntoBuffer (TIFF*, uint8*);
static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int writeBufferToContigStrips (TIFF*, uint8*, uint32);
static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t,
uint16, uint16, struct dump_opts *);
static int processCompressOptions(char*);
static void usage(int code);
/* All other functions by Richard Nolde, not found in tiffcp */
static void initImageData (struct image_data *);
static void initCropMasks (struct crop_mask *);
static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []);
static void initDumpOptions(struct dump_opts *);
/* Command line and file naming functions */
void process_command_opts (int, char *[], char *, char *, uint32 *,
uint16 *, uint16 *, uint32 *, uint32 *, uint32 *,
struct crop_mask *, struct pagedef *,
struct dump_opts *,
unsigned int *, unsigned int *);
static int update_output_file (TIFF **, char *, int, char *, unsigned int *);
/* * High level functions for whole image manipulation */
static int get_page_geometry (char *, struct pagedef*);
static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
struct offset *);
static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *);
static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **);
static int correct_orientation(struct image_data *, unsigned char **);
static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *);
static int processCropSelections(struct image_data *, struct crop_mask *,
unsigned char **, struct buffinfo []);
static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *,
struct dump_opts *, struct buffinfo [],
char *, char *, unsigned int*, unsigned int);
/* Section functions */
static int createImageSection(uint32, unsigned char **);
static int extractImageSection(struct image_data *, struct pageseg *,
unsigned char *, unsigned char *);
static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
struct dump_opts *, uint32, uint32,
double, double, unsigned char *);
static int writeImageSections(TIFF *, TIFF *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *, unsigned char *,
unsigned char **);
/* Whole image functions */
static int createCroppedImage(struct image_data *, struct crop_mask *,
unsigned char **, unsigned char **);
static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
struct dump_opts * dump,
uint32, uint32, unsigned char *, int, int);
/* Image manipulation functions */
static int rotateContigSamples8bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples16bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples24bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples32bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *,
unsigned char **, int);
static int mirrorImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
static int invertImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
/* Functions to reverse the sequence of samples in a scanline */
static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *);
/* Functions for manipulating individual samples in an image */
static int extractSeparateRegion(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *, int);
static int extractCompositeRegions(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *);
static int extractContigSamples8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesBytes (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32,
uint32, uint32, tsample_t, uint16,
uint16, uint16, struct dump_opts *);
/* Functions to combine separate planes into interleaved planes */
static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, tsample_t, uint16,
FILE *, int, int);
static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, uint32, uint32,
tsample_t, uint16, FILE *, int, int);
/* Dump functions for debugging */
static void dump_info (FILE *, int, char *, char *, ...);
static int dump_data (FILE *, int, char *, unsigned char *, uint32);
static int dump_byte (FILE *, int, char *, unsigned char);
static int dump_short (FILE *, int, char *, uint16);
static int dump_long (FILE *, int, char *, uint32);
static int dump_wide (FILE *, int, char *, uint64);
static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *);
/* End function declarations */
/* Functions derived in whole or in part from tiffcp */
/* The following functions are taken largely intact from tiffcp */
#define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
/* malloc size limit (in bytes)
* disabled when set to 0 */
static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
/**
* This custom malloc function enforce a maximum allocation size
*/
static void* limitMalloc(tmsize_t s)
{
if (maxMalloc && (s > maxMalloc)) {
fprintf(stderr, "MemoryLimitError: allocation of " TIFF_UINT64_FORMAT " bytes is forbidden. Limit is " TIFF_UINT64_FORMAT ".\n",
(uint64)s, (uint64)maxMalloc);
fprintf(stderr, " use -k option to change limit.\n"); return NULL;
}
return _TIFFmalloc(s);
}
static const char* usage_info[] = {
"usage: tiffcrop [options] source1 ... sourceN destination",
"where options are:",
" -h Print this syntax listing",
" -v Print tiffcrop version identifier and last revision date",
" ",
" -a Append to output instead of overwriting",
" -d offset Set initial directory offset, counting first image as one, not zero",
" -p contig Pack samples contiguously (e.g. RGBRGB...)",
" -p separate Store samples separately (e.g. RRR...GGG...BBB...)",
" -s Write output in strips",
" -t Write output in tiles",
" -i Ignore read errors",
" -k size set the memory allocation limit in MiB. 0 to disable limit",
" ",
" -r # Make each strip have no more than # rows",
" -w # Set output tile width (pixels)",
" -l # Set output tile length (pixels)",
" ",
" -f lsb2msb Force lsb-to-msb FillOrder for output",
" -f msb2lsb Force msb-to-lsb FillOrder for output",
"",
" -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] Compress output with deflate encoding",
" -c jpeg[:opts] Compress output with JPEG encoding",
" -c packbits Compress output with packbits encoding",
" -c g3[:opts] Compress output with CCITT Group 3 encoding",
" -c g4 Compress output with CCITT Group 4 encoding",
" -c none Use no compression algorithm on output",
" ",
"Group 3 options:",
" 1d Use default CCITT Group 3 1D-encoding",
" 2d Use optional CCITT Group 3 2D-encoding",
" fill Byte-align EOL codes",
"For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs",
" ",
"JPEG options:",
" # Set compression quality level (0-100, default 100)",
" raw Output color image as raw YCbCr",
" rgb Output color image as RGB",
"For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality",
" ",
"LZW and deflate options:",
" # Set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" ",
"Page and selection options:",
" -N odd|even|#,#-#,#|last sequences and ranges of images within file to process",
" The words odd or even may be used to specify all odd or even numbered images.",
" The word last may be used in place of a number in the sequence to indicate.",
" The final image in the file without knowing how many images there are.",
" Numbers are counted from one even though TIFF IFDs are counted from zero.",
" ",
" -E t|l|r|b edge to use as origin for width and length of crop region",
" -U units [in, cm, px ] inches, centimeters or pixels",
" ",
" -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas",
" -X # horizontal dimension of region to extract expressed in current units",
" -Y # vertical dimension of region to extract expressed in current units",
" -Z #:#,#:# zones of the image designated as position X of Y,",
" eg 1:3 would be first of three equal portions measured from reference edge",
" -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1",
" regions of the image designated by upper left and lower right coordinates",
"",
"Export grouping options:",
" -e c|d|i|m|s export mode for images and selections from input images.",
" When exporting a composite image from multiple zones or regions",
" (combined and image modes), the selections must have equal sizes",
" for the axis perpendicular to the edge specified with -E.",
" c|combined All images and selections are written to a single file (default).",
" with multiple selections from one image combined into a single image.",
" d|divided All images and selections are written to a single file",
" with each selection from one image written to a new image.",
" i|image Each input image is written to a new file (numeric filename sequence)",
" with multiple selections from the image combined into one image.",
" m|multiple Each input image is written to a new file (numeric filename sequence)",
" with each selection from the image written to a new image.",
" s|separated Individual selections from each image are written to separate files.",
"",
"Output options:",
" -H # Set horizontal resolution of output images to #",
" -V # Set vertical resolution of output images to #",
" -J # Set horizontal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" -K # Set verticalal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" ",
" -O orient orientation for output image, portrait, landscape, auto",
" -P page page size for output image segments, eg letter, legal, tabloid, etc",
" use #.#x#.# to specify a custom page size in the currently defined units",
" where #.# represents the width and length",
" -S cols:rows Divide the image into equal sized segments using cols across and rows down.",
" ",
" -F hor|vert|both",
" flip (mirror) image or region horizontally, vertically, or both",
" -R # [90,180,or 270] degrees clockwise rotation of image or extracted region",
" -I [black|white|data|both]",
" invert color space, eg dark to light for bilevel and grayscale images",
" If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ",
" tag to MinIsBlack or MinIsWhite without altering the image data",
" If the argument is data or both, the image data are modified:",
" both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,",
" data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag",
" ",
"-D opt1:value1,opt2:value2,opt3:value3:opt4:value4",
" Debug/dump program progress and/or data to non-TIFF files.",
" Options include the following and must be joined as a comma",
" separate list. The use of this option is generally limited to",
" program debugging and development of future options.",
" ",
" debug:N Display limited program progress indicators where larger N",
" increase the level of detail. Note: Tiffcrop may be compiled with",
" -DDEVELMODE to enable additional very low level debug reporting.",
"",
" Format:txt|raw Format any logged data as ASCII text or raw binary ",
" values. ASCII text dumps include strings of ones and zeroes",
" representing the binary values in the image data plus identifying headers.",
" ",
" level:N Specify the level of detail presented in the dump files.",
" This can vary from dumps of the entire input or output image data to dumps",
" of data processed by specific functions. Current range of levels is 1 to 3.",
" ",
" input:full-path-to-directory/input-dumpname",
" ",
" output:full-path-to-directory/output-dumpnaem",
" ",
" When dump files are being written, each image will be written to a separate",
" file with the name built by adding a numeric sequence value to the dumpname",
" and an extension of .txt for ASCII dumps or .bin for binary dumps.",
" ",
" The four debug/dump options are independent, though it makes little sense to",
" specify a dump file without specifying a detail level.",
"Note 1: The (-X|-Y), -Z, -z and -S options are mutually exclusive.\n"
" In no case should the options be applied to a given selection successively.\n"
"\n"
"Note 2: Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x options\n"
" such as - H, -V, -P, -J or -K are not supported and may cause buffer overflows.\n"
"\n"
" ",
NULL
};
/* This function could be modified to pass starting sample offset
* and number of samples as args to select fewer than spp
* from input image. These would then be passed to individual
* extractContigSampleXX routines.
*/
static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
tmsize_t tile_rowsize = TIFFTileRowSize(in);
tmsize_t src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(EXIT_FAILURE);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(EXIT_FAILURE);
}
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if( (size_t) tile_buffsize > 0xFFFFFFFFU - 3U )
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(EXIT_FAILURE);
}
tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
if (tilebuf == 0)
return 0;
tilebuf[tile_buffsize] = 0;
tilebuf[tile_buffsize+1] = 0;
tilebuf[tile_buffsize+2] = 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
}
static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf,
uint32 imagelength, uint32 imagewidth,
uint32 tw, uint32 tl,
uint16 spp, uint16 bps)
{
int i, status = 1, sample;
int shift_width, bytes_per_pixel;
uint16 bytes_per_sample;
uint32 row, col; /* Current row and col of image */
uint32 nrow, ncol; /* Number of rows and cols in current tile */
uint32 row_offset, col_offset; /* Output buffer offsets */
tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
tsample_t s;
uint8* bufp = (uint8*)obuf;
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *tbuff = NULL;
bytes_per_sample = (bps + 7) / 8;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
srcbuffs[sample] = NULL;
tbuff = (unsigned char *)limitMalloc(tilesize + NUM_BUFF_OVERSIZE_BYTES);
if (!tbuff)
{
TIFFError ("readSeparateTilesIntoBuffer",
"Unable to allocate tile read buffer for sample %d", sample);
for (i = 0; i < sample; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[sample] = tbuff;
}
/* Each tile contains only the data for a single plane
* arranged in scanlines of tw * bytes_per_sample bytes.
*/
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
for (s = 0; s < spp && s < MAX_SAMPLES; s++)
{ /* Read each plane of a tile set into srcbuffs[s] */
tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
if (tbytes < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile for row %lu col %lu, "
"sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
status = 0;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
}
/* Tiles on the right edge may be padded out to tw
* which must be a multiple of 16.
* Ncol represents the visible (non padding) portion.
*/
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
col_offset = ((col * spp * bps) + 7) / 8;
bufp = obuf + row_offset + col_offset;
if ((bps % 8) == 0)
{
if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth,
tw, spp, bps, NULL, 0, 0))
{
status = 0;
break;
}
}
else
{
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (shift_width)
{
case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps);
status = 0;
break;
}
}
}
}
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength)
{
uint32 row, nrows, rowsperstrip;
tstrip_t strip = 0;
tsize_t stripsize;
TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip)
{
nrows = (row + rowsperstrip > imagelength) ?
imagelength - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
return 1;
}
buf += stripsize;
}
return 0;
}
/* Abandon plans to modify code so that plannar orientation separate images
* do not have all samples for each channel written before all samples
* for the next channel have been abandoned.
* Libtiff internals seem to depend on all data for a given sample
* being contiguous within a strip or tile when PLANAR_CONFIG is
* separate. All strips or tiles of a given plane are written
* before any strips or tiles of a different plane are stored.
*/
static int
writeBufferToSeparateStrips (TIFF* out, uint8* buf,
uint32 length, uint32 width, uint16 spp,
struct dump_opts *dump)
{
uint8 *src;
uint16 bps;
uint32 row, nrows, rowsize, rowsperstrip;
uint32 bytes_per_sample;
tsample_t s;
tstrip_t strip = 0;
tsize_t stripsize = TIFFStripSize(out);
tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
tsize_t total_bytes = 0;
tdata_t obuf;
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
(void) TIFFGetFieldDefaulted(out, TIFFTAG_BITSPERSAMPLE, &bps);
bytes_per_sample = (bps + 7) / 8;
if( width == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / width ||
bps * spp * width > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (bps * spp * width) + 7");
return 1;
}
rowsize = ((bps * spp * width) + 7U) / 8; /* source has interleaved samples */
if( bytes_per_sample == 0 ||
rowsperstrip > TIFF_UINT32_MAX / bytes_per_sample ||
rowsperstrip * bytes_per_sample > TIFF_UINT32_MAX / (width + 1) )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing rowsperstrip * "
"bytes_per_sample * (width + 1)");
return 1;
}
rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
/* Add 3 padding bytes for extractContigSamples32bits */
obuf = limitMalloc (rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
if (obuf == NULL)
return 1;
for (s = 0; s < spp; s++)
{
for (row = 0; row < length; row += rowsperstrip)
{
nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
src = buf + (row * rowsize);
total_bytes += stripsize;
memset (obuf, '\0',rowstripsize + NUM_BUFF_OVERSIZE_BYTES);
if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump))
{
_TIFFfree(obuf);
return 1;
}
if ((dump->outfile != NULL) && (dump->level == 1))
{
if (scanlinesize > 0x0ffffffffULL) {
dump_info(dump->infile, dump->format, "loadImage",
"Attention: scanlinesize %"PRIu64" is larger than UINT32_MAX.\nFollowing dump might be wrong.",
scanlinesize);
}
dump_info(dump->outfile, dump->format,"",
"Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d",
s + 1, strip + 1, stripsize, row + 1, (uint32_t)scanlinesize, src - buf);
dump_buffer(dump->outfile, dump->format, nrows, (uint32_t)scanlinesize, row, obuf);
}
if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
_TIFFfree(obuf);
return 1;
}
}
}
_TIFFfree(obuf);
return 0;
}
/* Extract all planes from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts* dump)
{
uint16 bps;
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
tmsize_t tile_rowsize = TIFFTileRowSize(out);
uint8* bufp = (uint8*) buf;
tsize_t tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(out);
unsigned char *tilebuf = NULL;
if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
!TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
!TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
return 1;
if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
{
TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
exit(EXIT_FAILURE);
}
tile_buffsize = tilesize;
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("writeBufferToContigTiles",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != tile_buffsize / tile_rowsize)
{
TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
exit(EXIT_FAILURE);
}
}
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
/* Add 3 padding bytes for extractContigSamples32bits */
tilebuf = limitMalloc(tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
if (tilebuf == 0)
return 1;
memset(tilebuf, 0, tile_buffsize + NUM_BUFF_OVERSIZE_BYTES);
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
tw, 0, spp, spp, bps, dump) > 0)
{
TIFFError("writeBufferToContigTiles",
"Unable to extract data to tile for row %lu, col %lu",
(unsigned long) row, (unsigned long)col);
_TIFFfree(tilebuf);
return 1;
}
if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
{
TIFFError("writeBufferToContigTiles",
"Cannot write tile at %lu %lu",
(unsigned long) col, (unsigned long) row);
_TIFFfree(tilebuf);
return 1;
}
}
}
_TIFFfree(tilebuf);
return 0;
} /* end writeBufferToContigTiles */
/* Extract each plane from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts * dump)
{
/* Add 3 padding bytes for extractContigSamples32bits */
tdata_t obuf = limitMalloc(TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint16 bps;
tsample_t s;
uint8* bufp = (uint8*) buf;
if (obuf == NULL)
return 1;
memset(obuf, 0, TIFFTileSize(out) + NUM_BUFF_OVERSIZE_BYTES);
if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
!TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
!TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
return 1;
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7 )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
_TIFFfree(obuf);
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
for (s = 0; s < spp; s++)
{
if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
tw, s, 1, spp, bps, dump) > 0)
{
TIFFError("writeBufferToSeparateTiles",
"Unable to extract data to tile for row %lu, col %lu sample %d",
(unsigned long) row, (unsigned long)col, (int)s);
_TIFFfree(obuf);
return 1;
}
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
{
TIFFError("writeBufferToseparateTiles",
"Cannot write tile at %lu %lu sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 1;
}
}
}
}
_TIFFfree(obuf);
return 0;
} /* end writeBufferToSeparateTiles */
static void
processG3Options(char* cp)
{
if( (cp = strchr(cp, ':')) ) {
if (defg3opts == (uint32) -1)
defg3opts = 0;
do {
cp++;
if (strneq(cp, "1d", 2))
defg3opts &= ~GROUP3OPT_2DENCODING;
else if (strneq(cp, "2d", 2))
defg3opts |= GROUP3OPT_2DENCODING;
else if (strneq(cp, "fill", 4))
defg3opts |= GROUP3OPT_FILLBITS;
else
usage(EXIT_FAILURE);
} while( (cp = strchr(cp, ':')) );
}
}
static int
processCompressOptions(char* opt)
{
char* cp = NULL;
if (strneq(opt, "none",4))
{
defcompression = COMPRESSION_NONE;
}
else if (streq(opt, "packbits"))
{
defcompression = COMPRESSION_PACKBITS;
}
else if (strneq(opt, "jpeg", 4))
{
cp = strchr(opt, ':');
defcompression = COMPRESSION_JPEG;
while (cp)
{
if (isdigit((int)cp[1]))
quality = atoi(cp + 1);
else if (strneq(cp + 1, "raw", 3 ))
jpegcolormode = JPEGCOLORMODE_RAW;
else if (strneq(cp + 1, "rgb", 3 ))
jpegcolormode = JPEGCOLORMODE_RGB;
else
usage(EXIT_FAILURE);
cp = strchr(cp + 1, ':');
}
}
else if (strneq(opt, "g3", 2))
{
processG3Options(opt);
defcompression = COMPRESSION_CCITTFAX3;
}
else if (streq(opt, "g4"))
{
defcompression = COMPRESSION_CCITTFAX4;
}
else if (strneq(opt, "lzw", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_LZW;
}
else if (strneq(opt, "zip", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_ADOBE_DEFLATE;
}
else
return (0);
return (1);
}
static void
usage(int code)
{
int i;
FILE * out = (code == EXIT_SUCCESS) ? stdout : stderr;
fprintf(out, "\n%s\n", TIFFGetVersion());
for (i = 0; usage_info[i] != NULL; i++)
fprintf(out, "%s\n", usage_info[i]);
exit(code);
}
#define CopyField(tag, v) \
if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define CopyField2(tag, v1, v2) \
if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define CopyField3(tag, v1, v2, v3) \
if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define CopyField4(tag, v1, v2, v3, v4) \
if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
switch (type) {
case TIFF_SHORT:
if (count == 1) {
uint16 shortv;
CopyField(tag, shortv);
} else if (count == 2) {
uint16 shortv1, shortv2;
CopyField2(tag, shortv1, shortv2);
} else if (count == 4) {
uint16 *tr, *tg, *tb, *ta;
CopyField4(tag, tr, tg, tb, ta);
} else if (count == (uint16) -1) {
uint16 shortv1;
uint16* shortav;
CopyField2(tag, shortv1, shortav);
}
break;
case TIFF_LONG:
{ uint32 longv;
CopyField(tag, longv);
}
break;
case TIFF_RATIONAL:
if (count == 1) {
float floatv;
CopyField(tag, floatv);
} else if (count == (uint16) -1) {
float* floatav;
CopyField(tag, floatav);
}
break;
case TIFF_ASCII:
{ char* stringv;
CopyField(tag, stringv);
}
break;
case TIFF_DOUBLE:
if (count == 1) {
double doublev;
CopyField(tag, doublev);
} else if (count == (uint16) -1) {
double* doubleav;
CopyField(tag, doubleav);
}
break;
default:
TIFFError(TIFFFileName(in),
"Data type %d is not supported, tag %d skipped",
tag, type);
}
}
static struct cpTag {
uint16 tag;
uint16 count;
TIFFDataType type;
} tags[] = {
{ TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
{ TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
{ TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
{ TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
{ TIFFTAG_MAKE, 1, TIFF_ASCII },
{ TIFFTAG_MODEL, 1, TIFF_ASCII },
{ TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_PAGENAME, 1, TIFF_ASCII },
{ TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
{ TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
{ TIFFTAG_DATETIME, 1, TIFF_ASCII },
{ TIFFTAG_ARTIST, 1, TIFF_ASCII },
{ TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
{ TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL },
{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
{ TIFFTAG_INKSET, 1, TIFF_SHORT },
{ TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
{ TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
{ TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
{ TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
{ TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
{ TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
{ TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_STONITS, 1, TIFF_DOUBLE },
};
#define NTAGS (sizeof (tags) / sizeof (tags[0]))
#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
/* Functions written by Richard Nolde, with exceptions noted. */
void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum,
uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth,
uint32 *deftilelength, uint32 *defrowsperstrip,
struct crop_mask *crop_data, struct pagedef *page,
struct dump_opts *dump,
unsigned int *imagelist, unsigned int *image_count )
{
int c, good_args = 0;
char *opt_offset = NULL; /* Position in string of value sought */
char *opt_ptr = NULL; /* Pointer to next token in option set */
char *sep = NULL; /* Pointer to a token separator */
unsigned int i, j, start, end;
#if !HAVE_DECL_OPTARG
extern int optind;
extern char* optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv,
"ac:d:e:f:hik:l:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1)
{
good_args++;
switch (c) {
case 'a': mode[0] = 'a'; /* append to output */
break;
case 'c': if (!processCompressOptions(optarg)) /* compression scheme */
{
TIFFError ("Unknown compression option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */
if (start == 0)
{
TIFFError ("","Directory offset must be greater than zero");
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
*dirnum = start - 1;
break;
case 'e': switch (tolower((int) optarg[0])) /* image export modes*/
{
case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Composite */
case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Divided */
case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Image */
case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Multiple */
case 's': crop_data->exp_mode = FILE_PER_SELECTION;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Sections */
default: TIFFError ("Unknown export mode","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'f': if (streq(optarg, "lsb2msb")) /* fill order */
*deffillorder = FILLORDER_LSB2MSB;
else if (streq(optarg, "msb2lsb"))
*deffillorder = FILLORDER_MSB2LSB;
else
{
TIFFError ("Unknown fill order", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'h': usage(EXIT_SUCCESS);
break;
case 'i': ignore = TRUE; /* ignore errors */
break;
case 'k': maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
break;
case 'l': outtiled = TRUE; /* tile length */
*deftilelength = atoi(optarg);
break;
case 'p': /* planar configuration */
if (streq(optarg, "separate"))
*defconfig = PLANARCONFIG_SEPARATE;
else if (streq(optarg, "contig"))
*defconfig = PLANARCONFIG_CONTIG;
else
{
TIFFError ("Unknown planar configuration", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'r': /* rows/strip */
*defrowsperstrip = atol(optarg);
break;
case 's': /* generate stripped output */
outtiled = FALSE;
break;
case 't': /* generate tiled output */
outtiled = TRUE;
break;
case 'v': printf("Library Release: %s\n", TIFFGetVersion());
printf("Tiffcrop version: %s, last updated: %s\n",
tiffcrop_version_id, tiffcrop_rev_date);
printf("Tiffcp code: Copyright (c) 1988-1997 Sam Leffler\n");
printf(" : Copyright (c) 1991-1997 Silicon Graphics, Inc\n");
printf("Tiffcrop additions: Copyright (c) 2007-2010 Richard Nolde\n");
exit (EXIT_SUCCESS);
break;
case 'w': /* tile width */
outtiled = TRUE;
*deftilewidth = atoi(optarg);
break;
case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */
crop_data->crop_mode |= CROP_REGIONS;
for (i = 0, opt_ptr = strtok (optarg, ":");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ":")), i++)
{
crop_data->regions++;
if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
&crop_data->corners[i].X1, &crop_data->corners[i].Y1,
&crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4)
{
TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);;
}
break;
/* options for file open modes */
case 'B': *mp++ = 'b'; *mp = '\0';
break;
case 'L': *mp++ = 'l'; *mp = '\0';
break;
case 'M': *mp++ = 'm'; *mp = '\0';
break;
case 'C': *mp++ = 'c'; *mp = '\0';
break;
/* options for Debugging / data dump */
case 'D': for (i = 0, opt_ptr = strtok (optarg, ",");
(opt_ptr != NULL);
(opt_ptr = strtok (NULL, ",")), i++)
{
opt_offset = strpbrk(opt_ptr, ":=");
if (opt_offset == NULL)
{
TIFFError("Invalid dump option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
*opt_offset = '\0';
/* convert option to lowercase */
end = (unsigned int)strlen (opt_ptr);
for (i = 0; i < end; i++)
*(opt_ptr + i) = tolower((int) *(opt_ptr + i));
/* Look for dump format specification */
if (strncmp(opt_ptr, "for", 3) == 0)
{
/* convert value to lowercase */
end = (unsigned int)strlen (opt_offset + 1);
for (i = 1; i <= end; i++)
*(opt_offset + i) = tolower((int) *(opt_offset + i));
/* check dump format value */
if (strncmp (opt_offset + 1, "txt", 3) == 0)
{
dump->format = DUMP_TEXT;
strcpy (dump->mode, "w");
}
else
{
if (strncmp(opt_offset + 1, "raw", 3) == 0)
{
dump->format = DUMP_RAW;
strcpy (dump->mode, "wb");
}
else
{
TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
}
}
else
{ /* Look for dump level specification */
if (strncmp (opt_ptr, "lev", 3) == 0)
dump->level = atoi(opt_offset + 1);
/* Look for input data dump file name */
if (strncmp (opt_ptr, "in", 2) == 0)
{
strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20);
dump->infilename[PATH_MAX - 20] = '\0';
}
/* Look for output data dump file name */
if (strncmp (opt_ptr, "out", 3) == 0)
{
strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20);
dump->outfilename[PATH_MAX - 20] = '\0';
}
if (strncmp (opt_ptr, "deb", 3) == 0)
dump->debug = atoi(opt_offset + 1);
}
}
if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
{
if (dump->level == 1)
TIFFError("","Defaulting to dump level 1, no data.");
if (dump->format == DUMP_NONE)
{
TIFFError("", "You must specify a dump format for dump files");
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
}
break;
/* image manipulation routine options */
case 'm': /* margins to exclude from selection, uppercase M was already used */
/* order of values must be TOP, LEFT, BOTTOM, RIGHT */
crop_data->crop_mode |= CROP_MARGINS;
for (i = 0, opt_ptr = strtok (optarg, ",:");
((opt_ptr != NULL) && (i < 4));
(opt_ptr = strtok (NULL, ",:")), i++)
{
crop_data->margins[i] = atof(opt_ptr);
}
break;
case 'E': /* edge reference */
switch (tolower((int) optarg[0]))
{
case 't': crop_data->edge_ref = EDGE_TOP;
break;
case 'b': crop_data->edge_ref = EDGE_BOTTOM;
break;
case 'l': crop_data->edge_ref = EDGE_LEFT;
break;
case 'r': crop_data->edge_ref = EDGE_RIGHT;
break;
default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'F': /* flip eg mirror image or cropped segment, M was already used */
crop_data->crop_mode |= CROP_MIRROR;
switch (tolower((int) optarg[0]))
{
case 'h': crop_data->mirror = MIRROR_HORIZ;
break;
case 'v': crop_data->mirror = MIRROR_VERT;
break;
case 'b': crop_data->mirror = MIRROR_BOTH;
break;
default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'H': /* set horizontal resolution to new value */
page->hres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'I': /* invert the color space, eg black to white */
crop_data->crop_mode |= CROP_INVERT;
/* The PHOTOMETIC_INTERPRETATION tag may be updated */
if (streq(optarg, "black"))
{
crop_data->photometric = PHOTOMETRIC_MINISBLACK;
continue;
}
if (streq(optarg, "white"))
{
crop_data->photometric = PHOTOMETRIC_MINISWHITE;
continue;
}
if (streq(optarg, "data"))
{
crop_data->photometric = INVERT_DATA_ONLY;
continue;
}
if (streq(optarg, "both"))
{
crop_data->photometric = INVERT_DATA_AND_TAG;
continue;
}
TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
break;
case 'J': /* horizontal margin for sectioned ouput pages */
page->hmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'K': /* vertical margin for sectioned ouput pages*/
page->vmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'N': /* list of images to process */
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_IMAGES));
(opt_ptr = strtok (NULL, ",")))
{ /* We do not know how many images are in file yet
* so we build a list to include the maximum allowed
* and follow it until we hit the end of the file.
* Image count is not accurate for odd, even, last
* so page numbers won't be valid either.
*/
if (streq(opt_ptr, "odd"))
{
for (j = 1; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = (MAX_IMAGES - 1) / 2;
break;
}
else
{
if (streq(opt_ptr, "even"))
{
for (j = 2; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = MAX_IMAGES / 2;
break;
}
else
{
if (streq(opt_ptr, "last"))
imagelist[i++] = MAX_IMAGES;
else /* single value between commas */
{
sep = strpbrk(opt_ptr, ":-");
if (!sep)
imagelist[i++] = atoi(opt_ptr);
else
{
*sep = '\0';
start = atoi (opt_ptr);
if (!strcmp((sep + 1), "last"))
end = MAX_IMAGES;
else
end = atoi (sep + 1);
for (j = start; j <= end && j - start + i < MAX_IMAGES; j++)
imagelist[i++] = j;
}
}
}
}
}
*image_count = i;
break;
case 'O': /* page orientation */
switch (tolower((int) optarg[0]))
{
case 'a': page->orient = ORIENTATION_AUTO;
break;
case 'p': page->orient = ORIENTATION_PORTRAIT;
break;
case 'l': page->orient = ORIENTATION_LANDSCAPE;
break;
default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'P': /* page size selection */
if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
{
strcpy (page->name, "Custom");
page->mode |= PAGE_MODE_PAPERSIZE;
break;
}
if (get_page_geometry (optarg, page))
{
if (!strcmp(optarg, "list"))
{
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (EXIT_FAILURE);
}
TIFFError ("Invalid paper size", "%s", optarg);
TIFFError ("", "Select one of:");
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (EXIT_FAILURE);
}
else
{
page->mode |= PAGE_MODE_PAPERSIZE;
}
break;
case 'R': /* rotate image or cropped segment */
crop_data->crop_mode |= CROP_ROTATE;
switch (strtoul(optarg, NULL, 0))
{
case 90: crop_data->rotation = (uint16)90;
break;
case 180: crop_data->rotation = (uint16)180;
break;
case 270: crop_data->rotation = (uint16)270;
break;
default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */
sep = strpbrk(optarg, ",:");
if (sep)
{
*sep = '\0';
page->cols = atoi(optarg);
page->rows = atoi(sep +1);
}
else
{
page->cols = atoi(optarg);
page->rows = atoi(optarg);
}
if ((page->cols * page->rows) > MAX_SECTIONS)
{
TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS);
exit (EXIT_FAILURE);
}
page->mode |= PAGE_MODE_ROWSCOLS;
break;
case 'U': /* units for measurements and offsets */
if (streq(optarg, "in"))
{
crop_data->res_unit = RESUNIT_INCH;
page->res_unit = RESUNIT_INCH;
}
else if (streq(optarg, "cm"))
{
crop_data->res_unit = RESUNIT_CENTIMETER;
page->res_unit = RESUNIT_CENTIMETER;
}
else if (streq(optarg, "px"))
{
crop_data->res_unit = RESUNIT_NONE;
page->res_unit = RESUNIT_NONE;
}
else
{
TIFFError ("Illegal unit of measure","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
}
break;
case 'V': /* set vertical resolution to new value */
page->vres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'X': /* selection width */
crop_data->crop_mode |= CROP_WIDTH;
crop_data->width = atof(optarg);
break;
case 'Y': /* selection length */
crop_data->crop_mode |= CROP_LENGTH;
crop_data->length = atof(optarg);
break;
case 'Z': /* zones of an image X:Y read as zone X of Y */
crop_data->crop_mode |= CROP_ZONES;
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ",")), i++)
{
crop_data->zones++;
opt_offset = strchr(opt_ptr, ':');
if (!opt_offset) {
TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h");
exit(EXIT_FAILURE);
}
*opt_offset = '\0';
crop_data->zonelist[i].position = atoi(opt_ptr);
crop_data->zonelist[i].total = atoi(opt_offset + 1);
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS);
exit (EXIT_FAILURE);
}
break;
case '?': TIFFError ("For valid options type", "tiffcrop -h");
exit (EXIT_FAILURE);
/*NOTREACHED*/
}
}
/*-- Check for not allowed combinations (e.g. -X, -Y and -Z, -z and -S are
* mutually exclusive) --*/
char XY, Z, R, S;
XY = ((crop_data->crop_mode & CROP_WIDTH) ||
(crop_data->crop_mode & CROP_LENGTH))
? 1
: 0;
Z = (crop_data->crop_mode & CROP_ZONES) ? 1 : 0;
R = (crop_data->crop_mode & CROP_REGIONS) ? 1 : 0;
S = (page->mode & PAGE_MODE_ROWSCOLS) ? 1 : 0;
if (XY + Z + R + S > 1)
{
TIFFError("tiffcrop input error", "The crop options(-X|-Y), -Z, -z and "
"-S are mutually exclusive.->exit");
exit(EXIT_FAILURE);
}
/* Check for not allowed combination:
* Any of the -X, -Y, -Z and -z options together with other PAGE_MODE_x
options
* such as -H, -V, -P, -J or -K are not supported and may cause buffer
overflows.
. */
if ((XY + Z + R > 0) && page->mode != PAGE_MODE_NONE)
{
TIFFError("tiffcrop input error",
"Any of the crop options -X, -Y, -Z and -z together with "
"other PAGE_MODE_x options such as - H, -V, -P, -J or -K is "
"not supported and may cause buffer overflows..->exit");
exit(EXIT_FAILURE);
}
} /* end process_command_opts */
/* Start a new output file if one has not been previously opened or
* autoindex is set to non-zero. Update page and file counters
* so TIFFTAG PAGENUM will be correct in image.
*/
static int
update_output_file (TIFF **tiffout, char *mode, int autoindex,
char *outname, unsigned int *page)
{
static int findex = 0; /* file sequence indicator */
size_t basename_len;
char *sep;
char export_ext[16];
char exportname[PATH_MAX];
if (autoindex && (*tiffout != NULL))
{
/* Close any export file that was previously opened */
TIFFClose (*tiffout);
*tiffout = NULL;
}
memcpy (export_ext, ".tiff", 6);
memset (exportname, '\0', sizeof(exportname));
/* Leave room for page number portion of the new filename :
* hyphen + 6 digits + dot + 4 extension characters + null terminator */
#define FILENUM_MAX_LENGTH (1+6+1+4+1)
strncpy (exportname, outname, sizeof(exportname) - FILENUM_MAX_LENGTH);
if (*tiffout == NULL) /* This is a new export file */
{
if (autoindex)
{ /* create a new filename for each export */
findex++;
if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF")))
{
strncpy (export_ext, sep, 5);
*sep = '\0';
}
else
memcpy (export_ext, ".tiff", 5);
export_ext[5] = '\0';
basename_len = strlen(exportname);
/* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */
if (findex > MAX_EXPORT_PAGES)
{
TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES);
return 1;
}
/* We previously assured that there will be space left */
snprintf(exportname + basename_len, sizeof(exportname) - basename_len, "-%03d%.5s", findex, export_ext);
}
exportname[sizeof(exportname) - 1] = '\0';
*tiffout = TIFFOpen(exportname, mode);
if (*tiffout == NULL)
{
TIFFError("update_output_file", "Unable to open output file %s", exportname);
return 1;
}
*page = 0;
return 0;
}
else
(*page)++;
return 0;
} /* end update_output_file */
int
main(int argc, char* argv[])
{
#if !HAVE_DECL_OPTARG
extern int optind;
#endif
uint16 defconfig = (uint16) -1;
uint16 deffillorder = 0;
uint32 deftilewidth = (uint32) 0;
uint32 deftilelength = (uint32) 0;
uint32 defrowsperstrip = (uint32) 0;
uint32 dirnum = 0;
TIFF *in = NULL;
TIFF *out = NULL;
char mode[10];
char *mp = mode;
/** RJN additions **/
struct image_data image; /* Image parameters for one image */
struct crop_mask crop; /* Cropping parameters for all images */
struct pagedef page; /* Page definition for output pages */
struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
struct dump_opts dump; /* Data dump options */
unsigned char *read_buff = NULL; /* Input image data buffer */
unsigned char *crop_buff = NULL; /* Crop area buffer */
unsigned char *sect_buff = NULL; /* Image section buffer */
unsigned char *sect_src = NULL; /* Image section buffer pointer */
unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
unsigned int image_count = 0;
unsigned int dump_images = 0;
unsigned int next_image = 0;
unsigned int next_page = 0;
unsigned int total_pages = 0;
unsigned int total_images = 0;
unsigned int end_of_input = FALSE;
int seg;
size_t length;
char temp_filename[PATH_MAX + 16]; /* Extra space keeps the compiler from complaining */
assert(NUM_BUFF_OVERSIZE_BYTES >= 3);
little_endian = *((unsigned char *)&little_endian) & '1';
initImageData(&image);
initCropMasks(&crop);
initPageSetup(&page, sections, seg_buffs);
initDumpOptions(&dump);
process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig,
&deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip,
&crop, &page, &dump, imagelist, &image_count);
if (argc - optind < 2)
usage(EXIT_FAILURE);
if ((argc - optind) == 2)
pageNum = -1;
else
total_images = 0;
/* Read multiple input files and write to output file(s) */
while (optind < argc - 1)
{
in = TIFFOpen (argv[optind], "r");
if (in == NULL)
return (-3);
/* If only one input file is specified, we can use directory count */
total_images = TIFFNumberOfDirectories(in);
if (total_images > TIFF_DIR_MAX)
{
TIFFError (TIFFFileName(in), "File contains too many directories");
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
if (image_count == 0)
{
dirnum = 0;
total_pages = total_images; /* Only valid with single input file */
}
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
/* Total pages only valid for enumerated list of pages not derived
* using odd, even, or last keywords.
*/
if (image_count > total_images)
image_count = total_images;
total_pages = image_count;
}
/* MAX_IMAGES is used for special case "last" in selection list */
if (dirnum == (MAX_IMAGES - 1))
dirnum = total_images - 1;
if (dirnum > (total_images))
{
TIFFError (TIFFFileName(in),
"Invalid image number %d, File contains only %d images",
(int)dirnum + 1, total_images);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
{
TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
end_of_input = FALSE;
while (end_of_input == FALSE)
{
config = defconfig;
compression = defcompression;
predictor = defpredictor;
fillorder = deffillorder;
rowsperstrip = defrowsperstrip;
tilewidth = deftilewidth;
tilelength = deftilelength;
g3opts = defg3opts;
if (dump.format != DUMP_NONE)
{
/* manage input and/or output dump files here */
dump_images++;
length = strlen(dump.infilename);
if (length > 0)
{
if (dump.infile != NULL)
fclose (dump.infile);
/* dump.infilename is guaranteed to be NUL terminated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s",
dump.infilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (EXIT_FAILURE);
}
dump_info(dump.infile, dump.format, "Reading image","%d from %s",
dump_images, TIFFFileName(in));
}
length = strlen(dump.outfilename);
if (length > 0)
{
if (dump.outfile != NULL)
fclose (dump.outfile);
/* dump.outfilename is guaranteed to be NUL terminated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s",
dump.outfilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (EXIT_FAILURE);
}
dump_info(dump.outfile, dump.format, "Writing image","%d from %s",
dump_images, TIFFFileName(in));
}
}
if (dump.debug)
TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages);
if (loadImage(in, &image, &dump, &read_buff))
{
TIFFError("main", "Unable to load source image");
exit (EXIT_FAILURE);
}
/* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
*/
if (image.adjustments != 0)
{
if (correct_orientation(&image, &read_buff))
TIFFError("main", "Unable to correct image orientation");
}
if (getCropOffsets(&image, &crop, &dump))
{
TIFFError("main", "Unable to define crop regions");
exit (EXIT_FAILURE);
}
/* Crop input image and copy zones and regions from input image into seg_buffs or crop_buff. */
if (crop.selections > 0)
{
if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
{
TIFFError("main", "Unable to process image selections");
exit (EXIT_FAILURE);
}
}
else /* Single image segment without zones or regions */
{
if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
{
TIFFError("main", "Unable to create output image");
exit (EXIT_FAILURE);
}
}
/* Format and write selected image parts to output file(s). */
if (page.mode == PAGE_MODE_NONE)
{ /* Whole image or sections not based on output page size */
if (crop.selections > 0)
{
writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
mp, argv[argc - 1], &next_page, total_pages);
}
else /* One file all images and sections */
{
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1],
&next_page))
exit (EXIT_FAILURE);
if (writeCroppedImage(in, out, &image, &dump,crop.combined_width,
crop.combined_length, crop_buff, next_page, total_pages))
{
TIFFError("main", "Unable to write new image");
exit (EXIT_FAILURE);
}
}
}
else
{
/* If we used a crop buffer, our data is there, otherwise it is
* in the read_buffer
*/
if (crop_buff != NULL)
sect_src = crop_buff;
else
sect_src = read_buff;
/* Break input image into pages or rows and columns */
if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump))
{
TIFFError("main", "Unable to compute output section data");
exit (EXIT_FAILURE);
}
/* If there are multiple files on the command line, the final one is assumed
* to be the output filename into which the images are written.
*/
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page))
exit (EXIT_FAILURE);
if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, §_buff))
{
TIFFError("main", "Unable to write image sections");
exit (EXIT_FAILURE);
}
}
/* No image list specified, just read the next image */
if (image_count == 0)
dirnum++;
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
}
if (dirnum == MAX_IMAGES - 1)
dirnum = TIFFNumberOfDirectories(in) - 1;
if (!TIFFSetDirectory(in, (tdir_t)dirnum))
end_of_input = TRUE;
}
TIFFClose(in);
optind++;
}
/* If we did not use the read buffer as the crop buffer */
if (read_buff)
_TIFFfree(read_buff);
if (crop_buff)
_TIFFfree(crop_buff);
if (sect_buff)
_TIFFfree(sect_buff);
/* Clean up any segment buffers used for zones or regions */
for (seg = 0; seg < crop.selections; seg++)
_TIFFfree (seg_buffs[seg].buffer);
if (dump.format != DUMP_NONE)
{
if (dump.infile != NULL)
fclose (dump.infile);
if (dump.outfile != NULL)
{
dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out));
fclose (dump.outfile);
}
}
TIFFClose(out);
return (0);
} /* end main */
/* Debugging functions */
static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count)
{
int j, k;
uint32 i;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (i = 0; i < count; i++)
{
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s", dump_array);
}
fprintf (dumpfile,"\n");
}
else
{
if ((fwrite (data, 1, count, dumpfile)) != count)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data)
{
int j, k;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 1, 1, dumpfile)) != 1)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data)
{
int j, k;
char dump_array[20];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 15; k >= 0; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[17] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 2, 1, dumpfile)) != 2)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data)
{
int j, k;
char dump_array[40];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 31; k >= 0; j++, k--)
{
bitset = data & (((uint32)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[35] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 4, 1, dumpfile)) != 4)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data)
{
int j, k;
char dump_array[80];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 63; k >= 0; j++, k--)
{
bitset = data & (((uint64)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[71] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 8, 1, dumpfile)) != 8)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...)
{
if (format == DUMP_TEXT)
{
va_list ap;
va_start(ap, msg);
fprintf(dumpfile, "%s ", prefix);
vfprintf(dumpfile, msg, ap);
fprintf(dumpfile, "\n");
va_end(ap);
}
}
static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width,
uint32 row, unsigned char *buff)
{
int j, k;
uint32 i;
unsigned char * dump_ptr;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
for (i = 0; i < rows; i++)
{
dump_ptr = buff + (i * width);
if (format == DUMP_TEXT)
dump_info (dumpfile, format, "",
"Row %4d, %d bytes at offset %d",
row + i + 1, width, row * width);
for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10)
dump_data (dumpfile, format, "", dump_ptr, 10);
if (k > 0)
dump_data (dumpfile, format, "", dump_ptr, k);
}
return (0);
}
/* Extract one or more samples from an interleaved buffer. If count == 1,
* only the sample plane indicated by sample will be extracted. If count > 1,
* count samples beginning at sample will be extracted. Portions of a
* scanline can be extracted by specifying a start and end value.
*/
static int
extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int i, bytes_per_sample, sindex;
uint32 col, dst_rowsize, bit_offset;
uint32 src_byte /*, src_bit */;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesBytes","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid end column value %d ignored", end);
end = cols;
}
dst_rowsize = (bps * (end - start) * count) / 8;
bytes_per_sample = (bps + 7) / 8;
/* Optimize case for copying all samples */
if (count == spp)
{
src = in + (start * spp * bytes_per_sample);
_TIFFmemcpy (dst, src, dst_rowsize);
}
else
{
for (col = start; col < end; col++)
{
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
bit_offset = col * bps * spp;
if (sindex == 0)
{
src_byte = bit_offset / 8;
/* src_bit = bit_offset % 8; */
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
/* src_bit = (bit_offset + (sindex * bps)) % 8; */
}
src = in + src_byte;
for (i = 0; i < bytes_per_sample; i++)
*dst++ = *src++;
}
}
}
return (0);
} /* end extractContigSamplesBytes */
static int
extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = (buff2 | (buff1 >> ready_bits));
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples8bits */
static int
extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
{
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples16bits */
static int
extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
{
buff1 = (src[0] << 24);
if (matchbits & 0x00ff0000)
buff1 |= (src[1] << 16);
if (matchbits & 0x0000ff00)
buff1 |= (src[2] << 8);
if (matchbits & 0x000000ff)
buff1 |= src[3];
}
else
{
buff1 = src[0];
if (matchbits & 0x0000ff00)
buff1 |= (src[1] << 8);
if (matchbits & 0x00ff0000)
buff1 |= (src[2] << 16);
if (matchbits & 0xff000000)
buff1 |= (src[3] << 24);
}
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples24bits */
static int
extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = 0;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples32bits */
static int
extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
if ((col == start) && (sindex == sample))
buff2 = *src & ((uint8)-1) << (shift);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ |= buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = buff2 | (buff1 >> ready_bits);
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted8bits */
static int
extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint16)-1) << (8 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
buff2 = buff2 | (buff1 >> ready_bits);
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted16bits */
static int
extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint32)-1) << (16 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted24bits */
static int
extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = shift;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
if ((col == start) && (sindex == sample))
buff2 = buff3 & ((uint64)-1) << (32 - shift);
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted32bits */
static int
extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row, first_col = 0;
uint32 dst_rowsize, dst_offset;
tsample_t count = 1;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src_rowsize = ((bps * spp * cols) + 7) / 8;
dst_rowsize = ((bps * cols) + 7) / 8;
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToBuffer */
static int
extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
uint32 imagewidth, uint32 tilewidth, tsample_t sample,
uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row;
uint32 dst_rowsize, dst_offset;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToTileBuffer */
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
tmsize_t bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
tmsize_t stripsize = TIFFStripSize(in);
tmsize_t rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %"PRIu32": read %"PRId64" bytes, strip size %"PRIu64,
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %"PRIu32" after %"PRIu64" rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += stripsize;
}
return 1;
} /* end readContigStripsIntoBuffer */
static int
combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * spp * cols) + 7) / 8;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
row_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
col_offset = row_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
src += bytes_per_sample;
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamplesBytes */
static int
combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
/* int bytes_per_sample = 0; */
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples8bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples8bits */
static int
combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples16bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples16bits */
static int
combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples24bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = ((uint32)src[0] << 24) | ((uint32)src[1] << 16) | ((uint32)src[2] << 8) | (uint32)src[3];
else
buff1 = ((uint32)src[3] << 24) | ((uint32)src[2] << 16) | ((uint32)src[1] << 8) | (uint32)src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples24bits */
static int
combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples32bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateSamples32bits */
static int
combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = imagewidth * bytes_per_sample * spp;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
#ifdef DEVELMODE
TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d",
row, src_offset, dst - out);
#endif
for (col = 0; col < cols; col++)
{
col_offset = src_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamplesBytes */
static int
combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples8bits */
static int
combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples16bits */
static int
combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples24bits */
static int
combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateTileSamples32bits */
static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length,
uint32 width, uint16 spp,
struct dump_opts *dump)
{
int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
uint32 j;
tmsize_t bytes_read = 0;
uint16 bps = 0, planar;
uint32 nstrips;
uint32 strips_per_sample;
uint32 src_rowsize, dst_rowsize, rows_processed, rps;
uint32 rows_this_strip = 0;
tsample_t s;
tstrip_t strip;
tsize_t scanlinesize = TIFFScanlineSize(in);
tsize_t stripsize = TIFFStripSize(in);
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *buff = NULL;
unsigned char *dst = NULL;
if (obuf == NULL)
{
TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
}
memset (srcbuffs, '\0', sizeof(srcbuffs));
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (rps > length)
rps = length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
src_rowsize = ((bps * width) + 7) / 8;
dst_rowsize = ((bps * width * spp) + 7) / 8;
dst = obuf;
if ((dump->infile != NULL) && (dump->level == 3))
{
dump_info (dump->infile, dump->format, "",
"Image width %d, length %d, Scanline size, %4d bytes",
width, length, scanlinesize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d, Shift width %d",
bps, spp, shift_width);
}
/* Libtiff seems to assume/require that data for separate planes are
* written one complete plane after another and not interleaved in any way.
* Multiple scanlines and possibly strips of the same plane must be
* written before data for any other plane.
*/
nstrips = TIFFNumberOfStrips(in);
strips_per_sample = nstrips /spp;
/* Add 3 padding bytes for combineSeparateSamples32bits */
if( (size_t) stripsize > 0xFFFFFFFFU - 3U )
{
TIFFError("readSeparateStripsIntoBuffer", "Integer overflow when calculating buffer size.");
exit(EXIT_FAILURE);
}
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
srcbuffs[s] = NULL;
buff = limitMalloc(stripsize + NUM_BUFF_OVERSIZE_BYTES);
if (!buff)
{
TIFFError ("readSeparateStripsIntoBuffer",
"Unable to allocate strip read buffer for sample %d", s);
for (i = 0; i < s; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
buff[stripsize] = 0;
buff[stripsize+1] = 0;
buff[stripsize+2] = 0;
srcbuffs[s] = buff;
}
rows_processed = 0;
for (j = 0; (j < strips_per_sample) && (result == 1); j++)
{
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
strip = (s * strips_per_sample) + j;
bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
rows_this_strip = (uint32_t)(bytes_read / src_rowsize);
if (bytes_read < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu for sample %d",
(unsigned long) strip, s + 1);
result = 0;
break;
}
#ifdef DEVELMODE
TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d",
strip, bytes_read, rows_this_strip, shift_width);
#endif
}
if (rps > rows_this_strip)
rps = rows_this_strip;
dst = obuf + (dst_rowsize * rows_processed);
if ((bps % 8) == 0)
{
if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
}
else
{
switch (shift_width)
{
case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps);
result = 0;
break;
}
}
if ((rows_processed + rps) > length)
{
rows_processed = length;
rps = length - rows_processed;
}
else
rows_processed += rps;
}
/* free any buffers allocated for each plane or scanline and
* any temporary buffers
*/
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
if (buff != NULL)
_TIFFfree(buff);
}
return (result);
} /* end readSeparateStripsIntoBuffer */
static int
get_page_geometry (char *name, struct pagedef *page)
{
char *ptr;
int n;
for (ptr = name; *ptr; ptr++)
*ptr = (char)tolower((int)*ptr);
for (n = 0; n < MAX_PAPERNAMES; n++)
{
if (strcmp(name, PaperTable[n].name) == 0)
{
page->width = PaperTable[n].width;
page->length = PaperTable[n].length;
strncpy (page->name, PaperTable[n].name, 15);
page->name[15] = '\0';
return (0);
}
}
return (1);
}
static void
initPageSetup (struct pagedef *page, struct pageseg *pagelist,
struct buffinfo seg_buffs[])
{
int i;
strcpy (page->name, "");
page->mode = PAGE_MODE_NONE;
page->res_unit = RESUNIT_NONE;
page->hres = 0.0;
page->vres = 0.0;
page->width = 0.0;
page->length = 0.0;
page->hmargin = 0.0;
page->vmargin = 0.0;
page->rows = 0;
page->cols = 0;
page->orient = ORIENTATION_NONE;
for (i = 0; i < MAX_SECTIONS; i++)
{
pagelist[i].x1 = (uint32)0;
pagelist[i].x2 = (uint32)0;
pagelist[i].y1 = (uint32)0;
pagelist[i].y2 = (uint32)0;
pagelist[i].buffsize = (uint32)0;
pagelist[i].position = 0;
pagelist[i].total = 0;
}
for (i = 0; i < MAX_OUTBUFFS; i++)
{
seg_buffs[i].size = 0;
seg_buffs[i].buffer = NULL;
}
}
static void
initImageData (struct image_data *image)
{
image->xres = 0.0;
image->yres = 0.0;
image->width = 0;
image->length = 0;
image->res_unit = RESUNIT_NONE;
image->bps = 0;
image->spp = 0;
image->planar = 0;
image->photometric = 0;
image->orientation = 0;
image->compression = COMPRESSION_NONE;
image->adjustments = 0;
}
static void
initCropMasks (struct crop_mask *cps)
{
int i;
cps->crop_mode = CROP_NONE;
cps->res_unit = RESUNIT_NONE;
cps->edge_ref = EDGE_TOP;
cps->width = 0;
cps->length = 0;
for (i = 0; i < 4; i++)
cps->margins[i] = 0.0;
cps->bufftotal = (uint32)0;
cps->combined_width = (uint32)0;
cps->combined_length = (uint32)0;
cps->rotation = (uint16)0;
cps->photometric = INVERT_DATA_AND_TAG;
cps->mirror = (uint16)0;
cps->invert = (uint16)0;
cps->zones = (uint32)0;
cps->regions = (uint32)0;
for (i = 0; i < MAX_REGIONS; i++)
{
cps->corners[i].X1 = 0.0;
cps->corners[i].X2 = 0.0;
cps->corners[i].Y1 = 0.0;
cps->corners[i].Y2 = 0.0;
cps->regionlist[i].x1 = 0;
cps->regionlist[i].x2 = 0;
cps->regionlist[i].y1 = 0;
cps->regionlist[i].y2 = 0;
cps->regionlist[i].width = 0;
cps->regionlist[i].length = 0;
cps->regionlist[i].buffsize = 0;
cps->zonelist[i].position = 0;
cps->zonelist[i].total = 0;
}
cps->exp_mode = ONE_FILE_COMPOSITE;
cps->img_mode = COMPOSITE_IMAGES;
}
static void initDumpOptions(struct dump_opts *dump)
{
dump->debug = 0;
dump->format = DUMP_NONE;
dump->level = 1;
sprintf (dump->mode, "w");
memset (dump->infilename, '\0', PATH_MAX + 1);
memset (dump->outfilename, '\0',PATH_MAX + 1);
dump->infile = NULL;
dump->outfile = NULL;
}
/* Compute pixel offsets into the image for margins and fixed regions */
static int
computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,
struct offset *off)
{
double scale;
float xres, yres;
/* Values for these offsets are in pixels from start of image, not bytes,
* and are indexed from zero to width - 1 or length - 1 */
uint32 tmargin, bmargin, lmargin, rmargin;
uint32 startx, endx; /* offsets of first and last columns to extract */
uint32 starty, endy; /* offsets of first and last row to extract */
uint32 width, length, crop_width, crop_length;
uint32 i, max_width, max_length, zwidth, zlength, buffsize;
uint32 x1, x2, y1, y2;
if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)
{
xres = 1.0;
yres = 1.0;
}
else
{
if (((image->xres == 0) || (image->yres == 0)) &&
(crop->res_unit != RESUNIT_NONE) &&
((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
{
TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution");
TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again");
return (-1);
}
xres = image->xres;
yres = image->yres;
}
/* Translate user units to image units */
scale = 1.0;
switch (crop->res_unit) {
case RESUNIT_CENTIMETER:
if (image->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (image->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
if (crop->crop_mode & CROP_REGIONS)
{
max_width = max_length = 0;
for (i = 0; i < crop->regions; i++)
{
if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))
{
x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1 * scale * xres);
x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2 * scale * xres);
y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1 * scale * yres);
y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2 * scale * yres);
}
else
{
x1 = _TIFFClampDoubleToUInt32(crop->corners[i].X1);
x2 = _TIFFClampDoubleToUInt32(crop->corners[i].X2);
y1 = _TIFFClampDoubleToUInt32(crop->corners[i].Y1);
y2 = _TIFFClampDoubleToUInt32(crop->corners[i].Y2);
}
/* a) Region needs to be within image sizes 0.. width-1; 0..length-1
* b) Corners are expected to be submitted as top-left to bottom-right.
* Therefore, check that and reorder input.
* (be aware x,y are already casted to (uint32) and avoid (0 - 1) )
*/
uint32 aux;
if (x1 > x2) {
aux = x1;
x1 = x2;
x2 = aux;
}
if (y1 > y2) {
aux = y1;
y1 = y2;
y2 = aux;
}
if (x1 > image->width - 1)
crop->regionlist[i].x1 = image->width - 1;
else if (x1 > 0)
crop->regionlist[i].x1 = (uint32)(x1 - 1);
if (x2 > image->width - 1)
crop->regionlist[i].x2 = image->width - 1;
else if (x2 > 0)
crop->regionlist[i].x2 = (uint32)(x2 - 1);
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
if (y1 > image->length - 1)
crop->regionlist[i].y1 = image->length - 1;
else if (y1 > 0)
crop->regionlist[i].y1 = (uint32)(y1 - 1);
if (y2 > image->length - 1)
crop->regionlist[i].y2 = image->length - 1;
else if (y2 > 0)
crop->regionlist[i].y2 = (uint32)(y2 - 1);
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
if (zwidth > max_width)
max_width = zwidth;
if (zlength > max_length)
max_length = zlength;
buffsize = (uint32)
(((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
/* For composite images with more than one region, the
* combined_length or combined_width always needs to be equal,
* respectively.
* Otherwise, even the first section/region copy
* action might cause buffer overrun. */
if (crop->img_mode == COMPOSITE_IMAGES)
{
switch (crop->edge_ref)
{
case EDGE_LEFT:
case EDGE_RIGHT:
if (i > 0 && zlength != crop->combined_length)
{
TIFFError(
"computeInputPixelOffsets",
"Only equal length regions can be combined for "
"-E left or right");
return (-1);
}
crop->combined_length = zlength;
crop->combined_width += zwidth;
break;
case EDGE_BOTTOM:
case EDGE_TOP: /* width from left, length from top */
default:
if (i > 0 && zwidth != crop->combined_width)
{
TIFFError("computeInputPixelOffsets",
"Only equal width regions can be "
"combined for -E "
"top or bottom");
return (-1);
}
crop->combined_width = zwidth;
crop->combined_length += zlength;
break;
}
}
}
return (0);
} /* crop_mode == CROP_REGIONS */
/* Convert crop margins into offsets into image
* Margins are expressed as pixel rows and columns, not bytes
*/
if (crop->crop_mode & CROP_MARGINS)
{
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{ /* User has specified pixels as reference unit */
tmargin = _TIFFClampDoubleToUInt32(crop->margins[0]);
lmargin = _TIFFClampDoubleToUInt32(crop->margins[1]);
bmargin = _TIFFClampDoubleToUInt32(crop->margins[2]);
rmargin = _TIFFClampDoubleToUInt32(crop->margins[3]);
}
else
{ /* inches or centimeters specified */
tmargin = _TIFFClampDoubleToUInt32(crop->margins[0] * scale * yres);
lmargin = _TIFFClampDoubleToUInt32(crop->margins[1] * scale * xres);
bmargin = _TIFFClampDoubleToUInt32(crop->margins[2] * scale * yres);
rmargin = _TIFFClampDoubleToUInt32(crop->margins[3] * scale * xres);
}
if ((lmargin + rmargin) > image->width)
{
TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width");
lmargin = (uint32) 0;
rmargin = (uint32) 0;
return (-1);
}
if ((tmargin + bmargin) > image->length)
{
TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length");
tmargin = (uint32) 0;
bmargin = (uint32) 0;
return (-1);
}
} /* crop_mode == CROP_MARGINS */
else
{ /* no margins requested */
tmargin = (uint32) 0;
lmargin = (uint32) 0;
bmargin = (uint32) 0;
rmargin = (uint32) 0;
}
/* Width, height, and margins are expressed as pixel offsets into image */
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{
if (crop->crop_mode & CROP_WIDTH)
width = _TIFFClampDoubleToUInt32(crop->width);
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = _TIFFClampDoubleToUInt32(crop->length);
else
length = image->length - tmargin - bmargin;
}
else
{
if (crop->crop_mode & CROP_WIDTH)
width = _TIFFClampDoubleToUInt32(crop->width * scale * image->xres);
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = _TIFFClampDoubleToUInt32(crop->length * scale * image->yres);
else
length = image->length - tmargin - bmargin;
}
off->tmargin = tmargin;
off->bmargin = bmargin;
off->lmargin = lmargin;
off->rmargin = rmargin;
/* Calculate regions defined by margins, width, and length.
* Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
* since they are used to compute offsets into buffers */
switch (crop->edge_ref) {
case EDGE_BOTTOM:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
endy = image->length - bmargin - 1;
if ((endy - length) <= tmargin)
starty = tmargin;
else
starty = endy - length + 1;
break;
case EDGE_RIGHT:
endx = image->width - rmargin - 1;
if ((endx - width) <= lmargin)
startx = lmargin;
else
startx = endx - width + 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
case EDGE_TOP: /* width from left, length from top */
case EDGE_LEFT:
default:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
}
off->startx = startx;
off->starty = starty;
off->endx = endx;
off->endy = endy;
if (endx + 1 <= startx)
{
TIFFError("computeInputPixelOffsets",
"Invalid left/right margins and /or image crop width requested");
return (-1);
}
crop_width = endx - startx + 1;
if (crop_width > image->width)
crop_width = image->width;
if (endy + 1 <= starty)
{
TIFFError("computeInputPixelOffsets",
"Invalid top/bottom margins and /or image crop length requested");
return (-1);
}
crop_length = endy - starty + 1;
if (crop_length > image->length)
crop_length = image->length;
off->crop_width = crop_width;
off->crop_length = crop_length;
return (0);
} /* end computeInputPixelOffsets */
/*
* Translate crop options into pixel offsets for one or more regions of the image.
* Options are applied in this order: margins, specific width and length, zones,
* but all are optional. Margins are relative to each edge. Width, length and
* zones are relative to the specified reference edge. Zones are expressed as
* X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
* 2:3 would indicate the middle third of the region qualified by margins and
* any explicit width and length specified. Regions are specified by coordinates
* of the top left and lower right corners with range 1 to width or height.
*/
static int
getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump)
{
struct offset offsets;
int i;
int32 test;
uint32 seg, total, need_buff = 0;
uint32 buffsize;
uint32 zwidth, zlength;
memset(&offsets, '\0', sizeof(struct offset));
crop->bufftotal = 0;
crop->combined_width = (uint32)0;
crop->combined_length = (uint32)0;
crop->selections = 0;
/* Compute pixel offsets if margins or fixed width or length specified */
if ((crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_REGIONS) ||
(crop->crop_mode & CROP_LENGTH) ||
(crop->crop_mode & CROP_WIDTH))
{
if (computeInputPixelOffsets(crop, image, &offsets))
{
TIFFError ("getCropOffsets", "Unable to compute crop margins");
return (-1);
}
need_buff = TRUE;
crop->selections = crop->regions;
/* Regions are only calculated from top and left edges with no margins */
if (crop->crop_mode & CROP_REGIONS)
return (0);
}
else
{ /* cropped area is the full image */
offsets.tmargin = 0;
offsets.lmargin = 0;
offsets.bmargin = 0;
offsets.rmargin = 0;
offsets.crop_width = image->width;
offsets.crop_length = image->length;
offsets.startx = 0;
offsets.endx = image->width - 1;
offsets.starty = 0;
offsets.endy = image->length - 1;
need_buff = FALSE;
}
if (dump->outfile != NULL)
{
dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d",
offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin);
dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d",
offsets.crop_width, offsets.crop_length);
}
if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
{
if (need_buff == FALSE) /* No margins or fixed width or length areas */
{
crop->selections = 0;
crop->combined_width = image->width;
crop->combined_length = image->length;
return (0);
}
else
{
/* Use one region for margins and fixed width or length areas
* even though it was not formally declared as a region.
*/
crop->selections = 1;
crop->zones = 1;
crop->zonelist[0].total = 1;
crop->zonelist[0].position = 1;
}
}
else
crop->selections = crop->zones;
/* Initialize regions iterator i */
i = 0;
for (int j = 0; j < crop->zones; j++)
{
seg = crop->zonelist[j].position;
total = crop->zonelist[j].total;
/* check for not allowed zone cases like 0:0; 4:3; etc. and skip that input */
if (seg == 0 || total == 0 || seg > total) {
continue;
}
switch (crop->edge_ref)
{
case EDGE_LEFT: /* zones from left to right, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * 1.0 * (seg - 1) / total);
test = (int32)offsets.startx +
(int32)(offsets.crop_width * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_BOTTOM: /* width from left, zones from bottom to top */
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = test + 1;
test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
case EDGE_RIGHT: /* zones from right to left, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * (total - seg) * 1.0 / total);
test = offsets.startx +
(offsets.crop_width * (total - seg + 1) * 1.0 / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_TOP: /* width from left, zones from top to bottom */
default:
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total);
test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test - 1;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
} /* end switch statement */
buffsize = (uint32)
((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].width = (uint32) zwidth;
crop->regionlist[i].length = (uint32) zlength;
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (dump->outfile != NULL)
dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d",
i + 1, (uint32)zwidth, (uint32)zlength,
crop->regionlist[i].x1, crop->regionlist[i].x2,
crop->regionlist[i].y1, crop->regionlist[i].y2);
/* increment regions iterator */
i++;
}
/* set number of generated regions out of given zones */
crop->selections = i;
return (0);
} /* end getCropOffsets */
static int
computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts* dump)
{
double scale;
double pwidth, plength; /* Output page width and length in user units*/
uint32 iwidth, ilength; /* Input image width and length in pixels*/
uint32 owidth, olength; /* Output image width and length in pixels*/
uint32 orows, ocols; /* rows and cols for output */
uint32 hmargin, vmargin; /* Horizontal and vertical margins */
uint32 x1, x2, y1, y2, line_bytes;
/* unsigned int orientation; */
uint32 i, j, k;
scale = 1.0;
if (page->res_unit == RESUNIT_NONE)
page->res_unit = image->res_unit;
switch (image->res_unit) {
case RESUNIT_CENTIMETER:
if (page->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (page->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
/* get width, height, resolutions of input image selection */
if (crop->combined_width > 0)
iwidth = crop->combined_width;
else
iwidth = image->width;
if (crop->combined_length > 0)
ilength = crop->combined_length;
else
ilength = image->length;
if (page->hres <= 1.0)
page->hres = image->xres;
if (page->vres <= 1.0)
page->vres = image->yres;
if ((page->hres < 1.0) || (page->vres < 1.0))
{
TIFFError("computeOutputPixelOffsets",
"Invalid horizontal or vertical resolution specified or read from input image");
return (1);
}
/* If no page sizes are being specified, we just use the input image size to
* calculate maximum margins that can be taken from image.
*/
if (page->width <= 0)
pwidth = iwidth;
else
pwidth = page->width;
if (page->length <= 0)
plength = ilength;
else
plength = page->length;
if (dump->debug)
{
TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
"Hmargin: %3.2f, Vmargin: %3.2f",
page->name, page->vres, page->hres,
page->hmargin, page->vmargin);
TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f",
page->res_unit, scale, pwidth, plength);
}
/* compute margins at specified unit and resolution */
if (page->mode & PAGE_MODE_MARGINS)
{
if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER)
{ /* inches or centimeters specified */
hmargin = _TIFFClampDoubleToUInt32(page->hmargin * scale * page->hres * ((image->bps + 7) / 8));
vmargin = _TIFFClampDoubleToUInt32(page->vmargin * scale * page->vres * ((image->bps + 7) / 8));
}
else
{ /* Otherwise user has specified pixels as reference unit */
hmargin = _TIFFClampDoubleToUInt32(page->hmargin * scale * ((image->bps + 7) / 8));
vmargin = _TIFFClampDoubleToUInt32(page->vmargin * scale * ((image->bps + 7) / 8));
}
if ((hmargin * 2.0) > (pwidth * page->hres))
{
TIFFError("computeOutputPixelOffsets",
"Combined left and right margins exceed page width");
hmargin = (uint32) 0;
return (-1);
}
if ((vmargin * 2.0) > (plength * page->vres))
{
TIFFError("computeOutputPixelOffsets",
"Combined top and bottom margins exceed page length");
vmargin = (uint32) 0;
return (-1);
}
}
else
{
hmargin = 0;
vmargin = 0;
}
if (page->mode & PAGE_MODE_ROWSCOLS )
{
/* Maybe someday but not for now */
if (page->mode & PAGE_MODE_MARGINS)
TIFFError("computeOutputPixelOffsets",
"Output margins cannot be specified with rows and columns");
owidth = TIFFhowmany(iwidth, page->cols);
olength = TIFFhowmany(ilength, page->rows);
}
else
{
if (page->mode & PAGE_MODE_PAPERSIZE )
{
owidth = _TIFFClampDoubleToUInt32((pwidth * page->hres) - (hmargin * 2));
olength = _TIFFClampDoubleToUInt32((plength * page->vres) - (vmargin * 2));
}
else
{
owidth = _TIFFClampDoubleToUInt32(iwidth - (hmargin * 2 * page->hres));
olength = _TIFFClampDoubleToUInt32(ilength - (vmargin * 2 * page->vres));
}
}
if (owidth > iwidth)
owidth = iwidth;
if (olength > ilength)
olength = ilength;
if (owidth == 0 || olength == 0)
{
TIFFError("computeOutputPixelOffsets", "Integer overflow when calculating the number of pages");
exit(EXIT_FAILURE);
}
/* Compute the number of pages required for Portrait or Landscape */
switch (page->orient)
{
case ORIENTATION_NONE:
case ORIENTATION_PORTRAIT:
ocols = TIFFhowmany(iwidth, owidth);
orows = TIFFhowmany(ilength, olength);
/* orientation = ORIENTATION_PORTRAIT; */
break;
case ORIENTATION_LANDSCAPE:
ocols = TIFFhowmany(iwidth, olength);
orows = TIFFhowmany(ilength, owidth);
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
break;
case ORIENTATION_AUTO:
default:
x1 = TIFFhowmany(iwidth, owidth);
x2 = TIFFhowmany(ilength, olength);
y1 = TIFFhowmany(iwidth, olength);
y2 = TIFFhowmany(ilength, owidth);
if ( (x1 * x2) < (y1 * y2))
{ /* Portrait */
ocols = x1;
orows = x2;
/* orientation = ORIENTATION_PORTRAIT; */
}
else
{ /* Landscape */
ocols = y1;
orows = y2;
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
}
}
if (ocols < 1)
ocols = 1;
if (orows < 1)
orows = 1;
/* If user did not specify rows and cols, set them from calcuation */
if (page->rows < 1)
page->rows = orows;
if (page->cols < 1)
page->cols = ocols;
line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp;
if ((page->rows * page->cols) > MAX_SECTIONS)
{
TIFFError("computeOutputPixelOffsets",
"Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections");
return (-1);
}
/* build the list of offsets for each output section */
for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++)
{
y1 = (uint32)(olength * i);
y2 = (uint32)(olength * (i + 1) - 1);
if (y2 >= ilength)
y2 = ilength - 1;
for (j = 0; j < ocols; j++, k++)
{
x1 = (uint32)(owidth * j);
x2 = (uint32)(owidth * (j + 1) - 1);
if (x2 >= iwidth)
x2 = iwidth - 1;
sections[k].x1 = x1;
sections[k].x2 = x2;
sections[k].y1 = y1;
sections[k].y2 = y2;
sections[k].buffsize = line_bytes * olength;
sections[k].position = k + 1;
sections[k].total = orows * ocols;
}
}
return (0);
} /* end computeOutputPixelOffsets */
static int
loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint32 nstrips = 0, ntiles = 0;
uint16 planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
tmsize_t stsize = 0, tlsize = 0, buffsize = 0;
tmsize_t scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
tmsize_t tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static tmsize_t prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(EXIT_FAILURE);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(EXIT_FAILURE);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(EXIT_FAILURE);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(EXIT_FAILURE);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(EXIT_FAILURE);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(EXIT_FAILURE);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
new_buff = _TIFFrealloc(read_buff, buffsize + NUM_BUFF_OVERSIZE_BYTES);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
if (scanlinesize > 0x0ffffffffULL) {
dump_info(dump->infile, dump->format, "loadImage",
"Attention: scanlinesize %"PRIu64" is larger than UINT32_MAX.\nFollowing dump might be wrong.",
scanlinesize);
}
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, (uint32_t)scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr)
{
uint16 mirror, rotation;
unsigned char *work_buff;
work_buff = *work_buff_ptr;
if ((image == NULL) || (work_buff == NULL))
{
TIFFError ("correct_orientatin", "Invalid image or buffer pointer");
return (-1);
}
if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT))
{
mirror = (uint16)(image->adjustments & MIRROR_BOTH);
if (mirrorImage(image->spp, image->bps, mirror,
image->width, image->length, work_buff))
{
TIFFError ("correct_orientation", "Unable to mirror image");
return (-1);
}
}
if (image->adjustments & ROTATE_ANY)
{
if (image->adjustments & ROTATECW_90)
rotation = (uint16) 90;
else
if (image->adjustments & ROTATECW_180)
rotation = (uint16) 180;
else
if (image->adjustments & ROTATECW_270)
rotation = (uint16) 270;
else
{
TIFFError ("correct_orientation", "Invalid rotation value: %d",
image->adjustments & ROTATE_ANY);
return (-1);
}
/* Dummy variable in order not to switch two times the
* image->width,->length within rotateImage(),
* but switch xres, yres there. */
uint32_t width = image->width;
uint32_t length = image->length;
if (rotateImage(rotation, image, &width, &length, work_buff_ptr, TRUE))
{
TIFFError ("correct_orientation", "Unable to rotate image");
return (-1);
}
image->orientation = ORIENTATION_TOPLEFT;
}
return (0);
} /* end correct_orientation */
/* Extract multiple zones from an image and combine into a single composite image */
static int
extractCompositeRegions(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 i, trailing_bits, prev_trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_rowsize, dst_rowsize, src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint32 prev_length, prev_width, composite_width;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract one or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src = read_buff;
dst = crop_buff;
/* These are setup for adding additional sections */
prev_width = prev_length = 0;
prev_trailing_bits = trailing_bits = 0;
composite_width = crop->combined_width;
crop->combined_width = 0;
crop->combined_length = 0;
/* If there is more than one region, check beforehand whether all the width
* and length values of the regions are the same, respectively. */
switch (crop->edge_ref)
{
default:
case EDGE_TOP:
case EDGE_BOTTOM:
for (i = 1; i < crop->selections; i++)
{
uint32_t crop_width0 =
crop->regionlist[i - 1].x2 - crop->regionlist[i - 1].x1 + 1;
uint32_t crop_width1 =
crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
if (crop_width0 != crop_width1)
{
TIFFError("extractCompositeRegions",
"Only equal width regions can be combined for -E "
"top or bottom");
return (1);
}
}
break;
case EDGE_LEFT:
case EDGE_RIGHT:
for (i = 1; i < crop->selections; i++)
{
uint32_t crop_length0 =
crop->regionlist[i - 1].y2 - crop->regionlist[i - 1].y1 + 1;
uint32_t crop_length1 =
crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
if (crop_length0 != crop_length1)
{
TIFFError("extractCompositeRegions",
"Only equal length regions can be combined for "
"-E left or right");
return (1);
}
}
}
for (i = 0; i < crop->selections; i++)
{
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[i].y1;
last_row = crop->regionlist[i].y2;
first_col = crop->regionlist[i].x1;
last_col = crop->regionlist[i].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
/* These should not be needed for composite images */
crop->regionlist[i].width = crop_width;
crop->regionlist[i].length = crop_length;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * count) + 7) / 8);
switch (crop->edge_ref)
{
default:
case EDGE_TOP:
case EDGE_BOTTOM:
if ((crop->selections > i + 1) &&
(crop_width != crop->regionlist[i + 1].width))
{
TIFFError ("extractCompositeRegions",
"Only equal width regions can be combined for -E top or bottom");
return (1);
}
crop->combined_width = crop_width;
crop->combined_length += crop_length;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_length += crop_length;
break;
case EDGE_LEFT: /* splice the pieces of each row together, side by side */
case EDGE_RIGHT:
if ((crop->selections > i + 1) &&
(crop_length != crop->regionlist[i + 1].length))
{
TIFFError ("extractCompositeRegions",
"Only equal length regions can be combined for -E left or right");
return (1);
}
crop->combined_width += crop_width;
crop->combined_length = crop_length;
dst_rowsize = (((composite_width * bps * count) + 7) / 8);
trailing_bits = (crop_width * bps * count) % 8;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + prev_width;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_width += (crop_width * bps * count) / 8;
prev_trailing_bits += trailing_bits;
if (prev_trailing_bits > 7)
prev_trailing_bits-= 8;
break;
}
}
if (crop->combined_width != composite_width)
TIFFError("combineSeparateRegions","Combined width does not match composite width");
return (0);
} /* end extractCompositeRegions */
/* Copy a single region of input buffer to an output buffer.
* The read functions used copy separate plane data into a buffer
* as interleaved samples rather than separate planes so the same
* logic works to extract regions regardless of the way the data
* are organized in the input file. This function can be used to
* extract one or more samples from the input image by updating the
* parameters for starting sample and number of samples to copy in the
* fifth and eighth arguments of the call to extractContigSamples.
* They would be passed as new elements of the crop_mask struct.
*/
static int
extractSeparateRegion(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff,
int region)
{
int shift_width, prev_trailing_bits = 0;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, dst_rowsize;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract more or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0; /* Byte aligned data only */
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[region].y1;
last_row = crop->regionlist[region].y2;
first_col = crop->regionlist[region].x1;
last_col = crop->regionlist[region].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
crop->regionlist[region].width = crop_width;
crop->regionlist[region].length = crop_length;
src = read_buff;
dst = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps);
return (1);
}
}
return (0);
} /* end extractSeparateRegion */
static int
extractImageSection(struct image_data *image, struct pageseg *section,
unsigned char *src_buff, unsigned char *sect_buff)
{
unsigned char bytebuff1, bytebuff2;
#ifdef DEVELMODE
/* unsigned char *src, *dst; */
#endif
uint32 img_width, img_rowsize;
#ifdef DEVELMODE
uint32 img_length;
#endif
uint32 j, shift1, trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset, row_offset, col_offset;
uint32 offset1, full_bytes;
uint32 sect_width;
#ifdef DEVELMODE
uint32 sect_length;
#endif
uint16 bps, spp;
#ifdef DEVELMODE
int k;
unsigned char bitset;
#endif
img_width = image->width;
#ifdef DEVELMODE
img_length = image->length;
#endif
bps = image->bps;
spp = image->spp;
#ifdef DEVELMODE
/* src = src_buff; */
/* dst = sect_buff; */
#endif
src_offset = 0;
dst_offset = 0;
#ifdef DEVELMODE
char bitarray[39];
#endif
/* rows, columns, width, length are expressed in pixels
* first_row, last_row, .. are index into image array starting at 0 to width-1,
* last_col shall be also extracted. */
first_row = section->y1;
last_row = section->y2;
first_col = section->x1;
last_col = section->x2;
sect_width = last_col - first_col + 1;
#ifdef DEVELMODE
sect_length = last_row - first_row + 1;
#endif
/* The read function loadImage() used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
* Furthermore, bytes and bits are arranged in buffer according to COMPRESSION=1 and FILLORDER=1
*/
img_rowsize = (((img_width * spp * bps) + 7) / 8); /* row size in full bytes of source image */
full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */
trailing_bits = (sect_width * spp * bps) % 8; /* trailing bits within the last byte of destination buffer */
#ifdef DEVELMODE
TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n",
first_row, last_row, first_col, last_col);
TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n",
img_width, img_length, bps, spp);
TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n",
sect_width, sect_length, full_bytes, trailing_bits);
#endif
if ((bps % 8) == 0)
{
col_offset = (first_col * spp * bps) / 8;
for (row = first_row; row <= last_row; row++)
{
row_offset = row * img_rowsize;
src_offset = row_offset + col_offset;
#ifdef DEVELMODE
TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset);
#endif
_TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes);
dst_offset += full_bytes;
}
}
else
{ /* bps != 8 */
shift1 = ((first_col * spp * bps) % 8); /* shift1 = bits to skip in the first byte of source buffer*/
for (row = first_row; row <= last_row; row++)
{
/* pull out the first byte */
row_offset = row * img_rowsize;
offset1 = row_offset + ((first_col * spp * bps) / 8); /* offset1 = offset into source of byte with first bits to be extracted */
#ifdef DEVELMODE
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
sprintf(&bitarray[8], " ");
sprintf(&bitarray[9], " ");
for (j = 10, k = 7; j < 18; j++, k--)
{
bitset = *(src_buff + offset1 + full_bytes) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[18] = '\0';
TIFFError ("", "Row: %3d Offset1: %"PRIu32", Shift1: %"PRIu32", Offset2: %"PRIu32", Trailing_bits: %"PRIu32"\n",
row, offset1, shift1, offset1+full_bytes, trailing_bits);
#endif
bytebuff1 = bytebuff2 = 0;
if (shift1 == 0) /* the region is byte and sample aligned */
{
_TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes);
#ifdef DEVELMODE
TIFFError ("", " Aligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset);
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
/* Only copy higher bits of samples and mask lower bits of not wanted column samples to zero */
bytebuff2 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (8 - trailing_bits));
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n",
offset1 + full_bytes, dst_offset);
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
else /* each destination byte will have to be built from two source bytes*/
{
#ifdef DEVELMODE
TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset);
#endif
for (j = 0; j <= full_bytes; j++)
{
/* Skip the first shift1 bits and shift the source up by shift1 bits before save to destination.*/
/* Attention: src_buff size needs to be some bytes larger than image size, because could read behind image here. */
bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (8 - shift1));
sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
}
#ifdef DEVELMODE
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
/* Copy the trailing_bits for the last byte in the destination buffer.
Could come from one ore two bytes of the source buffer. */
if (trailing_bits != 0)
{
#ifdef DEVELMODE
TIFFError("", " Trailing bits %4"PRIu32" src offset: %8"PRIu32", Dst offset: %8"PRIu32"\n", trailing_bits, offset1 + full_bytes, dst_offset);
#endif
/* More than necessary bits are already copied into last destination buffer,
* only masking of last byte in destination buffer is necessary.*/
sect_buff[dst_offset] &= ((uint8_t)0xFF << (8 - trailing_bits));
}
#ifdef DEVELMODE
sprintf(&bitarray[28], " ");
sprintf(&bitarray[29], " ");
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
}
return (0);
} /* end extractImageSection */
static int
writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
struct image_data *image, struct dump_opts *dump,
struct buffinfo seg_buffs[], char *mp, char *filename,
unsigned int *page, unsigned int total_pages)
{
int i, page_count;
int autoindex = 0;
unsigned char *crop_buff = NULL;
/* Where we open a new file depends on the export mode */
switch (crop->exp_mode)
{
case ONE_FILE_COMPOSITE: /* Regions combined into single image */
autoindex = 0;
crop_buff = seg_buffs[0].buffer;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = total_pages;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case ONE_FILE_SEPARATED: /* Regions as separated images */
autoindex = 0;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = crop->selections * total_pages;
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
autoindex = 1;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[0].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
autoindex = 1;
page_count = crop->selections;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_SELECTION:
autoindex = 1;
page_count = 1;
for (i = 0; i < crop->selections; i++)
{
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
default: return (1);
}
return (0);
} /* end writeRegions */
static int
writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts * dump, unsigned char *src_buff,
unsigned char **sect_buff_ptr)
{
double hres, vres;
uint32 i, k, width, length, sectsize;
unsigned char *sect_buff = *sect_buff_ptr;
hres = page->hres;
vres = page->vres;
k = page->cols * page->rows;
if ((k < 1) || (k > MAX_SECTIONS))
{
TIFFError("writeImageSections",
"%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k);
return (-1);
}
for (i = 0; i < k; i++)
{
width = sections[i].x2 - sections[i].x1 + 1;
length = sections[i].y2 - sections[i].y1 + 1;
sectsize = (uint32)
ceil((width * image->bps * image->spp + 7) / (double)8) * length;
/* allocate a buffer if we don't have one already */
if (createImageSection(sectsize, sect_buff_ptr))
{
TIFFError("writeImageSections", "Unable to allocate section buffer");
exit(EXIT_FAILURE);
}
sect_buff = *sect_buff_ptr;
if (extractImageSection (image, §ions[i], src_buff, sect_buff))
{
TIFFError("writeImageSections", "Unable to extract image sections");
exit(EXIT_FAILURE);
}
/* call the write routine here instead of outside the loop */
if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff))
{
TIFFError("writeImageSections", "Unable to write image section");
exit(EXIT_FAILURE);
}
}
return (0);
} /* end writeImageSections */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
*/
static int
writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
double hres, double vres,
unsigned char *sect_buff)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
/* Calling this seems to reset the compression mode on the TIFF *in file.
TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
*/
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
/* This is the global variable compression which is set
* if the user has specified a command line option for
* a compression option. Should be passed around in one
* of the parameters instead of as a global. If no user
* option specified it will still be (uint16) -1. */
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{ /* OJPEG is no longer supported for writing so upgrade to JPEG */
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else /* Use the compression from the input file */
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
{
TIFFError ("writeSingleSection",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input photometric: %s",
(input_photometric == PHOTOMETRIC_RGB) ? "RGB" :
((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr"));
#endif
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeSingleSection",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
/* These are references to GLOBAL variables set by defaults
* and /or the compression flag
*/
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeSingleSection",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = (int)strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += ((int)strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Update these since they are overwritten from input res by loop above */
TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigTiles (out, sect_buff, length, width, spp, dump);
else
writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump);
}
else
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigStrips (out, sect_buff, length);
else
writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump);
}
if (!TIFFWriteDirectory(out))
{
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeSingleSection */
/* Create a buffer to write one section at a time */
static int
createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr)
{
unsigned char *sect_buff = NULL;
unsigned char *new_buff = NULL;
static uint32 prev_sectsize = 0;
sect_buff = *sect_buff_ptr;
if (!sect_buff)
{
sect_buff = (unsigned char *)limitMalloc(sectsize + NUM_BUFF_OVERSIZE_BYTES);
if (!sect_buff)
{
TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
return (-1);
}
_TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
{
if (prev_sectsize < sectsize)
{
new_buff = _TIFFrealloc(sect_buff, sectsize + NUM_BUFF_OVERSIZE_BYTES);
if (!new_buff)
{
_TIFFfree (sect_buff);
sect_buff = (unsigned char *)limitMalloc(sectsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
sect_buff = new_buff;
if (!sect_buff)
{
TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
return (-1);
}
_TIFFmemset(sect_buff, 0, sectsize + NUM_BUFF_OVERSIZE_BYTES);
}
}
prev_sectsize = sectsize;
*sect_buff_ptr = sect_buff;
return (0);
} /* end createImageSection */
/* Process selections defined by regions, zones, margins, or fixed sized areas */
static int
processCropSelections(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, struct buffinfo seg_buffs[])
{
int i;
uint32 width, length, total_width, total_length;
tsize_t cropsize;
unsigned char *crop_buff = NULL;
unsigned char *read_buff = NULL;
unsigned char *next_buff = NULL;
tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
if (crop->img_mode == COMPOSITE_IMAGES)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[0].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
else
{
prev_cropsize = seg_buffs[1].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = cropsize;
/* Checks for matching width or length as required */
if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
return (1);
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for composite regions");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
/* Mirror and Rotate will not work with multiple regions unless they are the same width */
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror composite regions %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, &crop_buff, FALSE))
{
TIFFError("processCropSelections",
"Failed to rotate composite regions by %d degrees", crop->rotation);
return (-1);
}
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8)
* image->spp) * crop->combined_length;
}
}
else /* Separated Images */
{
total_width = total_length = 0;
for (i = 0; i < crop->selections; i++)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[i].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = cropsize;
if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
{
TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i);
return (-1);
}
width = crop->regionlist[i].width;
length = crop->regionlist[i].length;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
width, length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for region");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
width, length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror crop region %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->regionlist[i].width,
&crop->regionlist[i].length, &crop_buff, FALSE))
{
TIFFError("processCropSelections",
"Failed to rotate crop region by %d degrees", crop->rotation);
return (-1);
}
total_width += crop->regionlist[i].width;
total_length += crop->regionlist[i].length;
crop->combined_width = total_width;
crop->combined_length = total_length;
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8)
* image->spp) * crop->regionlist[i].length;
}
}
}
return (0);
} /* end processCropSelections */
/* Copy the crop section of the data from the current image into a buffer
* and adjust the IFD values to reflect the new size. If no cropping is
* required, use the origial read buffer as the crop buffer.
*
* There is quite a bit of redundancy between this routine and the more
* specialized processCropSelections, but this provides
* the most optimized path when no Zones or Regions are required.
*/
static int
createCroppedImage(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr)
{
tsize_t cropsize;
unsigned char *read_buff = NULL;
unsigned char *crop_buff = NULL;
unsigned char *new_buff = NULL;
static tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
/* Memory is freed before crop_buff_ptr is overwritten */
if (*crop_buff_ptr != NULL)
{
_TIFFfree(*crop_buff_ptr);
}
/* process full image, no crop buffer needed */
*crop_buff_ptr = read_buff;
crop->combined_width = image->width;
crop->combined_length = image->length;
cropsize = crop->bufftotal;
crop_buff = *crop_buff_ptr;
if (!crop_buff)
{
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
if (!crop_buff)
{
TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
prev_cropsize = cropsize;
}
else
{
if (prev_cropsize < cropsize)
{
new_buff = _TIFFrealloc(crop_buff, cropsize + NUM_BUFF_OVERSIZE_BYTES);
if (!new_buff)
{
free (crop_buff);
crop_buff = (unsigned char *)limitMalloc(cropsize + NUM_BUFF_OVERSIZE_BYTES);
}
else
crop_buff = new_buff;
if (!crop_buff)
{
TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize + NUM_BUFF_OVERSIZE_BYTES);
}
}
*crop_buff_ptr = crop_buff;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage",
"Failed to invert colorspace for image or cropped selection");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, crop_buff_ptr, TRUE))
{
TIFFError("createCroppedImage",
"Failed to rotate image or cropped selection by %d degrees", crop->rotation);
return (-1);
}
}
if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */
*read_buff_ptr = NULL; /* so we don't try to free it later */
return (0);
} /* end createCroppedImage */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
* Use of global variables for config, compression and others
* should be replaced by addition to the crop_mask struct (which
* will be renamed to proc_opts indicating that is controls
* user supplied processing options, not just cropping) and
* then passed in as an argument.
*/
static int
writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
unsigned char *crop_buff, int pagenum, int total_pages)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeCroppedImage", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
{
TIFFError ("writeCroppedImage",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
{
if (input_compression == COMPRESSION_SGILOG ||
input_compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
}
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeCroppedImage",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeCroppedImage",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (bps != 1)
{
TIFFError("writeCroppedImage",
"Group 3/4 compression is not usable with bps > 1");
return (-1);
}
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
case COMPRESSION_NONE:
break;
default: break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = (int)strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += ((int)strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write contiguous tile data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate tile data for page %d", pagenum);
}
}
else
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigStrips (out, crop_buff, length))
TIFFError("","Unable to write contiguous strip data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate strip data for page %d", pagenum);
}
}
if (!TIFFWriteDirectory(out))
{
TIFFError("","Failed to write IFD for page number %d", pagenum);
return (-1);
}
return (0);
} /* end writeCroppedImage */
static int
rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 src_byte = 0, src_bit = 0;
uint32 row, rowsize = 0, bit_offset = 0;
uint8 matchbits = 0, maskbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples8bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length ; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*next) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end rotateContigSamples8bits */
static int
rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint16 matchbits = 0, maskbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples16bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 8) | next[1];
else
buff1 = (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end rotateContigSamples16bits */
static int
rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 matchbits = 0, maskbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint32)-1 >> (32 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
else
buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples24bits */
static int
rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 row, rowsize, bit_offset;
uint32 src_byte, src_bit;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint64)-1 >> (64 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples32bits */
/* Rotate an image by a multiple of 90 degrees clockwise */
static int
rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width,
uint32 *img_length, unsigned char **ibuff_ptr, int rot_image_params)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, src_offset, dst_offset;
uint32 i, col, width, length;
uint32 colsize, buffsize, col_offset, pix_offset;
unsigned char *ibuff;
unsigned char *src;
unsigned char *dst;
uint16 spp, bps;
float res_temp;
unsigned char *rbuff = NULL;
width = *img_width;
length = *img_length;
spp = image->spp;
bps = image->bps;
rowsize = ((bps * spp * width) + 7) / 8;
colsize = ((bps * spp * length) + 7) / 8;
if ((colsize * width) > (rowsize * length))
buffsize = (colsize + 1) * width;
else
buffsize = (rowsize + 1) * length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (rotation)
{
case 0:
case 360: return (0);
case 90:
case 180:
case 270: break;
default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation);
return (-1);
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if (!(rbuff = (unsigned char *)limitMalloc(buffsize + NUM_BUFF_OVERSIZE_BYTES)))
{
TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize + NUM_BUFF_OVERSIZE_BYTES);
return (-1);
}
_TIFFmemset(rbuff, '\0', buffsize + NUM_BUFF_OVERSIZE_BYTES);
ibuff = *ibuff_ptr;
switch (rotation)
{
case 180: if ((bps % 8) == 0) /* byte aligned data */
{
src = ibuff;
pix_offset = (spp * bps) / 8;
for (row = 0; row < length; row++)
{
dst_offset = (length - row - 1) * rowsize;
for (col = 0; col < width; col++)
{
col_offset = (width - col - 1) * pix_offset;
dst = rbuff + dst_offset + col_offset;
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *src++;
}
}
}
else
{ /* non 8 bit per sample data */
for (row = 0; row < length; row++)
{
src_offset = row * rowsize;
dst_offset = (length - row - 1) * rowsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (reverseSamples8bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (reverseSamples16bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
break;
case 90: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel);
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src -= rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = (length - 1) * rowsize;
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
/* Only toggle image parameters if whole input image is rotated. */
if (rot_image_params)
{
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
}
break;
case 270: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = col * bytes_per_pixel;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src += rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = 0;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
/* Only toggle image parameters if whole input image is rotated. */
if (rot_image_params)
{
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
}
break;
default:
break;
}
return (0);
} /* end rotateImage */
static int
reverseSamples8bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte, src_bit;
uint32 bit_offset = 0;
uint8 match_bits = 0, mask_bits = 0;
uint8 buff1 = 0, buff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples8bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint8)-1 >> ( 8 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (8 - src_bit - bps);
buff1 = ((*src) & match_bits) << (src_bit);
if (ready_bits < 8)
buff2 = (buff2 | (buff1 >> ready_bits));
else /* If we have a full buffer's worth, write it out */
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end reverseSamples8bits */
static int
reverseSamples16bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint16 match_bits = 0, mask_bits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSample16bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint16)-1 >> (16 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (16 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 8)
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end reverseSamples16bits */
static int
reverseSamples24bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint32 match_bits = 0, mask_bits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples24bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint32)-1 >> (32 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (32 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 16)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end reverseSamples24bits */
static int
reverseSamples32bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 bit_offset;
uint32 src_byte = 0, high_bit = 0;
uint32 col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 mask_bits = 0, match_bits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples32bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint64)-1 >> (64 - bps);
dst = obuff;
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (64 - high_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & match_bits) << (high_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (uint8_t)(buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (uint8_t)(buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (uint8_t)(buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (uint8_t)(buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end reverseSamples32bits */
static int
reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
/* Mirror an image horizontally or vertically */
static int
mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, row_offset;
unsigned char *line_buff = NULL;
unsigned char *src;
unsigned char *dst;
src = ibuff;
rowsize = ((width * bps * spp) + 7) / 8;
switch (mirror)
{
case MIRROR_BOTH:
case MIRROR_VERT:
line_buff = (unsigned char *)limitMalloc(rowsize + NUM_BUFF_OVERSIZE_BYTES);
if (line_buff == NULL)
{
TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize + NUM_BUFF_OVERSIZE_BYTES);
return (-1);
}
_TIFFmemset(line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
dst = ibuff + (rowsize * (length - 1));
for (row = 0; row < length / 2; row++)
{
_TIFFmemcpy(line_buff, src, rowsize);
_TIFFmemcpy(src, dst, rowsize);
_TIFFmemcpy(dst, line_buff, rowsize);
src += (rowsize);
dst -= (rowsize);
}
if (line_buff)
_TIFFfree(line_buff);
if (mirror == MIRROR_VERT)
break;
/* Fall through */
case MIRROR_HORIZ :
if ((bps % 8) == 0) /* byte aligned data */
{
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
dst = ibuff + row_offset + rowsize;
if (reverseSamplesBytes(spp, bps, width, src, dst))
{
return (-1);
}
}
}
else
{ /* non 8 bit per sample data */
if (!(line_buff = (unsigned char *)limitMalloc(rowsize + NUM_BUFF_OVERSIZE_BYTES)))
{
TIFFError("mirrorImage", "Unable to allocate mirror line buffer");
return (-1);
}
_TIFFmemset(line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
_TIFFmemset (line_buff, '\0', rowsize + NUM_BUFF_OVERSIZE_BYTES);
switch (shift_width)
{
case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
default: TIFFError("mirrorImage","Unsupported bit depth %d", bps);
_TIFFfree(line_buff);
return (-1);
}
}
if (line_buff)
_TIFFfree(line_buff);
}
break;
default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror);
return (-1);
break;
}
return (0);
}
/* Invert the light and dark values for a bilevel or grayscale image */
static int
invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff)
{
uint32 row, col;
unsigned char *src;
uint16 *src_uint16;
uint32 *src_uint32;
if (spp != 1)
{
TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel");
return (-1);
}
if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK)
{
TIFFError("invertImage", "Only black and white and grayscale images can be inverted");
return (-1);
}
src = work_buff;
if (src == NULL)
{
TIFFError ("invertImage", "Invalid crop buffer passed to invertImage");
return (-1);
}
switch (bps)
{
case 32: src_uint32 = (uint32 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint32 = ~(*src_uint32);
src_uint32++;
}
break;
case 16: src_uint16 = (uint16 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint16 = ~(*src_uint16);
src_uint16++;
}
break;
case 8:
case 4:
case 2:
case 1: for (row = 0; row < length; row++)
for (col = 0; col < width; col += 8 / bps)
{
*src = ~(*src);
src++;
}
break;
default: TIFFError("invertImage", "Unsupported bit depth %d", bps);
return (-1);
}
return (0);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
|