DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (5350524bb654)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <cmath>
#include "DataSurfaceHelpers.h"
#include "FilterNodeSoftware.h"
#include "2D.h"
#include "Tools.h"
#include "Blur.h"
#include <map>
#include "FilterProcessing.h"
#include "Logging.h"
#include "mozilla/PodOperations.h"
#include "mozilla/DebugOnly.h"

// #define DEBUG_DUMP_SURFACES

#ifdef DEBUG_DUMP_SURFACES
#include "gfxUtils.h" // not part of Moz2D
#endif

namespace mozilla {
namespace gfx {

namespace {

/**
 * This class provides a way to get a pow() results in constant-time. It works
 * by caching 129 ((1 << sCacheIndexPrecisionBits) + 1) values for bases between
 * 0 and 1 and a fixed exponent.
 **/
class PowCache
{
public:
  PowCache()
    : mNumPowTablePreSquares(-1)
  {
  }

  void CacheForExponent(Float aExponent)
  {
    // Since we are in the world where we only care about
    // input and results in [0,1], there is no point in
    // dealing with non-positive exponents.
    if (aExponent <= 0) {
      mNumPowTablePreSquares = -1;
      return;
    }
    int numPreSquares = 0;
    while (numPreSquares < 5 && aExponent > (1 << (numPreSquares + 2))) {
      numPreSquares++;
    }
    mNumPowTablePreSquares = numPreSquares;
    for (size_t i = 0; i < sCacheSize; i++) {
      // sCacheSize is chosen in such a way that a takes values
      // from 0.0 to 1.0 inclusive.
      Float a = i / Float(1 << sCacheIndexPrecisionBits);
      MOZ_ASSERT(0.0f <= a && a <= 1.0f, "We only want to cache for bases between 0 and 1.");

      for (int j = 0; j < mNumPowTablePreSquares; j++) {
        a = sqrt(a);
      }
      uint32_t cachedInt = pow(a, aExponent) * (1 << sOutputIntPrecisionBits);
      MOZ_ASSERT(cachedInt < (1 << (sizeof(mPowTable[i]) * 8)), "mPowCache integer type too small");

      mPowTable[i] = cachedInt;
    }
  }

  // Only call Pow() if HasPowerTable() would return true, to avoid complicating
  // this code and having it just return (1 << sOutputIntPrecisionBits))
  uint16_t Pow(uint16_t aBase)
  {
    MOZ_ASSERT(HasPowerTable());
    // Results should be similar to what the following code would produce:
    // Float x = Float(aBase) / (1 << sInputIntPrecisionBits);
    // return uint16_t(pow(x, aExponent) * (1 << sOutputIntPrecisionBits));

    MOZ_ASSERT(aBase <= (1 << sInputIntPrecisionBits), "aBase needs to be between 0 and 1!");

    uint32_t a = aBase;
    for (int j = 0; j < mNumPowTablePreSquares; j++) {
      a = a * a >> sInputIntPrecisionBits;
    }
    uint32_t i = a >> (sInputIntPrecisionBits - sCacheIndexPrecisionBits);
    MOZ_ASSERT(i < sCacheSize, "out-of-bounds mPowTable access");
    return mPowTable[i];
  }

  static const int sInputIntPrecisionBits = 15;
  static const int sOutputIntPrecisionBits = 15;
  static const int sCacheIndexPrecisionBits = 7;

  inline bool HasPowerTable() const
  {
    return mNumPowTablePreSquares >= 0;
  }

private:
  static const size_t sCacheSize = (1 << sCacheIndexPrecisionBits) + 1;

  int mNumPowTablePreSquares;
  uint16_t mPowTable[sCacheSize];
};

class PointLightSoftware
{
public:
  bool SetAttribute(uint32_t aIndex, Float) { return false; }
  bool SetAttribute(uint32_t aIndex, const Point3D &);
  void Prepare() {}
  Point3D GetVectorToLight(const Point3D &aTargetPoint);
  uint32_t GetColor(uint32_t aLightColor, const Point3D &aVectorToLight);

private:
  Point3D mPosition;
};

class SpotLightSoftware
{
public:
  SpotLightSoftware();
  bool SetAttribute(uint32_t aIndex, Float);
  bool SetAttribute(uint32_t aIndex, const Point3D &);
  void Prepare();
  Point3D GetVectorToLight(const Point3D &aTargetPoint);
  uint32_t GetColor(uint32_t aLightColor, const Point3D &aVectorToLight);

private:
  Point3D mPosition;
  Point3D mPointsAt;
  Point3D mVectorFromFocusPointToLight;
  Float mSpecularFocus;
  Float mLimitingConeAngle;
  Float mLimitingConeCos;
  PowCache mPowCache;
};

class DistantLightSoftware
{
public:
  DistantLightSoftware();
  bool SetAttribute(uint32_t aIndex, Float);
  bool SetAttribute(uint32_t aIndex, const Point3D &) { return false; }
  void Prepare();
  Point3D GetVectorToLight(const Point3D &aTargetPoint);
  uint32_t GetColor(uint32_t aLightColor, const Point3D &aVectorToLight);

private:
  Float mAzimuth;
  Float mElevation;
  Point3D mVectorToLight;
};

class DiffuseLightingSoftware
{
public:
  DiffuseLightingSoftware();
  bool SetAttribute(uint32_t aIndex, Float);
  void Prepare() {}
  uint32_t LightPixel(const Point3D &aNormal, const Point3D &aVectorToLight,
                      uint32_t aColor);

private:
  Float mDiffuseConstant;
};

class SpecularLightingSoftware
{
public:
  SpecularLightingSoftware();
  bool SetAttribute(uint32_t aIndex, Float);
  void Prepare();
  uint32_t LightPixel(const Point3D &aNormal, const Point3D &aVectorToLight,
                      uint32_t aColor);

private:
  Float mSpecularConstant;
  Float mSpecularExponent;
  uint32_t mSpecularConstantInt;
  PowCache mPowCache;
};

} // unnamed namespace

// from xpcom/ds/nsMathUtils.h
static int32_t
NS_lround(double x)
{
  return x >= 0.0 ? int32_t(x + 0.5) : int32_t(x - 0.5);
}

already_AddRefed<DataSourceSurface>
CloneAligned(DataSourceSurface* aSource)
{
  return CreateDataSourceSurfaceByCloning(aSource);
}

static void
FillRectWithPixel(DataSourceSurface *aSurface, const IntRect &aFillRect, IntPoint aPixelPos)
{
  MOZ_ASSERT(!aFillRect.Overflows());
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aFillRect),
             "aFillRect needs to be completely inside the surface");
  MOZ_ASSERT(SurfaceContainsPoint(aSurface, aPixelPos),
             "aPixelPos needs to be inside the surface");

  DataSourceSurface::ScopedMap surfMap(aSurface, DataSourceSurface::READ_WRITE);
  if(MOZ2D_WARN_IF(!surfMap.IsMapped())) {
    return;
  }
  uint8_t* sourcePixelData = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aPixelPos);
  uint8_t* data = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aFillRect.TopLeft());
  int bpp = BytesPerPixel(aSurface->GetFormat());

  // Fill the first row by hand.
  if (bpp == 4) {
    uint32_t sourcePixel = *(uint32_t*)sourcePixelData;
    for (int32_t x = 0; x < aFillRect.width; x++) {
      *((uint32_t*)data + x) = sourcePixel;
    }
  } else if (BytesPerPixel(aSurface->GetFormat()) == 1) {
    uint8_t sourcePixel = *sourcePixelData;
    memset(data, sourcePixel, aFillRect.width);
  }

  // Copy the first row into the other rows.
  for (int32_t y = 1; y < aFillRect.height; y++) {
    PodCopy(data + y * surfMap.GetStride(), data, aFillRect.width * bpp);
  }
}

static void
FillRectWithVerticallyRepeatingHorizontalStrip(DataSourceSurface *aSurface,
                                               const IntRect &aFillRect,
                                               const IntRect &aSampleRect)
{
  MOZ_ASSERT(!aFillRect.Overflows());
  MOZ_ASSERT(!aSampleRect.Overflows());
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aFillRect),
             "aFillRect needs to be completely inside the surface");
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aSampleRect),
             "aSampleRect needs to be completely inside the surface");

  DataSourceSurface::ScopedMap surfMap(aSurface, DataSourceSurface::READ_WRITE);
  if (MOZ2D_WARN_IF(!surfMap.IsMapped())) {
    return;
  }

  uint8_t* sampleData = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aSampleRect.TopLeft());
  uint8_t* data = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aFillRect.TopLeft());
  if (BytesPerPixel(aSurface->GetFormat()) == 4) {
    for (int32_t y = 0; y < aFillRect.height; y++) {
      PodCopy((uint32_t*)data, (uint32_t*)sampleData, aFillRect.width);
      data += surfMap.GetStride();
    }
  } else if (BytesPerPixel(aSurface->GetFormat()) == 1) {
    for (int32_t y = 0; y < aFillRect.height; y++) {
      PodCopy(data, sampleData, aFillRect.width);
      data += surfMap.GetStride();
    }
  }
}

static void
FillRectWithHorizontallyRepeatingVerticalStrip(DataSourceSurface *aSurface,
                                               const IntRect &aFillRect,
                                               const IntRect &aSampleRect)
{
  MOZ_ASSERT(!aFillRect.Overflows());
  MOZ_ASSERT(!aSampleRect.Overflows());
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aFillRect),
             "aFillRect needs to be completely inside the surface");
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aSampleRect),
             "aSampleRect needs to be completely inside the surface");

  DataSourceSurface::ScopedMap surfMap(aSurface, DataSourceSurface::READ_WRITE);
  if (MOZ2D_WARN_IF(!surfMap.IsMapped())) {
    return;
  }

  uint8_t* sampleData = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aSampleRect.TopLeft());
  uint8_t* data = DataAtOffset(aSurface, surfMap.GetMappedSurface(), aFillRect.TopLeft());
  if (BytesPerPixel(aSurface->GetFormat()) == 4) {
    for (int32_t y = 0; y < aFillRect.height; y++) {
      int32_t sampleColor = *((uint32_t*)sampleData);
      for (int32_t x = 0; x < aFillRect.width; x++) {
        *((uint32_t*)data + x) = sampleColor;
      }
      data += surfMap.GetStride();
      sampleData += surfMap.GetStride();
    }
  } else if (BytesPerPixel(aSurface->GetFormat()) == 1) {
    for (int32_t y = 0; y < aFillRect.height; y++) {
      uint8_t sampleColor = *sampleData;
      memset(data, sampleColor, aFillRect.width);
      data += surfMap.GetStride();
      sampleData += surfMap.GetStride();
    }
  }
}

static void
DuplicateEdges(DataSourceSurface* aSurface, const IntRect &aFromRect)
{
  MOZ_ASSERT(!aFromRect.Overflows());
  MOZ_ASSERT(IntRect(IntPoint(), aSurface->GetSize()).Contains(aFromRect),
             "aFromRect needs to be completely inside the surface");

  IntSize size = aSurface->GetSize();
  IntRect fill;
  IntRect sampleRect;
  for (int32_t ix = 0; ix < 3; ix++) {
    switch (ix) {
      case 0:
        fill.x = 0;
        fill.width = aFromRect.x;
        sampleRect.x = fill.XMost();
        sampleRect.width = 1;
        break;
      case 1:
        fill.x = aFromRect.x;
        fill.width = aFromRect.width;
        sampleRect.x = fill.x;
        sampleRect.width = fill.width;
        break;
      case 2:
        fill.x = aFromRect.XMost();
        fill.width = size.width - fill.x;
        sampleRect.x = fill.x - 1;
        sampleRect.width = 1;
        break;
    }
    if (fill.width <= 0) {
      continue;
    }
    bool xIsMiddle = (ix == 1);
    for (int32_t iy = 0; iy < 3; iy++) {
      switch (iy) {
        case 0:
          fill.y = 0;
          fill.height = aFromRect.y;
          sampleRect.y = fill.YMost();
          sampleRect.height = 1;
          break;
        case 1:
          fill.y = aFromRect.y;
          fill.height = aFromRect.height;
          sampleRect.y = fill.y;
          sampleRect.height = fill.height;
          break;
        case 2:
          fill.y = aFromRect.YMost();
          fill.height = size.height - fill.y;
          sampleRect.y = fill.y - 1;
          sampleRect.height = 1;
          break;
      }
      if (fill.height <= 0) {
        continue;
      }
      bool yIsMiddle = (iy == 1);
      if (!xIsMiddle && !yIsMiddle) {
        // Corner
        FillRectWithPixel(aSurface, fill, sampleRect.TopLeft());
      }
      if (xIsMiddle && !yIsMiddle) {
        // Top middle or bottom middle
        FillRectWithVerticallyRepeatingHorizontalStrip(aSurface, fill, sampleRect);
      }
      if (!xIsMiddle && yIsMiddle) {
        // Left middle or right middle
        FillRectWithHorizontallyRepeatingVerticalStrip(aSurface, fill, sampleRect);
      }
    }
  }
}

static IntPoint
TileIndex(const IntRect &aFirstTileRect, const IntPoint &aPoint)
{
  return IntPoint(int32_t(floor(double(aPoint.x - aFirstTileRect.x) / aFirstTileRect.width)),
                  int32_t(floor(double(aPoint.y - aFirstTileRect.y) / aFirstTileRect.height)));
}

static void
TileSurface(DataSourceSurface* aSource, DataSourceSurface* aTarget, const IntPoint &aOffset)
{
  IntRect sourceRect(aOffset, aSource->GetSize());
  IntRect targetRect(IntPoint(0, 0), aTarget->GetSize());
  IntPoint startIndex = TileIndex(sourceRect, targetRect.TopLeft());
  IntPoint endIndex = TileIndex(sourceRect, targetRect.BottomRight());

  for (int32_t ix = startIndex.x; ix <= endIndex.x; ix++) {
    for (int32_t iy = startIndex.y; iy <= endIndex.y; iy++) {
      IntPoint destPoint(sourceRect.x + ix * sourceRect.width,
                         sourceRect.y + iy * sourceRect.height);
      IntRect destRect(destPoint, sourceRect.Size());
      destRect = destRect.Intersect(targetRect);
      IntRect srcRect = destRect - destPoint;
      CopyRect(aSource, aTarget, srcRect, destRect.TopLeft());
    }
  }
}

static already_AddRefed<DataSourceSurface>
GetDataSurfaceInRect(SourceSurface *aSurface,
                     const IntRect &aSurfaceRect,
                     const IntRect &aDestRect,
                     ConvolveMatrixEdgeMode aEdgeMode)
{
  MOZ_ASSERT(aSurface ? aSurfaceRect.Size() == aSurface->GetSize() : aSurfaceRect.IsEmpty());

  if (aSurfaceRect.Overflows() || aDestRect.Overflows()) {
    // We can't rely on the intersection calculations below to make sense when
    // XMost() or YMost() overflow. Bail out.
    return nullptr;
  }

  IntRect sourceRect = aSurfaceRect;

  if (sourceRect.IsEqualEdges(aDestRect)) {
    return aSurface ? aSurface->GetDataSurface() : nullptr;
  }

  IntRect intersect = sourceRect.Intersect(aDestRect);
  IntRect intersectInSourceSpace = intersect - sourceRect.TopLeft();
  IntRect intersectInDestSpace = intersect - aDestRect.TopLeft();
  SurfaceFormat format = aSurface ? aSurface->GetFormat() : SurfaceFormat(SurfaceFormat::B8G8R8A8);

  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(aDestRect.Size(), format, true);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  if (!aSurface) {
    return target.forget();
  }

  RefPtr<DataSourceSurface> dataSource = aSurface->GetDataSurface();
  MOZ_ASSERT(dataSource);

  if (aEdgeMode == EDGE_MODE_WRAP) {
    TileSurface(dataSource, target, intersectInDestSpace.TopLeft());
    return target.forget();
  }

  CopyRect(dataSource, target, intersectInSourceSpace,
           intersectInDestSpace.TopLeft());

  if (aEdgeMode == EDGE_MODE_DUPLICATE) {
    DuplicateEdges(target, intersectInDestSpace);
  }

  return target.forget();
}

/* static */ already_AddRefed<FilterNode>
FilterNodeSoftware::Create(FilterType aType)
{
  RefPtr<FilterNodeSoftware> filter;
  switch (aType) {
    case FilterType::BLEND:
      filter = new FilterNodeBlendSoftware();
      break;
    case FilterType::TRANSFORM:
      filter = new FilterNodeTransformSoftware();
      break;
    case FilterType::MORPHOLOGY:
      filter = new FilterNodeMorphologySoftware();
      break;
    case FilterType::COLOR_MATRIX:
      filter = new FilterNodeColorMatrixSoftware();
      break;
    case FilterType::FLOOD:
      filter = new FilterNodeFloodSoftware();
      break;
    case FilterType::TILE:
      filter = new FilterNodeTileSoftware();
      break;
    case FilterType::TABLE_TRANSFER:
      filter = new FilterNodeTableTransferSoftware();
      break;
    case FilterType::DISCRETE_TRANSFER:
      filter = new FilterNodeDiscreteTransferSoftware();
      break;
    case FilterType::LINEAR_TRANSFER:
      filter = new FilterNodeLinearTransferSoftware();
      break;
    case FilterType::GAMMA_TRANSFER:
      filter = new FilterNodeGammaTransferSoftware();
      break;
    case FilterType::CONVOLVE_MATRIX:
      filter = new FilterNodeConvolveMatrixSoftware();
      break;
    case FilterType::DISPLACEMENT_MAP:
      filter = new FilterNodeDisplacementMapSoftware();
      break;
    case FilterType::TURBULENCE:
      filter = new FilterNodeTurbulenceSoftware();
      break;
    case FilterType::ARITHMETIC_COMBINE:
      filter = new FilterNodeArithmeticCombineSoftware();
      break;
    case FilterType::COMPOSITE:
      filter = new FilterNodeCompositeSoftware();
      break;
    case FilterType::GAUSSIAN_BLUR:
      filter = new FilterNodeGaussianBlurSoftware();
      break;
    case FilterType::DIRECTIONAL_BLUR:
      filter = new FilterNodeDirectionalBlurSoftware();
      break;
    case FilterType::CROP:
      filter = new FilterNodeCropSoftware();
      break;
    case FilterType::PREMULTIPLY:
      filter = new FilterNodePremultiplySoftware();
      break;
    case FilterType::UNPREMULTIPLY:
      filter = new FilterNodeUnpremultiplySoftware();
      break;
    case FilterType::POINT_DIFFUSE:
      filter = new FilterNodeLightingSoftware<PointLightSoftware, DiffuseLightingSoftware>("FilterNodeLightingSoftware<PointLight, DiffuseLighting>");
      break;
    case FilterType::POINT_SPECULAR:
      filter = new FilterNodeLightingSoftware<PointLightSoftware, SpecularLightingSoftware>("FilterNodeLightingSoftware<PointLight, SpecularLighting>");
      break;
    case FilterType::SPOT_DIFFUSE:
      filter = new FilterNodeLightingSoftware<SpotLightSoftware, DiffuseLightingSoftware>("FilterNodeLightingSoftware<SpotLight, DiffuseLighting>");
      break;
    case FilterType::SPOT_SPECULAR:
      filter = new FilterNodeLightingSoftware<SpotLightSoftware, SpecularLightingSoftware>("FilterNodeLightingSoftware<SpotLight, SpecularLighting>");
      break;
    case FilterType::DISTANT_DIFFUSE:
      filter = new FilterNodeLightingSoftware<DistantLightSoftware, DiffuseLightingSoftware>("FilterNodeLightingSoftware<DistantLight, DiffuseLighting>");
      break;
    case FilterType::DISTANT_SPECULAR:
      filter = new FilterNodeLightingSoftware<DistantLightSoftware, SpecularLightingSoftware>("FilterNodeLightingSoftware<DistantLight, SpecularLighting>");
      break;
  }
  return filter.forget();
}

void
FilterNodeSoftware::Draw(DrawTarget* aDrawTarget,
                         const Rect &aSourceRect,
                         const Point &aDestPoint,
                         const DrawOptions &aOptions)
{
#ifdef DEBUG_DUMP_SURFACES
  printf("<style>section{margin:10px;}</style><pre>\nRendering filter %s...\n", GetName());
#endif

  Rect renderRect = aSourceRect;
  renderRect.RoundOut();
  IntRect renderIntRect;
  if (!renderRect.ToIntRect(&renderIntRect)) {
#ifdef DEBUG_DUMP_SURFACES
    printf("render rect overflowed, not painting anything\n");
    printf("</pre>\n");
#endif
    return;
  }

  IntRect outputRect = GetOutputRectInRect(renderIntRect);
  if (outputRect.Overflows()) {
#ifdef DEBUG_DUMP_SURFACES
    printf("output rect overflowed, not painting anything\n");
    printf("</pre>\n");
#endif
    return;
  }

  RefPtr<DataSourceSurface> result;
  if (!outputRect.IsEmpty()) {
    result = GetOutput(outputRect);
  }

  if (!result) {
    // Null results are allowed and treated as transparent. Don't draw anything.
#ifdef DEBUG_DUMP_SURFACES
    printf("output returned null\n");
    printf("</pre>\n");
#endif
    return;
  }

#ifdef DEBUG_DUMP_SURFACES
  printf("output from %s:\n", GetName());
  printf("<img src='"); gfxUtils::DumpAsDataURL(result); printf("'>\n");
  printf("</pre>\n");
#endif

  Point sourceToDestOffset = aDestPoint - aSourceRect.TopLeft();
  Rect renderedSourceRect = Rect(outputRect).Intersect(aSourceRect);
  Rect renderedDestRect = renderedSourceRect + sourceToDestOffset;
  if (result->GetFormat() == SurfaceFormat::A8) {
    // Interpret the result as having implicitly black color channels.
    aDrawTarget->PushClipRect(renderedDestRect);
    aDrawTarget->MaskSurface(ColorPattern(Color(0.0, 0.0, 0.0, 1.0)),
                             result,
                             Point(outputRect.TopLeft()) + sourceToDestOffset,
                             aOptions);
    aDrawTarget->PopClip();
  } else {
    aDrawTarget->DrawSurface(result, renderedDestRect,
                             renderedSourceRect - Point(outputRect.TopLeft()),
                             DrawSurfaceOptions(), aOptions);
  }
}

already_AddRefed<DataSourceSurface>
FilterNodeSoftware::GetOutput(const IntRect &aRect)
{
  MOZ_ASSERT(GetOutputRectInRect(aRect).Contains(aRect));

  if (aRect.Overflows()) {
    return nullptr;
  }

  if (!mCachedRect.Contains(aRect)) {
    RequestRect(aRect);
    mCachedOutput = Render(mRequestedRect);
    if (!mCachedOutput) {
      mCachedRect = IntRect();
      mRequestedRect = IntRect();
      return nullptr;
    }
    mCachedRect = mRequestedRect;
    mRequestedRect = IntRect();
  } else {
    MOZ_ASSERT(mCachedOutput, "cached rect but no cached output?");
  }
  return GetDataSurfaceInRect(mCachedOutput, mCachedRect, aRect, EDGE_MODE_NONE);
}

void
FilterNodeSoftware::RequestRect(const IntRect &aRect)
{
  if (mRequestedRect.Contains(aRect)) {
    // Bail out now. Otherwise pathological filters can spend time exponential
    // in the number of primitives, e.g. if each primitive takes the
    // previous primitive as its two inputs.
    return;
  }
  mRequestedRect = mRequestedRect.Union(aRect);
  RequestFromInputsForRect(aRect);
}

void
FilterNodeSoftware::RequestInputRect(uint32_t aInputEnumIndex, const IntRect &aRect)
{
  if (aRect.Overflows()) {
    return;
  }

  int32_t inputIndex = InputIndex(aInputEnumIndex);
  if (inputIndex < 0 || (uint32_t)inputIndex >= NumberOfSetInputs()) {
    gfxDevCrash(LogReason::FilterInputError) << "Invalid input " << inputIndex << " vs. " << NumberOfSetInputs();
    return;
  }
  if (mInputSurfaces[inputIndex]) {
    return;
  }
  RefPtr<FilterNodeSoftware> filter = mInputFilters[inputIndex];
  MOZ_ASSERT(filter, "missing input");
  filter->RequestRect(filter->GetOutputRectInRect(aRect));
}

SurfaceFormat
FilterNodeSoftware::DesiredFormat(SurfaceFormat aCurrentFormat,
                                  FormatHint aFormatHint)
{
  if (aCurrentFormat == SurfaceFormat::A8 && aFormatHint == CAN_HANDLE_A8) {
    return SurfaceFormat::A8;
  }
  return SurfaceFormat::B8G8R8A8;
}

already_AddRefed<DataSourceSurface>
FilterNodeSoftware::GetInputDataSourceSurface(uint32_t aInputEnumIndex,
                                              const IntRect& aRect,
                                              FormatHint aFormatHint,
                                              ConvolveMatrixEdgeMode aEdgeMode,
                                              const IntRect *aTransparencyPaddedSourceRect)
{
  if (aRect.Overflows()) {
    return nullptr;
  }

#ifdef DEBUG_DUMP_SURFACES
  printf("<section><h1>GetInputDataSourceSurface with aRect: %d, %d, %d, %d</h1>\n",
         aRect.x, aRect.y, aRect.width, aRect.height);
#endif
  int32_t inputIndex = InputIndex(aInputEnumIndex);
  if (inputIndex < 0 || (uint32_t)inputIndex >= NumberOfSetInputs()) {
    gfxDevCrash(LogReason::FilterInputData) << "Invalid data " << inputIndex << " vs. " << NumberOfSetInputs();
    return nullptr;
  }

  if (aRect.IsEmpty()) {
    return nullptr;
  }

  RefPtr<SourceSurface> surface;
  IntRect surfaceRect;

  if (mInputSurfaces[inputIndex]) {
    // Input from input surface
    surface = mInputSurfaces[inputIndex];
#ifdef DEBUG_DUMP_SURFACES
    printf("input from input surface:\n");
#endif
    surfaceRect = IntRect(IntPoint(0, 0), surface->GetSize());
  } else {
    // Input from input filter
#ifdef DEBUG_DUMP_SURFACES
    printf("getting input from input filter %s...\n", mInputFilters[inputIndex]->GetName());
#endif
    RefPtr<FilterNodeSoftware> filter = mInputFilters[inputIndex];
    MOZ_ASSERT(filter, "missing input");
    IntRect inputFilterOutput = filter->GetOutputRectInRect(aRect);
    if (!inputFilterOutput.IsEmpty()) {
      surface = filter->GetOutput(inputFilterOutput);
    }
#ifdef DEBUG_DUMP_SURFACES
    printf("input from input filter %s:\n", mInputFilters[inputIndex]->GetName());
#endif
    surfaceRect = inputFilterOutput;
    MOZ_ASSERT(!surface || surfaceRect.Size() == surface->GetSize());
  }

  if (surface && surface->GetFormat() == SurfaceFormat::UNKNOWN) {
#ifdef DEBUG_DUMP_SURFACES
    printf("wrong input format</section>\n\n");
#endif
    return nullptr;
  }

  if (!surfaceRect.IsEmpty() && !surface) {
#ifdef DEBUG_DUMP_SURFACES
    printf(" -- no input --</section>\n\n");
#endif
    return nullptr;
  }

  if (aTransparencyPaddedSourceRect && !aTransparencyPaddedSourceRect->IsEmpty()) {
    IntRect srcRect = aTransparencyPaddedSourceRect->Intersect(aRect);
    surface = GetDataSurfaceInRect(surface, surfaceRect, srcRect, EDGE_MODE_NONE);
    surfaceRect = srcRect;
  }

  RefPtr<DataSourceSurface> result =
    GetDataSurfaceInRect(surface, surfaceRect, aRect, aEdgeMode);

  if (result) {
    // TODO: This isn't safe since we don't have a guarantee
    // that future Maps will have the same stride
    DataSourceSurface::MappedSurface map;
    if (result->Map(DataSourceSurface::READ, &map)) {
       // Unmap immediately since CloneAligned hasn't been updated
       // to use the Map API yet. We can still read the stride/data
       // values as long as we don't try to dereference them.
      result->Unmap();
      if (map.mStride != GetAlignedStride<16>(map.mStride, 1) ||
          reinterpret_cast<uintptr_t>(map.mData) % 16 != 0) {
        // Align unaligned surface.
        result = CloneAligned(result);
      }
    } else {
      result = nullptr;
    }
  }


  if (!result) {
#ifdef DEBUG_DUMP_SURFACES
    printf(" -- no input --</section>\n\n");
#endif
    return nullptr;
  }

  SurfaceFormat currentFormat = result->GetFormat();
  if (DesiredFormat(currentFormat, aFormatHint) == SurfaceFormat::B8G8R8A8 &&
      currentFormat != SurfaceFormat::B8G8R8A8) {
    result = FilterProcessing::ConvertToB8G8R8A8(result);
  }

#ifdef DEBUG_DUMP_SURFACES
  printf("<img src='"); gfxUtils::DumpAsDataURL(result); printf("'></section>");
#endif

  MOZ_ASSERT(!result || result->GetSize() == aRect.Size(), "wrong surface size");

  return result.forget();
}

IntRect
FilterNodeSoftware::GetInputRectInRect(uint32_t aInputEnumIndex,
                                       const IntRect &aInRect)
{
  if (aInRect.Overflows()) {
    return IntRect();
  }

  int32_t inputIndex = InputIndex(aInputEnumIndex);
  if (inputIndex < 0 || (uint32_t)inputIndex >= NumberOfSetInputs()) {
    gfxDevCrash(LogReason::FilterInputRect) << "Invalid rect " << inputIndex << " vs. " << NumberOfSetInputs();
    return IntRect();
  }
  if (mInputSurfaces[inputIndex]) {
    return aInRect.Intersect(IntRect(IntPoint(0, 0),
                                     mInputSurfaces[inputIndex]->GetSize()));
  }
  RefPtr<FilterNodeSoftware> filter = mInputFilters[inputIndex];
  MOZ_ASSERT(filter, "missing input");
  return filter->GetOutputRectInRect(aInRect);
}

size_t
FilterNodeSoftware::NumberOfSetInputs()
{
  return std::max(mInputSurfaces.size(), mInputFilters.size());
}

void
FilterNodeSoftware::AddInvalidationListener(FilterInvalidationListener* aListener)
{
  MOZ_ASSERT(aListener, "null listener");
  mInvalidationListeners.push_back(aListener);
}

void
FilterNodeSoftware::RemoveInvalidationListener(FilterInvalidationListener* aListener)
{
  MOZ_ASSERT(aListener, "null listener");
  std::vector<FilterInvalidationListener*>::iterator it =
    std::find(mInvalidationListeners.begin(), mInvalidationListeners.end(), aListener);
  mInvalidationListeners.erase(it);
}

void
FilterNodeSoftware::FilterInvalidated(FilterNodeSoftware* aFilter)
{
  Invalidate();
}

void
FilterNodeSoftware::Invalidate()
{
  mCachedOutput = nullptr;
  mCachedRect = IntRect();
  for (std::vector<FilterInvalidationListener*>::iterator it = mInvalidationListeners.begin();
       it != mInvalidationListeners.end(); it++) {
    (*it)->FilterInvalidated(this);
  }
}

FilterNodeSoftware::~FilterNodeSoftware()
{
  MOZ_ASSERT(!mInvalidationListeners.size(),
             "All invalidation listeners should have unsubscribed themselves by now!");

  for (std::vector<RefPtr<FilterNodeSoftware> >::iterator it = mInputFilters.begin();
       it != mInputFilters.end(); it++) {
    if (*it) {
      (*it)->RemoveInvalidationListener(this);
    }
  }
}

void
FilterNodeSoftware::SetInput(uint32_t aIndex, FilterNode *aFilter)
{
  if (aFilter && aFilter->GetBackendType() != FILTER_BACKEND_SOFTWARE) {
    MOZ_ASSERT(false, "can only take software filters as inputs");
    return;
  }
  SetInput(aIndex, nullptr, static_cast<FilterNodeSoftware*>(aFilter));
}

void
FilterNodeSoftware::SetInput(uint32_t aIndex, SourceSurface *aSurface)
{
  SetInput(aIndex, aSurface, nullptr);
}

void
FilterNodeSoftware::SetInput(uint32_t aInputEnumIndex,
                             SourceSurface *aSurface,
                             FilterNodeSoftware *aFilter)
{
  int32_t inputIndex = InputIndex(aInputEnumIndex);
  if (inputIndex < 0) {
    gfxDevCrash(LogReason::FilterInputSet) << "Invalid set " << inputIndex;
    return;
  }
  if ((uint32_t)inputIndex >= NumberOfSetInputs()) {
    mInputSurfaces.resize(inputIndex + 1);
    mInputFilters.resize(inputIndex + 1);
  }
  mInputSurfaces[inputIndex] = aSurface;
  if (mInputFilters[inputIndex]) {
    mInputFilters[inputIndex]->RemoveInvalidationListener(this);
  }
  if (aFilter) {
    aFilter->AddInvalidationListener(this);
  }
  mInputFilters[inputIndex] = aFilter;
  if (!aSurface && !aFilter && (size_t)inputIndex == NumberOfSetInputs()) {
    mInputSurfaces.resize(inputIndex);
    mInputFilters.resize(inputIndex);
  }
  Invalidate();
}

FilterNodeBlendSoftware::FilterNodeBlendSoftware()
 : mBlendMode(BLEND_MODE_MULTIPLY)
{}

int32_t
FilterNodeBlendSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_BLEND_IN: return 0;
    case IN_BLEND_IN2: return 1;
    default: return -1;
  }
}

void
FilterNodeBlendSoftware::SetAttribute(uint32_t aIndex, uint32_t aBlendMode)
{
  MOZ_ASSERT(aIndex == ATT_BLEND_BLENDMODE);
  mBlendMode = static_cast<BlendMode>(aBlendMode);
  Invalidate();
}

static CompositionOp ToBlendOp(BlendMode aOp)
{
  switch (aOp) {
  case BLEND_MODE_MULTIPLY:
    return CompositionOp::OP_MULTIPLY;
  case BLEND_MODE_SCREEN:
    return CompositionOp::OP_SCREEN;
  case BLEND_MODE_OVERLAY:
    return CompositionOp::OP_OVERLAY;
  case BLEND_MODE_DARKEN:
    return CompositionOp::OP_DARKEN;
  case BLEND_MODE_LIGHTEN:
    return CompositionOp::OP_LIGHTEN;
  case BLEND_MODE_COLOR_DODGE:
    return CompositionOp::OP_COLOR_DODGE;
  case BLEND_MODE_COLOR_BURN:
    return CompositionOp::OP_COLOR_BURN;
  case BLEND_MODE_HARD_LIGHT:
    return CompositionOp::OP_HARD_LIGHT;
  case BLEND_MODE_SOFT_LIGHT:
    return CompositionOp::OP_SOFT_LIGHT;
  case BLEND_MODE_DIFFERENCE:
    return CompositionOp::OP_DIFFERENCE;
  case BLEND_MODE_EXCLUSION:
    return CompositionOp::OP_EXCLUSION;
  case BLEND_MODE_HUE:
    return CompositionOp::OP_HUE;
  case BLEND_MODE_SATURATION:
    return CompositionOp::OP_SATURATION;
  case BLEND_MODE_COLOR:
    return CompositionOp::OP_COLOR;
  case BLEND_MODE_LUMINOSITY:
    return CompositionOp::OP_LUMINOSITY;
  default:
    return CompositionOp::OP_OVER;
  }

  return CompositionOp::OP_OVER;
}

already_AddRefed<DataSourceSurface>
FilterNodeBlendSoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> input1 =
    GetInputDataSourceSurface(IN_BLEND_IN, aRect, NEED_COLOR_CHANNELS);
  RefPtr<DataSourceSurface> input2 =
    GetInputDataSourceSurface(IN_BLEND_IN2, aRect, NEED_COLOR_CHANNELS);

  // Null inputs need to be treated as transparent.

  // First case: both are transparent.
  if (!input1 && !input2) {
    // Then the result is transparent, too.
    return nullptr;
  }

  // Second case: one of them is transparent. Return the non-transparent one.
  if (!input1 || !input2) {
    return input1 ? input1.forget() : input2.forget();
  }

  // Third case: both are non-transparent.
  // Apply normal filtering.
  RefPtr<DataSourceSurface> target = FilterProcessing::ApplyBlending(input1, input2, mBlendMode);
  if (target != nullptr) {
    return target.forget();
  }

  IntSize size = input1->GetSize();
  target =
    Factory::CreateDataSourceSurface(size, SurfaceFormat::B8G8R8A8);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  CopyRect(input1, target, IntRect(IntPoint(), size), IntPoint());

  // This needs to stay in scope until the draw target has been flushed.
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::READ_WRITE);
  if (MOZ2D_WARN_IF(!targetMap.IsMapped())) {
    return nullptr;
  }

  RefPtr<DrawTarget> dt =
    Factory::CreateDrawTargetForData(BackendType::CAIRO,
                                     targetMap.GetData(),
                                     target->GetSize(),
                                     targetMap.GetStride(),
                                     target->GetFormat());

  if (!dt) {
    gfxWarning() << "FilterNodeBlendSoftware::Render failed in CreateDrawTargetForData";
    return nullptr;
  }

  Rect r(0, 0, size.width, size.height);
  dt->DrawSurface(input2, r, r, DrawSurfaceOptions(), DrawOptions(1.0f, ToBlendOp(mBlendMode)));
  dt->Flush();
  return target.forget();
}

void
FilterNodeBlendSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_BLEND_IN, aRect);
  RequestInputRect(IN_BLEND_IN2, aRect);
}

IntRect
FilterNodeBlendSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return GetInputRectInRect(IN_BLEND_IN, aRect).Union(
    GetInputRectInRect(IN_BLEND_IN2, aRect)).Intersect(aRect);
}

FilterNodeTransformSoftware::FilterNodeTransformSoftware()
  : mSamplingFilter(SamplingFilter::GOOD)
{}

int32_t
FilterNodeTransformSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_TRANSFORM_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeTransformSoftware::SetAttribute(uint32_t aIndex, uint32_t aFilter)
{
  MOZ_ASSERT(aIndex == ATT_TRANSFORM_FILTER);
  mSamplingFilter = static_cast<SamplingFilter>(aFilter);
  Invalidate();
}

void
FilterNodeTransformSoftware::SetAttribute(uint32_t aIndex, const Matrix &aMatrix)
{
  MOZ_ASSERT(aIndex == ATT_TRANSFORM_MATRIX);
  mMatrix = aMatrix;
  Invalidate();
}

IntRect
FilterNodeTransformSoftware::SourceRectForOutputRect(const IntRect &aRect)
{
  if (aRect.IsEmpty()) {
    return IntRect();
  }

  Matrix inverted(mMatrix);
  if (!inverted.Invert()) {
    return IntRect();
  }

  Rect neededRect = inverted.TransformBounds(Rect(aRect));
  neededRect.RoundOut();
  IntRect neededIntRect;
  if (!neededRect.ToIntRect(&neededIntRect)) {
    return IntRect();
  }
  return GetInputRectInRect(IN_TRANSFORM_IN, neededIntRect);
}

already_AddRefed<DataSourceSurface>
FilterNodeTransformSoftware::Render(const IntRect& aRect)
{
  IntRect srcRect = SourceRectForOutputRect(aRect);

  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_TRANSFORM_IN, srcRect);

  if (!input) {
    return nullptr;
  }

  Matrix transform = Matrix::Translation(srcRect.x, srcRect.y) * mMatrix *
                     Matrix::Translation(-aRect.x, -aRect.y);
  if (transform.IsIdentity() && srcRect.Size() == aRect.Size()) {
    return input.forget();
  }

  RefPtr<DataSourceSurface> surf =
    Factory::CreateDataSourceSurface(aRect.Size(), input->GetFormat(), true);

  if (!surf) {
    return nullptr;
  }

  DataSourceSurface::MappedSurface mapping;
  if (!surf->Map(DataSourceSurface::MapType::WRITE, &mapping)) {
    gfxCriticalError() << "FilterNodeTransformSoftware::Render failed to map surface";
    return nullptr;
  }

  RefPtr<DrawTarget> dt =
    Factory::CreateDrawTargetForData(BackendType::CAIRO,
                                     mapping.mData,
                                     surf->GetSize(),
                                     mapping.mStride,
                                     surf->GetFormat());
  if (!dt) {
    gfxWarning() << "FilterNodeTransformSoftware::Render failed in CreateDrawTargetForData";
    return nullptr;
  }

  Rect r(0, 0, srcRect.width, srcRect.height);
  dt->SetTransform(transform);
  dt->DrawSurface(input, r, r, DrawSurfaceOptions(mSamplingFilter));

  dt->Flush();
  surf->Unmap();
  return surf.forget();
}

void
FilterNodeTransformSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_TRANSFORM_IN, SourceRectForOutputRect(aRect));
}

IntRect
FilterNodeTransformSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect srcRect = SourceRectForOutputRect(aRect);
  if (srcRect.IsEmpty()) {
    return IntRect();
  }

  Rect outRect = mMatrix.TransformBounds(Rect(srcRect));
  outRect.RoundOut();
  IntRect outIntRect;
  if (!outRect.ToIntRect(&outIntRect)) {
    return IntRect();
  }
  return outIntRect.Intersect(aRect);
}

FilterNodeMorphologySoftware::FilterNodeMorphologySoftware()
 : mOperator(MORPHOLOGY_OPERATOR_ERODE)
{}

int32_t
FilterNodeMorphologySoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_MORPHOLOGY_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeMorphologySoftware::SetAttribute(uint32_t aIndex,
                                           const IntSize &aRadii)
{
  MOZ_ASSERT(aIndex == ATT_MORPHOLOGY_RADII);
  mRadii.width = std::min(std::max(aRadii.width, 0), 100000);
  mRadii.height = std::min(std::max(aRadii.height, 0), 100000);
  Invalidate();
}

void
FilterNodeMorphologySoftware::SetAttribute(uint32_t aIndex,
                                           uint32_t aOperator)
{
  MOZ_ASSERT(aIndex == ATT_MORPHOLOGY_OPERATOR);
  mOperator = static_cast<MorphologyOperator>(aOperator);
  Invalidate();
}

static already_AddRefed<DataSourceSurface>
ApplyMorphology(const IntRect& aSourceRect, DataSourceSurface* aInput,
                const IntRect& aDestRect, int32_t rx, int32_t ry,
                MorphologyOperator aOperator)
{
  IntRect srcRect = aSourceRect - aDestRect.TopLeft();
  IntRect destRect = aDestRect - aDestRect.TopLeft();
  IntRect tmpRect(destRect.x, srcRect.y, destRect.width, srcRect.height);
#ifdef DEBUG
  IntMargin margin = srcRect - destRect;
  MOZ_ASSERT(margin.top >= ry && margin.right >= rx &&
             margin.bottom >= ry && margin.left >= rx, "insufficient margin");
#endif

  RefPtr<DataSourceSurface> tmp;
  if (rx == 0) {
    tmp = aInput;
  } else {
    tmp = Factory::CreateDataSourceSurface(tmpRect.Size(), SurfaceFormat::B8G8R8A8);
    if (MOZ2D_WARN_IF(!tmp)) {
      return nullptr;
    }

    DataSourceSurface::ScopedMap sourceMap(aInput, DataSourceSurface::READ);
    DataSourceSurface::ScopedMap tmpMap(tmp, DataSourceSurface::WRITE);
    if (MOZ2D_WARN_IF(!sourceMap.IsMapped() || !tmpMap.IsMapped())) {
      return nullptr;
    }
    uint8_t* sourceData = DataAtOffset(aInput, sourceMap.GetMappedSurface(),
                                       destRect.TopLeft() - srcRect.TopLeft());
    uint8_t* tmpData = DataAtOffset(tmp, tmpMap.GetMappedSurface(),
                                    destRect.TopLeft() - tmpRect.TopLeft());

    FilterProcessing::ApplyMorphologyHorizontal(
      sourceData, sourceMap.GetStride(), tmpData, tmpMap.GetStride(), tmpRect, rx, aOperator);
  }

  RefPtr<DataSourceSurface> dest;
  if (ry == 0) {
    dest = tmp;
  } else {
    dest = Factory::CreateDataSourceSurface(destRect.Size(), SurfaceFormat::B8G8R8A8);
    if (MOZ2D_WARN_IF(!dest)) {
      return nullptr;
    }

    DataSourceSurface::ScopedMap tmpMap(tmp, DataSourceSurface::READ);
    DataSourceSurface::ScopedMap destMap(dest, DataSourceSurface::WRITE);
    if (MOZ2D_WARN_IF(!tmpMap.IsMapped() || !destMap.IsMapped())) {
      return nullptr;
    }
    int32_t tmpStride = tmpMap.GetStride();
    uint8_t* tmpData = DataAtOffset(tmp, tmpMap.GetMappedSurface(), destRect.TopLeft() - tmpRect.TopLeft());

    int32_t destStride = destMap.GetStride();
    uint8_t* destData = destMap.GetData();

    FilterProcessing::ApplyMorphologyVertical(
      tmpData, tmpStride, destData, destStride, destRect, ry, aOperator);
  }

  return dest.forget();
}

already_AddRefed<DataSourceSurface>
FilterNodeMorphologySoftware::Render(const IntRect& aRect)
{
  IntRect srcRect = aRect;
  srcRect.Inflate(mRadii);

  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_MORPHOLOGY_IN, srcRect, NEED_COLOR_CHANNELS);
  if (!input) {
    return nullptr;
  }

  int32_t rx = mRadii.width;
  int32_t ry = mRadii.height;

  if (rx == 0 && ry == 0) {
    return input.forget();
  }

  return ApplyMorphology(srcRect, input, aRect, rx, ry, mOperator);
}

void
FilterNodeMorphologySoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  IntRect srcRect = aRect;
  srcRect.Inflate(mRadii);
  RequestInputRect(IN_MORPHOLOGY_IN, srcRect);
}

IntRect
FilterNodeMorphologySoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect inflatedSourceRect = aRect;
  inflatedSourceRect.Inflate(mRadii);
  IntRect inputRect = GetInputRectInRect(IN_MORPHOLOGY_IN, inflatedSourceRect);
  if (mOperator == MORPHOLOGY_OPERATOR_ERODE) {
    inputRect.Deflate(mRadii);
  } else {
    inputRect.Inflate(mRadii);
  }
  return inputRect.Intersect(aRect);
}

int32_t
FilterNodeColorMatrixSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_COLOR_MATRIX_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeColorMatrixSoftware::SetAttribute(uint32_t aIndex,
                                            const Matrix5x4 &aMatrix)
{
  MOZ_ASSERT(aIndex == ATT_COLOR_MATRIX_MATRIX);
  mMatrix = aMatrix;
  Invalidate();
}

void
FilterNodeColorMatrixSoftware::SetAttribute(uint32_t aIndex,
                                            uint32_t aAlphaMode)
{
  MOZ_ASSERT(aIndex == ATT_COLOR_MATRIX_ALPHA_MODE);
  mAlphaMode = (AlphaMode)aAlphaMode;
  Invalidate();
}

static already_AddRefed<DataSourceSurface>
Premultiply(DataSourceSurface* aSurface)
{
  if (aSurface->GetFormat() == SurfaceFormat::A8) {
    RefPtr<DataSourceSurface> surface(aSurface);
    return surface.forget();
  }

  IntSize size = aSurface->GetSize();
  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(size, SurfaceFormat::B8G8R8A8);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  DataSourceSurface::ScopedMap inputMap(aSurface, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!inputMap.IsMapped() || !targetMap.IsMapped())) {
    return nullptr;
  }

  uint8_t* inputData = inputMap.GetData();
  int32_t inputStride = inputMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  FilterProcessing::DoPremultiplicationCalculation(
    size, targetData, targetStride, inputData, inputStride);

  return target.forget();
}

static already_AddRefed<DataSourceSurface>
Unpremultiply(DataSourceSurface* aSurface)
{
  if (aSurface->GetFormat() == SurfaceFormat::A8) {
    RefPtr<DataSourceSurface> surface(aSurface);
    return surface.forget();
  }

  IntSize size = aSurface->GetSize();
  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(size, SurfaceFormat::B8G8R8A8);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  DataSourceSurface::ScopedMap inputMap(aSurface, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!inputMap.IsMapped() || !targetMap.IsMapped())) {
    return nullptr;
  }

  uint8_t* inputData = inputMap.GetData();
  int32_t inputStride = inputMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  FilterProcessing::DoUnpremultiplicationCalculation(
    size, targetData, targetStride, inputData, inputStride);

  return target.forget();
}

already_AddRefed<DataSourceSurface>
FilterNodeColorMatrixSoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_COLOR_MATRIX_IN, aRect, NEED_COLOR_CHANNELS);
  if (!input) {
    return nullptr;
  }

  if (mAlphaMode == ALPHA_MODE_PREMULTIPLIED) {
    input = Unpremultiply(input);
  }

  RefPtr<DataSourceSurface> result =
    FilterProcessing::ApplyColorMatrix(input, mMatrix);

  if (mAlphaMode == ALPHA_MODE_PREMULTIPLIED) {
    result = Premultiply(result);
  }

  return result.forget();
}

void
FilterNodeColorMatrixSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_COLOR_MATRIX_IN, aRect);
}

IntRect
FilterNodeColorMatrixSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  if (mMatrix._54 > 0.0f) {
    return aRect;
  }
  return GetInputRectInRect(IN_COLOR_MATRIX_IN, aRect);
}

void
FilterNodeFloodSoftware::SetAttribute(uint32_t aIndex, const Color &aColor)
{
  MOZ_ASSERT(aIndex == ATT_FLOOD_COLOR);
  mColor = aColor;
  Invalidate();
}

static uint32_t
ColorToBGRA(const Color& aColor)
{
  union {
    uint32_t color;
    uint8_t components[4];
  };
  components[B8G8R8A8_COMPONENT_BYTEOFFSET_R] = NS_lround(aColor.r * aColor.a * 255.0f);
  components[B8G8R8A8_COMPONENT_BYTEOFFSET_G] = NS_lround(aColor.g * aColor.a * 255.0f);
  components[B8G8R8A8_COMPONENT_BYTEOFFSET_B] = NS_lround(aColor.b * aColor.a * 255.0f);
  components[B8G8R8A8_COMPONENT_BYTEOFFSET_A] = NS_lround(aColor.a * 255.0f);
  return color;
}

static SurfaceFormat
FormatForColor(Color aColor)
{
  if (aColor.r == 0 && aColor.g == 0 && aColor.b == 0) {
    return SurfaceFormat::A8;
  }
  return SurfaceFormat::B8G8R8A8;
}

already_AddRefed<DataSourceSurface>
FilterNodeFloodSoftware::Render(const IntRect& aRect)
{
  SurfaceFormat format = FormatForColor(mColor);
  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(aRect.Size(), format);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!targetMap.IsMapped())) {
    return nullptr;
  }

  uint8_t* targetData = targetMap.GetData();
  int32_t stride = targetMap.GetStride();

  if (format == SurfaceFormat::B8G8R8A8) {
    uint32_t color = ColorToBGRA(mColor);
    for (int32_t y = 0; y < aRect.height; y++) {
      for (int32_t x = 0; x < aRect.width; x++) {
        *((uint32_t*)targetData + x) = color;
      }
      PodZero(&targetData[aRect.width * 4], stride - aRect.width * 4);
      targetData += stride;
    }
  } else if (format == SurfaceFormat::A8) {
    uint8_t alpha = NS_lround(mColor.a * 255.0f);
    for (int32_t y = 0; y < aRect.height; y++) {
      for (int32_t x = 0; x < aRect.width; x++) {
        targetData[x] = alpha;
      }
      PodZero(&targetData[aRect.width], stride - aRect.width);
      targetData += stride;
    }
  } else {
    gfxDevCrash(LogReason::FilterInputFormat) << "Bad format in flood render " << (int)format;
    return nullptr;
  }

  return target.forget();
}

// Override GetOutput to get around caching. Rendering simple floods is
// comparatively fast.
already_AddRefed<DataSourceSurface>
FilterNodeFloodSoftware::GetOutput(const IntRect& aRect)
{
  return Render(aRect);
}

IntRect
FilterNodeFloodSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  if (mColor.a == 0.0f) {
    return IntRect();
  }
  return aRect;
}

int32_t
FilterNodeTileSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_TILE_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeTileSoftware::SetAttribute(uint32_t aIndex,
                                     const IntRect &aSourceRect)
{
  MOZ_ASSERT(aIndex == ATT_TILE_SOURCE_RECT);
  mSourceRect = IntRect(int32_t(aSourceRect.x), int32_t(aSourceRect.y),
                        int32_t(aSourceRect.width), int32_t(aSourceRect.height));
  Invalidate();
}

namespace {
struct CompareIntRects
{
  bool operator()(const IntRect& a, const IntRect& b) const
  {
    if (a.x != b.x) {
      return a.x < b.x;
    }
    if (a.y != b.y) {
      return a.y < b.y;
    }
    if (a.width != b.width) {
      return a.width < b.width;
    }
    return a.height < b.height;
  }
};

} // namespace

already_AddRefed<DataSourceSurface>
FilterNodeTileSoftware::Render(const IntRect& aRect)
{
  if (mSourceRect.IsEmpty()) {
    return nullptr;
  }

  if (mSourceRect.Contains(aRect)) {
    return GetInputDataSourceSurface(IN_TILE_IN, aRect);
  }

  RefPtr<DataSourceSurface> target;

  typedef std::map<IntRect, RefPtr<DataSourceSurface>, CompareIntRects> InputMap;
  InputMap inputs;

  IntPoint startIndex = TileIndex(mSourceRect, aRect.TopLeft());
  IntPoint endIndex = TileIndex(mSourceRect, aRect.BottomRight());
  for (int32_t ix = startIndex.x; ix <= endIndex.x; ix++) {
    for (int32_t iy = startIndex.y; iy <= endIndex.y; iy++) {
      IntPoint sourceToDestOffset(ix * mSourceRect.width,
                                  iy * mSourceRect.height);
      IntRect destRect = aRect.Intersect(mSourceRect + sourceToDestOffset);
      IntRect srcRect = destRect - sourceToDestOffset;
      if (srcRect.IsEmpty()) {
        continue;
      }

      RefPtr<DataSourceSurface> input;
      InputMap::iterator it = inputs.find(srcRect);
      if (it == inputs.end()) {
        input = GetInputDataSourceSurface(IN_TILE_IN, srcRect);
        inputs[srcRect] = input;
      } else {
        input = it->second;
      }
      if (!input) {
        return nullptr;
      }
      if (!target) {
        // We delay creating the target until now because we want to use the
        // same format as our input filter, and we do not actually know the
        // input format before we call GetInputDataSourceSurface.
        target = Factory::CreateDataSourceSurface(aRect.Size(), input->GetFormat());
        if (MOZ2D_WARN_IF(!target)) {
          return nullptr;
        }
      }

      if (input->GetFormat() != target->GetFormat()) {
        // Different rectangles of the input can have different formats. If
        // that happens, just convert everything to B8G8R8A8.
        target = FilterProcessing::ConvertToB8G8R8A8(target);
        input = FilterProcessing::ConvertToB8G8R8A8(input);
        if (MOZ2D_WARN_IF(!target) || MOZ2D_WARN_IF(!input)) {
          return nullptr;
        }
      }

      CopyRect(input, target, srcRect - srcRect.TopLeft(), destRect.TopLeft() - aRect.TopLeft());
    }
  }

  return target.forget();
}

void
FilterNodeTileSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  // Do not request anything.
  // Source rects for the tile filter can be discontinuous with large gaps
  // between them. Requesting those from our input filter might cause it to
  // render the whole bounding box of all of them, which would be wasteful.
}

IntRect
FilterNodeTileSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return aRect;
}

FilterNodeComponentTransferSoftware::FilterNodeComponentTransferSoftware()
 : mDisableR(true)
 , mDisableG(true)
 , mDisableB(true)
 , mDisableA(true)
{}

void
FilterNodeComponentTransferSoftware::SetAttribute(uint32_t aIndex,
                                                  bool aDisable)
{
  switch (aIndex) {
    case ATT_TRANSFER_DISABLE_R:
      mDisableR = aDisable;
      break;
    case ATT_TRANSFER_DISABLE_G:
      mDisableG = aDisable;
      break;
    case ATT_TRANSFER_DISABLE_B:
      mDisableB = aDisable;
      break;
    case ATT_TRANSFER_DISABLE_A:
      mDisableA = aDisable;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeComponentTransferSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeComponentTransferSoftware::GenerateLookupTable(ptrdiff_t aComponent,
                                                         uint8_t aTables[4][256],
                                                         bool aDisabled)
{
  if (aDisabled) {
    static uint8_t sIdentityLookupTable[256];
    static bool sInitializedIdentityLookupTable = false;
    if (!sInitializedIdentityLookupTable) {
      for (int32_t i = 0; i < 256; i++) {
        sIdentityLookupTable[i] = i;
      }
      sInitializedIdentityLookupTable = true;
    }
    memcpy(aTables[aComponent], sIdentityLookupTable, 256);
  } else {
    FillLookupTable(aComponent, aTables[aComponent]);
  }
}

template<uint32_t BytesPerPixel>
static void TransferComponents(DataSourceSurface* aInput,
                               DataSourceSurface* aTarget,
                               const uint8_t aLookupTables[BytesPerPixel][256])
{
  MOZ_ASSERT(aInput->GetFormat() == aTarget->GetFormat(), "different formats");
  IntSize size = aInput->GetSize();

  DataSourceSurface::ScopedMap sourceMap(aInput, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(aTarget, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!sourceMap.IsMapped() || !targetMap.IsMapped())) {
    return;
  }

  uint8_t* sourceData = sourceMap.GetData();
  int32_t sourceStride = sourceMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  MOZ_ASSERT(sourceStride <= targetStride, "target smaller than source");

  for (int32_t y = 0; y < size.height; y++) {
    for (int32_t x = 0; x < size.width; x++) {
      uint32_t sourceIndex = y * sourceStride + x * BytesPerPixel;
      uint32_t targetIndex = y * targetStride + x * BytesPerPixel;
      for (uint32_t i = 0; i < BytesPerPixel; i++) {
        targetData[targetIndex + i] = aLookupTables[i][sourceData[sourceIndex + i]];
      }
    }

    // Zero padding to keep valgrind happy.
    PodZero(&targetData[y * targetStride + size.width * BytesPerPixel],
            targetStride - size.width * BytesPerPixel);
  }
}

bool
IsAllZero(uint8_t aLookupTable[256])
{
  for (int32_t i = 0; i < 256; i++) {
    if (aLookupTable[i] != 0) {
      return false;
    }
  }
  return true;
}

already_AddRefed<DataSourceSurface>
FilterNodeComponentTransferSoftware::Render(const IntRect& aRect)
{
  if (mDisableR && mDisableG && mDisableB && mDisableA) {
    return GetInputDataSourceSurface(IN_TRANSFER_IN, aRect);
  }

  uint8_t lookupTables[4][256];
  GenerateLookupTable(B8G8R8A8_COMPONENT_BYTEOFFSET_R, lookupTables, mDisableR);
  GenerateLookupTable(B8G8R8A8_COMPONENT_BYTEOFFSET_G, lookupTables, mDisableG);
  GenerateLookupTable(B8G8R8A8_COMPONENT_BYTEOFFSET_B, lookupTables, mDisableB);
  GenerateLookupTable(B8G8R8A8_COMPONENT_BYTEOFFSET_A, lookupTables, mDisableA);

  bool needColorChannels =
    lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_R][0] != 0 ||
    lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_G][0] != 0 ||
    lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_B][0] != 0;

  FormatHint pref = needColorChannels ? NEED_COLOR_CHANNELS : CAN_HANDLE_A8;

  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_TRANSFER_IN, aRect, pref);
  if (!input) {
    return nullptr;
  }

  if (input->GetFormat() == SurfaceFormat::B8G8R8A8 && !needColorChannels) {
    bool colorChannelsBecomeBlack =
      IsAllZero(lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_R]) &&
      IsAllZero(lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_G]) &&
      IsAllZero(lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_B]);

    if (colorChannelsBecomeBlack) {
      input = FilterProcessing::ExtractAlpha(input);
    }
  }

  SurfaceFormat format = input->GetFormat();
  if (format == SurfaceFormat::A8 && mDisableA) {
    return input.forget();
  }

  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(aRect.Size(), format);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  if (format == SurfaceFormat::A8) {
    TransferComponents<1>(input, target, &lookupTables[B8G8R8A8_COMPONENT_BYTEOFFSET_A]);
  } else {
    TransferComponents<4>(input, target, lookupTables);
  }

  return target.forget();
}

void
FilterNodeComponentTransferSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_TRANSFER_IN, aRect);
}

IntRect
FilterNodeComponentTransferSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  if (mDisableA) {
    return GetInputRectInRect(IN_TRANSFER_IN, aRect);
  }
  return aRect;
}

int32_t
FilterNodeComponentTransferSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_TRANSFER_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeTableTransferSoftware::SetAttribute(uint32_t aIndex,
                                              const Float* aFloat,
                                              uint32_t aSize)
{
  std::vector<Float> table(aFloat, aFloat + aSize);
  switch (aIndex) {
    case ATT_TABLE_TRANSFER_TABLE_R:
      mTableR = table;
      break;
    case ATT_TABLE_TRANSFER_TABLE_G:
      mTableG = table;
      break;
    case ATT_TABLE_TRANSFER_TABLE_B:
      mTableB = table;
      break;
    case ATT_TABLE_TRANSFER_TABLE_A:
      mTableA = table;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeTableTransferSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeTableTransferSoftware::FillLookupTable(ptrdiff_t aComponent,
                                                 uint8_t aTable[256])
{
  switch (aComponent) {
    case B8G8R8A8_COMPONENT_BYTEOFFSET_R:
      FillLookupTableImpl(mTableR, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_G:
      FillLookupTableImpl(mTableG, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_B:
      FillLookupTableImpl(mTableB, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_A:
      FillLookupTableImpl(mTableA, aTable);
      break;
    default:
      MOZ_ASSERT(false, "unknown component");
      break;
  }
}

void
FilterNodeTableTransferSoftware::FillLookupTableImpl(std::vector<Float>& aTableValues,
                                                     uint8_t aTable[256])
{
  uint32_t tvLength = aTableValues.size();
  if (tvLength < 2) {
    return;
  }

  for (size_t i = 0; i < 256; i++) {
    uint32_t k = (i * (tvLength - 1)) / 255;
    Float v1 = aTableValues[k];
    Float v2 = aTableValues[std::min(k + 1, tvLength - 1)];
    int32_t val =
      int32_t(255 * (v1 + (i/255.0f - k/float(tvLength-1))*(tvLength - 1)*(v2 - v1)));
    val = std::min(255, val);
    val = std::max(0, val);
    aTable[i] = val;
  }
}

void
FilterNodeDiscreteTransferSoftware::SetAttribute(uint32_t aIndex,
                                              const Float* aFloat,
                                              uint32_t aSize)
{
  std::vector<Float> discrete(aFloat, aFloat + aSize);
  switch (aIndex) {
    case ATT_DISCRETE_TRANSFER_TABLE_R:
      mTableR = discrete;
      break;
    case ATT_DISCRETE_TRANSFER_TABLE_G:
      mTableG = discrete;
      break;
    case ATT_DISCRETE_TRANSFER_TABLE_B:
      mTableB = discrete;
      break;
    case ATT_DISCRETE_TRANSFER_TABLE_A:
      mTableA = discrete;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeDiscreteTransferSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeDiscreteTransferSoftware::FillLookupTable(ptrdiff_t aComponent,
                                                    uint8_t aTable[256])
{
  switch (aComponent) {
    case B8G8R8A8_COMPONENT_BYTEOFFSET_R:
      FillLookupTableImpl(mTableR, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_G:
      FillLookupTableImpl(mTableG, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_B:
      FillLookupTableImpl(mTableB, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_A:
      FillLookupTableImpl(mTableA, aTable);
      break;
    default:
      MOZ_ASSERT(false, "unknown component");
      break;
  }
}

void
FilterNodeDiscreteTransferSoftware::FillLookupTableImpl(std::vector<Float>& aTableValues,
                                                        uint8_t aTable[256])
{
  uint32_t tvLength = aTableValues.size();
  if (tvLength < 1) {
    return;
  }

  for (size_t i = 0; i < 256; i++) {
    uint32_t k = (i * tvLength) / 255;
    k = std::min(k, tvLength - 1);
    Float v = aTableValues[k];
    int32_t val = NS_lround(255 * v);
    val = std::min(255, val);
    val = std::max(0, val);
    aTable[i] = val;
  }
}

FilterNodeLinearTransferSoftware::FilterNodeLinearTransferSoftware()
 : mSlopeR(0)
 , mSlopeG(0)
 , mSlopeB(0)
 , mSlopeA(0)
 , mInterceptR(0)
 , mInterceptG(0)
 , mInterceptB(0)
 , mInterceptA(0)
{}

void
FilterNodeLinearTransferSoftware::SetAttribute(uint32_t aIndex,
                                               Float aValue)
{
  switch (aIndex) {
    case ATT_LINEAR_TRANSFER_SLOPE_R:
      mSlopeR = aValue;
      break;
    case ATT_LINEAR_TRANSFER_INTERCEPT_R:
      mInterceptR = aValue;
      break;
    case ATT_LINEAR_TRANSFER_SLOPE_G:
      mSlopeG = aValue;
      break;
    case ATT_LINEAR_TRANSFER_INTERCEPT_G:
      mInterceptG = aValue;
      break;
    case ATT_LINEAR_TRANSFER_SLOPE_B:
      mSlopeB = aValue;
      break;
    case ATT_LINEAR_TRANSFER_INTERCEPT_B:
      mInterceptB = aValue;
      break;
    case ATT_LINEAR_TRANSFER_SLOPE_A:
      mSlopeA = aValue;
      break;
    case ATT_LINEAR_TRANSFER_INTERCEPT_A:
      mInterceptA = aValue;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeLinearTransferSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeLinearTransferSoftware::FillLookupTable(ptrdiff_t aComponent,
                                                  uint8_t aTable[256])
{
  switch (aComponent) {
    case B8G8R8A8_COMPONENT_BYTEOFFSET_R:
      FillLookupTableImpl(mSlopeR, mInterceptR, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_G:
      FillLookupTableImpl(mSlopeG, mInterceptG, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_B:
      FillLookupTableImpl(mSlopeB, mInterceptB, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_A:
      FillLookupTableImpl(mSlopeA, mInterceptA, aTable);
      break;
    default:
      MOZ_ASSERT(false, "unknown component");
      break;
  }
}

void
FilterNodeLinearTransferSoftware::FillLookupTableImpl(Float aSlope,
                                                      Float aIntercept,
                                                      uint8_t aTable[256])
{
  for (size_t i = 0; i < 256; i++) {
    int32_t val = NS_lround(aSlope * i + 255 * aIntercept);
    val = std::min(255, val);
    val = std::max(0, val);
    aTable[i] = val;
  }
}

FilterNodeGammaTransferSoftware::FilterNodeGammaTransferSoftware()
 : mAmplitudeR(0)
 , mAmplitudeG(0)
 , mAmplitudeB(0)
 , mAmplitudeA(0)
 , mExponentR(0)
 , mExponentG(0)
 , mExponentB(0)
 , mExponentA(0)
{}

void
FilterNodeGammaTransferSoftware::SetAttribute(uint32_t aIndex,
                                              Float aValue)
{
  switch (aIndex) {
    case ATT_GAMMA_TRANSFER_AMPLITUDE_R:
      mAmplitudeR = aValue;
      break;
    case ATT_GAMMA_TRANSFER_EXPONENT_R:
      mExponentR = aValue;
      break;
    case ATT_GAMMA_TRANSFER_OFFSET_R:
      mOffsetR = aValue;
      break;
    case ATT_GAMMA_TRANSFER_AMPLITUDE_G:
      mAmplitudeG = aValue;
      break;
    case ATT_GAMMA_TRANSFER_EXPONENT_G:
      mExponentG = aValue;
      break;
    case ATT_GAMMA_TRANSFER_OFFSET_G:
      mOffsetG = aValue;
      break;
    case ATT_GAMMA_TRANSFER_AMPLITUDE_B:
      mAmplitudeB = aValue;
      break;
    case ATT_GAMMA_TRANSFER_EXPONENT_B:
      mExponentB = aValue;
      break;
    case ATT_GAMMA_TRANSFER_OFFSET_B:
      mOffsetB = aValue;
      break;
    case ATT_GAMMA_TRANSFER_AMPLITUDE_A:
      mAmplitudeA = aValue;
      break;
    case ATT_GAMMA_TRANSFER_EXPONENT_A:
      mExponentA = aValue;
      break;
    case ATT_GAMMA_TRANSFER_OFFSET_A:
      mOffsetA = aValue;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeGammaTransferSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeGammaTransferSoftware::FillLookupTable(ptrdiff_t aComponent,
                                                 uint8_t aTable[256])
{
  switch (aComponent) {
    case B8G8R8A8_COMPONENT_BYTEOFFSET_R:
      FillLookupTableImpl(mAmplitudeR, mExponentR, mOffsetR, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_G:
      FillLookupTableImpl(mAmplitudeG, mExponentG, mOffsetG, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_B:
      FillLookupTableImpl(mAmplitudeB, mExponentB, mOffsetB, aTable);
      break;
    case B8G8R8A8_COMPONENT_BYTEOFFSET_A:
      FillLookupTableImpl(mAmplitudeA, mExponentA, mOffsetA, aTable);
      break;
    default:
      MOZ_ASSERT(false, "unknown component");
      break;
  }
}

void
FilterNodeGammaTransferSoftware::FillLookupTableImpl(Float aAmplitude,
                                                     Float aExponent,
                                                     Float aOffset,
                                                     uint8_t aTable[256])
{
  for (size_t i = 0; i < 256; i++) {
    int32_t val = NS_lround(255 * (aAmplitude * pow(i / 255.0f, aExponent) + aOffset));
    val = std::min(255, val);
    val = std::max(0, val);
    aTable[i] = val;
  }
}

FilterNodeConvolveMatrixSoftware::FilterNodeConvolveMatrixSoftware()
 : mDivisor(0)
 , mBias(0)
 , mEdgeMode(EDGE_MODE_DUPLICATE)
 , mPreserveAlpha(false)
{}

int32_t
FilterNodeConvolveMatrixSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_CONVOLVE_MATRIX_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               const IntSize &aKernelSize)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_KERNEL_SIZE);
  mKernelSize = aKernelSize;
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               const Float *aMatrix,
                                               uint32_t aSize)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_KERNEL_MATRIX);
  mKernelMatrix = std::vector<Float>(aMatrix, aMatrix + aSize);
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex, Float aValue)
{
  switch (aIndex) {
    case ATT_CONVOLVE_MATRIX_DIVISOR:
      mDivisor = aValue;
      break;
    case ATT_CONVOLVE_MATRIX_BIAS:
      mBias = aValue;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeConvolveMatrixSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex, const Size &aKernelUnitLength)
{
  switch (aIndex) {
    case ATT_CONVOLVE_MATRIX_KERNEL_UNIT_LENGTH:
      mKernelUnitLength = aKernelUnitLength;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeConvolveMatrixSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               const IntPoint &aTarget)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_TARGET);
  mTarget = aTarget;
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               const IntRect &aSourceRect)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_SOURCE_RECT);
  mSourceRect = aSourceRect;
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               uint32_t aEdgeMode)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_EDGE_MODE);
  mEdgeMode = static_cast<ConvolveMatrixEdgeMode>(aEdgeMode);
  Invalidate();
}

void
FilterNodeConvolveMatrixSoftware::SetAttribute(uint32_t aIndex,
                                               bool aPreserveAlpha)
{
  MOZ_ASSERT(aIndex == ATT_CONVOLVE_MATRIX_PRESERVE_ALPHA);
  mPreserveAlpha = aPreserveAlpha;
  Invalidate();
}

#ifdef DEBUG
static bool sColorSamplingAccessControlEnabled = false;
static uint8_t* sColorSamplingAccessControlStart = nullptr;
static uint8_t* sColorSamplingAccessControlEnd = nullptr;

struct DebugOnlyAutoColorSamplingAccessControl
{
  explicit DebugOnlyAutoColorSamplingAccessControl(DataSourceSurface* aSurface)
  {
    sColorSamplingAccessControlStart = aSurface->GetData();
    sColorSamplingAccessControlEnd = sColorSamplingAccessControlStart +
      aSurface->Stride() * aSurface->GetSize().height;
    sColorSamplingAccessControlEnabled = true;
  }

  ~DebugOnlyAutoColorSamplingAccessControl()
  {
    sColorSamplingAccessControlEnabled = false;
  }
};

static inline void
DebugOnlyCheckColorSamplingAccess(const uint8_t* aSampleAddress)
{
  if (sColorSamplingAccessControlEnabled) {
    MOZ_ASSERT(aSampleAddress >= sColorSamplingAccessControlStart, "accessing before start");
    MOZ_ASSERT(aSampleAddress < sColorSamplingAccessControlEnd, "accessing after end");
  }
}
#else
typedef DebugOnly<DataSourceSurface*> DebugOnlyAutoColorSamplingAccessControl;
#define DebugOnlyCheckColorSamplingAccess(address)
#endif

static inline uint8_t
ColorComponentAtPoint(const uint8_t *aData, int32_t aStride, int32_t x, int32_t y, size_t bpp, ptrdiff_t c)
{
  DebugOnlyCheckColorSamplingAccess(&aData[y * aStride + bpp * x + c]);
  return aData[y * aStride + bpp * x + c];
}

static inline int32_t
ColorAtPoint(const uint8_t *aData, int32_t aStride, int32_t x, int32_t y)
{
  DebugOnlyCheckColorSamplingAccess(aData + y * aStride + 4 * x);
  return *(uint32_t*)(aData + y * aStride + 4 * x);
}

// Accepts fractional x & y and does bilinear interpolation.
// Only call this if the pixel (floor(x)+1, floor(y)+1) is accessible.
static inline uint8_t
ColorComponentAtPoint(const uint8_t *aData, int32_t aStride, Float x, Float y, size_t bpp, ptrdiff_t c)
{
  const uint32_t f = 256;
  const int32_t lx = floor(x);
  const int32_t ly = floor(y);
  const int32_t tux = uint32_t((x - lx) * f);
  const int32_t tlx = f - tux;
  const int32_t tuy = uint32_t((y - ly) * f);
  const int32_t tly = f - tuy;
  const uint8_t &cll = ColorComponentAtPoint(aData, aStride, lx,     ly,     bpp, c);
  const uint8_t &cul = ColorComponentAtPoint(aData, aStride, lx + 1, ly,     bpp, c);
  const uint8_t &clu = ColorComponentAtPoint(aData, aStride, lx,     ly + 1, bpp, c);
  const uint8_t &cuu = ColorComponentAtPoint(aData, aStride, lx + 1, ly + 1, bpp, c);
  return ((cll * tlx + cul * tux) * tly +
          (clu * tlx + cuu * tux) * tuy + f * f / 2) / (f * f);
}

static int32_t
ClampToNonZero(int32_t a)
{
  return a * (a >= 0);
}

template<typename CoordType>
static void
ConvolvePixel(const uint8_t *aSourceData,
              uint8_t *aTargetData,
              int32_t aWidth, int32_t aHeight,
              int32_t aSourceStride, int32_t aTargetStride,
              int32_t aX, int32_t aY,
              const int32_t *aKernel,
              int32_t aBias, int32_t shiftL, int32_t shiftR,
              bool aPreserveAlpha,
              int32_t aOrderX, int32_t aOrderY,
              int32_t aTargetX, int32_t aTargetY,
              CoordType aKernelUnitLengthX,
              CoordType aKernelUnitLengthY)
{
  int32_t sum[4] = {0, 0, 0, 0};
  int32_t offsets[4] = { B8G8R8A8_COMPONENT_BYTEOFFSET_R,
                         B8G8R8A8_COMPONENT_BYTEOFFSET_G,
                         B8G8R8A8_COMPONENT_BYTEOFFSET_B,
                         B8G8R8A8_COMPONENT_BYTEOFFSET_A };
  int32_t channels = aPreserveAlpha ? 3 : 4;
  int32_t roundingAddition = shiftL == 0 ? 0 : 1 << (shiftL - 1);

  for (int32_t y = 0; y < aOrderY; y++) {
    CoordType sampleY = aY + (y - aTargetY) * aKernelUnitLengthY;
    for (int32_t x = 0; x < aOrderX; x++) {
      CoordType sampleX = aX + (x - aTargetX) * aKernelUnitLengthX;
      for (int32_t i = 0; i < channels; i++) {
        sum[i] += aKernel[aOrderX * y + x] *
          ColorComponentAtPoint(aSourceData, aSourceStride,
                                sampleX, sampleY, 4, offsets[i]);
      }
    }
  }
  for (int32_t i = 0; i < channels; i++) {
    int32_t clamped = umin(ClampToNonZero(sum[i] + aBias), 255 << shiftL >> shiftR);
    aTargetData[aY * aTargetStride + 4 * aX + offsets[i]] =
      (clamped + roundingAddition) << shiftR >> shiftL;
  }
  if (aPreserveAlpha) {
    aTargetData[aY * aTargetStride + 4 * aX + B8G8R8A8_COMPONENT_BYTEOFFSET_A] =
      aSourceData[aY * aSourceStride + 4 * aX + B8G8R8A8_COMPONENT_BYTEOFFSET_A];
  }
}

already_AddRefed<DataSourceSurface>
FilterNodeConvolveMatrixSoftware::Render(const IntRect& aRect)
{
  if (mKernelUnitLength.width == floor(mKernelUnitLength.width) &&
      mKernelUnitLength.height == floor(mKernelUnitLength.height)) {
    return DoRender(aRect, (int32_t)mKernelUnitLength.width, (int32_t)mKernelUnitLength.height);
  }
  return DoRender(aRect, mKernelUnitLength.width, mKernelUnitLength.height);
}

static std::vector<Float>
ReversedVector(const std::vector<Float> &aVector)
{
  size_t length = aVector.size();
  std::vector<Float> result(length, 0);
  for (size_t i = 0; i < length; i++) {
    result[length - 1 - i] = aVector[i];
  }
  return result;
}

static std::vector<Float>
ScaledVector(const std::vector<Float> &aVector, Float aDivisor)
{
  size_t length = aVector.size();
  std::vector<Float> result(length, 0);
  for (size_t i = 0; i < length; i++) {
    result[i] = aVector[i] / aDivisor;
  }
  return result;
}

static Float
MaxVectorSum(const std::vector<Float> &aVector)
{
  Float sum = 0;
  size_t length = aVector.size();
  for (size_t i = 0; i < length; i++) {
    if (aVector[i] > 0) {
      sum += aVector[i];
    }
  }
  return sum;
}

// Returns shiftL and shiftR in such a way that
// a << shiftL >> shiftR is roughly a * aFloat.
static void
TranslateDoubleToShifts(double aDouble, int32_t &aShiftL, int32_t &aShiftR)
{
  aShiftL = 0;
  aShiftR = 0;
  if (aDouble <= 0) {
    MOZ_CRASH("GFX: TranslateDoubleToShifts");
  }
  if (aDouble < 1) {
    while (1 << (aShiftR + 1) < 1 / aDouble) {
      aShiftR++;
    }
  } else {
    while (1 << (aShiftL + 1) < aDouble) {
      aShiftL++;
    }
  }
}

template<typename CoordType>
already_AddRefed<DataSourceSurface>
FilterNodeConvolveMatrixSoftware::DoRender(const IntRect& aRect,
                                           CoordType aKernelUnitLengthX,
                                           CoordType aKernelUnitLengthY)
{
  if (mKernelSize.width <= 0 || mKernelSize.height <= 0 ||
      mKernelMatrix.size() != uint32_t(mKernelSize.width * mKernelSize.height) ||
      !IntRect(IntPoint(0, 0), mKernelSize).Contains(mTarget) ||
      mDivisor == 0) {
    return Factory::CreateDataSourceSurface(aRect.Size(), SurfaceFormat::B8G8R8A8, true);
  }

  IntRect srcRect = InflatedSourceRect(aRect);

  // Inflate the source rect by another pixel because the bilinear filtering in
  // ColorComponentAtPoint may want to access the margins.
  srcRect.Inflate(1);

  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_CONVOLVE_MATRIX_IN, srcRect, NEED_COLOR_CHANNELS, mEdgeMode, &mSourceRect);

  if (!input) {
    return nullptr;
  }

  DebugOnlyAutoColorSamplingAccessControl accessControl(input);

  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(aRect.Size(), SurfaceFormat::B8G8R8A8, true);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  IntPoint offset = aRect.TopLeft() - srcRect.TopLeft();

  DataSourceSurface::ScopedMap sourceMap(input, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!sourceMap.IsMapped() || !targetMap.IsMapped())) {
    return nullptr;
  }

  uint8_t* sourceData = DataAtOffset(input, sourceMap.GetMappedSurface(), offset);
  int32_t sourceStride = sourceMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  // Why exactly are we reversing the kernel?
  std::vector<Float> kernel = ReversedVector(mKernelMatrix);
  kernel = ScaledVector(kernel, mDivisor);
  Float maxResultAbs = std::max(MaxVectorSum(kernel) + mBias,
                                MaxVectorSum(ScaledVector(kernel, -1)) - mBias);
  maxResultAbs = std::max(maxResultAbs, 1.0f);

  double idealFactor = INT32_MAX / 2.0 / maxResultAbs / 255.0 * 0.999;
  MOZ_ASSERT(255.0 * maxResultAbs * idealFactor <= INT32_MAX / 2.0, "badly chosen float-to-int scale");
  int32_t shiftL, shiftR;
  TranslateDoubleToShifts(idealFactor, shiftL, shiftR);
  double factorFromShifts = Float(1 << shiftL) / Float(1 << shiftR);
  MOZ_ASSERT(255.0 * maxResultAbs * factorFromShifts <= INT32_MAX / 2.0, "badly chosen float-to-int scale");

  int32_t* intKernel = new int32_t[kernel.size()];
  for (size_t i = 0; i < kernel.size(); i++) {
    intKernel[i] = NS_lround(kernel[i] * factorFromShifts);
  }
  int32_t bias = NS_lround(mBias * 255 * factorFromShifts);

  for (int32_t y = 0; y < aRect.height; y++) {
    for (int32_t x = 0; x < aRect.width; x++) {
      ConvolvePixel(sourceData, targetData,
                    aRect.width, aRect.height, sourceStride, targetStride,
                    x, y, intKernel, bias, shiftL, shiftR, mPreserveAlpha,
                    mKernelSize.width, mKernelSize.height, mTarget.x, mTarget.y,
                    aKernelUnitLengthX, aKernelUnitLengthY);
    }
  }
  delete[] intKernel;

  return target.forget();
}

void
FilterNodeConvolveMatrixSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_CONVOLVE_MATRIX_IN, InflatedSourceRect(aRect));
}

IntRect
FilterNodeConvolveMatrixSoftware::InflatedSourceRect(const IntRect &aDestRect)
{
  if (aDestRect.IsEmpty()) {
    return IntRect();
  }

  IntMargin margin;
  margin.left = ceil(mTarget.x * mKernelUnitLength.width);
  margin.top = ceil(mTarget.y * mKernelUnitLength.height);
  margin.right = ceil((mKernelSize.width - mTarget.x - 1) * mKernelUnitLength.width);
  margin.bottom = ceil((mKernelSize.height - mTarget.y - 1) * mKernelUnitLength.height);

  IntRect srcRect = aDestRect;
  srcRect.Inflate(margin);
  return srcRect;
}

IntRect
FilterNodeConvolveMatrixSoftware::InflatedDestRect(const IntRect &aSourceRect)
{
  if (aSourceRect.IsEmpty()) {
    return IntRect();
  }

  IntMargin margin;
  margin.left = ceil((mKernelSize.width - mTarget.x - 1) * mKernelUnitLength.width);
  margin.top = ceil((mKernelSize.height - mTarget.y - 1) * mKernelUnitLength.height);
  margin.right = ceil(mTarget.x * mKernelUnitLength.width);
  margin.bottom = ceil(mTarget.y * mKernelUnitLength.height);

  IntRect destRect = aSourceRect;
  destRect.Inflate(margin);
  return destRect;
}

IntRect
FilterNodeConvolveMatrixSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect srcRequest = InflatedSourceRect(aRect);
  IntRect srcOutput = GetInputRectInRect(IN_COLOR_MATRIX_IN, srcRequest);
  return InflatedDestRect(srcOutput).Intersect(aRect);
}

FilterNodeDisplacementMapSoftware::FilterNodeDisplacementMapSoftware()
 : mScale(0.0f)
 , mChannelX(COLOR_CHANNEL_R)
 , mChannelY(COLOR_CHANNEL_G)
{}

int32_t
FilterNodeDisplacementMapSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_DISPLACEMENT_MAP_IN: return 0;
    case IN_DISPLACEMENT_MAP_IN2: return 1;
    default: return -1;
  }
}

void
FilterNodeDisplacementMapSoftware::SetAttribute(uint32_t aIndex,
                                                Float aScale)
{
  MOZ_ASSERT(aIndex == ATT_DISPLACEMENT_MAP_SCALE);
  mScale = aScale;
  Invalidate();
}

void
FilterNodeDisplacementMapSoftware::SetAttribute(uint32_t aIndex, uint32_t aValue)
{
  switch (aIndex) {
    case ATT_DISPLACEMENT_MAP_X_CHANNEL:
      mChannelX = static_cast<ColorChannel>(aValue);
      break;
    case ATT_DISPLACEMENT_MAP_Y_CHANNEL:
      mChannelY = static_cast<ColorChannel>(aValue);
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeDisplacementMapSoftware::SetAttribute");
  }
  Invalidate();
}

already_AddRefed<DataSourceSurface>
FilterNodeDisplacementMapSoftware::Render(const IntRect& aRect)
{
  IntRect srcRect = InflatedSourceOrDestRect(aRect);
  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_DISPLACEMENT_MAP_IN, srcRect, NEED_COLOR_CHANNELS);
  RefPtr<DataSourceSurface> map =
    GetInputDataSourceSurface(IN_DISPLACEMENT_MAP_IN2, aRect, NEED_COLOR_CHANNELS);
  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(aRect.Size(), SurfaceFormat::B8G8R8A8);
  if (MOZ2D_WARN_IF(!(input && map && target))) {
    return nullptr;
  }

  IntPoint offset = aRect.TopLeft() - srcRect.TopLeft();

  DataSourceSurface::ScopedMap inputMap(input, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap mapMap(map, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!(inputMap.IsMapped() && mapMap.IsMapped() && targetMap.IsMapped()))) {
    return nullptr;
  }

  uint8_t* sourceData = DataAtOffset(input, inputMap.GetMappedSurface(), offset);
  int32_t sourceStride = inputMap.GetStride();
  uint8_t* mapData = mapMap.GetData();
  int32_t mapStride = mapMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  static const ptrdiff_t channelMap[4] = {
                             B8G8R8A8_COMPONENT_BYTEOFFSET_R,
                             B8G8R8A8_COMPONENT_BYTEOFFSET_G,
                             B8G8R8A8_COMPONENT_BYTEOFFSET_B,
                             B8G8R8A8_COMPONENT_BYTEOFFSET_A };
  uint16_t xChannel = channelMap[mChannelX];
  uint16_t yChannel = channelMap[mChannelY];

  float scaleOver255 = mScale / 255.0f;
  float scaleAdjustment = -0.5f * mScale;

  for (int32_t y = 0; y < aRect.height; y++) {
    for (int32_t x = 0; x < aRect.width; x++) {
      uint32_t mapIndex = y * mapStride + 4 * x;
      uint32_t targIndex = y * targetStride + 4 * x;
      int32_t sourceX = x +
        scaleOver255 * mapData[mapIndex + xChannel] + scaleAdjustment;
      int32_t sourceY = y +
        scaleOver255 * mapData[mapIndex + yChannel] + scaleAdjustment;
      *(uint32_t*)(targetData + targIndex) =
        ColorAtPoint(sourceData, sourceStride, sourceX, sourceY);
    }

    // Keep valgrind happy.
    PodZero(&targetData[y * targetStride + 4 * aRect.width], targetStride - 4 * aRect.width);
  }

  return target.forget();
}

void
FilterNodeDisplacementMapSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_DISPLACEMENT_MAP_IN, InflatedSourceOrDestRect(aRect));
  RequestInputRect(IN_DISPLACEMENT_MAP_IN2, aRect);
}

IntRect
FilterNodeDisplacementMapSoftware::InflatedSourceOrDestRect(const IntRect &aDestOrSourceRect)
{
  IntRect sourceOrDestRect = aDestOrSourceRect;
  sourceOrDestRect.Inflate(ceil(fabs(mScale) / 2));
  return sourceOrDestRect;
}

IntRect
FilterNodeDisplacementMapSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect srcRequest = InflatedSourceOrDestRect(aRect);
  IntRect srcOutput = GetInputRectInRect(IN_DISPLACEMENT_MAP_IN, srcRequest);
  return InflatedSourceOrDestRect(srcOutput).Intersect(aRect);
}

FilterNodeTurbulenceSoftware::FilterNodeTurbulenceSoftware()
 : mNumOctaves(0)
 , mSeed(0)
 , mStitchable(false)
 , mType(TURBULENCE_TYPE_TURBULENCE)
{}

int32_t
FilterNodeTurbulenceSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  return -1;
}

void
FilterNodeTurbulenceSoftware::SetAttribute(uint32_t aIndex, const Size &aBaseFrequency)
{
  switch (aIndex) {
    case ATT_TURBULENCE_BASE_FREQUENCY:
      mBaseFrequency = aBaseFrequency;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeTurbulenceSoftware::SetAttribute");
      break;
  }
  Invalidate();
}

void
FilterNodeTurbulenceSoftware::SetAttribute(uint32_t aIndex, const IntRect &aRect)
{
  switch (aIndex) {
    case ATT_TURBULENCE_RECT:
      mRenderRect = aRect;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeTurbulenceSoftware::SetAttribute");
      break;
  }
  Invalidate();
}

void
FilterNodeTurbulenceSoftware::SetAttribute(uint32_t aIndex, bool aStitchable)
{
  MOZ_ASSERT(aIndex == ATT_TURBULENCE_STITCHABLE);
  mStitchable = aStitchable;
  Invalidate();
}

void
FilterNodeTurbulenceSoftware::SetAttribute(uint32_t aIndex, uint32_t aValue)
{
  switch (aIndex) {
    case ATT_TURBULENCE_NUM_OCTAVES:
      mNumOctaves = aValue;
      break;
    case ATT_TURBULENCE_SEED:
      mSeed = aValue;
      break;
    case ATT_TURBULENCE_TYPE:
      mType = static_cast<TurbulenceType>(aValue);
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeTurbulenceSoftware::SetAttribute");
      break;
  }
  Invalidate();
}

already_AddRefed<DataSourceSurface>
FilterNodeTurbulenceSoftware::Render(const IntRect& aRect)
{
  return FilterProcessing::RenderTurbulence(
    aRect.Size(), aRect.TopLeft(), mBaseFrequency,
    mSeed, mNumOctaves, mType, mStitchable, Rect(mRenderRect));
}

IntRect
FilterNodeTurbulenceSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return aRect.Intersect(mRenderRect);
}

FilterNodeArithmeticCombineSoftware::FilterNodeArithmeticCombineSoftware()
 : mK1(0), mK2(0), mK3(0), mK4(0)
{
}

int32_t
FilterNodeArithmeticCombineSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_ARITHMETIC_COMBINE_IN: return 0;
    case IN_ARITHMETIC_COMBINE_IN2: return 1;
    default: return -1;
  }
}

void
FilterNodeArithmeticCombineSoftware::SetAttribute(uint32_t aIndex,
                                                  const Float* aFloat,
                                                  uint32_t aSize)
{
  MOZ_ASSERT(aIndex == ATT_ARITHMETIC_COMBINE_COEFFICIENTS);
  MOZ_RELEASE_ASSERT(aSize == 4);

  mK1 = aFloat[0];
  mK2 = aFloat[1];
  mK3 = aFloat[2];
  mK4 = aFloat[3];

  Invalidate();
}

already_AddRefed<DataSourceSurface>
FilterNodeArithmeticCombineSoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> input1 =
    GetInputDataSourceSurface(IN_ARITHMETIC_COMBINE_IN, aRect, NEED_COLOR_CHANNELS);
  RefPtr<DataSourceSurface> input2 =
    GetInputDataSourceSurface(IN_ARITHMETIC_COMBINE_IN2, aRect, NEED_COLOR_CHANNELS);
  if (!input1 && !input2) {
    return nullptr;
  }

  // If one input is null, treat it as transparent by adjusting the factors.
  Float k1 = mK1, k2 = mK2, k3 = mK3, k4 = mK4;
  if (!input1) {
    k1 = 0.0f;
    k2 = 0.0f;
    input1 = input2;
  }

  if (!input2) {
    k1 = 0.0f;
    k3 = 0.0f;
    input2 = input1;
  }

  return FilterProcessing::ApplyArithmeticCombine(input1, input2, k1, k2, k3, k4);
}

void
FilterNodeArithmeticCombineSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_ARITHMETIC_COMBINE_IN, aRect);
  RequestInputRect(IN_ARITHMETIC_COMBINE_IN2, aRect);
}

IntRect
FilterNodeArithmeticCombineSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  if (mK4 > 0.0f) {
    return aRect;
  }
  IntRect rectFrom1 = GetInputRectInRect(IN_ARITHMETIC_COMBINE_IN, aRect).Intersect(aRect);
  IntRect rectFrom2 = GetInputRectInRect(IN_ARITHMETIC_COMBINE_IN2, aRect).Intersect(aRect);
  IntRect result;
  if (mK1 > 0.0f) {
    result = rectFrom1.Intersect(rectFrom2);
  }
  if (mK2 > 0.0f) {
    result = result.Union(rectFrom1);
  }
  if (mK3 > 0.0f) {
    result = result.Union(rectFrom2);
  }
  return result;
}

FilterNodeCompositeSoftware::FilterNodeCompositeSoftware()
 : mOperator(COMPOSITE_OPERATOR_OVER)
{}

int32_t
FilterNodeCompositeSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  return aInputEnumIndex - IN_COMPOSITE_IN_START;
}

void
FilterNodeCompositeSoftware::SetAttribute(uint32_t aIndex, uint32_t aCompositeOperator)
{
  MOZ_ASSERT(aIndex == ATT_COMPOSITE_OPERATOR);
  mOperator = static_cast<CompositeOperator>(aCompositeOperator);
  Invalidate();
}

already_AddRefed<DataSourceSurface>
FilterNodeCompositeSoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> start =
    GetInputDataSourceSurface(IN_COMPOSITE_IN_START, aRect, NEED_COLOR_CHANNELS);
  RefPtr<DataSourceSurface> dest =
    Factory::CreateDataSourceSurface(aRect.Size(), SurfaceFormat::B8G8R8A8, true);
  if (MOZ2D_WARN_IF(!dest)) {
    return nullptr;
  }

  if (start) {
    CopyRect(start, dest, aRect - aRect.TopLeft(), IntPoint());
  }

  for (size_t inputIndex = 1; inputIndex < NumberOfSetInputs(); inputIndex++) {
    RefPtr<DataSourceSurface> input =
      GetInputDataSourceSurface(IN_COMPOSITE_IN_START + inputIndex, aRect, NEED_COLOR_CHANNELS);
    if (input) {
      FilterProcessing::ApplyComposition(input, dest, mOperator);
    } else {
      // We need to treat input as transparent. Depending on the composite
      // operator, different things happen to dest.
      switch (mOperator) {
        case COMPOSITE_OPERATOR_OVER:
        case COMPOSITE_OPERATOR_ATOP:
        case COMPOSITE_OPERATOR_XOR:
          // dest is unchanged.
          break;
        case COMPOSITE_OPERATOR_OUT:
          // dest is now transparent, but it can become non-transparent again
          // when compositing additional inputs.
          ClearDataSourceSurface(dest);
          break;
        case COMPOSITE_OPERATOR_IN:
          // Transparency always wins. We're completely transparent now and
          // no additional input can get rid of that transparency.
          return nullptr;
      }
    }
  }
  return dest.forget();
}

void
FilterNodeCompositeSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  for (size_t inputIndex = 0; inputIndex < NumberOfSetInputs(); inputIndex++) {
    RequestInputRect(IN_COMPOSITE_IN_START + inputIndex, aRect);
  }
}

IntRect
FilterNodeCompositeSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect rect;
  for (size_t inputIndex = 0; inputIndex < NumberOfSetInputs(); inputIndex++) {
    IntRect inputRect = GetInputRectInRect(IN_COMPOSITE_IN_START + inputIndex, aRect);
    if (mOperator == COMPOSITE_OPERATOR_IN && inputIndex > 0) {
      rect = rect.Intersect(inputRect);
    } else {
      rect = rect.Union(inputRect);
    }
  }
  return rect;
}

int32_t
FilterNodeBlurXYSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_GAUSSIAN_BLUR_IN: return 0;
    default: return -1;
  }
}

already_AddRefed<DataSourceSurface>
FilterNodeBlurXYSoftware::Render(const IntRect& aRect)
{
  Size sigmaXY = StdDeviationXY();
  IntSize d = AlphaBoxBlur::CalculateBlurRadius(Point(sigmaXY.width, sigmaXY.height));

  if (d.width == 0 && d.height == 0) {
    return GetInputDataSourceSurface(IN_GAUSSIAN_BLUR_IN, aRect);
  }

  IntRect srcRect = InflatedSourceOrDestRect(aRect);
  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_GAUSSIAN_BLUR_IN, srcRect);
  if (!input) {
    return nullptr;
  }

  RefPtr<DataSourceSurface> target;
  Rect r(0, 0, srcRect.width, srcRect.height);

  if (input->GetFormat() == SurfaceFormat::A8) {
    target = Factory::CreateDataSourceSurface(srcRect.Size(), SurfaceFormat::A8);
    if (MOZ2D_WARN_IF(!target)) {
      return nullptr;
    }
    CopyRect(input, target, IntRect(IntPoint(), input->GetSize()), IntPoint());

    DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::READ_WRITE);
    if (MOZ2D_WARN_IF(!targetMap.IsMapped())) {
      return nullptr;
    }
    AlphaBoxBlur blur(r, targetMap.GetStride(), sigmaXY.width, sigmaXY.height);
    blur.Blur(targetMap.GetData());
  } else {
    RefPtr<DataSourceSurface> channel0, channel1, channel2, channel3;
    FilterProcessing::SeparateColorChannels(input, channel0, channel1, channel2, channel3);
    if (MOZ2D_WARN_IF(!(channel0 && channel1 && channel2 && channel3))) {
      return nullptr;
    }
    {
      DataSourceSurface::ScopedMap channel0Map(channel0, DataSourceSurface::READ_WRITE);
      DataSourceSurface::ScopedMap channel1Map(channel1, DataSourceSurface::READ_WRITE);
      DataSourceSurface::ScopedMap channel2Map(channel2, DataSourceSurface::READ_WRITE);
      DataSourceSurface::ScopedMap channel3Map(channel3, DataSourceSurface::READ_WRITE);
      if (MOZ2D_WARN_IF(!(channel0Map.IsMapped() && channel1Map.IsMapped() &&
                          channel2Map.IsMapped() && channel3Map.IsMapped()))) {
        return nullptr;
      }

      AlphaBoxBlur blur(r, channel0Map.GetStride(), sigmaXY.width, sigmaXY.height);
      blur.Blur(channel0Map.GetData());
      blur.Blur(channel1Map.GetData());
      blur.Blur(channel2Map.GetData());
      blur.Blur(channel3Map.GetData());
    }
    target = FilterProcessing::CombineColorChannels(channel0, channel1, channel2, channel3);
  }

  return GetDataSurfaceInRect(target, srcRect, aRect, EDGE_MODE_NONE);
}

void
FilterNodeBlurXYSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_GAUSSIAN_BLUR_IN, InflatedSourceOrDestRect(aRect));
}

IntRect
FilterNodeBlurXYSoftware::InflatedSourceOrDestRect(const IntRect &aDestRect)
{
  Size sigmaXY = StdDeviationXY();
  IntSize d = AlphaBoxBlur::CalculateBlurRadius(Point(sigmaXY.width, sigmaXY.height));
  IntRect srcRect = aDestRect;
  srcRect.Inflate(d);
  return srcRect;
}

IntRect
FilterNodeBlurXYSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  IntRect srcRequest = InflatedSourceOrDestRect(aRect);
  IntRect srcOutput = GetInputRectInRect(IN_GAUSSIAN_BLUR_IN, srcRequest);
  return InflatedSourceOrDestRect(srcOutput).Intersect(aRect);
}

FilterNodeGaussianBlurSoftware::FilterNodeGaussianBlurSoftware()
 : mStdDeviation(0)
{}

static float
ClampStdDeviation(float aStdDeviation)
{
  // Cap software blur radius for performance reasons.
  return std::min(std::max(0.0f, aStdDeviation), 100.0f);
}

void
FilterNodeGaussianBlurSoftware::SetAttribute(uint32_t aIndex,
                                             float aStdDeviation)
{
  switch (aIndex) {
    case ATT_GAUSSIAN_BLUR_STD_DEVIATION:
      mStdDeviation = ClampStdDeviation(aStdDeviation);
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeGaussianBlurSoftware::SetAttribute");
  }
  Invalidate();
}

Size
FilterNodeGaussianBlurSoftware::StdDeviationXY()
{
  return Size(mStdDeviation, mStdDeviation);
}

FilterNodeDirectionalBlurSoftware::FilterNodeDirectionalBlurSoftware()
 : mBlurDirection(BLUR_DIRECTION_X)
{}

void
FilterNodeDirectionalBlurSoftware::SetAttribute(uint32_t aIndex,
                                                Float aStdDeviation)
{
  switch (aIndex) {
    case ATT_DIRECTIONAL_BLUR_STD_DEVIATION:
      mStdDeviation = ClampStdDeviation(aStdDeviation);
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeDirectionalBlurSoftware::SetAttribute");
  }
  Invalidate();
}

void
FilterNodeDirectionalBlurSoftware::SetAttribute(uint32_t aIndex,
                                                uint32_t aBlurDirection)
{
  switch (aIndex) {
    case ATT_DIRECTIONAL_BLUR_DIRECTION:
      mBlurDirection = (BlurDirection)aBlurDirection;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeDirectionalBlurSoftware::SetAttribute");
  }
  Invalidate();
}

Size
FilterNodeDirectionalBlurSoftware::StdDeviationXY()
{
  float sigmaX = mBlurDirection == BLUR_DIRECTION_X ? mStdDeviation : 0;
  float sigmaY = mBlurDirection == BLUR_DIRECTION_Y ? mStdDeviation : 0;
  return Size(sigmaX, sigmaY);
}

int32_t
FilterNodeCropSoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_CROP_IN: return 0;
    default: return -1;
  }
}

void
FilterNodeCropSoftware::SetAttribute(uint32_t aIndex,
                                     const Rect &aSourceRect)
{
  MOZ_ASSERT(aIndex == ATT_CROP_RECT);
  Rect srcRect = aSourceRect;
  srcRect.Round();
  if (!srcRect.ToIntRect(&mCropRect)) {
    mCropRect = IntRect();
  }
  Invalidate();
}

already_AddRefed<DataSourceSurface>
FilterNodeCropSoftware::Render(const IntRect& aRect)
{
  return GetInputDataSourceSurface(IN_CROP_IN, aRect.Intersect(mCropRect));
}

void
FilterNodeCropSoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_CROP_IN, aRect.Intersect(mCropRect));
}

IntRect
FilterNodeCropSoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return GetInputRectInRect(IN_CROP_IN, aRect).Intersect(mCropRect);
}

int32_t
FilterNodePremultiplySoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_PREMULTIPLY_IN: return 0;
    default: return -1;
  }
}

already_AddRefed<DataSourceSurface>
FilterNodePremultiplySoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_PREMULTIPLY_IN, aRect);
  return input ? Premultiply(input) : nullptr;
}

void
FilterNodePremultiplySoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_PREMULTIPLY_IN, aRect);
}

IntRect
FilterNodePremultiplySoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return GetInputRectInRect(IN_PREMULTIPLY_IN, aRect);
}

int32_t
FilterNodeUnpremultiplySoftware::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_UNPREMULTIPLY_IN: return 0;
    default: return -1;
  }
}

already_AddRefed<DataSourceSurface>
FilterNodeUnpremultiplySoftware::Render(const IntRect& aRect)
{
  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_UNPREMULTIPLY_IN, aRect);
  return input ? Unpremultiply(input) : nullptr;
}

void
FilterNodeUnpremultiplySoftware::RequestFromInputsForRect(const IntRect &aRect)
{
  RequestInputRect(IN_UNPREMULTIPLY_IN, aRect);
}

IntRect
FilterNodeUnpremultiplySoftware::GetOutputRectInRect(const IntRect& aRect)
{
  return GetInputRectInRect(IN_UNPREMULTIPLY_IN, aRect);
}

bool
PointLightSoftware::SetAttribute(uint32_t aIndex, const Point3D &aPoint)
{
  switch (aIndex) {
    case ATT_POINT_LIGHT_POSITION:
      mPosition = aPoint;
      break;
    default:
      return false;
  }
  return true;
}

SpotLightSoftware::SpotLightSoftware()
 : mSpecularFocus(0)
 , mLimitingConeAngle(0)
 , mLimitingConeCos(1)
{
}

bool
SpotLightSoftware::SetAttribute(uint32_t aIndex, const Point3D &aPoint)
{
  switch (aIndex) {
    case ATT_SPOT_LIGHT_POSITION:
      mPosition = aPoint;
      break;
    case ATT_SPOT_LIGHT_POINTS_AT:
      mPointsAt = aPoint;
      break;
    default:
      return false;
  }
  return true;
}

bool
SpotLightSoftware::SetAttribute(uint32_t aIndex, Float aValue)
{
  switch (aIndex) {
    case ATT_SPOT_LIGHT_LIMITING_CONE_ANGLE:
      mLimitingConeAngle = aValue;
      break;
    case ATT_SPOT_LIGHT_FOCUS:
      mSpecularFocus = aValue;
      break;
    default:
      return false;
  }
  return true;
}

DistantLightSoftware::DistantLightSoftware()
 : mAzimuth(0)
 , mElevation(0)
{
}

bool
DistantLightSoftware::SetAttribute(uint32_t aIndex, Float aValue)
{
  switch (aIndex) {
    case ATT_DISTANT_LIGHT_AZIMUTH:
      mAzimuth = aValue;
      break;
    case ATT_DISTANT_LIGHT_ELEVATION:
      mElevation = aValue;
      break;
    default:
      return false;
  }
  return true;
}

static inline Point3D Normalized(const Point3D &vec) {
  Point3D copy(vec);
  copy.Normalize();
  return copy;
}

template<typename LightType, typename LightingType>
FilterNodeLightingSoftware<LightType, LightingType>::FilterNodeLightingSoftware(const char* aTypeName)
 : mSurfaceScale(0)
#if defined(MOZILLA_INTERNAL_API) && (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
 , mTypeName(aTypeName)
#endif
{}

template<typename LightType, typename LightingType>
int32_t
FilterNodeLightingSoftware<LightType, LightingType>::InputIndex(uint32_t aInputEnumIndex)
{
  switch (aInputEnumIndex) {
    case IN_LIGHTING_IN: return 0;
    default: return -1;
  }
}

template<typename LightType, typename LightingType>
void
FilterNodeLightingSoftware<LightType, LightingType>::SetAttribute(uint32_t aIndex, const Point3D &aPoint)
{
  if (mLight.SetAttribute(aIndex, aPoint)) {
    Invalidate();
    return;
  }
  MOZ_CRASH("GFX: FilterNodeLightingSoftware::SetAttribute point");
}

template<typename LightType, typename LightingType>
void
FilterNodeLightingSoftware<LightType, LightingType>::SetAttribute(uint32_t aIndex, Float aValue)
{
  if (mLight.SetAttribute(aIndex, aValue) ||
      mLighting.SetAttribute(aIndex, aValue)) {
    Invalidate();
    return;
  }
  switch (aIndex) {
    case ATT_LIGHTING_SURFACE_SCALE:
      mSurfaceScale = std::fpclassify(aValue) == FP_SUBNORMAL ? 0.0 : aValue;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeLightingSoftware::SetAttribute float");
  }
  Invalidate();
}

template<typename LightType, typename LightingType>
void
FilterNodeLightingSoftware<LightType, LightingType>::SetAttribute(uint32_t aIndex, const Size &aKernelUnitLength)
{
  switch (aIndex) {
    case ATT_LIGHTING_KERNEL_UNIT_LENGTH:
      mKernelUnitLength = aKernelUnitLength;
      break;
    default:
      MOZ_CRASH("GFX: FilterNodeLightingSoftware::SetAttribute size");
  }
  Invalidate();
}

template<typename LightType, typename LightingType>
void
FilterNodeLightingSoftware<LightType, LightingType>::SetAttribute(uint32_t aIndex, const Color &aColor)
{
  MOZ_ASSERT(aIndex == ATT_LIGHTING_COLOR);
  mColor = aColor;
  Invalidate();
}

template<typename LightType, typename LightingType>
IntRect
FilterNodeLightingSoftware<LightType, LightingType>::GetOutputRectInRect(const IntRect& aRect)
{
  return aRect;
}

Point3D
PointLightSoftware::GetVectorToLight(const Point3D &aTargetPoint)
{
  return Normalized(mPosition - aTargetPoint);
}

uint32_t
PointLightSoftware::GetColor(uint32_t aLightColor, const Point3D &aVectorToLight)
{
  return aLightColor;
}

void
SpotLightSoftware::Prepare()
{
  mVectorFromFocusPointToLight = Normalized(mPointsAt - mPosition);
  mLimitingConeCos = std::max<double>(cos(mLimitingConeAngle * M_PI/180.0), 0.0);
  mPowCache.CacheForExponent(mSpecularFocus);
}

Point3D
SpotLightSoftware::GetVectorToLight(const Point3D &aTargetPoint)
{
  return Normalized(mPosition - aTargetPoint);
}

uint32_t
SpotLightSoftware::GetColor(uint32_t aLightColor, const Point3D &aVectorToLight)
{
  union {
    uint32_t color;
    uint8_t colorC[4];
  };

  Float dot = -aVectorToLight.DotProduct(mVectorFromFocusPointToLight);
  if (!mPowCache.HasPowerTable()) {
    dot *= (dot >= mLimitingConeCos);
    color = aLightColor;
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_R] *= dot;
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_G] *= dot;
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_B] *= dot;
  } else {
    color = aLightColor;
    uint16_t doti = dot * (dot >= 0) * (1 << PowCache::sInputIntPrecisionBits);
    uint32_t tmp = mPowCache.Pow(doti) * (dot >= mLimitingConeCos);
    MOZ_ASSERT(tmp <= (1 << PowCache::sOutputIntPrecisionBits), "pow() result must not exceed 1.0");
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_R] = uint8_t((colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_R] * tmp) >> PowCache::sOutputIntPrecisionBits);
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_G] = uint8_t((colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_G] * tmp) >> PowCache::sOutputIntPrecisionBits);
    colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_B] = uint8_t((colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_B] * tmp) >> PowCache::sOutputIntPrecisionBits);
  }
  colorC[B8G8R8A8_COMPONENT_BYTEOFFSET_A] = 255;
  return color;
}

void
DistantLightSoftware::Prepare()
{
  const double radPerDeg = M_PI / 180.0;
  mVectorToLight.x = cos(mAzimuth * radPerDeg) * cos(mElevation * radPerDeg);
  mVectorToLight.y = sin(mAzimuth * radPerDeg) * cos(mElevation * radPerDeg);
  mVectorToLight.z = sin(mElevation * radPerDeg);
}

Point3D
DistantLightSoftware::GetVectorToLight(const Point3D &aTargetPoint)
{
  return mVectorToLight;
}

uint32_t
DistantLightSoftware::GetColor(uint32_t aLightColor, const Point3D &aVectorToLight)
{
  return aLightColor;
}

template<typename CoordType>
static Point3D
GenerateNormal(const uint8_t *data, int32_t stride,
               int32_t x, int32_t y, float surfaceScale,
               CoordType dx, CoordType dy)
{
  const uint8_t *index = data + y * stride + x;

  CoordType zero = 0;

  // See this for source of constants:
  //   http://www.w3.org/TR/SVG11/filters.html#feDiffuseLightingElement
  int16_t normalX =
    -1 * ColorComponentAtPoint(index, stride, -dx, -dy, 1, 0) +
     1 * ColorComponentAtPoint(index, stride, dx, -dy, 1, 0) +
    -2 * ColorComponentAtPoint(index, stride, -dx, zero, 1, 0) +
     2 * ColorComponentAtPoint(index, stride, dx, zero, 1, 0) +
    -1 * ColorComponentAtPoint(index, stride, -dx, dy, 1, 0) +
     1 * ColorComponentAtPoint(index, stride, dx, dy, 1, 0);

  int16_t normalY =
    -1 * ColorComponentAtPoint(index, stride, -dx, -dy, 1, 0) +
    -2 * ColorComponentAtPoint(index, stride, zero, -dy, 1, 0) +
    -1 * ColorComponentAtPoint(index, stride, dx, -dy, 1, 0) +
     1 * ColorComponentAtPoint(index, stride, -dx, dy, 1, 0) +
     2 * ColorComponentAtPoint(index, stride, zero, dy, 1, 0) +
     1 * ColorComponentAtPoint(index, stride, dx, dy, 1, 0);

  Point3D normal;
  normal.x = -surfaceScale * normalX / 4.0f;
  normal.y = -surfaceScale * normalY / 4.0f;
  normal.z = 255;
  return Normalized(normal);
}

template<typename LightType, typename LightingType>
already_AddRefed<DataSourceSurface>
FilterNodeLightingSoftware<LightType, LightingType>::Render(const IntRect& aRect)
{
  if (mKernelUnitLength.width == floor(mKernelUnitLength.width) &&
      mKernelUnitLength.height == floor(mKernelUnitLength.height)) {
    return DoRender(aRect, (int32_t)mKernelUnitLength.width, (int32_t)mKernelUnitLength.height);
  }
  return DoRender(aRect, mKernelUnitLength.width, mKernelUnitLength.height);
}

template<typename LightType, typename LightingType>
void
FilterNodeLightingSoftware<LightType, LightingType>::RequestFromInputsForRect(const IntRect &aRect)
{
  IntRect srcRect = aRect;
  srcRect.Inflate(ceil(mKernelUnitLength.width),
                  ceil(mKernelUnitLength.height));
  RequestInputRect(IN_LIGHTING_IN, srcRect);
}

template<typename LightType, typename LightingType> template<typename CoordType>
already_AddRefed<DataSourceSurface>
FilterNodeLightingSoftware<LightType, LightingType>::DoRender(const IntRect& aRect,
                                                              CoordType aKernelUnitLengthX,
                                                              CoordType aKernelUnitLengthY)
{
  MOZ_ASSERT(aKernelUnitLengthX > 0, "aKernelUnitLengthX can be a negative or zero value");
  MOZ_ASSERT(aKernelUnitLengthY > 0, "aKernelUnitLengthY can be a negative or zero value");

  IntRect srcRect = aRect;
  IntSize size = aRect.Size();
  srcRect.Inflate(ceil(float(aKernelUnitLengthX)),
                  ceil(float(aKernelUnitLengthY)));

  // Inflate the source rect by another pixel because the bilinear filtering in
  // ColorComponentAtPoint may want to access the margins.
  srcRect.Inflate(1);

  RefPtr<DataSourceSurface> input =
    GetInputDataSourceSurface(IN_LIGHTING_IN, srcRect, CAN_HANDLE_A8,
                              EDGE_MODE_NONE);

  if (!input) {
    return nullptr;
  }

  if (input->GetFormat() != SurfaceFormat::A8) {
    input = FilterProcessing::ExtractAlpha(input);
  }

  DebugOnlyAutoColorSamplingAccessControl accessControl(input);

  RefPtr<DataSourceSurface> target =
    Factory::CreateDataSourceSurface(size, SurfaceFormat::B8G8R8A8);
  if (MOZ2D_WARN_IF(!target)) {
    return nullptr;
  }

  IntPoint offset = aRect.TopLeft() - srcRect.TopLeft();


  DataSourceSurface::ScopedMap sourceMap(input, DataSourceSurface::READ);
  DataSourceSurface::ScopedMap targetMap(target, DataSourceSurface::WRITE);
  if (MOZ2D_WARN_IF(!(sourceMap.IsMapped() && targetMap.IsMapped()))) {
    return nullptr;
  }

  uint8_t* sourceData = DataAtOffset(input, sourceMap.GetMappedSurface(), offset);
  int32_t sourceStride = sourceMap.GetStride();
  uint8_t* targetData = targetMap.GetData();
  int32_t targetStride = targetMap.GetStride();

  uint32_t lightColor = ColorToBGRA(mColor);
  mLight.Prepare();
  mLighting.Prepare();

  for (int32_t y = 0; y < size.height; y++) {
    for (int32_t x = 0; x < size.width; x++) {
      int32_t sourceIndex = y * sourceStride + x;
      int32_t targetIndex = y * targetStride + 4 * x;

      Point3D normal = GenerateNormal(sourceData, sourceStride,
                                      x, y, mSurfaceScale,
                                      aKernelUnitLengthX, aKernelUnitLengthY);

      IntPoint pointInFilterSpace(aRect.x + x, aRect.y + y);
      Float Z = mSurfaceScale * sourceData[sourceIndex] / 255.0f;
      Point3D pt(pointInFilterSpace.x, pointInFilterSpace.y, Z);
      Point3D rayDir = mLight.GetVectorToLight(pt);
      uint32_t color = mLight.GetColor(lightColor, rayDir);

      *(uint32_t*)(targetData + targetIndex) = mLighting.LightPixel(normal, rayDir, color);
    }

    // Zero padding to keep valgrind happy.
    PodZero(&targetData[y * targetStride + 4 * size.width], targetStride - 4 * size.width);
  }

  return target.forget();
}

DiffuseLightingSoftware::DiffuseLightingSoftware()
 : mDiffuseConstant(0)
{
}

bool
DiffuseLightingSoftware::SetAttribute(uint32_t aIndex, Float aValue)
{
  switch (aIndex) {
    case ATT_DIFFUSE_LIGHTING_DIFFUSE_CONSTANT:
      mDiffuseConstant = aValue;
      break;
    default:
      return false;
  }
  return true;
}

uint32_t
DiffuseLightingSoftware::LightPixel(const Point3D &aNormal,
                                    const Point3D &aVectorToLight,
                                    uint32_t aColor)
{
  Float dotNL = std::max(0.0f, aNormal.DotProduct(aVectorToLight));
  Float diffuseNL = mDiffuseConstant * dotNL;

  union {
    uint32_t bgra;
    uint8_t components[4];
  } color = { aColor };
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_B] =
    umin(uint32_t(diffuseNL * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_B]), 255U);
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_G] =
    umin(uint32_t(diffuseNL * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_G]), 255U);
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_R] =
    umin(uint32_t(diffuseNL * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_R]), 255U);
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_A] = 255;
  return color.bgra;
}

SpecularLightingSoftware::SpecularLightingSoftware()
 : mSpecularConstant(0)
 , mSpecularExponent(0)
 , mSpecularConstantInt(0)
{
}

bool
SpecularLightingSoftware::SetAttribute(uint32_t aIndex, Float aValue)
{
  switch (aIndex) {
    case ATT_SPECULAR_LIGHTING_SPECULAR_CONSTANT:
      mSpecularConstant = std::min(std::max(aValue, 0.0f), 255.0f);
      break;
    case ATT_SPECULAR_LIGHTING_SPECULAR_EXPONENT:
      mSpecularExponent = std::min(std::max(aValue, 1.0f), 128.0f);
      break;
    default:
      return false;
  }
  return true;
}

void
SpecularLightingSoftware::Prepare()
{
  mPowCache.CacheForExponent(mSpecularExponent);
  mSpecularConstantInt = uint32_t(mSpecularConstant * (1 << 8));
}

uint32_t
SpecularLightingSoftware::LightPixel(const Point3D &aNormal,
                                     const Point3D &aVectorToLight,
                                     uint32_t aColor)
{
  Point3D vectorToEye(0, 0, 1);
  Point3D halfwayVector = Normalized(aVectorToLight + vectorToEye);
  Float dotNH = aNormal.DotProduct(halfwayVector);
  uint16_t dotNHi = uint16_t(dotNH * (dotNH >= 0) * (1 << PowCache::sInputIntPrecisionBits));
  // The exponent for specular is in [1,128] range, so we don't need to check and
  // optimize for the "default power table" scenario here.
  MOZ_ASSERT(mPowCache.HasPowerTable());
  uint32_t specularNHi = uint32_t(mSpecularConstantInt) * mPowCache.Pow(dotNHi) >> 8;

  union {
    uint32_t bgra;
    uint8_t components[4];
  } color = { aColor };
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_B] =
    umin(
      (specularNHi * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_B]) >> PowCache::sOutputIntPrecisionBits, 255U);
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_G] =
    umin(
      (specularNHi * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_G]) >> PowCache::sOutputIntPrecisionBits, 255U);
  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_R] =
    umin(
      (specularNHi * color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_R]) >> PowCache::sOutputIntPrecisionBits, 255U);

  color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_A] =
    umax(color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_B],
      umax(color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_G],
               color.components[B8G8R8A8_COMPONENT_BYTEOFFSET_R]));
  return color.bgra;
}

} // namespace gfx
} // namespace mozilla