1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073
|
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host_impl.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "base/auto_reset.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/read_only_shared_memory_region.h"
#include "base/metrics/histogram.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/common/task_annotator.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "base/trace_event/traced_value.h"
#include "base/trace_event/typed_macros.h"
#include "base/types/optional_ref.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "cc/base/devtools_instrumentation.h"
#include "cc/base/features.h"
#include "cc/base/histograms.h"
#include "cc/base/math_util.h"
#include "cc/base/switches.h"
#include "cc/benchmarks/benchmark_instrumentation.h"
#include "cc/debug/rendering_stats_instrumentation.h"
#include "cc/input/browser_controls_offset_manager.h"
#include "cc/input/browser_controls_offset_tag_modifications.h"
#include "cc/input/page_scale_animation.h"
#include "cc/input/scrollbar_animation_controller.h"
#include "cc/layers/append_quads_context.h"
#include "cc/layers/append_quads_data.h"
#include "cc/layers/effect_tree_layer_list_iterator.h"
#include "cc/layers/heads_up_display_layer_impl.h"
#include "cc/layers/layer_impl.h"
#include "cc/layers/render_surface_impl.h"
#include "cc/layers/surface_layer_impl.h"
#include "cc/layers/video_layer_impl.h"
#include "cc/layers/viewport.h"
#include "cc/metrics/compositor_frame_reporting_controller.h"
#include "cc/metrics/custom_metrics_recorder.h"
#include "cc/metrics/frame_sequence_metrics.h"
#include "cc/metrics/frame_sequence_tracker.h"
#include "cc/metrics/lcd_text_metrics_reporter.h"
#include "cc/metrics/submit_info.h"
#include "cc/metrics/ukm_dropped_frames_data.h"
#include "cc/metrics/ukm_smoothness_data.h"
#include "cc/paint/display_item_list.h"
#include "cc/paint/paint_worklet_job.h"
#include "cc/paint/paint_worklet_layer_painter.h"
#include "cc/raster/gpu_raster_buffer_provider.h"
#include "cc/raster/one_copy_raster_buffer_provider.h"
#include "cc/raster/raster_buffer_provider.h"
#include "cc/raster/synchronous_task_graph_runner.h"
#include "cc/raster/zero_copy_raster_buffer_provider.h"
#include "cc/resources/memory_history.h"
#include "cc/resources/resource_pool.h"
#include "cc/resources/ui_resource_bitmap.h"
#include "cc/tiles/eviction_tile_priority_queue.h"
#include "cc/tiles/frame_viewer_instrumentation.h"
#include "cc/tiles/gpu_image_decode_cache.h"
#include "cc/tiles/picture_layer_tiling.h"
#include "cc/tiles/raster_tile_priority_queue.h"
#include "cc/tiles/software_image_decode_cache.h"
#include "cc/tiles/tiles_with_resource_iterator.h"
#include "cc/trees/compositor_commit_data.h"
#include "cc/trees/damage_tracker.h"
#include "cc/trees/debug_rect_history.h"
#include "cc/trees/effect_node.h"
#include "cc/trees/image_animation_controller.h"
#include "cc/trees/latency_info_swap_promise_monitor.h"
#include "cc/trees/layer_context.h"
#include "cc/trees/layer_tree_frame_sink.h"
#include "cc/trees/layer_tree_host_impl_client.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/mobile_optimized_viewport_util.h"
#include "cc/trees/mutator_host.h"
#include "cc/trees/presentation_time_callback_buffer.h"
#include "cc/trees/raster_capabilities.h"
#include "cc/trees/render_frame_metadata.h"
#include "cc/trees/render_frame_metadata_observer.h"
#include "cc/trees/scroll_node.h"
#include "cc/trees/single_thread_proxy.h"
#include "cc/trees/trace_utils.h"
#include "cc/trees/tree_synchronizer.h"
#include "cc/view_transition/view_transition_request.h"
#include "components/viz/client/client_resource_provider.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_timing_details.h"
#include "components/viz/common/hit_test/hit_test_region_list.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/quads/compositor_frame_metadata.h"
#include "components/viz/common/quads/compositor_render_pass_draw_quad.h"
#include "components/viz/common/quads/frame_deadline.h"
#include "components/viz/common/quads/shared_element_draw_quad.h"
#include "components/viz/common/quads/shared_quad_state.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/resources/platform_color.h"
#include "components/viz/common/resources/shared_image_format.h"
#include "components/viz/common/resources/shared_image_format_utils.h"
#include "components/viz/common/traced_value.h"
#include "components/viz/common/transition_utils.h"
#include "components/viz/common/view_transition_element_resource_id.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/client_shared_image.h"
#include "gpu/command_buffer/client/context_support.h"
#include "gpu/command_buffer/client/raster_interface.h"
#include "gpu/command_buffer/client/shared_image_interface.h"
#include "gpu/command_buffer/common/shared_image_capabilities.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/ipc/client/client_shared_image_interface.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_latency_info.pbzero.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/display_color_spaces.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/skia_span_util.h"
namespace cc {
namespace {
// In BuildHitTestData we iterate all layers to find all layers that overlap
// OOPIFs, but when the number of layers is greater than
// |kAssumeOverlapThreshold|, it can be inefficient to accumulate layer bounds
// for overlap checking. As a result, we are conservative and make OOPIFs
// kHitTestAsk after the threshold is reached.
const size_t kAssumeOverlapThreshold = 100;
constexpr auto kHasInputResetDelay = base::Milliseconds(250);
// gfx::DisplayColorSpaces stores up to 3 different color spaces. This should be
// updated to match any size changes in DisplayColorSpaces.
constexpr size_t kContainsSrgbCacheSize = 3;
static_assert(kContainsSrgbCacheSize ==
gfx::DisplayColorSpaces::kConfigCount / 2,
"sRGB cache must match the size of DisplayColorSpaces");
void AccumulateInvalidatedArea(
LayerImpl* layer,
base::CheckedNumeric<uint32_t>& total_invalidated_area_out) {
const Region invalidation_region = layer->GetInvalidationRegionForDebugging();
if (invalidation_region.IsEmpty() || !layer->draws_content()) {
return;
}
for (gfx::Rect rect : invalidation_region) {
total_invalidated_area_out +=
MathUtil::MapEnclosingClippedRect(layer->ScreenSpaceTransform(), rect)
.size()
.GetCheckedArea();
}
}
bool IsMobileOptimized(LayerTreeImpl* active_tree) {
return util::IsMobileOptimized(active_tree->min_page_scale_factor(),
active_tree->max_page_scale_factor(),
active_tree->current_page_scale_factor(),
active_tree->ScrollableViewportSize(),
active_tree->ScrollableSize(),
active_tree->viewport_mobile_optimized());
}
void DidVisibilityChange(LayerTreeHostImpl* id, bool visible) {
if (visible) {
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
"cc,benchmark", "LayerTreeHostImpl::SetVisible", TRACE_ID_LOCAL(id),
"LayerTreeHostImpl", static_cast<void*>(id));
return;
}
TRACE_EVENT_NESTABLE_ASYNC_END0(
"cc,benchmark", "LayerTreeHostImpl::SetVisible", TRACE_ID_LOCAL(id));
}
void PopulateMetadataContentColorUsage(
const LayerTreeHostImpl::FrameData* frame,
viz::CompositorFrameMetadata* metadata) {
metadata->content_color_usage = gfx::ContentColorUsage::kSRGB;
for (const LayerImpl* layer : frame->will_draw_layers) {
metadata->content_color_usage =
std::max(metadata->content_color_usage, layer->GetContentColorUsage());
}
}
// Dump verbose log with
// --vmodule=layer_tree_host_impl=3 for renderer only, or
// --vmodule=layer_tree_host_impl=4 for all clients.
bool VerboseLogEnabled() {
if (!VLOG_IS_ON(3))
return false;
if (VLOG_IS_ON(4))
return true;
const char* client_name = GetClientNameForMetrics();
return client_name && UNSAFE_TODO(strcmp(client_name, "Renderer")) == 0;
}
const char* ClientNameForVerboseLog() {
const char* client_name = GetClientNameForMetrics();
return client_name ? client_name : "<unknown client>";
}
#define VERBOSE_LOG() \
VLOG_IF(3, VerboseLogEnabled()) << ClientNameForVerboseLog() << ": "
} // namespace
// Holds either a created ImageDecodeCache or a ptr to a shared
// GpuImageDecodeCache.
class LayerTreeHostImpl::ImageDecodeCacheHolder {
public:
ImageDecodeCacheHolder(
const RasterCapabilities& raster_caps,
scoped_refptr<viz::RasterContextProvider> worker_context_provider,
size_t decoded_image_working_set_budget_bytes,
RasterDarkModeFilter* dark_mode_filter) {
if (raster_caps.use_gpu_rasterization) {
auto color_type = viz::ToClosestSkColorType(raster_caps.tile_format);
image_decode_cache_ = std::make_unique<GpuImageDecodeCache>(
worker_context_provider.get(),
/*use_transfer_cache=*/true, color_type,
decoded_image_working_set_budget_bytes, raster_caps.max_texture_size,
dark_mode_filter);
} else {
image_decode_cache_ = std::make_unique<SoftwareImageDecodeCache>(
viz::ToClosestSkColorType(raster_caps.tile_format),
decoded_image_working_set_budget_bytes);
}
if (image_decode_cache_) {
image_decode_cache_ptr_ = image_decode_cache_.get();
}
}
void SetShouldAggressivelyFreeResources(bool aggressively_free_resources) {
if (image_decode_cache_) {
image_decode_cache_->SetShouldAggressivelyFreeResources(
aggressively_free_resources);
}
}
ImageDecodeCache* image_decode_cache() const {
DCHECK(image_decode_cache_ptr_);
return image_decode_cache_ptr_;
}
ImageDecodeCacheHolder(const ImageDecodeCacheHolder&) = delete;
ImageDecodeCacheHolder& operator=(const ImageDecodeCacheHolder&) = delete;
private:
std::unique_ptr<ImageDecodeCache> image_decode_cache_;
// RAW_PTR_EXCLUSION: ImageDecodeCache is marked as not supported by raw_ptr.
// See raw_ptr.h for more information.
RAW_PTR_EXCLUSION ImageDecodeCache* image_decode_cache_ptr_ = nullptr;
};
void LayerTreeHostImpl::DidUpdateScrollAnimationCurve() {
// Because we updated the animation target, notify the
// `LatencyInfoSwapPromiseMonitor` to tell it that something happened that
// will cause a swap in the future. This will happen within the scope of the
// dispatch of a gesture scroll update input event. If we don't notify during
// the handling of the input event, the `LatencyInfo` associated with the
// input event will not be added as a swap promise and we won't get any swap
// results.
NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
}
void LayerTreeHostImpl::DidStartPinchZoom() {
client_->RenewTreePriority();
frame_trackers_.StartSequence(FrameSequenceTrackerType::kPinchZoom);
}
void LayerTreeHostImpl::DidEndPinchZoom() {
// When a pinch ends, we may be displaying content cached at incorrect scales,
// so updating draw properties and drawing will ensure we are using the right
// scales that we want when we're not inside a pinch.
active_tree_->set_needs_update_draw_properties();
SetNeedsRedraw();
frame_trackers_.StopSequence(FrameSequenceTrackerType::kPinchZoom);
}
void LayerTreeHostImpl::DidUpdatePinchZoom() {
SetNeedsRedraw();
client_->RenewTreePriority();
}
void LayerTreeHostImpl::DidStartScroll() {
scroll_affects_scroll_handler_ = active_tree()->have_scroll_event_handlers();
if (!settings().single_thread_proxy_scheduler) {
client_->SetHasActiveThreadedScroll(true);
}
client_->RenewTreePriority();
}
void LayerTreeHostImpl::DidEndScroll() {
scroll_affects_scroll_handler_ = false;
scroll_checkerboards_incomplete_recording_ = false;
if (!settings().single_thread_proxy_scheduler) {
client_->SetHasActiveThreadedScroll(false);
client_->SetWaitingForScrollEvent(false);
}
#if BUILDFLAG(IS_ANDROID)
if (render_frame_metadata_observer_) {
render_frame_metadata_observer_->DidEndScroll();
}
#endif
}
void LayerTreeHostImpl::DidMouseLeave() {
for (auto& pair : scrollbar_animation_controllers_)
pair.second->DidMouseLeave();
}
void LayerTreeHostImpl::SetNeedsFullViewportRedraw() {
// TODO(bokan): Do these really need to be manually called? (Rather than
// damage/redraw being set from scroll offset changes).
SetFullViewportDamage();
SetNeedsRedraw();
}
void LayerTreeHostImpl::SetDeferBeginMainFrame(
bool defer_begin_main_frame) const {
client_->SetDeferBeginMainFrameFromImpl(defer_begin_main_frame);
}
void LayerTreeHostImpl::UpdateBrowserControlsState(
BrowserControlsState constraints,
BrowserControlsState current,
bool animate,
base::optional_ref<const BrowserControlsOffsetTagModifications>
offset_tag_modifications) {
browser_controls_offset_manager_->UpdateBrowserControlsState(
constraints, current, animate, offset_tag_modifications);
}
bool LayerTreeHostImpl::HasScrollLinkedAnimation(ElementId for_scroller) const {
return mutator_host_->HasScrollLinkedAnimation(for_scroller);
}
bool LayerTreeHostImpl::IsInHighLatencyMode() const {
return impl_thread_phase_ == ImplThreadPhase::IDLE;
}
const LayerTreeSettings& LayerTreeHostImpl::GetSettings() const {
return settings();
}
LayerTreeHostImpl& LayerTreeHostImpl::GetImplDeprecated() {
return *this;
}
const LayerTreeHostImpl& LayerTreeHostImpl::GetImplDeprecated() const {
return *this;
}
LayerTreeHostImpl::FrameData::FrameData() = default;
LayerTreeHostImpl::FrameData::~FrameData() = default;
LayerTreeHostImpl::UIResourceData::UIResourceData() = default;
LayerTreeHostImpl::UIResourceData::~UIResourceData() = default;
LayerTreeHostImpl::UIResourceData::UIResourceData(UIResourceData&&) noexcept =
default;
LayerTreeHostImpl::UIResourceData& LayerTreeHostImpl::UIResourceData::operator=(
UIResourceData&&) = default;
std::unique_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
const LayerTreeSettings& settings,
LayerTreeHostImplClient* client,
TaskRunnerProvider* task_runner_provider,
RenderingStatsInstrumentation* rendering_stats_instrumentation,
TaskGraphRunner* task_graph_runner,
std::unique_ptr<MutatorHost> mutator_host,
RasterDarkModeFilter* dark_mode_filter,
int id,
scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner,
LayerTreeHostSchedulingClient* scheduling_client) {
return base::WrapUnique(new LayerTreeHostImpl(
settings, client, task_runner_provider, rendering_stats_instrumentation,
task_graph_runner, std::move(mutator_host), dark_mode_filter, id,
std::move(image_worker_task_runner), scheduling_client));
}
LayerTreeHostImpl::LayerTreeHostImpl(
const LayerTreeSettings& settings,
LayerTreeHostImplClient* client,
TaskRunnerProvider* task_runner_provider,
RenderingStatsInstrumentation* rendering_stats_instrumentation,
TaskGraphRunner* task_graph_runner,
std::unique_ptr<MutatorHost> mutator_host,
RasterDarkModeFilter* dark_mode_filter,
int id,
scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner,
LayerTreeHostSchedulingClient* scheduling_client)
: client_(client),
scheduling_client_(scheduling_client),
task_runner_provider_(task_runner_provider),
current_begin_frame_tracker_(FROM_HERE),
settings_(settings),
use_layer_context_for_animations_(
settings_.UseLayerContextForAnimations()),
is_synchronous_single_threaded_(!task_runner_provider->HasImplThread() &&
!settings_.single_thread_proxy_scheduler),
cached_managed_memory_policy_(settings.memory_policy),
// Must be initialized after is_synchronous_single_threaded_ and
// task_runner_provider_.
tile_manager_(this,
GetTaskRunner(),
std::move(image_worker_task_runner),
is_synchronous_single_threaded_
? std::numeric_limits<size_t>::max()
: settings.scheduled_raster_task_limit,
RunningOnRendererProcess(),
settings.ToTileManagerSettings()),
memory_history_(MemoryHistory::Create()),
debug_rect_history_(DebugRectHistory::Create()),
mutator_host_(std::move(mutator_host)),
dark_mode_filter_(dark_mode_filter),
rendering_stats_instrumentation_(rendering_stats_instrumentation),
micro_benchmark_controller_(this),
task_graph_runner_(task_graph_runner),
id_(id),
consecutive_frame_with_damage_count_(settings.damaged_frame_limit),
// It is safe to use base::Unretained here since we will outlive the
// ImageAnimationController.
image_animation_controller_(GetTaskRunner(),
this,
settings_.enable_image_animation_resync),
compositor_frame_reporting_controller_(
std::make_unique<CompositorFrameReportingController>(
/*should_report_histograms=*/!settings
.single_thread_proxy_scheduler,
/*should_report_ukm=*/!settings.single_thread_proxy_scheduler,
id)),
frame_trackers_(settings.single_thread_proxy_scheduler),
lcd_text_metrics_reporter_(LCDTextMetricsReporter::CreateIfNeeded(this)),
has_input_resetter_(
GetTaskRunner(),
base::BindRepeating(&LayerTreeHostImpl::ResetHasInputForFrameInterval,
base::Unretained(this)),
kHasInputResetDelay),
contains_srgb_cache_(kContainsSrgbCacheSize) {
resource_provider_ = std::make_unique<viz::ClientResourceProvider>(
task_runner_provider_->MainThreadTaskRunner(),
task_runner_provider_->HasImplThread()
? task_runner_provider_->ImplThreadTaskRunner()
: task_runner_provider_->MainThreadTaskRunner(),
base::BindRepeating(&LayerTreeHostImpl::MaybeFlushPendingWork,
weak_factory_.GetWeakPtr()));
DCHECK(mutator_host_);
mutator_host_->SetMutatorHostClient(this);
mutator_events_ = mutator_host_->CreateEvents();
DCHECK(task_runner_provider_->IsImplThread());
DidVisibilityChange(this, visible_);
// LTHI always has an active tree.
active_tree_ = std::make_unique<LayerTreeImpl>(
*this, viz::BeginFrameArgs(), new SyncedScale, new SyncedBrowserControls,
new SyncedBrowserControls, new SyncedElasticOverscroll);
active_tree_->property_trees()->set_is_active(true);
viewport_ = Viewport::Create(this);
TRACE_EVENT_OBJECT_CREATED_WITH_ID(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"cc::LayerTreeHostImpl", id_);
browser_controls_offset_manager_ = BrowserControlsOffsetManager::Create(
this, settings.top_controls_show_threshold,
settings.top_controls_hide_threshold);
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableLayerTreeHostMemoryPressure)) {
memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>(
FROM_HERE, base::BindRepeating(&LayerTreeHostImpl::OnMemoryPressure,
base::Unretained(this)));
}
SetDebugState(settings.initial_debug_state);
compositor_frame_reporting_controller_->SetFrameSorter(&frame_sorter_);
compositor_frame_reporting_controller_->SetFrameSequenceTrackerCollection(
&frame_trackers_);
const bool is_ui = settings.is_layer_tree_for_ui;
if (is_ui) {
compositor_frame_reporting_controller_->set_event_latency_tracker(this);
#if BUILDFLAG(IS_CHROMEOS)
frame_sorter_.EnableReportForUI();
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kCompositorAnimation);
#endif // BUILDFLAG(IS_CHROMEOS)
}
frame_trackers_.set_custom_tracker_results_added_callback(base::BindRepeating(
&LayerTreeHostImpl::NotifyCompositorMetricsTrackerResults,
weak_factory_.GetWeakPtr()));
if (settings_.is_layer_tree_for_ui) {
total_invalidated_area_ = 0u;
}
}
LayerTreeHostImpl::~LayerTreeHostImpl() {
DCHECK(task_runner_provider_->IsImplThread());
TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
TRACE_EVENT_OBJECT_DELETED_WITH_ID(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"cc::LayerTreeHostImpl", id_);
// The frame sink is released before shutdown, which takes down
// all the resource and raster structures.
DCHECK(!layer_tree_frame_sink_);
DCHECK(!resource_pool_);
DCHECK(!image_decode_cache_holder_);
DCHECK(!single_thread_synchronous_task_graph_runner_);
DetachInputDelegateAndRenderFrameObserver();
// The layer trees must be destroyed before the LayerTreeHost. Also, if they
// are holding onto any resources, destroying them will release them, before
// we mark any leftover resources as lost.
if (recycle_tree_)
recycle_tree_->Shutdown();
if (pending_tree_)
pending_tree_->Shutdown();
active_tree_->Shutdown();
recycle_tree_ = nullptr;
pending_tree_ = nullptr;
active_tree_ = nullptr;
// All resources should already be removed, so lose anything still exported.
resource_provider_->ShutdownAndReleaseAllResources();
mutator_host_->ClearMutators();
mutator_host_->SetMutatorHostClient(nullptr);
// The `compositor_frame_reporting_controller_`
// was given a `this` pointer for the event_latency_tracker and thus needs
// to be nulled to prevent it dangling. Members will be destroyed in reverse
// order of their declaration, so since event latency tracker is destroyed
// first, we need to clar the pointer that
// `compositor_frame_reporting_controller_` holds.
compositor_frame_reporting_controller_->set_event_latency_tracker(nullptr);
// CFRC needs to unregister the frame trackers from the frame_sorter observer
// set before being cleaned up.
compositor_frame_reporting_controller_->ClearFrameSequenceTrackerCollection();
}
InputHandler& LayerTreeHostImpl::GetInputHandler() {
DCHECK(input_delegate_) << "Requested InputHandler when one wasn't bound. "
"Call BindToInputHandler to bind to one";
return static_cast<InputHandler&>(*input_delegate_.get());
}
const InputHandler& LayerTreeHostImpl::GetInputHandler() const {
DCHECK(input_delegate_) << "Requested InputHandler when one wasn't bound. "
"Call BindToInputHandler to bind to one";
return static_cast<const InputHandler&>(*input_delegate_.get());
}
void LayerTreeHostImpl::BeginMainFrameAborted(
CommitEarlyOutReason reason,
std::vector<std::unique_ptr<SwapPromise>> swap_promises,
const viz::BeginFrameArgs& args,
bool next_bmf,
bool scroll_and_viewport_changes_synced) {
// If the begin frame data was handled, then scroll and scale set was applied
// by the main thread, so the active tree needs to be updated as if these sent
// values were applied and committed.
bool main_frame_applied_deltas = MainFrameAppliedDeltas(reason);
active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit(
next_bmf, main_frame_applied_deltas);
if (main_frame_applied_deltas) {
if (pending_tree_) {
pending_tree_->AppendSwapPromises(std::move(swap_promises));
} else {
base::TimeTicks timestamp = base::TimeTicks::Now();
for (const auto& swap_promise : swap_promises) {
SwapPromise::DidNotSwapAction action =
swap_promise->DidNotSwap(SwapPromise::COMMIT_NO_UPDATE, timestamp);
DCHECK_EQ(action, SwapPromise::DidNotSwapAction::BREAK_PROMISE);
}
}
}
// Notify the browser controls manager that we have processed any
// controls constraint update.
if (scroll_and_viewport_changes_synced && browser_controls_manager()) {
browser_controls_manager()->NotifyConstraintSyncedToMainThread();
}
}
void LayerTreeHostImpl::ReadyToCommit(
bool scroll_and_viewport_changes_synced,
const BeginMainFrameMetrics* begin_main_frame_metrics,
bool commit_timeout) {
if (((begin_main_frame_metrics &&
begin_main_frame_metrics->should_measure_smoothness) ||
commit_timeout) &&
!frame_sorter_.first_contentful_paint_received()) {
frame_sorter_.OnFirstContentfulPaintReceived();
}
// Notify the browser controls manager that we have processed any
// controls constraint update.
if (scroll_and_viewport_changes_synced && browser_controls_manager()) {
browser_controls_manager()->NotifyConstraintSyncedToMainThread();
}
// If the scroll offsets were not synchronized, undo the sending of offsets
// similar to what's done when the commit is aborted.
if (!scroll_and_viewport_changes_synced) {
active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit(
/*next_bmf=*/false, /*main_frame_applied_deltas=*/false);
}
}
void LayerTreeHostImpl::BeginCommit(int source_frame_number,
BeginMainFrameTraceId trace_id) {
TRACE_EVENT0("cc", "LayerTreeHostImpl::BeginCommit");
if (!CommitsToActiveTree()) {
CreatePendingTree();
}
sync_tree()->set_source_frame_number(source_frame_number);
sync_tree()->set_trace_id(trace_id);
}
// This function commits the LayerTreeHost, as represented by CommitState, to an
// impl tree. When modifying this function -- and all code that it calls into
// -- care must be taken to avoid using LayerTreeHost directly (e.g., via
// state.root_layer->layer_tree_host()) as that will likely introduce thread
// safety violations. Any information that is needed from LayerTreeHost should
// instead be plumbed through CommitState (see
// LayerTreeHost::ActivateCommitState() for reference).
void LayerTreeHostImpl::FinishCommit(
CommitState& state,
const ThreadUnsafeCommitState& unsafe_state) {
TRACE_EVENT0("cc,benchmark", "LayerTreeHostImpl::FinishCommit");
LayerTreeImpl* tree = sync_tree();
{
// Instead of individual `Layer::PushPropertiesTo` triggering separate
// thread hops to the main-thread, to complete releasing resources. Batch
// all of them together for after `PullPropertiesFrom` completes.
viz::ClientResourceProvider::ScopedBatchResourcesRelease
scoped_resource_release =
resource_provider_->CreateScopedBatchResourcesRelease();
tree->PullPropertiesFrom(state, unsafe_state);
}
// Check whether the impl scroll animating nodes were removed by the commit.
mutator_host()->HandleRemovedScrollAnimatingElements(CommitsToActiveTree());
PullLayerTreeHostPropertiesFrom(state);
// Transfer image decode requests to the impl thread.
for (auto& entry : state.queued_image_decodes) {
QueueImageDecode(std::get<0>(entry), *std::get<1>(entry),
std::get<2>(entry));
}
for (auto& benchmark : state.benchmarks)
ScheduleMicroBenchmark(std::move(benchmark));
new_local_surface_id_expected_ = false;
// Dump property trees and layers if VerboseLogEnabled().
VERBOSE_LOG() << "After finishing commit on impl, the sync tree:"
<< "\nproperty_trees:\n"
<< tree->property_trees()->ToString() << "\n"
<< "cc::LayerImpls:\n"
<< tree->LayerListAsJson();
}
void LayerTreeHostImpl::PullLayerTreeHostPropertiesFrom(
const CommitState& commit_state) {
// TODO(bokan): The |external_pinch_gesture_active| should not be going
// through the LayerTreeHost but directly from InputHandler to InputHandler.
SetExternalPinchGestureActive(commit_state.is_external_pinch_gesture_active);
if (commit_state.needs_gpu_rasterization_histogram)
RecordGpuRasterizationHistogram();
SetDebugState(commit_state.debug_state);
SetVisualDeviceViewportSize(commit_state.visual_device_viewport_size);
set_viewport_mobile_optimized(commit_state.is_viewport_mobile_optimized);
SetPrefersReducedMotion(commit_state.prefers_reduced_motion);
SetMayThrottleIfUndrawnFrames(commit_state.may_throttle_if_undrawn_frames);
}
void LayerTreeHostImpl::RecordGpuRasterizationHistogram() {
// Record how widely gpu rasterization is enabled.
// This number takes device/gpu allowlist/denylist into account.
// Note that we do not consider the forced gpu rasterization mode, which is
// mostly used for debugging purposes.
UMA_HISTOGRAM_BOOLEAN("Renderer4.GpuRasterizationEnabled",
raster_caps().use_gpu_rasterization);
}
void LayerTreeHostImpl::CommitComplete() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
TRACE_EVENT(
"cc,benchmark", "LayerTreeHostImpl::CommitComplete",
[&](perfetto::EventContext ctx) {
EmitMainFramePipelineStep(
ctx, sync_tree()->trace_id(),
perfetto::protos::pbzero::MainFramePipeline::Step::COMMIT_COMPLETE);
});
if (input_delegate_)
input_delegate_->DidCommit();
if (CommitsToActiveTree()) {
active_tree_->HandleScrollbarShowRequests();
// We have to activate animations here or "IsActive()" is true on the layers
// but the animations aren't activated yet so they get ignored by
// UpdateDrawProperties.
ActivateAnimations();
}
// We clear the entries that were never mutated by CC animations from the last
// commit until now. Moreover, we reset the values of input properties and
// relies on the fact that CC animation will mutate those values when pending
// tree is animated below.
// With that, when CC finishes animating an input property, the value of that
// property stays at finish state until a commit kicks in, which is consistent
// with current composited animations.
paint_worklet_tracker_.ClearUnusedInputProperties();
// Start animations before UpdateDrawProperties and PrepareTiles, as they can
// change the results. When doing commit to the active tree, this must happen
// after ActivateAnimations() in order for this ticking to be propagated
// to layers on the active tree.
if (CommitsToActiveTree()) {
Animate();
} else {
AnimatePendingTreeAfterCommit();
}
UpdateSyncTreeAfterCommitOrImplSideInvalidation();
micro_benchmark_controller_.DidCompleteCommit();
if (mutator_host_->CurrentFrameHadRAF())
frame_trackers_.StartSequence(FrameSequenceTrackerType::kRAF);
if (mutator_host_->HasCanvasInvalidation())
frame_trackers_.StartSequence(FrameSequenceTrackerType::kCanvasAnimation);
if (mutator_host_->CurrentFrameHadRAF() || mutator_host_->HasJSAnimation())
frame_trackers_.StartSequence(FrameSequenceTrackerType::kJSAnimation);
if (mutator_host_->MainThreadAnimationsCount() > 0 ||
mutator_host_->HasSmilAnimation()) {
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kMainThreadAnimation);
if (mutator_host_->HasViewTransition()) {
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kSETMainThreadAnimation);
}
}
for (const auto& info :
mutator_host_->TakePendingCompositorMetricsTrackerInfos()) {
const MutatorHost::TrackedAnimationSequenceId sequence_id = info.id;
const bool start = info.start;
if (start)
frame_trackers_.StartCustomSequence(sequence_id);
else
frame_trackers_.StopCustomSequence(sequence_id);
}
}
void LayerTreeHostImpl::UpdateSyncTreeAfterCommitOrImplSideInvalidation() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
sync_tree()->set_needs_update_draw_properties();
// We need an update immediately post-commit to have the opportunity to create
// tilings.
// We can avoid updating the ImageAnimationController during this
// DrawProperties update since it will be done when we animate the controller
// below.
bool update_tiles = true;
bool update_image_animation_controller = false;
sync_tree()->UpdateDrawProperties(update_tiles,
update_image_animation_controller);
sync_tree()->InvalidateRasterInducingScrolls(
pending_invalidation_raster_inducing_scrolls_);
pending_invalidation_raster_inducing_scrolls_.clear();
// Defer invalidating images until UpdateDrawProperties and
// InvalidateRasterInducingScroll is performed since those update whether an
// image should be animated based on its visibility and the updated data for
// the image from the main frame.
PaintImageIdFlatSet images_to_invalidate =
tile_manager_.TakeImagesToInvalidateOnSyncTree();
const auto& animated_images =
image_animation_controller_.AnimateForSyncTree(CurrentBeginFrameArgs());
images_to_invalidate.insert(animated_images.begin(), animated_images.end());
// Invalidate cached PaintRecords for worklets whose input properties were
// mutated since the last pending tree. We keep requesting invalidations until
// the animation is ticking on impl thread. Note that this works since the
// animation starts ticking on the pending tree
// (AnimatePendingTreeAfterCommit) which committed this animation timeline.
// After this the animation may only tick on the active tree for impl-side
// invalidations (since AnimatePendingTreeAfterCommit is not done for pending
// trees created by impl-side invalidations). But we ensure here that we
// request another invalidation if an input property was mutated on the active
// tree.
if (paint_worklet_tracker_.InvalidatePaintWorkletsOnPendingTree()) {
client_->SetNeedsImplSideInvalidation(
true /* needs_first_draw_on_activation */);
}
PaintImageIdFlatSet dirty_paint_worklet_ids;
PaintWorkletJobMap dirty_paint_worklets =
GatherDirtyPaintWorklets(&dirty_paint_worklet_ids);
images_to_invalidate.insert(dirty_paint_worklet_ids.begin(),
dirty_paint_worklet_ids.end());
sync_tree()->InvalidateRegionForImages(images_to_invalidate);
// Note that it is important to push the state for checkerboarded and animated
// images prior to PrepareTiles here when committing to the active tree. This
// is because new tiles on the active tree depend on tree specific state
// cached in these components, which must be pushed to active before preparing
// tiles for the updated active tree.
if (CommitsToActiveTree()) {
ActivateStateForImages();
}
sync_tree()->SetCreatedBeginFrameArgs(CurrentBeginFrameArgs());
if (!paint_worklet_painter_) {
// Blink should not send us any PaintWorklet inputs until we have a painter
// registered.
DCHECK(sync_tree()->picture_layers_with_paint_worklets().empty());
pending_tree_fully_painted_ = true;
NotifyPendingTreeFullyPainted();
return;
}
if (!dirty_paint_worklets.size()) {
pending_tree_fully_painted_ = true;
NotifyPendingTreeFullyPainted();
return;
}
client_->NotifyPaintWorkletStateChange(
Scheduler::PaintWorkletState::PROCESSING);
auto done_callback = base::BindOnce(
&LayerTreeHostImpl::OnPaintWorkletResultsReady, base::Unretained(this));
paint_worklet_painter_->DispatchWorklets(std::move(dirty_paint_worklets),
std::move(done_callback));
}
PaintWorkletJobMap LayerTreeHostImpl::GatherDirtyPaintWorklets(
PaintImageIdFlatSet* dirty_paint_worklet_ids) const {
PaintWorkletJobMap dirty_paint_worklets;
for (PictureLayerImpl* layer :
sync_tree()->picture_layers_with_paint_worklets()) {
for (const auto& entry : layer->GetPaintWorkletRecordMap()) {
const scoped_refptr<const PaintWorkletInput>& input = entry.first;
const PaintImage::Id& paint_image_id = entry.second.first;
const std::optional<PaintRecord>& record = entry.second.second;
// If we already have a record we can reuse it and so the
// PaintWorkletInput isn't dirty.
if (record)
continue;
// Mark this PaintWorklet as needing invalidation.
dirty_paint_worklet_ids->insert(paint_image_id);
// Create an entry in the appropriate PaintWorkletJobVector for this dirty
// PaintWorklet.
int worklet_id = input->WorkletId();
auto& job_vector = dirty_paint_worklets[worklet_id];
if (!job_vector)
job_vector = base::MakeRefCounted<PaintWorkletJobVector>();
PaintWorkletJob::AnimatedPropertyValues animated_property_values;
for (const auto& element : input->GetPropertyKeys()) {
DCHECK(!animated_property_values.contains(element));
const PaintWorkletInput::PropertyValue& animated_property_value =
paint_worklet_tracker_.GetPropertyAnimationValue(element);
// No value indicates that the input property was not mutated by CC
// animation.
if (animated_property_value.has_value())
animated_property_values.emplace(element, animated_property_value);
}
job_vector->data.emplace_back(layer->id(), input,
std::move(animated_property_values));
}
}
return dirty_paint_worklets;
}
void LayerTreeHostImpl::OnPaintWorkletResultsReady(PaintWorkletJobMap results) {
#if DCHECK_IS_ON()
// Nothing else should have painted the PaintWorklets while we were waiting,
// and the results should have painted every PaintWorklet, so these should be
// the same.
PaintImageIdFlatSet dirty_paint_worklet_ids;
DCHECK_EQ(results.size(),
GatherDirtyPaintWorklets(&dirty_paint_worklet_ids).size());
#endif
for (const auto& entry : results) {
for (const PaintWorkletJob& job : entry.second->data) {
LayerImpl* layer_impl =
pending_tree_->FindPendingTreeLayerById(job.layer_id());
// Painting the pending tree occurs asynchronously but stalls the pending
// tree pipeline, so nothing should have changed while we were doing that.
DCHECK(layer_impl);
static_cast<PictureLayerImpl*>(layer_impl)
->SetPaintWorkletRecord(job.input(), job.output());
}
}
// While the pending tree is being painted by PaintWorklets, we restrict the
// tiles the TileManager is able to see. This may cause the TileManager to
// believe that it has finished rastering all the necessary tiles. When we
// finish painting the tree and release all the tiles, we need to mark the
// tile priorities as dirty so that the TileManager logic properly re-runs.
tile_priorities_dirty_ = true;
// Set the painted state before calling the scheduler, to ensure any callback
// running as a result sees the correct painted state.
pending_tree_fully_painted_ = true;
client_->NotifyPaintWorkletStateChange(Scheduler::PaintWorkletState::IDLE);
// The pending tree may have been force activated from the signal to the
// scheduler above, in which case there is no longer a tree to paint.
if (pending_tree_)
NotifyPendingTreeFullyPainted();
}
void LayerTreeHostImpl::NotifyPendingTreeFullyPainted() {
// The pending tree must be fully painted at this point.
DCHECK(pending_tree_fully_painted_ && !settings_.trees_in_viz_in_viz_process);
// Nobody should claim the pending tree is fully painted if there is an
// ongoing dispatch.
DCHECK(!paint_worklet_painter_ ||
!paint_worklet_painter_->HasOngoingDispatch());
// Start working on newly created tiles immediately if needed.
// TODO(vmpstr): Investigate always having PrepareTiles issue
// NotifyReadyToActivate, instead of handling it here.
bool did_prepare_tiles = PrepareTiles();
if (!did_prepare_tiles) {
NotifyReadyToActivate();
// Ensure we get ReadyToDraw signal even when PrepareTiles not run. This
// is important for SingleThreadProxy and impl-side painting case. For
// STP, we commit to active tree and RequiresHighResToDraw, and set
// Scheduler to wait for ReadyToDraw signal to avoid Checkerboard.
if (CommitsToActiveTree() ||
settings_.wait_for_all_pipeline_stages_before_draw) {
NotifyReadyToDraw();
}
}
}
bool LayerTreeHostImpl::CanDraw() const {
// Note: If you are changing this function or any other function that might
// affect the result of CanDraw, make sure to call
// client_->OnCanDrawStateChanged in the proper places and update the
// NotifyIfCanDrawChanged test.
if (!layer_tree_frame_sink_) {
TRACE_EVENT_INSTANT0("cc",
"LayerTreeHostImpl::CanDraw no LayerTreeFrameSink",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
// TODO(boliu): Make draws without layers work and move this below
// |resourceless_software_draw_| check. Tracked in crbug.com/264967.
if (active_tree_->LayerListIsEmpty()) {
TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
if (resourceless_software_draw_)
return true;
// Do not draw while evicted. Await the activation of a tree containing a
// newer viz::Surface
if (base::FeatureList::IsEnabled(features::kEvictionThrottlesDraw) &&
evicted_local_surface_id_.is_valid()) {
TRACE_EVENT_INSTANT0(
"cc",
"LayerTreeHostImpl::CanDraw viz::Surface evicted and not recreated",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
if (active_tree_->GetDeviceViewport().IsEmpty()) {
TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
if (EvictedUIResourcesExist()) {
TRACE_EVENT_INSTANT0(
"cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
return true;
}
void LayerTreeHostImpl::AnimatePendingTreeAfterCommit() {
// Animate the pending tree layer animations to put them at initial positions
// and starting state. There is no need to run other animations on pending
// tree because they depend on user inputs so the state is identical to what
// the active tree has.
AnimateLayers(CurrentBeginFrameArgs().frame_time, /* is_active_tree */ false);
}
void LayerTreeHostImpl::Animate() {
AnimateInternal();
}
void LayerTreeHostImpl::AnimateInternal() {
DCHECK(task_runner_provider_->IsImplThread());
base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
// mithro(TODO): Enable these checks.
// DCHECK(!current_begin_frame_tracker_.HasFinished());
// DCHECK(monotonic_time == current_begin_frame_tracker_.Current().frame_time)
// << "Called animate with unknown frame time!?";
bool did_animate = false;
// TODO(bokan): This should return did_animate, see TODO in
// ElasticOverscrollController::Animate. crbug.com/551138.
if (input_delegate_)
input_delegate_->TickAnimations(monotonic_time);
did_animate |= AnimatePageScale(monotonic_time);
did_animate |= AnimateLayers(monotonic_time, /* is_active_tree */ true);
did_animate |= AnimateScrollbars(monotonic_time);
did_animate |= AnimateBrowserControls(monotonic_time);
if (did_animate) {
// Animating stuff can change the root scroll offset, so inform the
// synchronous input handler.
if (input_delegate_)
input_delegate_->RootLayerStateMayHaveChanged();
// If the tree changed, then we want to draw at the end of the current
// frame.
SetNeedsRedraw(/*animation_only*/ true);
}
}
bool LayerTreeHostImpl::PrepareTiles() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
tile_priorities_dirty_ |= active_tree() && active_tree()->UpdateTiles();
tile_priorities_dirty_ |= pending_tree() && pending_tree()->UpdateTiles();
if (!tile_priorities_dirty_)
return false;
bool did_prepare_tiles = tile_manager_.PrepareTiles(global_tile_state_);
if (did_prepare_tiles)
tile_priorities_dirty_ = false;
client_->DidPrepareTiles();
return did_prepare_tiles;
}
void LayerTreeHostImpl::StartPageScaleAnimation(const gfx::Point& target_offset,
bool anchor_point,
float page_scale,
base::TimeDelta duration) {
if (!InnerViewportScrollNode())
return;
gfx::PointF scroll_total = active_tree_->TotalScrollOffset();
gfx::SizeF scrollable_size = active_tree_->ScrollableSize();
gfx::SizeF viewport_size(
active_tree_->InnerViewportScrollNode()->container_bounds);
if (viewport_size.IsEmpty()) {
// Avoid divide by zero. Besides nothing should see the animation anyway.
return;
}
// TODO(miletus) : Pass in ScrollOffset.
page_scale_animation_ = PageScaleAnimation::Create(
scroll_total, active_tree_->current_page_scale_factor(), viewport_size,
scrollable_size);
if (anchor_point) {
gfx::PointF anchor(target_offset);
page_scale_animation_->ZoomWithAnchor(anchor, page_scale,
duration.InSecondsF());
} else {
gfx::PointF scaled_target_offset(target_offset);
page_scale_animation_->ZoomTo(scaled_target_offset, page_scale,
duration.InSecondsF());
}
SetNeedsOneBeginImplFrame();
client_->SetNeedsCommitOnImplThread();
client_->RenewTreePriority();
}
void LayerTreeHostImpl::SetNeedsAnimateInput() {
SetNeedsOneBeginImplFrame();
}
std::unique_ptr<LatencyInfoSwapPromiseMonitor>
LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
ui::LatencyInfo* latency) {
return std::make_unique<LatencyInfoSwapPromiseMonitor>(latency, this);
}
std::unique_ptr<EventsMetricsManager::ScopedMonitor>
LayerTreeHostImpl::GetScopedEventMetricsMonitor(
EventsMetricsManager::ScopedMonitor::DoneCallback done_callback) {
return events_metrics_manager_.GetScopedMonitor(std::move(done_callback));
}
void LayerTreeHostImpl::DidScrollForMetrics() {
return events_metrics_manager_.set_did_scroll(true);
}
void LayerTreeHostImpl::NotifyInputEvent(bool is_fling) {
has_input_for_frame_interval_ = true;
has_input_resetter_.Schedule();
has_non_fling_input_since_last_frame_ |= (!is_fling);
}
void LayerTreeHostImpl::QueueSwapPromiseForMainThreadScrollUpdate(
std::unique_ptr<SwapPromise> swap_promise) {
swap_promises_for_main_thread_scroll_update_.push_back(
std::move(swap_promise));
}
void LayerTreeHostImpl::FrameData::AsValueInto(
base::trace_event::TracedValue* value) const {
value->SetBoolean("has_no_damage", has_no_damage);
// Quad data can be quite large, so only dump render passes if we are
// logging verbosely or viz.quads tracing category is enabled.
bool quads_enabled = VerboseLogEnabled();
if (!quads_enabled) {
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("viz.quads"),
&quads_enabled);
}
if (quads_enabled) {
value->BeginArray("render_passes");
for (const auto& render_pass : render_passes) {
value->BeginDictionary();
render_pass->AsValueInto(value);
value->EndDictionary();
}
value->EndArray();
}
}
std::string LayerTreeHostImpl::FrameData::ToString() const {
base::trace_event::TracedValueJSON value;
AsValueInto(&value);
return value.ToFormattedJSON();
}
DrawMode LayerTreeHostImpl::GetDrawMode() const {
if (resourceless_software_draw_) {
return DRAW_MODE_RESOURCELESS_SOFTWARE;
} else if (layer_tree_frame_sink_->context_provider() ||
(settings_.trees_in_viz_in_viz_process &&
settings_.display_tree_draw_mode_is_gpu)) {
return DRAW_MODE_HARDWARE;
} else {
return DRAW_MODE_SOFTWARE;
}
}
static void AppendQuadsToFillScreen(
viz::CompositorRenderPass* target_render_pass,
const RenderSurfaceImpl* root_render_surface,
SkColor4f screen_background_color,
const Region& fill_region) {
if (!root_render_surface || !screen_background_color.fA)
return;
if (fill_region.IsEmpty())
return;
// Manually create the quad state for the gutter quads, as the root layer
// doesn't have any bounds and so can't generate this itself.
// TODO(danakj): Make the gutter quads generated by the solid color layer
// (make it smarter about generating quads to fill unoccluded areas).
const gfx::Rect root_target_rect = root_render_surface->content_rect();
viz::SharedQuadState* shared_quad_state =
target_render_pass->CreateAndAppendSharedQuadState();
shared_quad_state->SetAll(
gfx::Transform(), root_target_rect, root_target_rect,
gfx::MaskFilterInfo(), std::nullopt, screen_background_color.isOpaque(),
/*opacity_f=*/1.f, SkBlendMode::kSrcOver, /*sorting_context=*/0,
/*layer_id=*/0u, /*fast_rounded_corner=*/false);
for (gfx::Rect screen_space_rect : fill_region) {
gfx::Rect visible_screen_space_rect = screen_space_rect;
// Skip the quad culler and just append the quads directly to avoid
// occlusion checks.
auto* quad =
target_render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
quad->SetNew(shared_quad_state, screen_space_rect,
visible_screen_space_rect, screen_background_color, false);
}
}
static viz::CompositorRenderPass* FindRenderPassById(
const viz::CompositorRenderPassList& list,
viz::CompositorRenderPassId id) {
auto it = std::ranges::find(list, id, &viz::CompositorRenderPass::id);
return it == list.end() ? nullptr : it->get();
}
bool LayerTreeHostImpl::HasDamage() const {
DCHECK(!active_tree()->needs_update_draw_properties());
DCHECK(CanDraw());
// When touch handle visibility changes there is no visible damage
// because touch handles are composited in the browser. However we
// still want the browser to be notified that the handles changed
// through the |ViewHostMsg_SwapCompositorFrame| IPC so we keep
// track of handle visibility changes here.
if (active_tree()->HandleVisibilityChanged())
return true;
if (!viewport_damage_rect_.IsEmpty())
return true;
// If the set of referenced surfaces has changed then we must submit a new
// CompositorFrame to update surface references.
if (last_draw_referenced_surfaces_ != active_tree()->SurfaceRanges())
return true;
// If we have a new LocalSurfaceId, we must always submit a CompositorFrame
// because the parent is blocking on us.
if (last_draw_local_surface_id_ != GetCurrentLocalSurfaceId()) {
return true;
}
const LayerTreeImpl* active_tree = active_tree_.get();
// Make sure we propagate the primary main item sequence number. If there is
// no stored sequence number, we don't need to damage: either damage will
// happen anyway, or we're not generating metadata entries.
if (last_draw_render_frame_metadata_ &&
last_draw_render_frame_metadata_
->primary_main_frame_item_sequence_number !=
active_tree->primary_main_frame_item_sequence_number()) {
return true;
}
// If the root render surface has no visible damage, then don't generate a
// frame at all.
const RenderSurfaceImpl* root_surface = active_tree->RootRenderSurface();
bool root_surface_has_visible_damage =
root_surface->GetDamageRect().Intersects(root_surface->content_rect());
bool hud_wants_to_draw_ = active_tree->hud_layer() &&
active_tree->hud_layer()->IsAnimatingHUDContents();
return root_surface_has_visible_damage ||
active_tree_->property_trees()->effect_tree().HasCopyRequests() ||
hud_wants_to_draw_ || active_tree_->HasViewTransitionRequests();
}
DrawResult LayerTreeHostImpl::CalculateRenderPasses(FrameData* frame) {
DCHECK(frame->render_passes.empty());
DCHECK(CanDraw());
DCHECK(!active_tree_->LayerListIsEmpty());
// For now, we use damage tracking to compute a global scissor. To do this, we
// must compute all damage tracking before drawing anything, so that we know
// the root damage rect. The root damage rect is then used to scissor each
// surface.
DamageTracker::UpdateDamageTracking(active_tree_.get());
frame->damage_reasons =
active_tree_->RootRenderSurface()->damage_tracker()->GetDamageReasons();
if (HasDamage()) {
consecutive_frame_with_damage_count_++;
} else {
TRACE_EVENT0("cc",
"LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
frame->has_no_damage = true;
DCHECK(!resourceless_software_draw_);
consecutive_frame_with_damage_count_ = 0;
return DrawResult::kSuccess;
}
TRACE_EVENT_BEGIN2("cc,benchmark", "LayerTreeHostImpl::CalculateRenderPasses",
"render_surface_list.size()",
static_cast<uint64_t>(frame->render_surface_list->size()),
"RequiresHighResToDraw", RequiresHighResToDraw());
// HandleVisibilityChanged contributed to the above damage check, so reset it
// now that we're going to draw.
// TODO(jamwalla): only call this if we are sure the frame draws. Tracked in
// crbug.com/805673.
active_tree_->ResetHandleVisibilityChanged();
frame->has_view_transition_save_directive =
active_tree_->HasViewTransitionSaveRequest();
base::flat_set<viz::ViewTransitionElementResourceId> known_resource_ids;
base::flat_set<blink::ViewTransitionToken> capture_view_transition_tokens =
active_tree()->GetCaptureViewTransitionTokens();
// Create the render passes in dependency order.
size_t render_surface_list_size = frame->render_surface_list->size();
for (size_t i = 0; i < render_surface_list_size; ++i) {
const size_t surface_index = render_surface_list_size - 1 - i;
RenderSurfaceImpl* render_surface =
(*frame->render_surface_list)[surface_index];
const bool is_root_surface =
render_surface->EffectTreeIndex() == kContentsRootPropertyNodeId;
const bool should_draw_into_render_pass =
is_root_surface || render_surface->contributes_to_drawn_surface() ||
render_surface->CopyOfOutputRequired();
const auto& view_transition_element_resource_id =
render_surface->ViewTransitionElementResourceId();
if (should_draw_into_render_pass) {
// Create a capture render pass if we're in the capture phase for this
// render surface.
if (render_surface->has_view_transition_capture_contributions()) {
frame->render_passes.push_back(
render_surface->CreateViewTransitionCaptureRenderPass(
capture_view_transition_tokens));
}
frame->render_passes.push_back(
render_surface->CreateRenderPass(capture_view_transition_tokens));
}
if (view_transition_element_resource_id.IsValid()) {
known_resource_ids.insert(view_transition_element_resource_id);
}
}
// When we are displaying the HUD, change the root damage rect to cover the
// entire root surface. This will disable partial-swap/scissor optimizations
// that would prevent the HUD from updating, since the HUD does not cause
// damage itself, to prevent it from messing with damage visualizations. Since
// damage visualizations are done off the LayerImpls and RenderSurfaceImpls,
// changing the RenderPass does not affect them.
if (active_tree_->hud_layer()) {
viz::CompositorRenderPass* root_pass = frame->render_passes.back().get();
root_pass->damage_rect = root_pass->output_rect;
}
// Grab this region here before iterating layers. Taking copy requests from
// the layers while constructing the render passes will dirty the render
// surface layer list and this unoccluded region, flipping the dirty bit to
// true, and making us able to query for it without doing
// UpdateDrawProperties again. The value inside the Region is not actually
// changed until UpdateDrawProperties happens, so a reference to it is safe.
const Region& unoccluded_screen_space_region =
active_tree_->UnoccludedScreenSpaceRegion();
// Typically when we are missing a texture and use a checkerboard quad, we
// still draw the frame. However when the layer being checkerboarded is moving
// due to an impl-animation, we drop the frame to avoid flashing due to the
// texture suddenly appearing in the future.
DrawResult draw_result = DrawResult::kSuccess;
int num_missing_tiles = 0;
CHECK(!frame->checkerboarded_needs_raster);
CHECK(!frame->checkerboarded_needs_record);
frame->has_copy_requests =
active_tree()->property_trees()->effect_tree().HasCopyRequests();
bool have_missing_animated_tiles = false;
const bool compute_video_layer_preferred_interval =
!features::UseSurfaceLayerForVideo();
if (settings_.enable_compositing_based_throttling)
throttle_decider_.Prepare();
const auto& context = AppendQuadsContext{
GetDrawMode(), std::move(capture_view_transition_tokens),
/* for_view_transition_capture= */ false};
const auto& view_transition_capture_context = AppendQuadsContext{
context.draw_mode, context.capture_view_transition_tokens,
/* for_view_transition_capture= */ true};
// In TreesInViz mode, FrameData built in the renderer side is abandoned
// and later rebuilt in viz side. Therefore, certain steps can be skipped.
bool output_frame_data = !settings_.TreesInVizInClientProcess();
for (EffectTreeLayerListIterator it(active_tree());
it.state() != EffectTreeLayerListIterator::State::kEnd; ++it) {
RenderSurfaceImpl* target_render_surface = it.target_render_surface();
viz::CompositorRenderPass* target_render_pass = FindRenderPassById(
frame->render_passes, target_render_surface->render_pass_id());
viz::CompositorRenderPass* view_transition_capture_render_pass =
(output_frame_data &&
target_render_surface->has_view_transition_capture_contributions())
? FindRenderPassById(frame->render_passes,
it.target_render_surface()
->view_transition_capture_render_pass_id())
: nullptr;
AppendQuadsData append_quads_data;
if (it.state() == EffectTreeLayerListIterator::State::kTargetSurface) {
// TODO(zmo): Make sure EffectTree's copy requests are sent to viz.
if (output_frame_data && target_render_surface->HasCopyRequest()) {
active_tree()
->property_trees()
->effect_tree_mutable()
.TakeCopyRequestsAndTransformToSurface(
target_render_surface->EffectTreeIndex(),
&target_render_pass->copy_requests);
}
// The only place where enable_compositing_based_throttling is set
// to true is AshWindowTreeHost::Create().
// TODO(zmo): Audit if this is necessary for UI in TreesInViz mode.
if (settings_.enable_compositing_based_throttling && target_render_pass) {
throttle_decider_.ProcessRenderPass(*target_render_pass);
}
} else if (it.state() ==
EffectTreeLayerListIterator::State::kContributingSurface) {
if (output_frame_data) {
RenderSurfaceImpl* render_surface = it.current_render_surface();
if (render_surface->contributes_to_drawn_surface()) {
render_surface->AppendQuads(context, target_render_pass,
&append_quads_data);
if (view_transition_capture_render_pass) {
AppendQuadsData data;
render_surface->AppendQuads(view_transition_capture_context,
view_transition_capture_render_pass,
&data);
}
}
}
} else if (it.state() == EffectTreeLayerListIterator::State::kLayer) {
LayerImpl* layer = it.current_layer();
if (layer->WillDraw(context.draw_mode, resource_provider_.get())) {
DCHECK_EQ(active_tree_.get(), layer->layer_tree_impl());
// This is necessary in TreesInViz mode to trigger DidDraw() through
// LayerTreeHostImpl::DidDrawAllLayers().
frame->will_draw_layers.push_back(layer);
if (output_frame_data && compute_video_layer_preferred_interval &&
layer->GetLayerType() == mojom::LayerType::kVideo) {
VideoLayerImpl* video_layer = static_cast<VideoLayerImpl*>(layer);
std::optional<base::TimeDelta> video_preferred_interval =
video_layer->GetPreferredRenderInterval();
if (video_preferred_interval) {
frame->video_layer_preferred_intervals[video_preferred_interval
.value()]++;
}
}
layer->NotifyKnownResourceIdsBeforeAppendQuads(known_resource_ids);
if (output_frame_data) {
layer->AppendQuads(context, target_render_pass, &append_quads_data);
if (view_transition_capture_render_pass) {
AppendQuadsData data;
layer->AppendQuads(view_transition_capture_context,
view_transition_capture_render_pass, &data);
}
}
} else {
// The only place where enable_compositing_based_throttling is set
// to true is AshWindowTreeHost::Create().
// TODO(zmo): Audit if this is necessary for UI in TreesInViz mode.
if (settings_.enable_compositing_based_throttling) {
throttle_decider_.ProcessLayerNotToDraw(layer);
}
}
if (output_frame_data) {
rendering_stats_instrumentation_->AddVisibleContentArea(
append_quads_data.visible_layer_area);
rendering_stats_instrumentation_->AddApproximatedVisibleContentArea(
append_quads_data.approximated_visible_content_area);
num_missing_tiles += append_quads_data.num_missing_tiles;
frame->checkerboarded_needs_raster |=
append_quads_data.checkerboarded_needs_raster;
frame->checkerboarded_needs_record |=
append_quads_data.checkerboarded_needs_record;
if (append_quads_data.num_missing_tiles > 0) {
have_missing_animated_tiles |=
layer->screen_space_transform_is_animating();
}
}
// TODO(zmo): Audit if this is necessary when UI is moved to TreesInViz.
if (settings_.is_layer_tree_for_ui) {
AccumulateInvalidatedArea(layer, total_invalidated_area_.value());
}
}
if (output_frame_data) {
frame->activation_dependencies.insert(
frame->activation_dependencies.end(),
append_quads_data.activation_dependencies.begin(),
append_quads_data.activation_dependencies.end());
if (append_quads_data.deadline_in_frames) {
if (!frame->deadline_in_frames) {
frame->deadline_in_frames = append_quads_data.deadline_in_frames;
} else {
frame->deadline_in_frames =
std::max(*frame->deadline_in_frames,
*append_quads_data.deadline_in_frames);
}
}
frame->use_default_lower_bound_deadline |=
append_quads_data.use_default_lower_bound_deadline;
frame->has_shared_element_resources |=
append_quads_data.has_shared_element_resources;
}
}
// If CommitsToActiveTree() is true, then we wait to draw until
// NotifyReadyToDraw. That means we're in as good shape as is possible now,
// so there's no reason to stop the draw now (and this is not supported by
// SingleThreadProxy).
if (have_missing_animated_tiles && !CommitsToActiveTree()) {
draw_result = DrawResult::kAbortedCheckerboardAnimations;
}
// When we require high res to draw, abort the draw (almost) always. This does
// not cause the scheduler to do a main frame, instead it will continue to try
// drawing until we finally complete, so the copy request will not be lost.
// TODO(weiliangc): Remove RequiresHighResToDraw. crbug.com/469175
if (frame->checkerboarded_needs_raster) {
if (RequiresHighResToDraw())
draw_result = DrawResult::kAbortedMissingHighResContent;
}
// When doing a resourceless software draw, we don't have control over the
// surface the compositor draws to, so even though the frame may not be
// complete, the previous frame has already been potentially lost, so an
// incomplete frame is better than nothing, so this takes highest precedence.
if (resourceless_software_draw_)
draw_result = DrawResult::kSuccess;
#if DCHECK_IS_ON()
for (const auto& render_pass : frame->render_passes) {
for (auto* quad : render_pass->quad_list)
DCHECK(quad->shared_quad_state);
}
DCHECK_EQ(frame->render_passes.back()->output_rect.origin(),
active_tree_->GetDeviceViewport().origin());
#endif
bool has_transparent_background =
!active_tree_->background_color().isOpaque();
auto* root_render_surface = active_tree_->RootRenderSurface();
if (root_render_surface && !has_transparent_background) {
frame->render_passes.back()->has_transparent_background = false;
// If any tiles are missing, then fill behind the entire root render
// surface. This is a workaround for this edge case, instead of tracking
// individual tiles that are missing.
Region fill_region = unoccluded_screen_space_region;
if (num_missing_tiles > 0)
fill_region = root_render_surface->content_rect();
AppendQuadsToFillScreen(frame->render_passes.back().get(),
root_render_surface,
active_tree_->background_color(), fill_region);
}
RemoveRenderPasses(frame);
// If we're making a frame to draw, it better have at least one render pass.
DCHECK(!frame->render_passes.empty());
TRACE_EVENT_END2("cc,benchmark", "LayerTreeHostImpl::CalculateRenderPasses",
"draw_result", draw_result, "missing tiles",
num_missing_tiles);
// Draw has to be successful to not drop the copy request layer.
// When we have a copy request for a layer, we need to draw even if there
// would be animating checkerboards, because failing under those conditions
// triggers a new main frame, which may cause the copy request layer to be
// destroyed.
// TODO(weiliangc): Test copy request w/ LayerTreeFrameSink recreation. Would
// trigger this DCHECK.
DCHECK(!frame->has_copy_requests || draw_result == DrawResult::kSuccess);
return draw_result;
}
void LayerTreeHostImpl::DidAnimateScrollOffset() {
client_->SetNeedsCommitOnImplThread();
client_->RenewTreePriority();
}
void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
viewport_damage_rect_.Union(damage_rect);
}
void LayerTreeHostImpl::InvalidateContentOnImplSide() {
DCHECK(!pending_tree_ && !settings_.trees_in_viz_in_viz_process);
// Invalidation should never be ran outside the impl frame for non
// synchronous compositor mode. For devices that use synchronous compositor,
// e.g. Android Webview, the assertion is not guaranteed because it may ask
// for a frame at any time.
DCHECK(impl_thread_phase_ == ImplThreadPhase::INSIDE_IMPL_FRAME ||
settings_.using_synchronous_renderer_compositor);
if (!CommitsToActiveTree()) {
CreatePendingTree();
if (frame_trackers_.GetScrollingThread() ==
FrameInfo::SmoothEffectDrivingThread::kRaster) {
// If scrolling via raster, take EventMetrics and associate
// them with newly-created pending tree.
pending_tree()->AppendEventMetricsFromRasterThread(
events_metrics_manager_.TakeSavedEventsMetrics());
}
AnimatePendingTreeAfterCommit();
}
UpdateSyncTreeAfterCommitOrImplSideInvalidation();
}
void LayerTreeHostImpl::InvalidateLayerTreeFrameSink(bool needs_redraw) {
DCHECK(layer_tree_frame_sink());
layer_tree_frame_sink()->Invalidate(needs_redraw);
}
DrawResult LayerTreeHostImpl::PrepareToDraw(FrameData* frame) {
TRACE_EVENT1("cc", "LayerTreeHostImpl::PrepareToDraw", "SourceFrameNumber",
active_tree_->source_frame_number());
if (input_delegate_)
input_delegate_->WillDraw();
// No need to record metrics each time we draw, 1% is enough.
constexpr double kSamplingFrequency = .01;
if (!downsample_metrics_ ||
metrics_subsampler_.ShouldSample(kSamplingFrequency)) {
// These metrics are only for the renderer process.
if (RunningOnRendererProcess()) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Compositing.Renderer.NumActiveLayers",
base::saturated_cast<int>(active_tree_->NumLayers()), 1, 1000, 20);
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Compositing.Renderer.NumActivePictureLayers",
base::saturated_cast<int>(active_tree_->picture_layers().size()), 1,
1000, 20);
}
}
// Tick worklet animations here, just before draw, to give animation worklets
// as much time as possible to produce their output for this frame. Note that
// an animation worklet is asked to produce its output at the beginning of the
// frame along side other animations but its output arrives asynchronously so
// we tick worklet animations and apply that output here instead.
mutator_host_->TickWorkletAnimations();
bool ok = active_tree_->UpdateDrawProperties(
/*update_tiles=*/true, /*update_image_animation_controller=*/true);
DCHECK(ok) << "UpdateDrawProperties failed during draw";
if (!settings_.trees_in_viz_in_viz_process) {
// This will cause NotifyTileStateChanged() to be called for any tiles that
// completed, which will add damage for visible tiles to the frame for them
// so they appear as part of the current frame being drawn.
tile_manager_.PrepareToDraw();
}
frame->render_surface_list = &active_tree_->GetRenderSurfaceList();
frame->render_passes.clear();
frame->will_draw_layers.clear();
frame->has_no_damage = false;
if (active_tree_->RootRenderSurface()) {
active_tree_->RootRenderSurface()->damage_tracker()->AddDamageNextUpdate(
viewport_damage_rect_);
}
DrawResult draw_result = CalculateRenderPasses(frame);
// Dump render passes and draw quads if VerboseLogEnabled().
VERBOSE_LOG() << "Prepare to draw\n" << frame->ToString();
if (draw_result != DrawResult::kSuccess) {
DCHECK(!resourceless_software_draw_);
return draw_result;
}
// If we return DrawResult::kSuccess, then we expect DrawLayers() to be called
// before this function is called again.
return DrawResult::kSuccess;
}
void LayerTreeHostImpl::RemoveRenderPasses(FrameData* frame) {
// There is always at least a root RenderPass.
DCHECK_GE(frame->render_passes.size(), 1u);
// A set of RenderPasses that we have seen.
base::flat_set<viz::CompositorRenderPassId> pass_exists;
// A set of viz::RenderPassDrawQuads that we have seen (stored by the
// RenderPasses they refer to).
base::flat_map<viz::CompositorRenderPassId, int> pass_references;
// A set of viz::SharedElementDrawQuad references that we have seen.
base::flat_set<viz::ViewTransitionElementResourceId>
view_transition_quad_references;
// Iterate RenderPasses in draw order, removing empty render passes (except
// the root RenderPass).
for (size_t i = 0; i < frame->render_passes.size(); ++i) {
viz::CompositorRenderPass* pass = frame->render_passes[i].get();
// Remove orphan viz::RenderPassDrawQuads.
for (auto it = pass->quad_list.begin(); it != pass->quad_list.end();) {
if (it->material == viz::DrawQuad::Material::kSharedElement) {
view_transition_quad_references.insert(
viz::SharedElementDrawQuad::MaterialCast(*it)->element_resource_id);
++it;
continue;
}
if (it->material != viz::DrawQuad::Material::kCompositorRenderPass) {
++it;
continue;
}
const viz::CompositorRenderPassDrawQuad* quad =
viz::CompositorRenderPassDrawQuad::MaterialCast(*it);
// If the RenderPass doesn't exist, we can remove the quad.
if (pass_exists.count(quad->render_pass_id)) {
// Otherwise, save a reference to the RenderPass so we know there's a
// quad using it.
pass_references[quad->render_pass_id]++;
++it;
} else {
it = pass->quad_list.EraseAndInvalidateAllPointers(it);
}
}
if (i == frame->render_passes.size() - 1) {
// Don't remove the root RenderPass.
break;
}
if (pass->quad_list.empty() && pass->copy_requests.empty() &&
!pass->subtree_capture_id.is_valid() && pass->filters.IsEmpty() &&
pass->backdrop_filters.IsEmpty() &&
// TODO(khushalsagar) : Send information about no-op passes to viz to
// retain this optimization for shared elements. See crbug.com/1265178.
!pass->view_transition_element_resource_id.IsValid()) {
// Remove the pass and decrement |i| to counter the for loop's increment,
// so we don't skip the next pass in the loop.
frame->render_passes.erase(frame->render_passes.begin() + i);
--i;
continue;
}
pass_exists.insert(pass->id);
}
// Remove RenderPasses that are not referenced by any draw quads or copy
// requests (except the root RenderPass).
for (size_t i = 0; i < frame->render_passes.size() - 1; ++i) {
// Iterating from the back of the list to the front, skipping over the
// back-most (root) pass, in order to remove each qualified RenderPass, and
// drop references to earlier RenderPasses allowing them to be removed to.
viz::CompositorRenderPass* pass =
frame->render_passes[frame->render_passes.size() - 2 - i].get();
if (!pass->copy_requests.empty()) {
continue;
}
if (pass_references[pass->id])
continue;
// Retain render passes generating ViewTransition snapshots if they are
// referenced by a quad or this frame will process a save directive. We need
// to render and screenshot offscreen content as well, which won't be
// referenced by a quad.
if (pass->view_transition_element_resource_id.IsValid() &&
(frame->has_view_transition_save_directive ||
view_transition_quad_references.contains(
pass->view_transition_element_resource_id))) {
continue;
}
for (auto it = pass->quad_list.begin(); it != pass->quad_list.end(); ++it) {
if (const viz::CompositorRenderPassDrawQuad* quad =
it->DynamicCast<viz::CompositorRenderPassDrawQuad>()) {
pass_references[quad->render_pass_id]--;
}
}
frame->render_passes.erase(frame->render_passes.end() - 2 - i);
--i;
}
}
void LayerTreeHostImpl::EvictTexturesForTesting() {
UpdateTileManagerMemoryPolicy(ManagedMemoryPolicy(0));
}
void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(
bool block,
bool notify_if_blocked) {
NOTREACHED();
}
void LayerTreeHostImpl::BlockImplSideInvalidationRequestsForTesting(
bool block) {
NOTREACHED();
}
void LayerTreeHostImpl::ResetTreesForTesting() {
if (active_tree_)
active_tree_->DetachLayers();
active_tree_ = std::make_unique<LayerTreeImpl>(
*this, CurrentBeginFrameArgs(), active_tree()->page_scale_factor(),
active_tree()->top_controls_shown_ratio(),
active_tree()->bottom_controls_shown_ratio(),
active_tree()->elastic_overscroll());
active_tree_->property_trees()->set_is_active(true);
active_tree_->property_trees()->clear();
if (pending_tree_)
pending_tree_->DetachLayers();
pending_tree_ = nullptr;
if (recycle_tree_)
recycle_tree_->DetachLayers();
recycle_tree_ = nullptr;
}
size_t LayerTreeHostImpl::SourceAnimationFrameNumberForTesting() const {
return *next_frame_token_;
}
void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
const ManagedMemoryPolicy& policy) {
if (!resource_pool_)
return;
global_tile_state_.hard_memory_limit_in_bytes = 0;
global_tile_state_.soft_memory_limit_in_bytes = 0;
if (visible_ && policy.bytes_limit_when_visible > 0) {
global_tile_state_.hard_memory_limit_in_bytes =
policy.bytes_limit_when_visible;
global_tile_state_.soft_memory_limit_in_bytes =
(static_cast<int64_t>(global_tile_state_.hard_memory_limit_in_bytes) *
settings_.max_memory_for_prepaint_percentage) /
100;
}
global_tile_state_.memory_limit_policy =
ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
visible_ ? policy.priority_cutoff_when_visible
: gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
global_tile_state_.num_resources_limit = policy.num_resources_limit;
if (global_tile_state_.hard_memory_limit_in_bytes > 0) {
// If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
// consider our contexts visible. Notify the contexts here. We handle
// becoming invisible in NotifyAllTileTasksComplete to avoid interrupting
// running work.
SetContextVisibility(true);
// If |global_tile_state_.hard_memory_limit_in_bytes| is greater than 0, we
// allow the image decode controller to retain resources. We handle the
// equal to 0 case in NotifyAllTileTasksComplete to avoid interrupting
// running work.
if (image_decode_cache_holder_)
image_decode_cache_holder_->SetShouldAggressivelyFreeResources(false);
} else {
// When the memory policy is set to zero, its important to release any
// decoded images cached by the tracker. But we can not re-checker any
// images that have been displayed since the resources, if held by the
// browser, may be reused. Which is why its important to maintain the
// decode policy tracking.
bool can_clear_decode_policy_tracking = false;
tile_manager_.ClearCheckerImageTracking(can_clear_decode_policy_tracking);
}
DCHECK(resource_pool_);
// Soft limit is used for resource pool such that memory returns to soft
// limit after going over.
resource_pool_->SetResourceUsageLimits(
global_tile_state_.soft_memory_limit_in_bytes,
global_tile_state_.num_resources_limit);
DidModifyTilePriorities(/*pending_update_tiles=*/false);
}
void LayerTreeHostImpl::DidModifyTilePriorities(bool pending_update_tiles) {
if (settings_.trees_in_viz_in_viz_process) {
return;
}
// Mark priorities as (maybe) dirty and schedule a PrepareTiles().
if (!pending_update_tiles) {
tile_priorities_dirty_ = true;
tile_manager_.DidModifyTilePriorities();
}
client_->SetNeedsPrepareTilesOnImplThread();
}
void LayerTreeHostImpl::SetTargetLocalSurfaceId(
const viz::LocalSurfaceId& target_local_surface_id) {
target_local_surface_id_ = target_local_surface_id;
}
std::unique_ptr<RasterTilePriorityQueue> LayerTreeHostImpl::BuildRasterQueue(
TreePriority tree_priority,
RasterTilePriorityQueue::Type type) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::BuildRasterQueue");
return RasterTilePriorityQueue::Create(
active_tree_->picture_layers(),
pending_tree_ && pending_tree_fully_painted_
? pending_tree_->picture_layers()
: std::vector<raw_ptr<PictureLayerImpl, VectorExperimental>>(),
tree_priority, type);
}
std::unique_ptr<EvictionTilePriorityQueue>
LayerTreeHostImpl::BuildEvictionQueue() {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::BuildEvictionQueue");
std::unique_ptr<EvictionTilePriorityQueue> queue(
new EvictionTilePriorityQueue);
queue->Build(
active_tree_->picture_layers(),
pending_tree_
? pending_tree_->picture_layers()
: std::vector<raw_ptr<PictureLayerImpl, VectorExperimental>>());
return queue;
}
std::unique_ptr<TilesWithResourceIterator>
LayerTreeHostImpl::CreateTilesWithResourceIterator() {
return std::make_unique<TilesWithResourceIterator>(
&active_tree_->picture_layers(),
pending_tree_ ? &pending_tree_->picture_layers() : nullptr);
}
gfx::DisplayColorSpaces LayerTreeHostImpl::GetDisplayColorSpaces() const {
// The pending tree will has the most recently updated color space, so use it.
if (pending_tree_) {
return pending_tree_->display_color_spaces();
}
if (active_tree_) {
return active_tree_->display_color_spaces();
}
return gfx::DisplayColorSpaces();
}
void LayerTreeHostImpl::SetIsLikelyToRequireADraw(
bool is_likely_to_require_a_draw) {
// Proactively tell the scheduler that we expect to draw within each vsync
// until we get all the tiles ready to draw. If we happen to miss a required
// for draw tile here, then we will miss telling the scheduler each frame that
// we intend to draw so it may make worse scheduling decisions.
is_likely_to_require_a_draw_ = is_likely_to_require_a_draw;
}
viz::SharedImageFormat LayerTreeHostImpl::GetTileFormat() const {
return raster_caps_.tile_format;
}
TargetColorParams LayerTreeHostImpl::GetTargetColorParams(
gfx::ContentColorUsage content_color_usage) const {
TargetColorParams params;
// If we are likely to software composite the resource, we use sRGB because
// software compositing is unable to perform color conversion.
if (!layer_tree_frame_sink_ || !layer_tree_frame_sink_->context_provider())
return params;
gfx::DisplayColorSpaces display_cs = GetDisplayColorSpaces();
params.sdr_max_luminance_nits = display_cs.GetSDRMaxLuminanceNits();
if (settings_.prefer_raster_in_srgb &&
content_color_usage == gfx::ContentColorUsage::kSRGB) {
return params;
}
auto hdr_color_space =
display_cs.GetOutputColorSpace(gfx::ContentColorUsage::kHDR,
/*needs_alpha=*/false);
// Always specify a color space if color correct rasterization is requested
// (not specifying a color space indicates that no color conversion is
// required).
if (!hdr_color_space.IsValid())
return params;
if (hdr_color_space.IsHDR()) {
if (content_color_usage == gfx::ContentColorUsage::kHDR) {
// Rasterization of HDR content is always done in extended-sRGB space.
params.color_space = gfx::ColorSpace::CreateExtendedSRGB();
// Only report the HDR capabilities if they are requested.
params.hdr_max_luminance_relative =
display_cs.GetHDRMaxLuminanceRelative();
} else {
// If the content is not HDR, then use Display P3 as the rasterization
// color space.
params.color_space = gfx::ColorSpace::CreateDisplayP3D65();
}
return params;
}
params.color_space = hdr_color_space;
return params;
}
bool LayerTreeHostImpl::CheckColorSpaceContainsSrgb(
const gfx::ColorSpace& color_space) const {
constexpr gfx::ColorSpace srgb = gfx::ColorSpace::CreateSRGB();
// Color spaces without a custom primary matrix are cheap to compute, so the
// cache can be bypassed.
if (color_space.GetPrimaryID() != gfx::ColorSpace::PrimaryID::CUSTOM)
return color_space.Contains(srgb);
auto it = contains_srgb_cache_.Get(color_space);
if (it != contains_srgb_cache_.end())
return it->second;
bool result = color_space.Contains(srgb);
contains_srgb_cache_.Put(color_space, result);
return result;
}
void LayerTreeHostImpl::RequestImplSideInvalidationForCheckerImagedTiles() {
// When using impl-side invalidation for checker-imaging, a pending tree does
// not need to be flushed as an independent update through the pipeline.
bool needs_first_draw_on_activation = false;
client_->SetNeedsImplSideInvalidation(needs_first_draw_on_activation);
}
size_t LayerTreeHostImpl::GetFrameIndexForImage(const PaintImage& paint_image,
WhichTree tree) const {
if (!paint_image.ShouldAnimate())
return PaintImage::kDefaultFrameIndex;
return image_animation_controller_.GetFrameIndexForImage(
paint_image.stable_id(), tree);
}
int LayerTreeHostImpl::GetMSAASampleCountForRaster(
const DisplayItemList& display_list) const {
if (display_list.num_slow_paths_up_to_min_for_MSAA() <
kMinNumberOfSlowPathsForMSAA) {
return 0;
}
if (!raster_caps().can_use_msaa) {
return 0;
}
if (display_list.has_non_aa_paint()) {
return 0;
}
return RequestedMSAASampleCount();
}
bool LayerTreeHostImpl::HasPendingTree() {
return pending_tree_ != nullptr;
}
void LayerTreeHostImpl::NotifyReadyToActivate() {
// The TileManager may call this method while the pending tree is still being
// painted, as it isn't aware of the ongoing paint. We shouldn't tell the
// scheduler we are ready to activate in that case, as if we do it will
// immediately activate once we call NotifyPaintWorkletStateChange, rather
// than wait for the TileManager to actually raster the content!
if (!pending_tree_fully_painted_)
return;
client_->NotifyReadyToActivate();
}
void LayerTreeHostImpl::NotifyReadyToDraw() {
// Tiles that are ready will cause NotifyTileStateChanged() to be called so we
// don't need to schedule a draw here. Just stop WillBeginImplFrame() from
// causing optimistic requests to draw a frame.
is_likely_to_require_a_draw_ = false;
client_->NotifyReadyToDraw();
}
void LayerTreeHostImpl::NotifyAllTileTasksCompleted() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
// The tile tasks started by the most recent call to PrepareTiles have
// completed. Now is a good time to free resources if necessary.
if (global_tile_state_.hard_memory_limit_in_bytes == 0) {
// Free image decode controller resources before notifying the
// contexts of visibility change. This ensures that the imaged decode
// controller has released all Skia refs at the time Skia's cleanup
// executes (within worker context's cleanup).
if (image_decode_cache_holder_)
image_decode_cache_holder_->SetShouldAggressivelyFreeResources(true);
SetContextVisibility(false);
}
}
void LayerTreeHostImpl::NotifyTileStateChanged(const Tile* tile,
bool update_damage) {
DCHECK(!settings_.trees_in_viz_in_viz_process);
TRACE_EVENT0("cc", "LayerTreeHostImpl::NotifyTileStateChanged");
LayerImpl* layer_impl = nullptr;
// We must have a pending or active tree layer here, since the layer is
// guaranteed to outlive its tiles.
const bool is_pending_tree =
tile->tiling()->tree() == WhichTree::PENDING_TREE;
if (is_pending_tree) {
layer_impl = pending_tree_->FindPendingTreeLayerById(tile->layer_id());
} else {
layer_impl = active_tree_->FindActiveTreeLayerById(tile->layer_id());
}
layer_impl->NotifyTileStateChanged(tile, update_damage);
if (settings_.TreesInVizInClientProcess() && !is_pending_tree &&
!CommitsToActiveTree()) {
// Tiles for the tree currently being committed to (Pending or Active)
// are pushed to the display during UpdateDisplayTree. For active tree,
// if we're not committing to Active, tiles are pushed immediately via
// UpdateDisplayTile.
layer_context_->UpdateDisplayTile(
static_cast<PictureLayerImpl&>(*layer_impl), *tile,
*resource_provider(), *layer_tree_frame_sink_->context_provider(),
update_damage);
}
if (!client_->IsInsideDraw() && tile->required_for_draw()) {
// The LayerImpl::NotifyTileStateChanged() should damage the layer, so this
// redraw will make those tiles be displayed.
SetNeedsRedraw();
}
}
void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
DCHECK(task_runner_provider_->IsImplThread());
SetMemoryPolicyImpl(policy);
// This is short term solution to synchronously drop tile resources when
// using synchronous compositing to avoid memory usage regression.
// TODO(boliu): crbug.com/499004 to track removing this.
if (!policy.bytes_limit_when_visible && resource_pool_ &&
settings_.using_synchronous_renderer_compositor) {
ReleaseTileResources();
CleanUpTileManagerResources();
// Force a call to NotifyAllTileTasks completed - otherwise this logic may
// be skipped if no work was enqueued at the time the tile manager was
// destroyed.
NotifyAllTileTasksCompleted();
CreateTileManagerResources();
RecreateTileResources();
}
}
void LayerTreeHostImpl::SetTreeActivationCallback(
base::RepeatingClosure callback) {
DCHECK(task_runner_provider_->IsImplThread());
tree_activation_callback_ = std::move(callback);
}
void LayerTreeHostImpl::SetMemoryPolicyImpl(const ManagedMemoryPolicy& policy) {
if (cached_managed_memory_policy_ == policy)
return;
ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
cached_managed_memory_policy_ = policy;
ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
if (old_policy == actual_policy)
return;
UpdateTileManagerMemoryPolicy(actual_policy);
// If there is already enough memory to draw everything imaginable and the
// new memory limit does not change this, then do not re-commit. Don't bother
// skipping commits if this is not visible (commits don't happen when not
// visible, there will almost always be a commit when this becomes visible).
bool needs_commit = true;
if (visible() &&
actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
actual_policy.priority_cutoff_when_visible ==
old_policy.priority_cutoff_when_visible) {
needs_commit = false;
}
if (needs_commit)
client_->SetNeedsCommitOnImplThread();
}
void LayerTreeHostImpl::SetExternalTilePriorityConstraints(
const gfx::Rect& viewport_rect,
const gfx::Transform& transform) {
const bool tile_priority_params_changed =
viewport_rect_for_tile_priority_ != viewport_rect;
viewport_rect_for_tile_priority_ = viewport_rect;
if (tile_priority_params_changed) {
active_tree_->set_needs_update_draw_properties();
if (pending_tree_)
pending_tree_->set_needs_update_draw_properties();
// Compositor, not LayerTreeFrameSink, is responsible for setting damage
// and triggering redraw for constraint changes.
SetFullViewportDamage();
SetNeedsRedraw();
}
}
void LayerTreeHostImpl::DidReceiveCompositorFrameAck() {
client_->DidReceiveCompositorFrameAckOnImplThread();
}
void LayerTreeHostImpl::DidPresentCompositorFrame(
uint32_t frame_token,
const viz::FrameTimingDetails& details) {
PresentationTimeCallbackBuffer::PendingCallbacks activated_callbacks =
presentation_time_callbacks_.PopPendingCallbacks(
frame_token, details.presentation_feedback.failed());
// Send all tasks to the client so that it can decide which tasks
// should run on which thread.
client_->DidPresentCompositorFrameOnImplThread(
frame_token, std::move(activated_callbacks), details);
// Send all pending lag events waiting on the frame pointed by |frame_token|.
// It is posted as a task because LayerTreeHostImpl::DidPresentCompositorFrame
// is in the rendering critical path (it is called by AsyncLayerTreeFrameSink
// ::OnBeginFrame).
GetTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(&LayerTreeHostImpl::LogAverageLagEvents,
weak_factory_.GetWeakPtr(), frame_token, details));
}
void LayerTreeHostImpl::LogAverageLagEvents(
uint32_t frame_token,
const viz::FrameTimingDetails& details) {
lag_tracking_manager_.DidPresentCompositorFrame(frame_token, details);
}
void LayerTreeHostImpl::NotifyCompositorMetricsTrackerResults(
const CustomTrackerResults& results) {
client_->NotifyCompositorMetricsTrackerResults(results);
}
void LayerTreeHostImpl::DidNotNeedBeginFrame() {
frame_trackers_.NotifyPauseFrameProduction();
if (lcd_text_metrics_reporter_)
lcd_text_metrics_reporter_->NotifyPauseFrameProduction();
}
void LayerTreeHostImpl::ReclaimResources(
std::vector<viz::ReturnedResource> resources) {
resource_provider_->ReceiveReturnsFromParent(std::move(resources));
// In OOM, we now might be able to release more resources that were held
// because they were exported.
if (resource_pool_) {
resource_pool_->ReduceResourceUsage();
}
// If we're not visible, we likely released resources, so we want to
// aggressively flush here to make sure those DeleteSharedImage() calls make
// it to the GPU process to free up the memory.
MaybeFlushPendingWork();
if (base::FeatureList::IsEnabled(
features::kReclaimResourcesDelayedFlushInBackground)) {
// There are cases where the release callbacks executed from the call above
// don't actually free the GPU resource from this thread. For instance, for
// TextureLayer,
// TextureLayer::TransferableResourceHolder::~TransferableResourceHolder()
// posts a task to the main thread, and so flushing here is not sufficient.
//
// Ideally, we would not rely on a time-based delay, but given layering,
// threading and possibly unknown cases where the release can jump from
// thread to thread, this is likely a more practical solution. See
// crbug.com/1449271 for an example.
GetTaskRunner()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&LayerTreeHostImpl::MaybeFlushPendingWork,
weak_factory_.GetWeakPtr()),
base::Seconds(1));
}
}
void LayerTreeHostImpl::MaybeFlushPendingWork() {
// If we're not in background, delayed work will be flushed "at some point",
// and we also may have something better to do.
if (visible_ || !has_valid_layer_tree_frame_sink_) {
return;
}
auto* compositor_context = layer_tree_frame_sink_->context_provider();
if (!compositor_context || !compositor_context->ContextSupport()) {
return;
}
compositor_context->ContextSupport()->FlushPendingWork();
}
void LayerTreeHostImpl::OnDraw(const gfx::Transform& transform,
const gfx::Rect& viewport,
bool resourceless_software_draw,
bool skip_draw) {
DCHECK(!resourceless_software_draw_);
// This function is only ever called by Android WebView, in which case we
// expect the device viewport to be at the origin. We never expect an
// external viewport to be set otherwise.
DCHECK(active_tree_->internal_device_viewport().origin().IsOrigin());
#if DCHECK_IS_ON()
base::AutoReset<bool> reset_sync_draw(&doing_sync_draw_, true);
#endif
if (skip_draw) {
client_->OnDrawForLayerTreeFrameSink(resourceless_software_draw_, true);
return;
}
const bool transform_changed = external_transform_ != transform;
const bool viewport_changed = external_viewport_ != viewport;
external_transform_ = transform;
external_viewport_ = viewport;
{
base::AutoReset<bool> resourceless_software_draw_reset(
&resourceless_software_draw_, resourceless_software_draw);
// For resourceless software draw, always set full damage to ensure they
// always swap. Otherwise, need to set redraw for any changes to draw
// parameters.
if (transform_changed || viewport_changed || resourceless_software_draw_) {
SetFullViewportDamage();
SetNeedsRedraw();
active_tree_->set_needs_update_draw_properties();
}
if (resourceless_software_draw)
client_->OnCanDrawStateChanged(CanDraw());
client_->OnDrawForLayerTreeFrameSink(resourceless_software_draw_,
skip_draw);
}
if (resourceless_software_draw) {
active_tree_->set_needs_update_draw_properties();
client_->OnCanDrawStateChanged(CanDraw());
// This draw may have reset all damage, which would lead to subsequent
// incorrect hardware draw, so explicitly set damage for next hardware
// draw as well.
SetFullViewportDamage();
}
}
void LayerTreeHostImpl::OnCompositorFrameTransitionDirectiveProcessed(
uint32_t sequence_id) {
// We cache the computed content rect for each view-transition capture
// surface. This rect is then used to map the generated render pass or texture
// to the target coordinate space.
viz::ViewTransitionElementResourceRects rects_for_this_sequence;
auto it = view_transition_content_rects_.find(sequence_id);
// The map entry would exist only if there are actual rects (non-root
// elements).
if (it != view_transition_content_rects_.end()) {
it->second.swap(rects_for_this_sequence);
view_transition_content_rects_.erase(it);
}
client_->NotifyTransitionRequestFinished(sequence_id,
std::move(rects_for_this_sequence));
}
void LayerTreeHostImpl::SetViewTransitionContentRect(
uint32_t sequence_id,
const viz::ViewTransitionElementResourceId& id,
const gfx::RectF& rect) {
view_transition_content_rects_[sequence_id].insert(std::make_pair(id, rect));
}
void LayerTreeHostImpl::OnSurfaceEvicted(
const viz::LocalSurfaceId& local_surface_id) {
// Don't evict if the host has given us a newer viz::SurfaceId. Instead handle
// resource returns as normal, and begin producing from the new tree.
if (target_local_surface_id_.IsNewerThanOrEmbeddingChanged(
local_surface_id)) {
return;
}
evicted_local_surface_id_ = local_surface_id;
resource_provider_->SetEvicted(true);
client_->OnCanDrawStateChanged(CanDraw());
}
void LayerTreeHostImpl::ReportEventLatency(
std::vector<EventLatencyTracker::LatencyData> latencies) {
if (auto* recorder = CustomMetricRecorder::Get())
recorder->ReportEventLatency(std::move(latencies));
}
void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
client_->OnCanDrawStateChanged(CanDraw());
}
viz::RegionCaptureBounds LayerTreeHostImpl::CollectRegionCaptureBounds() {
viz::RegionCaptureBounds bounds;
for (const auto* layer : base::Reversed(*active_tree())) {
if (!layer->capture_bounds())
continue;
for (const auto& bounds_pair : layer->capture_bounds()->bounds()) {
// Perform transformation from the coordinate system of this |layer|
// to that of the root render surface.
gfx::Rect bounds_in_screen_space = MathUtil::ProjectEnclosingClippedRect(
layer->ScreenSpaceTransform(), bounds_pair.second);
const RenderSurfaceImpl* root_surface =
active_tree()->RootRenderSurface();
const gfx::Rect content_rect_in_screen_space = gfx::ToEnclosedRect(
MathUtil::MapClippedRect(root_surface->screen_space_transform(),
root_surface->DrawableContentRect()));
// The transformed bounds may be partially or entirely offscreen.
bounds_in_screen_space.Intersect(content_rect_in_screen_space);
bounds.Set(bounds_pair.first, bounds_in_screen_space);
}
}
return bounds;
}
viz::CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() {
viz::CompositorFrameMetadata metadata;
metadata.frame_token = ++next_frame_token_;
metadata.device_scale_factor = active_tree_->painted_device_scale_factor() *
active_tree_->device_scale_factor();
metadata.page_scale_factor = active_tree_->current_page_scale_factor();
metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
if (InnerViewportScrollNode()) {
// Uses InnerViewportScrollNode's container bounds in since it represents
// visual scroll layers.
metadata.visible_viewport_size =
gfx::ScaleToFlooredSize(InnerViewportScrollNode()->container_bounds,
1 / metadata.device_scale_factor);
}
metadata.root_background_color = active_tree_->background_color();
metadata.may_throttle_if_undrawn_frames = may_throttle_if_undrawn_frames_;
presentation_time_callbacks_.RegisterMainThreadCallbacks(
metadata.frame_token, active_tree_->TakePresentationCallbacks());
presentation_time_callbacks_.RegisterMainThreadSuccessfulCallbacks(
metadata.frame_token,
active_tree_->TakeSuccessfulPresentationCallbacks());
if (input_delegate_) {
metadata.is_handling_interaction =
GetActivelyScrollingType() != ActivelyScrollingType::kNone ||
input_delegate_->IsHandlingTouchSequence();
}
auto active_types = FrameSequenceTrackerActiveTypes();
metadata.is_handling_animation = HasMainThreadAnimation(active_types) ||
HasCompositorThreadAnimation(active_types);
const base::flat_set<viz::SurfaceRange>& referenced_surfaces =
active_tree_->SurfaceRanges();
for (auto& surface_range : referenced_surfaces)
metadata.referenced_surfaces.push_back(surface_range);
if (last_draw_referenced_surfaces_ != referenced_surfaces)
last_draw_referenced_surfaces_ = referenced_surfaces;
metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
if (browser_controls_offset_manager_->TopControlsHeight() > 0) {
float visible_height =
browser_controls_offset_manager_->TopControlsHeight() *
browser_controls_offset_manager_->TopControlsShownRatio();
metadata.top_controls_visible_height.emplace(visible_height);
#if BUILDFLAG(IS_ANDROID)
if (features::IsBrowserControlsInVizEnabled()) {
const viz::OffsetTag& top_controls_offset_tag =
browser_controls_offset_manager_->TopControlsOffsetTag();
const viz::OffsetTag& content_offset_tag =
browser_controls_offset_manager_->ContentOffsetTag();
if (top_controls_offset_tag) {
CHECK(!content_offset_tag.IsEmpty());
float offset = browser_controls_offset_manager_->TopControlsHeight() -
visible_height;
if (visible_height == 0) {
// The toolbar hairline is still shown after the top controls are
// completely scrolled off screen. Shift the top controls a bit more
// so that the hairline disappears.
offset +=
browser_controls_offset_manager_->TopControlsAdditionalHeight();
}
// ViewAndroid::OnTopControlsChanged() also rounds the offset before
// handing it off to Android.
gfx::Vector2dF offset2d(0.0f, -std::round(offset));
metadata.offset_tag_values.emplace_back(top_controls_offset_tag,
offset2d);
}
if (content_offset_tag) {
float offset = browser_controls_offset_manager_->TopControlsHeight() -
visible_height;
// ViewAndroid::OnTopControlsChanged() also rounds the offset before
// handing it off to Android.
gfx::Vector2dF offset2d(0.0f, -std::round(offset));
metadata.offset_tag_values.emplace_back(content_offset_tag, offset2d);
}
}
#endif
}
#if BUILDFLAG(IS_ANDROID)
if (browser_controls_offset_manager_->BottomControlsHeight() > 0 &&
features::IsBcivBottomControlsEnabled()) {
const viz::OffsetTag& bottom_controls_offset_tag =
browser_controls_offset_manager_->BottomControlsOffsetTag();
if (bottom_controls_offset_tag) {
float bottom_controls_visible_height =
browser_controls_offset_manager_->BottomControlsHeight() *
browser_controls_offset_manager_->BottomControlsShownRatio();
float offset = browser_controls_offset_manager_->BottomControlsHeight() -
bottom_controls_visible_height;
if (bottom_controls_visible_height == 0) {
// Similar to the top toolbar hairline, there are visual effects
// on the top most bottom controls that are still shown after being
// completely scrolled off screen. Shift the bottom controls a bit
// more so that these visual effects disappear.
offset +=
browser_controls_offset_manager_->BottomControlsAdditionalHeight();
}
// ViewAndroid::OnTopControlsChanged() also rounds the offset before
// handing it off to Android.
gfx::Vector2dF offset2d(0.0f, std::round(offset));
metadata.offset_tag_values.emplace_back(bottom_controls_offset_tag,
offset2d);
}
}
#endif
if (InnerViewportScrollNode()) {
// TODO(miletus) : Change the metadata to hold ScrollOffset.
metadata.root_scroll_offset = active_tree_->TotalScrollOffset();
}
metadata.display_transform_hint = active_tree_->display_transform_hint();
metadata.is_mobile_optimized = IsMobileOptimized(active_tree_.get());
if (const gfx::DelegatedInkMetadata* delegated_ink_metadata_ptr =
active_tree_->delegated_ink_metadata()) {
std::unique_ptr<gfx::DelegatedInkMetadata> delegated_ink_metadata =
std::make_unique<gfx::DelegatedInkMetadata>(
*delegated_ink_metadata_ptr);
delegated_ink_metadata->set_frame_time(CurrentBeginFrameArgs().frame_time);
TRACE_EVENT_WITH_FLOW1(
"delegated_ink_trails",
"Delegated Ink Metadata set on compositor frame metadata",
TRACE_ID_GLOBAL(delegated_ink_metadata->trace_id()),
TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "metadata",
delegated_ink_metadata->ToString());
metadata.delegated_ink_metadata = std::move(delegated_ink_metadata);
}
metadata.capture_bounds = CollectRegionCaptureBounds();
if (!screenshot_destination_.is_empty()) {
metadata.screenshot_destination =
blink::SameDocNavigationScreenshotDestinationToken(
screenshot_destination_);
screenshot_destination_ = base::UnguessableToken();
}
metadata.is_software = GetDrawMode() != DrawMode::DRAW_MODE_HARDWARE;
return metadata;
}
RenderFrameMetadata LayerTreeHostImpl::MakeRenderFrameMetadata(
FrameData* frame) {
RenderFrameMetadata metadata;
metadata.root_scroll_offset = active_tree_->TotalScrollOffset();
metadata.root_background_color = active_tree_->background_color();
metadata.is_scroll_offset_at_top = active_tree_->TotalScrollOffset().y() == 0;
metadata.device_scale_factor = active_tree_->painted_device_scale_factor() *
active_tree_->device_scale_factor();
active_tree_->GetViewportSelection(&metadata.selection);
metadata.is_mobile_optimized = IsMobileOptimized(active_tree_.get());
metadata.viewport_size_in_pixels = active_tree_->GetDeviceViewport().size();
metadata.page_scale_factor = active_tree_->current_page_scale_factor();
metadata.external_page_scale_factor =
active_tree_->external_page_scale_factor();
metadata.top_controls_height =
browser_controls_offset_manager_->TopControlsHeight();
metadata.top_controls_shown_ratio =
browser_controls_offset_manager_->TopControlsShownRatio();
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
metadata.bottom_controls_height =
browser_controls_offset_manager_->BottomControlsHeight();
metadata.bottom_controls_shown_ratio =
browser_controls_offset_manager_->BottomControlsShownRatio();
metadata.top_controls_min_height_offset =
browser_controls_offset_manager_->TopControlsMinHeightOffset();
metadata.bottom_controls_min_height_offset =
browser_controls_offset_manager_->BottomControlsMinHeightOffset();
metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
metadata.root_layer_size = active_tree_->ScrollableSize();
if (InnerViewportScrollNode()) {
DCHECK(OuterViewportScrollNode());
metadata.root_overflow_y_hidden =
!OuterViewportScrollNode()->user_scrollable_vertical ||
!InnerViewportScrollNode()->user_scrollable_vertical;
}
metadata.has_transparent_background =
frame->render_passes.back()->has_transparent_background;
metadata.has_offset_tag = browser_controls_offset_manager_->HasOffsetTag();
#endif
bool allocate_new_local_surface_id = false;
if (last_draw_render_frame_metadata_) {
const float last_root_scroll_offset_y =
last_draw_render_frame_metadata_->root_scroll_offset
.value_or(gfx::PointF())
.y();
const float new_root_scroll_offset_y =
metadata.root_scroll_offset.value().y();
if (!MathUtil::IsWithinEpsilon(last_root_scroll_offset_y,
new_root_scroll_offset_y)) {
viz::VerticalScrollDirection new_vertical_scroll_direction =
(last_root_scroll_offset_y < new_root_scroll_offset_y)
? viz::VerticalScrollDirection::kDown
: viz::VerticalScrollDirection::kUp;
// Changes in vertical scroll direction happen instantaneously. This being
// the case, a new vertical scroll direction should only be present in the
// singular metadata for the render frame in which the direction change
// occurred. If the vertical scroll direction detected here matches that
// which we've previously cached, then this frame is not the instant in
// which the direction change occurred and is therefore not propagated.
if (last_vertical_scroll_direction_ != new_vertical_scroll_direction)
metadata.new_vertical_scroll_direction = new_vertical_scroll_direction;
}
allocate_new_local_surface_id =
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
last_draw_render_frame_metadata_->top_controls_height !=
metadata.top_controls_height ||
last_draw_render_frame_metadata_->top_controls_shown_ratio !=
metadata.top_controls_shown_ratio;
#elif BUILDFLAG(IS_ANDROID)
last_draw_render_frame_metadata_->top_controls_height !=
metadata.top_controls_height ||
last_draw_render_frame_metadata_->bottom_controls_height !=
metadata.bottom_controls_height ||
last_draw_render_frame_metadata_->selection != metadata.selection ||
last_draw_render_frame_metadata_->has_transparent_background !=
metadata.has_transparent_background;
if (features::IsBrowserControlsInVizEnabled()) {
// When the browser controls become locked, the browser will update the
// offset tags, and also update the controls' offsets if they don't match
// the current renderer scroll position. These updates result in a new
// renderer frame, but sometimes it gets drawn before the browser frame
// with the updated offsets arrives, which causes the controls to jump, so
// we need a new surface id here to sync the updates.
allocate_new_local_surface_id |=
(last_draw_render_frame_metadata_->has_offset_tag &&
!metadata.has_offset_tag);
// If BCIV is enabled but there's no offset tags, it means the controls
// aren't scrollable, and any movement of the controls is the result of
// the browser updating their offsets and submitting a new browser frame.
// We need a new surface id in this case, as this is identical to the
// situation without BCIV.
if (!browser_controls_offset_manager_->HasOffsetTag()) {
allocate_new_local_surface_id |=
last_draw_render_frame_metadata_->top_controls_shown_ratio !=
metadata.top_controls_shown_ratio ||
last_draw_render_frame_metadata_->bottom_controls_shown_ratio !=
metadata.bottom_controls_shown_ratio;
} else if (!features::IsBcivBottomControlsEnabled()) {
// When AndroidBrowserControlsInViz is enabled, don't always use
// bottom_controls_shown_ratio to determine if surface sync is needed,
// because it changes even when there are no bottom controls.
bool bottom_controls_exist =
metadata.bottom_controls_height != 0 ||
last_draw_render_frame_metadata_->bottom_controls_height != 0;
allocate_new_local_surface_id |=
bottom_controls_exist &&
last_draw_render_frame_metadata_->bottom_controls_shown_ratio !=
metadata.bottom_controls_shown_ratio;
}
} else {
allocate_new_local_surface_id |=
last_draw_render_frame_metadata_->top_controls_shown_ratio !=
metadata.top_controls_shown_ratio ||
last_draw_render_frame_metadata_->bottom_controls_shown_ratio !=
metadata.bottom_controls_shown_ratio;
}
#else
last_draw_render_frame_metadata_->top_controls_height !=
metadata.top_controls_height ||
last_draw_render_frame_metadata_->top_controls_shown_ratio !=
metadata.top_controls_shown_ratio ||
last_draw_render_frame_metadata_->bottom_controls_height !=
metadata.bottom_controls_height ||
last_draw_render_frame_metadata_->bottom_controls_shown_ratio !=
metadata.bottom_controls_shown_ratio ||
last_draw_render_frame_metadata_->selection != metadata.selection ||
last_draw_render_frame_metadata_->has_transparent_background !=
metadata.has_transparent_background;
#endif
}
if (GetCurrentLocalSurfaceId().is_valid()) {
if (allocate_new_local_surface_id)
AllocateLocalSurfaceId();
metadata.local_surface_id = GetCurrentLocalSurfaceId();
}
metadata.primary_main_frame_item_sequence_number =
active_tree()->primary_main_frame_item_sequence_number();
return metadata;
}
std::optional<SubmitInfo> LayerTreeHostImpl::DrawLayers(FrameData* frame) {
DCHECK(CanDraw());
DCHECK_EQ(frame->has_no_damage, frame->render_passes.empty());
ResetRequiresHighResToDraw();
if (frame->has_no_damage) {
DCHECK(!resourceless_software_draw_);
TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoDamage", TRACE_EVENT_SCOPE_THREAD);
active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
active_tree()->ResetAllChangeTracking();
// Drop pending event metrics for UI when the frame has no damage because
// it could leave the event metrics pending indefinitely and also breaks the
// association between input events and screen updates.
// See b/297940877.
if (settings_.is_layer_tree_for_ui) {
std::ignore = active_tree()->TakeEventsMetrics();
std::ignore = active_tree()->TakeRasterEventsMetrics();
std::ignore = events_metrics_manager_.TakeSavedEventsMetrics();
}
return std::nullopt;
}
layer_tree_frame_sink_->set_source_frame_number(
active_tree_->source_frame_number());
bool drawn_with_new_layer_tree = true;
if (last_draw_active_tree_begin_frame_args_.IsValid()) {
// If the active tree's BFA are the same as the last frame that we drew,
// then we are reusing a tree. If we are not, then we know we are
// activating a new layer in the tree.
drawn_with_new_layer_tree =
active_tree_->CreatedBeginFrameArgs().frame_id !=
last_draw_active_tree_begin_frame_args_.frame_id;
}
last_draw_active_tree_begin_frame_args_ =
active_tree_->CreatedBeginFrameArgs();
auto compositor_frame = GenerateCompositorFrame(frame);
const auto frame_token = compositor_frame.metadata.frame_token;
frame->frame_token = frame_token;
bool top_controls_moved = false;
float current_top_controls =
compositor_frame.metadata.top_controls_visible_height.value_or(0.f);
if (current_top_controls != top_controls_visible_height_) {
top_controls_moved = true;
top_controls_visible_height_ = current_top_controls;
}
#if DCHECK_IS_ON()
const viz::BeginFrameId begin_frame_ack_frame_id =
compositor_frame.metadata.begin_frame_ack.frame_id;
#endif
EventMetricsSet events_metrics(
active_tree()->TakeEventsMetrics(),
events_metrics_manager_.TakeSavedEventsMetrics(),
active_tree()->TakeRasterEventsMetrics());
lag_tracking_manager_.CollectScrollEventsFromFrame(frame_token,
events_metrics);
std::optional<float> normalized_invalidated_area;
if (settings_.is_layer_tree_for_ui) {
CHECK(total_invalidated_area_.has_value());
const gfx::Rect& output_rect =
active_tree()->RootRenderSurface()->content_rect();
normalized_invalidated_area =
static_cast<float>(
total_invalidated_area_.value().ValueOrDefault(UINT_MAX)) /
output_rect.size().GetArea();
total_invalidated_area_ = 0;
}
// Dump property trees and layers if VerboseLogEnabled().
VERBOSE_LOG() << "Submitting a frame:\n"
<< viz::TransitionUtils::RenderPassListToString(
compositor_frame.render_pass_list);
base::TimeTicks submit_time = base::TimeTicks::Now();
if (settings_.TreesInVizInClientProcess()) {
UpdateDisplayTree(*frame);
layer_tree_frame_sink_->ExportFrameTiming();
// For the display compositor we should have already submitted at display
// Immediately queue a DidReceiveCompositorFrameAck.
GetTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(&LayerTreeHostImpl::DidReceiveCompositorFrameAck,
weak_factory_.GetWeakPtr()));
} else {
TRACE_EVENT(
"viz,benchmark,graphics.pipeline", "Graphics.Pipeline",
perfetto::Flow::Global(CurrentBeginFrameArgs().trace_id),
[&](perfetto::EventContext ctx) {
base::TaskAnnotator::EmitTaskTimingDetails(ctx);
auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
auto* data = event->set_chrome_graphics_pipeline();
data->set_step(perfetto::protos::pbzero::ChromeGraphicsPipeline::
StepName::STEP_SUBMIT_COMPOSITOR_FRAME);
data->set_surface_frame_trace_id(CurrentBeginFrameArgs().trace_id);
for (const ui::LatencyInfo& latency :
compositor_frame.metadata.latency_info) {
data->add_latency_ids(latency.trace_id());
}
});
layer_tree_frame_sink_->SubmitCompositorFrame(
std::move(compositor_frame),
/*hit_test_data_changed=*/false);
// After we submit a frame, if we're expecting a new local surface id, then
// notify about that immediately.
// TODO(vmpstr): When it comes to ViewTransitions, it is possible that we
// can just avoid sending the save directive/copy output requests until the
// next frame. However, because this frame submission might race with
// LayerTreeHostImpl::NotifyNewLocalSurfaceIdExpectedWhilePaused, this call
// is more consistent and 'resolves' the race as far as viz is concerned. If
// this is an issue in practice, we need to think of a different approach.
if (new_local_surface_id_expected_) {
layer_tree_frame_sink_->NotifyNewLocalSurfaceIdExpectedWhilePaused();
}
}
#if DCHECK_IS_ON()
if (!doing_sync_draw_) {
// The throughput computation (in |FrameSequenceTracker|) depends on the
// compositor-frame submission to happen while a BeginFrameArgs is 'active'
// (i.e. between calls to WillBeginImplFrame() and DidFinishImplFrame()).
// Verify that this is the case.
// No begin-frame is available when doing sync draws, so avoid doing this
// check in that case.
const auto& bfargs = current_begin_frame_tracker_.Current();
DCHECK_EQ(bfargs.frame_id, begin_frame_ack_frame_id);
}
#endif
if (!mutator_host_->NextFrameHasPendingRAF())
frame_trackers_.StopSequence(FrameSequenceTrackerType::kRAF);
if (!mutator_host_->HasCanvasInvalidation())
frame_trackers_.StopSequence(FrameSequenceTrackerType::kCanvasAnimation);
if (!mutator_host_->NextFrameHasPendingRAF() &&
!mutator_host_->HasJSAnimation())
frame_trackers_.StopSequence(FrameSequenceTrackerType::kJSAnimation);
if (mutator_host_->MainThreadAnimationsCount() == 0 &&
!mutator_host_->HasSmilAnimation()) {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kMainThreadAnimation);
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kSETMainThreadAnimation);
} else if (!mutator_host_->HasViewTransition()) {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kSETMainThreadAnimation);
}
if (lcd_text_metrics_reporter_) {
lcd_text_metrics_reporter_->NotifySubmitFrame(
frame->origin_begin_main_frame_args);
}
// Clears the list of swap promises after calling DidSwap on each of them to
// signal that the swap is over.
active_tree()->ClearSwapPromises();
if (frame->has_copy_requests) {
// Any copy requests left in the tree are not going to get serviced, and
// should be aborted.
active_tree()->property_trees()->effect_tree_mutable().ClearCopyRequests();
// Draw properties depend on copy requests.
active_tree()->set_needs_update_draw_properties();
// TODO(crbug.com/40447355): This workaround to prevent creating
// unnecessarily persistent render passes. When a copy request is made, it
// may force a separate render pass for the layer, which will persist until
// a new commit removes it. Force a commit after copy requests, to remove
// extra render passes.
client_->SetNeedsCommitOnImplThread();
}
// The next frame should start by assuming nothing has changed, and changes
// are noted as they occur.
// TODO(boliu): If we did a temporary software renderer frame, propagate the
// damage forward to the next frame.
for (size_t i = 0; i < frame->render_surface_list->size(); i++) {
auto* surface = (*frame->render_surface_list)[i];
surface->damage_tracker()->DidDrawDamagedArea();
}
if (active_tree_->RootRenderSurface()) {
viewport_damage_rect_ = gfx::Rect();
}
active_tree_->ResetAllChangeTracking();
if (!GetSettings().is_layer_tree_for_ui) {
devtools_instrumentation::DidDrawFrame(
id_, frame->begin_frame_ack.frame_id.sequence_number);
}
benchmark_instrumentation::IssueImplThreadRenderingStatsEvent(
rendering_stats_instrumentation_->TakeImplThreadRenderingStats());
if (settings_.enable_compositing_based_throttling &&
throttle_decider_.HasThrottlingChanged()) {
client_->FrameSinksToThrottleUpdated(throttle_decider_.ids());
}
if (GetActivelyScrollingType() != ActivelyScrollingType::kNone &&
frame->checkerboarded_needs_record) {
scroll_checkerboards_incomplete_recording_ = true;
}
return SubmitInfo{frame_token,
submit_time,
frame->checkerboarded_needs_raster,
frame->checkerboarded_needs_record,
top_controls_moved,
std::move(events_metrics),
drawn_with_new_layer_tree,
active_tree_->did_raster_inducing_scroll(),
normalized_invalidated_area};
}
viz::CompositorFrame LayerTreeHostImpl::GenerateCompositorFrame(
FrameData* frame) {
if (!settings_.trees_in_viz_in_viz_process) {
memory_history_->SaveEntry(tile_manager_.memory_stats_from_last_assign());
}
if (debug_state_.ShowDebugRects()) {
debug_rect_history_->SaveDebugRectsForCurrentFrame(
active_tree(), active_tree_->hud_layer(), *frame->render_surface_list,
debug_state_);
}
TRACE_EVENT_INSTANT2("cc", "Scroll Delta This Frame",
TRACE_EVENT_SCOPE_THREAD, "x",
scroll_accumulated_this_frame_.x(), "y",
scroll_accumulated_this_frame_.y());
scroll_accumulated_this_frame_ = gfx::Vector2dF();
bool is_new_trace;
TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
if (is_new_trace) {
if (pending_tree_) {
for (auto* layer : *pending_tree_)
layer->DidBeginTracing();
}
for (auto* layer : *active_tree_)
layer->DidBeginTracing();
}
{
TRACE_EVENT0("cc", "DrawLayers.FrameViewerTracing");
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
frame_viewer_instrumentation::CategoryLayerTree(),
"cc::LayerTreeHostImpl", id_, AsValueWithFrame(frame));
}
const DrawMode draw_mode = GetDrawMode();
// Because the contents of the HUD depend on everything else in the frame, the
// contents of its texture are updated as the last thing before the frame is
// drawn.
if (active_tree_->hud_layer()) {
TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
active_tree_->hud_layer()->UpdateHudTexture(
draw_mode, layer_tree_frame_sink_, resource_provider_.get(),
raster_caps(), frame->render_passes);
}
viz::CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
// Don't compute transition directives in TreesInViz mode because
// the requests will be sent over to viz to compute them.
// If we call TakeViewTransitionRequests() here, it will clear the requests
// and send none to viz.
if (!settings_.TreesInVizInClientProcess()) {
ViewTransitionRequest::ViewTransitionElementMap view_transition_element_map;
const auto& capture_view_transition_tokens =
active_tree_->GetCaptureViewTransitionTokens();
for (RenderSurfaceImpl* render_surface : *frame->render_surface_list) {
const auto& view_transition_element_resource_id =
render_surface->OwningEffectNode()
->view_transition_element_resource_id;
if (!view_transition_element_resource_id.IsValid()) {
continue;
}
DCHECK(!base::Contains(view_transition_element_map,
view_transition_element_resource_id))
<< "Cannot map " << view_transition_element_resource_id.ToString()
<< " to render pass "
<< render_surface->render_pass_id().GetUnsafeValue()
<< "; It already maps to render pass "
<< view_transition_element_map[view_transition_element_resource_id]
.GetUnsafeValue();
if (view_transition_element_resource_id.MatchesToken(
capture_view_transition_tokens)) {
view_transition_element_map[view_transition_element_resource_id] =
render_surface->view_transition_capture_render_pass_id();
} else {
view_transition_element_map[view_transition_element_resource_id] =
render_surface->render_pass_id();
}
}
auto display_color_spaces = GetDisplayColorSpaces();
for (auto& request : active_tree_->TakeViewTransitionRequests(
/*should_set_needs_update_draw_properties=*/true)) {
if (resourceless_software_draw_) {
OnCompositorFrameTransitionDirectiveProcessed(request->sequence_id());
} else {
metadata.transition_directives.push_back(request->ConstructDirective(
view_transition_element_map, display_color_spaces));
}
}
} else {
// In TreesInViz mode, we call TakeViewTransitionRequest() later in
// VizLayerContext::UpdateDisplayTreeFrom(), but we still want to set
// the flag here to avoid changing the flow of computing. Also, we will
// skip setting the flag when TakeViewTransitionRequest() is called later
// to avoid triggering a DCHECK.
if (active_tree_->HasViewTransitionRequests()) {
active_tree_->set_needs_update_draw_properties();
}
}
PopulateMetadataContentColorUsage(frame, &metadata);
metadata.has_shared_element_resources = frame->has_shared_element_resources;
metadata.deadline = viz::FrameDeadline(
CurrentBeginFrameArgs().frame_time,
frame->deadline_in_frames.value_or(0u), CurrentBeginFrameArgs().interval,
frame->use_default_lower_bound_deadline);
metadata.frame_interval_inputs.frame_time =
CurrentBeginFrameArgs().frame_time;
metadata.frame_interval_inputs.has_input = has_input_for_frame_interval_;
metadata.frame_interval_inputs.has_user_input =
has_non_fling_input_since_last_frame_;
has_non_fling_input_since_last_frame_ = false;
if (frame->damage_reasons.Has(DamageReason::kCompositorScroll)) {
// Sanity check frame time delta.
if (begin_frame_time_delta_.InMicroseconds() < 100 ||
begin_frame_time_delta_.InMicroseconds() > 1000000) {
metadata.frame_interval_inputs.major_scroll_speed_in_pixels_per_second =
0.f;
} else {
metadata.frame_interval_inputs.major_scroll_speed_in_pixels_per_second =
frame_max_scroll_delta_ / begin_frame_time_delta_.InSecondsF();
}
metadata.frame_interval_inputs.content_interval_info.push_back(
{viz::ContentFrameIntervalType::kCompositorScroll, base::TimeDelta(),
1u});
frame->damage_reasons.Remove(DamageReason::kCompositorScroll);
}
if (!frame->video_layer_preferred_intervals.empty() &&
frame->damage_reasons.Has(DamageReason::kVideoLayer)) {
for (auto& [video_interval, count] :
frame->video_layer_preferred_intervals) {
metadata.frame_interval_inputs.content_interval_info.push_back(
{viz::ContentFrameIntervalType::kVideo, video_interval, count - 1u});
}
frame->damage_reasons.Remove(DamageReason::kVideoLayer);
}
if (frame->damage_reasons.Has(DamageReason::kAnimatedImage)) {
std::optional<ImageAnimationController::ConsistentFrameDuration>
animating_image_duration =
image_animation_controller_.GetConsistentContentFrameDuration();
if (animating_image_duration) {
metadata.frame_interval_inputs.content_interval_info.push_back(
{viz::ContentFrameIntervalType::kAnimatingImage,
animating_image_duration->frame_duration,
animating_image_duration->num_images - 1u});
frame->damage_reasons.Remove(DamageReason::kAnimatedImage);
}
}
if (frame->damage_reasons.Has(DamageReason::kScrollbarFadeOutAnimation)) {
// Lower fade out animation to 20hz somewhat arbitrarily since it's small
// and hard to notice a low frame rate.
metadata.frame_interval_inputs.content_interval_info.push_back(
{viz::ContentFrameIntervalType::kScrollBarFadeOutAnimation,
base::Hertz(20)});
frame->damage_reasons.Remove(DamageReason::kScrollbarFadeOutAnimation);
}
// If all RedrawReasons have been recorded in `content_interval_info` and
// removed, then can set `has_only_content_frame_interval_updates`.
metadata.frame_interval_inputs.has_only_content_frame_interval_updates =
frame->damage_reasons.empty();
metadata.activation_dependencies = std::move(frame->activation_dependencies);
active_tree()->FinishSwapPromises(&metadata);
// The swap-promises should not change the frame-token.
DCHECK_EQ(metadata.frame_token, *next_frame_token_);
// In TreesInViz mode in viz, we need to compute
// |last_draw_render_frame_metadata_| because it impacts HasDamage()
// computation.
if (render_frame_metadata_observer_ ||
settings_.trees_in_viz_in_viz_process) {
last_draw_render_frame_metadata_ = MakeRenderFrameMetadata(frame);
if (gfx::DelegatedInkMetadata* ink_metadata =
metadata.delegated_ink_metadata.get()) {
last_draw_render_frame_metadata_->delegated_ink_metadata =
DelegatedInkBrowserMetadata(ink_metadata->is_hovering());
}
// We cache the value of any new vertical scroll direction so that we can
// accurately determine when the next change in vertical scroll direction
// occurs. Note that |kNull| is only used to indicate the absence of a
// vertical scroll direction and should therefore be ignored.
if (last_draw_render_frame_metadata_->new_vertical_scroll_direction !=
viz::VerticalScrollDirection::kNull) {
last_vertical_scroll_direction_ =
last_draw_render_frame_metadata_->new_vertical_scroll_direction;
}
// TODO(zmo): Consider plumbing the observer to viz as well.
if (render_frame_metadata_observer_) {
render_frame_metadata_observer_->OnRenderFrameSubmission(
*last_draw_render_frame_metadata_, &metadata,
active_tree()->TakeForceSendMetadataRequest());
}
}
if (!CommitsToActiveTree() && !metadata.latency_info.empty()) {
base::TimeTicks draw_time = base::TimeTicks::Now();
ApplyFirstScrollTracking(metadata.latency_info.front(),
metadata.frame_token);
for (auto& latency : metadata.latency_info) {
latency.AddLatencyNumberWithTimestamp(
ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT, draw_time);
}
}
// Collect all resource ids in the render passes into a single array.
std::vector<viz::ResourceId> resources;
for (const auto& render_pass : frame->render_passes) {
for (auto* quad : render_pass->quad_list) {
if (quad->resource_id != viz::kInvalidResourceId) {
resources.push_back(quad->resource_id);
}
}
}
DCHECK(frame->begin_frame_ack.frame_id.IsSequenceValid());
metadata.begin_frame_ack = frame->begin_frame_ack;
viz::CompositorFrame compositor_frame;
compositor_frame.metadata = std::move(metadata);
resource_provider_->PrepareSendToParent(
resources, &compositor_frame.resource_list,
layer_tree_frame_sink_->context_provider());
compositor_frame.render_pass_list = std::move(frame->render_passes);
// We should always have a valid LocalSurfaceId in LayerTreeImpl unless we
// don't have a scheduler because without a scheduler commits are not deferred
// and LayerTrees without valid LocalSurfaceId might slip through, but
// single-thread-without-scheduler mode is only used in tests so it doesn't
// matter.
CHECK(!settings_.single_thread_proxy_scheduler ||
active_tree()->local_surface_id_from_parent().is_valid());
if (!settings_.trees_in_viz_in_viz_process) {
// In TreesInViz viz process, this ends up in LayerTreeHostImpl again
// and doesn't change anything.
layer_tree_frame_sink_->SetLocalSurfaceId(GetCurrentLocalSurfaceId());
}
last_draw_local_surface_id_ = GetCurrentLocalSurfaceId();
if (const char* client_name = GetClientNameForMetrics()) {
size_t total_quad_count = 0;
for (const auto& pass : compositor_frame.render_pass_list) {
total_quad_count += pass->quad_list.size();
}
UMA_HISTOGRAM_COUNTS_1000(
base::StringPrintf("Compositing.%s.CompositorFrame.Quads", client_name),
total_quad_count);
}
return compositor_frame;
}
void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
// TODO(lethalantidote): LayerImpl::DidDraw can be removed when
// VideoLayerImpl is removed.
for (LayerImpl* layer : frame.will_draw_layers) {
layer->DidDraw(resource_provider_.get());
}
for (VideoFrameController* it : video_frame_controllers_) {
it->DidDrawFrame();
}
}
void LayerTreeHostImpl::UpdateDisplayTree(FrameData& frame) {
DCHECK(settings_.TreesInVizInClientProcess());
DCHECK(layer_context_);
layer_context_->UpdateDisplayTreeFrom(
*active_tree(), *resource_provider(),
*layer_tree_frame_sink_->context_provider(), viewport_damage_rect_,
target_local_surface_id_);
}
int LayerTreeHostImpl::RequestedMSAASampleCount() const {
if (settings_.gpu_rasterization_msaa_sample_count == -1) {
// On "low-end" devices use 4 samples per pixel to save memory.
if (base::SysInfo::IsLowEndDevice())
return 4;
// Use the most up-to-date version of device_scale_factor that we have.
float device_scale_factor = pending_tree_
? pending_tree_->device_scale_factor()
: active_tree_->device_scale_factor();
// Note: this is invalid for HiDPI devices, the device scale factor should
// be multiplied by `active_tree()->painted_device_scale_factor()`. This was
// experimented with, but since DMSAA is used almost everywhere, did not
// make a difference in the end. Regardless, the above computation is
// technically incorrect.
return device_scale_factor >= 2.0f ? 4 : 8;
}
return settings_.gpu_rasterization_msaa_sample_count;
}
void LayerTreeHostImpl::UpdateRasterCapabilities() {
CHECK(layer_tree_frame_sink_);
raster_caps_ = RasterCapabilities();
auto* context_provider = layer_tree_frame_sink_->context_provider();
auto* worker_context_provider =
layer_tree_frame_sink_->worker_context_provider();
CHECK_EQ(!!worker_context_provider, !!context_provider);
if (!worker_context_provider) {
// No context provider means software raster + compositing.
raster_caps_.max_texture_size = settings_.max_render_buffer_bounds_for_sw;
// Software compositor always uses BGRA 8888 format for tiles.
raster_caps_.tile_format = viz::SinglePlaneFormat::kBGRA_8888;
raster_caps_.ui_rgba_format =
layer_tree_frame_sink_->shared_image_interface()
? viz::SinglePlaneFormat::kBGRA_8888
: viz::SinglePlaneFormat::kRGBA_8888;
return;
}
viz::RasterContextProvider::ScopedRasterContextLock scoped_lock(
worker_context_provider);
const auto& context_caps = worker_context_provider->ContextCapabilities();
const auto& shared_image_caps =
worker_context_provider->SharedImageInterface()->GetCapabilities();
raster_caps_.max_texture_size = context_caps.max_texture_size;
raster_caps_.ui_rgba_format =
viz::PlatformColor::BestSupportedTextureFormat(context_caps);
raster_caps_.tile_overlay_candidate =
settings_.use_gpu_memory_buffer_resources &&
shared_image_caps.supports_scanout_shared_images;
if (settings_.gpu_rasterization_disabled || !context_caps.gpu_rasterization) {
// This is the GPU compositing but software rasterization path. Pick the
// best format for GPU textures to be uploaded to.
raster_caps_.tile_format =
settings_.use_rgba_4444
? viz::SinglePlaneFormat::kRGBA_4444
: viz::PlatformColor::BestSupportedTextureFormat(context_caps);
return;
}
// GPU compositing + rasterization is enabled if we get this far.
raster_caps_.use_gpu_rasterization = true;
raster_caps_.can_use_msaa =
!context_caps.msaa_is_slow && !context_caps.avoid_stencil_buffers;
raster_caps_.tile_format =
settings_.use_rgba_4444
? viz::SinglePlaneFormat::kRGBA_4444
: viz::PlatformColor::BestSupportedRenderBufferFormat(context_caps);
}
ImageDecodeCache* LayerTreeHostImpl::GetImageDecodeCache() const {
return image_decode_cache_holder_
? image_decode_cache_holder_->image_decode_cache()
: nullptr;
}
void LayerTreeHostImpl::RegisterMainThreadPresentationTimeCallbackForTesting(
uint32_t frame_token,
PresentationTimeCallbackBuffer::Callback callback) {
std::vector<PresentationTimeCallbackBuffer::Callback> as_vector;
as_vector.push_back(std::move(callback));
presentation_time_callbacks_.RegisterMainThreadCallbacks(
frame_token, std::move(as_vector));
}
void LayerTreeHostImpl::
RegisterMainThreadSuccessfulPresentationTimeCallbackForTesting(
uint32_t frame_token,
PresentationTimeCallbackBuffer::SuccessfulCallbackWithDetails
callback) {
std::vector<PresentationTimeCallbackBuffer::SuccessfulCallbackWithDetails>
as_vector;
as_vector.push_back(std::move(callback));
presentation_time_callbacks_.RegisterMainThreadSuccessfulCallbacks(
frame_token, std::move(as_vector));
}
void LayerTreeHostImpl::
RegisterCompositorThreadSuccessfulPresentationTimeCallbackForTesting(
uint32_t frame_token,
PresentationTimeCallbackBuffer::SuccessfulCallback callback) {
std::vector<PresentationTimeCallbackBuffer::SuccessfulCallback> as_vector;
as_vector.push_back(std::move(callback));
presentation_time_callbacks_.RegisterCompositorThreadSuccessfulCallbacks(
frame_token, std::move(as_vector));
}
bool LayerTreeHostImpl::WillBeginImplFrame(const viz::BeginFrameArgs& args) {
if (!settings().single_thread_proxy_scheduler) {
client_->SetWaitingForScrollEvent(input_delegate_ &&
input_delegate_->IsCurrentlyScrolling() &&
!input_delegate_->HasQueuedInput());
}
frame_max_scroll_delta_ = 0.f;
if (current_begin_frame_tracker_.HasLast()) {
begin_frame_time_delta_ =
args.frame_time - current_begin_frame_tracker_.Last().frame_time;
} else {
begin_frame_time_delta_ = base::TimeDelta();
}
impl_thread_phase_ = ImplThreadPhase::INSIDE_IMPL_FRAME;
current_begin_frame_tracker_.Start(args);
frame_trackers_.NotifyBeginImplFrame(args);
compositor_frame_reporting_controller_->SetNeedsRasterPropertiesAnimated(
paint_worklet_tracker_.HasInputPropertiesAnimatedOnImpl());
if (!GetSettings().is_layer_tree_for_ui) {
devtools_instrumentation::DidBeginFrame(id_, args.frame_time,
args.frame_id.sequence_number);
}
// When there is a |target_local_surface_id_|, we do not wish to begin
// producing Impl Frames for an older viz::LocalSurfaceId, as it will never
// be displayed.
//
// Once the Main thread has finished adjusting to the new visual properties,
// it will push the updated viz::LocalSurfaceId. Begin Impl Frame production
// if it has already become activated, or is on the |pending_tree| to be
// activated during this frame's production.
//
// However when using a synchronous compositor we skip this throttling
// completely.
if (!settings_.using_synchronous_renderer_compositor) {
const viz::LocalSurfaceId& upcoming_lsid =
pending_tree() ? pending_tree()->local_surface_id_from_parent()
: active_tree()->local_surface_id_from_parent();
if (target_local_surface_id_.IsNewerThan(upcoming_lsid)) {
return false;
}
}
if (is_likely_to_require_a_draw_) {
// Optimistically schedule a draw. This will let us expect the tile manager
// to complete its work so that we can draw new tiles within the impl frame
// we are beginning now.
SetNeedsRedraw(/*animation_only*/ true);
}
if (input_delegate_)
input_delegate_->WillBeginImplFrame(args);
Animate();
image_animation_controller_.WillBeginImplFrame(args);
for (VideoFrameController* it : video_frame_controllers_) {
it->OnBeginFrame(args);
}
bool recent_frame_had_no_damage =
consecutive_frame_with_damage_count_ < settings_.damaged_frame_limit;
// Check damage early if the setting is enabled and a recent frame had no
// damage. HasDamage() expects CanDraw to be true. If we can't check damage,
// return true to indicate that there might be damage in this frame.
if (settings_.enable_early_damage_check && recent_frame_had_no_damage &&
CanDraw()) {
bool ok = active_tree()->UpdateDrawProperties(
/*update_tiles=*/true, /*update_image_animation_controller=*/true);
DCHECK(ok);
DamageTracker::UpdateDamageTracking(active_tree_.get());
bool has_damage = HasDamage();
// Animations are updated after we attempt to draw. If the frame is aborted,
// update animations now.
if (!has_damage)
UpdateAnimationState(true);
return has_damage;
}
// Assume there is damage if we cannot check for damage.
return true;
}
void LayerTreeHostImpl::DidFinishImplFrame(const viz::BeginFrameArgs& args) {
frame_trackers_.NotifyFrameEnd(current_begin_frame_tracker_.Current(), args);
impl_thread_phase_ = ImplThreadPhase::IDLE;
current_begin_frame_tracker_.Finish();
if (input_delegate_) {
input_delegate_->DidFinishImplFrame();
}
}
void LayerTreeHostImpl::DidNotProduceFrame(const viz::BeginFrameAck& ack,
FrameSkippedReason reason) {
TRACE_EVENT2(
"cc,benchmark", "LayerTreeHostImpl::DidNotProduceFrame",
"FrameSkippedReason",
[](FrameSkippedReason reason) {
switch (reason) {
case FrameSkippedReason::kRecoverLatency:
return "kRecoverLatency";
case FrameSkippedReason::kNoDamage:
return "kNoDamage";
case FrameSkippedReason::kWaitingOnMain:
return "kWaitingOnMain";
case FrameSkippedReason::kDrawThrottled:
return "kDrawThrottled";
}
return "";
}(reason),
"Frame Sequence Number", ack.frame_id.sequence_number);
if (layer_tree_frame_sink_) {
layer_tree_frame_sink_->DidNotProduceFrame(ack, reason);
}
// While scrolling, we save all event metrics. It is possible that this
// results in a 0 delta scroll, which has no damage. We take the metrics here
// so that they are terminated now. This prevents them from being incorrectly
// associated with a future produced frame. So that jank measurements have
// accurate deltas.
events_metrics_manager_.TakeSavedEventsMetrics();
}
void LayerTreeHostImpl::OnBeginImplFrameDeadline() {
if (!input_delegate_) {
return;
}
input_delegate_->OnBeginImplFrameDeadline();
}
void LayerTreeHostImpl::SynchronouslyInitializeAllTiles() {
// Only valid for the single-threaded non-scheduled/synchronous case
// using the zero copy raster worker pool.
tile_manager_.FlushImageControllerTasksForTesting(); // IN-TEST
single_thread_synchronous_task_graph_runner_->RunUntilIdle();
}
static uint32_t GetFlagsForSurfaceLayer(const SurfaceLayerImpl* layer) {
uint32_t flags = viz::HitTestRegionFlags::kHitTestMouse |
viz::HitTestRegionFlags::kHitTestTouch;
if (layer->range().IsValid()) {
flags |= viz::HitTestRegionFlags::kHitTestChildSurface;
} else {
flags |= viz::HitTestRegionFlags::kHitTestMine;
}
return flags;
}
static void PopulateHitTestRegion(viz::HitTestRegion* hit_test_region,
const LayerImpl* layer,
uint32_t flags,
uint32_t async_hit_test_reasons,
const gfx::Rect& rect,
const viz::SurfaceId& surface_id,
float device_scale_factor) {
hit_test_region->frame_sink_id = surface_id.frame_sink_id();
hit_test_region->flags = flags;
hit_test_region->async_hit_test_reasons = async_hit_test_reasons;
DCHECK_EQ(!!async_hit_test_reasons,
!!(flags & viz::HitTestRegionFlags::kHitTestAsk));
hit_test_region->rect = rect;
// The transform of hit test region maps a point from parent hit test region
// to the local space. This is the inverse of screen space transform. Because
// hit test query wants the point in target to be in Pixel space, we
// counterscale the transform here. Note that the rect is scaled by dsf, so
// the point and the rect are still in the same space.
gfx::Transform surface_to_root_transform = layer->ScreenSpaceTransform();
surface_to_root_transform.Scale(SK_Scalar1 / device_scale_factor,
SK_Scalar1 / device_scale_factor);
surface_to_root_transform.Flatten();
// TODO(sunxd): Avoid losing precision by not using inverse if possible.
// Note: |transform| is set to the identity if |surface_to_root_transform| is
// not invertible, which is what we want.
hit_test_region->transform = surface_to_root_transform.InverseOrIdentity();
}
std::optional<viz::HitTestRegionList> LayerTreeHostImpl::BuildHitTestData() {
TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildHitTestData");
std::optional<viz::HitTestRegionList> hit_test_region_list(std::in_place);
hit_test_region_list->flags = viz::HitTestRegionFlags::kHitTestMine |
viz::HitTestRegionFlags::kHitTestMouse |
viz::HitTestRegionFlags::kHitTestTouch;
hit_test_region_list->bounds = active_tree_->GetDeviceViewport();
hit_test_region_list->transform = DrawTransform();
float device_scale_factor = active_tree()->device_scale_factor();
Region overlapping_region;
size_t num_iterated_layers = 0;
// If the layer tree contains more than 100 layers, we stop accumulating
// layers in |overlapping_region| to save compositor frame submitting time, as
// a result we do async hit test on any surface layers that
bool assume_overlap = false;
for (const auto* layer : base::Reversed(*active_tree())) {
if (layer->is_surface_layer()) {
const auto* surface_layer = static_cast<const SurfaceLayerImpl*>(layer);
// We should not skip a non-hit-testable surface layer if
// - it has pointer-events: none because viz hit test needs to know the
// information to ensure all descendant OOPIFs to ignore hit tests; or
// - it draws content to track overlaps.
if (!layer->HitTestable() && !layer->draws_content() &&
!surface_layer->has_pointer_events_none()) {
continue;
}
// If a surface layer is created not by child frame compositor or the
// frame owner has pointer-events: none property, the surface layer
// becomes not hit testable. We should not generate data for it.
if (!surface_layer->surface_hit_testable() ||
!surface_layer->range().IsValid()) {
// We collect any overlapped regions that does not have pointer-events:
// none.
if (!surface_layer->has_pointer_events_none() && !assume_overlap) {
overlapping_region.Union(MathUtil::MapEnclosingClippedRect(
layer->ScreenSpaceTransform(),
gfx::Rect(surface_layer->bounds())));
}
continue;
}
gfx::Rect content_rect(gfx::ScaleToEnclosingRect(
gfx::Rect(surface_layer->bounds()), device_scale_factor));
gfx::Rect layer_screen_space_rect = MathUtil::MapEnclosingClippedRect(
surface_layer->ScreenSpaceTransform(),
gfx::Rect(surface_layer->bounds()));
auto flag = GetFlagsForSurfaceLayer(surface_layer);
uint32_t async_hit_test_reasons =
viz::AsyncHitTestReasons::kNotAsyncHitTest;
if (surface_layer->has_pointer_events_none())
flag |= viz::HitTestRegionFlags::kHitTestIgnore;
if (assume_overlap ||
overlapping_region.Intersects(layer_screen_space_rect)) {
flag |= viz::HitTestRegionFlags::kHitTestAsk;
async_hit_test_reasons |= viz::AsyncHitTestReasons::kOverlappedRegion;
}
bool layer_hit_test_region_is_masked =
active_tree()
->property_trees()
->effect_tree()
.HitTestMayBeAffectedByMask(surface_layer->effect_tree_index());
if (surface_layer->is_clipped() || layer_hit_test_region_is_masked) {
bool layer_hit_test_region_is_rectangle =
!layer_hit_test_region_is_masked &&
surface_layer->ScreenSpaceTransform().Preserves2dAxisAlignment() &&
active_tree()
->property_trees()
->effect_tree()
.ClippedHitTestRegionIsRectangle(
surface_layer->effect_tree_index());
content_rect =
gfx::ScaleToEnclosingRect(surface_layer->visible_layer_rect(),
device_scale_factor, device_scale_factor);
if (!layer_hit_test_region_is_rectangle) {
flag |= viz::HitTestRegionFlags::kHitTestAsk;
async_hit_test_reasons |= viz::AsyncHitTestReasons::kIrregularClip;
}
}
const auto& surface_id = surface_layer->range().end();
hit_test_region_list->regions.emplace_back();
PopulateHitTestRegion(&hit_test_region_list->regions.back(), layer, flag,
async_hit_test_reasons, content_rect, surface_id,
device_scale_factor);
continue;
}
if (!layer->HitTestable()) {
continue;
}
// TODO(sunxd): Submit all overlapping layer bounds as hit test regions.
// Also investigate if we can use visible layer rect as overlapping regions.
num_iterated_layers++;
if (num_iterated_layers > kAssumeOverlapThreshold)
assume_overlap = true;
if (!assume_overlap) {
overlapping_region.Union(MathUtil::MapEnclosingClippedRect(
layer->ScreenSpaceTransform(), gfx::Rect(layer->bounds())));
}
}
return hit_test_region_list;
}
void LayerTreeHostImpl::DidLoseLayerTreeFrameSink() {
// Check that we haven't already detected context loss because we get it via
// two paths: compositor context loss on the compositor thread and worker
// context loss posted from main thread to compositor thread. We do not want
// to reset the context recovery state in the scheduler.
if (!has_valid_layer_tree_frame_sink_)
return;
has_valid_layer_tree_frame_sink_ = false;
client_->DidLoseLayerTreeFrameSinkOnImplThread();
lag_tracking_manager_.Clear();
frame_sorter_.Reset(/*reset_fcp=*/false);
}
bool LayerTreeHostImpl::OnlyExpandTopControlsAtPageTop() const {
return active_tree_->only_expand_top_controls_at_page_top();
}
bool LayerTreeHostImpl::HaveRootScrollNode() const {
return InnerViewportScrollNode();
}
void LayerTreeHostImpl::SetNeedsCommit() {
client_->SetNeedsCommitOnImplThread();
}
ScrollNode* LayerTreeHostImpl::InnerViewportScrollNode() const {
return active_tree_->InnerViewportScrollNode();
}
ScrollNode* LayerTreeHostImpl::OuterViewportScrollNode() const {
return active_tree_->OuterViewportScrollNode();
}
ScrollNode* LayerTreeHostImpl::CurrentlyScrollingNode() {
return active_tree()->CurrentlyScrollingNode();
}
const ScrollNode* LayerTreeHostImpl::CurrentlyScrollingNode() const {
return active_tree()->CurrentlyScrollingNode();
}
bool LayerTreeHostImpl::IsPinchGestureActive() const {
if (!input_delegate_)
return false;
return GetInputHandler().pinch_gesture_active();
}
ActivelyScrollingType LayerTreeHostImpl::GetActivelyScrollingType() const {
if (!input_delegate_)
return ActivelyScrollingType::kNone;
return input_delegate_->GetActivelyScrollingType();
}
bool LayerTreeHostImpl::IsCurrentScrollMainRepainted() const {
return input_delegate_ && input_delegate_->IsCurrentScrollMainRepainted();
}
bool LayerTreeHostImpl::ScrollAffectsScrollHandler() const {
if (!input_delegate_)
return false;
return settings_.enable_synchronized_scrolling &&
scroll_affects_scroll_handler_;
}
void LayerTreeHostImpl::SetExternalPinchGestureActive(bool active) {
DCHECK(input_delegate_ || !active);
if (input_delegate_)
GetInputHandler().set_external_pinch_gesture_active(active);
}
void LayerTreeHostImpl::CreatePendingTree() {
CHECK(!CommitsToActiveTree());
CHECK(!pending_tree_);
if (recycle_tree_) {
recycle_tree_.swap(pending_tree_);
} else {
pending_tree_ = std::make_unique<LayerTreeImpl>(
*this, CurrentBeginFrameArgs(), active_tree()->page_scale_factor(),
active_tree()->top_controls_shown_ratio(),
active_tree()->bottom_controls_shown_ratio(),
active_tree()->elastic_overscroll());
}
pending_tree_fully_painted_ = false;
client_->OnCanDrawStateChanged(CanDraw());
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
"cc", "PendingTree:waiting", TRACE_ID_LOCAL(pending_tree_.get()),
"active_lsid", active_tree()->local_surface_id_from_parent().ToString());
}
void LayerTreeHostImpl::PushScrollbarOpacitiesFromActiveToPending() {
if (!active_tree())
return;
for (auto& pair : scrollbar_animation_controllers_) {
for (auto* scrollbar : pair.second->Scrollbars()) {
if (const EffectNode* source_effect_node =
active_tree()
->property_trees()
->effect_tree()
.FindNodeFromElementId(scrollbar->element_id())) {
if (EffectNode* target_effect_node =
pending_tree()
->property_trees()
->effect_tree_mutable()
.FindNodeFromElementId(scrollbar->element_id())) {
DCHECK(target_effect_node);
float source_opacity = source_effect_node->opacity;
float target_opacity = target_effect_node->opacity;
if (source_opacity == target_opacity)
continue;
target_effect_node->opacity = source_opacity;
pending_tree()
->property_trees()
->effect_tree_mutable()
.set_needs_update(true);
}
}
}
}
}
void LayerTreeHostImpl::ActivateSyncTree() {
TRACE_EVENT(
"cc,benchmark", "LayerTreeHostImpl::ActivateSyncTree",
[&](perfetto::EventContext ctx) {
EmitMainFramePipelineStep(
ctx, sync_tree()->trace_id(),
perfetto::protos::pbzero::MainFramePipeline::Step::ACTIVATE);
});
if (pending_tree_) {
TRACE_EVENT_NESTABLE_ASYNC_END1(
"cc", "PendingTree:waiting", TRACE_ID_LOCAL(pending_tree_.get()),
"pending_lsid",
pending_tree_->local_surface_id_from_parent().ToString());
active_tree_->lifecycle().AdvanceTo(LayerTreeLifecycle::kBeginningSync);
// Process any requests in the UI resource queue. The request queue is
// given in LayerTreeHost::FinishCommit. This must take place before the
// swap.
pending_tree_->ProcessUIResourceRequestQueue();
if (pending_tree_->needs_full_tree_sync()) {
TreeSynchronizer::SynchronizeTrees(pending_tree_.get(),
active_tree_.get());
// If this tree uses a LayerContext for display, ensure the new layer list
// is pushed to Viz during the next update.
active_tree_->set_needs_full_tree_sync(true);
}
PushScrollbarOpacitiesFromActiveToPending();
pending_tree_->PushPropertyTreesTo(active_tree_.get());
active_tree_->lifecycle().AdvanceTo(
LayerTreeLifecycle::kSyncedPropertyTrees);
TreeSynchronizer::PushLayerProperties(pending_tree(), active_tree());
active_tree_->lifecycle().AdvanceTo(
LayerTreeLifecycle::kSyncedLayerProperties);
pending_tree_->PushPropertiesTo(active_tree_.get());
if (!pending_tree_->LayerListIsEmpty())
pending_tree_->property_trees()->ResetAllChangeTracking();
active_tree_->lifecycle().AdvanceTo(LayerTreeLifecycle::kNotSyncing);
// Now that we've synced everything from the pending tree to the active
// tree, rename the pending tree the recycle tree so we can reuse it on the
// next sync.
DCHECK(!recycle_tree_);
pending_tree_.swap(recycle_tree_);
// ScrollTimelines track a scroll source (i.e. a scroll node in the scroll
// tree), whose ElementId may change between the active and pending trees.
// Therefore we must inform all ScrollTimelines when the pending tree is
// promoted to active.
mutator_host_->PromoteScrollTimelinesPendingToActive();
// If we commit to the active tree directly, this is already done during
// commit.
ActivateAnimations();
// Update the state for images in ImageAnimationController and TileManager
// before dirtying tile priorities. Since these components cache tree
// specific state, these should be updated before DidModifyTilePriorities
// which can synchronously issue a PrepareTiles. Note that if we commit to
// the active tree directly, this is already done during commit.
ActivateStateForImages();
} else {
active_tree_->ProcessUIResourceRequestQueue();
}
active_tree_->UpdateViewportContainerSizes();
if (InnerViewportScrollNode()) {
active_tree_->property_trees()
->scroll_tree_mutable()
.ClampScrollToMaxScrollOffset(*InnerViewportScrollNode(),
active_tree_.get());
DCHECK(OuterViewportScrollNode());
active_tree_->property_trees()
->scroll_tree_mutable()
.ClampScrollToMaxScrollOffset(*OuterViewportScrollNode(),
active_tree_.get());
}
active_tree_->DidBecomeActive();
client_->RenewTreePriority();
// If we have any picture layers, then by activating we also modified tile
// priorities.
if (!active_tree_->picture_layers().empty())
DidModifyTilePriorities(/*pending_update_tiles=*/false);
auto screenshot_token = active_tree()->TakeScreenshotDestinationToken();
if (GetCurrentLocalSurfaceId().is_valid()) {
// Since the screenshot will be issued against the previous `viz::Surface`
// we need to make sure the renderer has at least embedded a valid surface
// previously.
screenshot_destination_ = std::move(screenshot_token);
} else if (!screenshot_token.is_empty()) {
LOG(ERROR)
<< "Cannot issue a copy because the previous surface is invalid.";
}
UpdateChildLocalSurfaceId();
client_->OnCanDrawStateChanged(CanDraw());
client_->DidActivateSyncTree();
if (!tree_activation_callback_.is_null())
tree_activation_callback_.Run();
std::unique_ptr<PendingPageScaleAnimation> pending_page_scale_animation =
active_tree_->TakePendingPageScaleAnimation();
if (pending_page_scale_animation) {
StartPageScaleAnimation(pending_page_scale_animation->target_offset,
pending_page_scale_animation->use_anchor,
pending_page_scale_animation->scale,
pending_page_scale_animation->duration);
}
if (input_delegate_)
input_delegate_->DidActivatePendingTree();
// Dump property trees and layers if VerboseLogEnabled().
VERBOSE_LOG() << "After activating sync tree, the active tree:"
<< "\nproperty_trees:\n"
<< active_tree_->property_trees()->ToString() << "\n"
<< "cc::LayerImpls:\n"
<< active_tree_->LayerListAsJson();
}
void LayerTreeHostImpl::ActivateStateForImages() {
if (settings_.trees_in_viz_in_viz_process) {
return;
}
image_animation_controller_.DidActivate();
tile_manager_.DidActivateSyncTree();
}
void LayerTreeHostImpl::OnMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel level) {
if (settings_.trees_in_viz_in_viz_process) {
return;
}
// Only work for low-end devices for now.
if (!base::SysInfo::IsLowEndDevice())
return;
if (!ImageDecodeCacheUtils::ShouldEvictCaches(level))
return;
// TODO(crbug.com/42050253): Unlocking decoded-image-tracker images causes
// flickering in visible trees if Out-Of-Process rasterization is enabled.
#if BUILDFLAG(IS_FUCHSIA)
if (use_gpu_rasterization() && visible())
return;
#endif // BUILDFLAG(IS_FUCHSIA)
ReleaseTileResources();
active_tree_->OnPurgeMemory();
if (pending_tree_)
pending_tree_->OnPurgeMemory();
if (recycle_tree_)
recycle_tree_->OnPurgeMemory();
EvictAllUIResources();
if (resource_pool_)
resource_pool_->OnMemoryPressure(level);
tile_manager_.decoded_image_tracker().UnlockAllImages();
// There is no need to notify the |image_decode_cache| about the memory
// pressure as it (the gpu one as the software one doesn't keep outstanding
// images pinned) listens to memory pressure events and purges memory base on
// the ImageDecodeCacheUtils::ShouldEvictCaches' return value.
}
void LayerTreeHostImpl::SetVisible(bool visible) {
DCHECK(task_runner_provider_->IsImplThread());
if (visible_ == visible)
return;
visible_ = visible;
if (layer_context_) {
layer_context_->SetVisible(visible);
}
if (!visible_) {
frame_sorter_.Reset(/*reset_fcp=*/false);
// When page is invisible, throw away corresponding EventsMetrics since
// these metrics will be incorrect due to duration of page being invisible.
active_tree()->TakeEventsMetrics();
active_tree()->TakeRasterEventsMetrics();
events_metrics_manager_.TakeSavedEventsMetrics();
if (pending_tree()) {
pending_tree()->TakeEventsMetrics();
pending_tree()->TakeRasterEventsMetrics();
}
}
// Notify reporting controller of transition between visible and invisible
compositor_frame_reporting_controller_->SetVisible(visible_);
DidVisibilityChange(this, visible_);
if (!settings_.trees_in_viz_in_viz_process) {
UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
}
// If we just became visible, we have to ensure that we draw high res tiles,
// to prevent checkerboard/low res flashes.
if (visible_) {
// TODO(crbug.com/40410467): Replace with RequiresHighResToDraw.
SetRequiresHighResToDraw();
// Prior CompositorFrame may have been discarded and thus we need to ensure
// that we submit a new one, even if there are no tiles. Therefore, force a
// full viewport redraw. However, this is unnecessary when we become visible
// for the first time (before the first commit) as there is no prior
// CompositorFrame to replace. We can safely use |!active_tree_->
// LayerListIsEmpty()| as a proxy for this, because we wouldn't be able to
// draw anything even if this is not the first time we become visible.
if (!active_tree_->LayerListIsEmpty()) {
SetFullViewportDamage();
SetNeedsRedraw();
}
} else if (!settings_.trees_in_viz_in_viz_process) {
EvictAllUIResources();
// Call PrepareTiles to evict tiles when we become invisible.
PrepareTiles();
tile_manager_.decoded_image_tracker().UnlockAllImages();
}
active_tree_->SetVisible(visible);
resource_provider_->SetVisible(visible);
}
void LayerTreeHostImpl::SetNeedsOneBeginImplFrame() {
NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
client_->SetNeedsOneBeginImplFrameOnImplThread();
}
void LayerTreeHostImpl::SetNeedsRedraw(bool animation_only) {
NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
if (settings_.TreesInVizInClientProcess()) {
if (!animation_only || !use_layer_context_for_animations_) {
client_->SetNeedsRedrawOnImplThread();
}
} else {
client_->SetNeedsRedrawOnImplThread();
}
}
ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
ManagedMemoryPolicy actual = cached_managed_memory_policy_;
// The following may lower the cutoff, but should never raise it.
if (debug_state_.rasterize_only_visible_content) {
actual.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
} else if (use_gpu_rasterization() &&
actual.priority_cutoff_when_visible ==
gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING) {
actual.priority_cutoff_when_visible =
gpu::MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
}
return actual;
}
void LayerTreeHostImpl::ReleaseTreeResources() {
active_tree_->ReleaseResources();
if (pending_tree_)
pending_tree_->ReleaseResources();
if (recycle_tree_)
recycle_tree_->ReleaseResources();
EvictAllUIResources();
}
void LayerTreeHostImpl::ReleaseTileResources() {
if (settings_.trees_in_viz_in_viz_process) {
return;
}
active_tree_->ReleaseTileResources();
if (pending_tree_)
pending_tree_->ReleaseTileResources();
if (recycle_tree_)
recycle_tree_->ReleaseTileResources();
// Need to update tiles again in order to kick of raster work for all the
// tiles that are dropped here.
active_tree_->set_needs_update_draw_properties();
}
void LayerTreeHostImpl::RecreateTileResources() {
if (settings_.trees_in_viz_in_viz_process) {
return;
}
active_tree_->RecreateTileResources();
if (pending_tree_) {
pending_tree_->RecreateTileResources();
}
if (recycle_tree_) {
recycle_tree_->RecreateTileResources();
}
}
void LayerTreeHostImpl::CreateTileManagerResources() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
image_decode_cache_holder_ = std::make_unique<ImageDecodeCacheHolder>(
raster_caps(), layer_tree_frame_sink_->worker_context_provider(),
settings_.decoded_image_working_set_budget_bytes, dark_mode_filter_);
if (raster_caps().use_gpu_rasterization) {
pending_raster_queries_ = std::make_unique<RasterQueryQueue>(
layer_tree_frame_sink_->worker_context_provider());
}
raster_buffer_provider_ = CreateRasterBufferProvider();
// Pass the single-threaded synchronous task graph runner to the worker pool
// if we're in synchronous single-threaded mode.
TaskGraphRunner* task_graph_runner = task_graph_runner_;
if (is_synchronous_single_threaded_) {
DCHECK(!single_thread_synchronous_task_graph_runner_);
single_thread_synchronous_task_graph_runner_ =
std::make_unique<SynchronousTaskGraphRunner>();
task_graph_runner = single_thread_synchronous_task_graph_runner_.get();
}
tile_manager_.SetResources(resource_pool_.get(), GetImageDecodeCache(),
task_graph_runner, raster_buffer_provider_.get(),
raster_caps().use_gpu_rasterization,
pending_raster_queries_.get());
tile_manager_.SetCheckerImagingForceDisabled(
settings_.only_checker_images_with_gpu_raster &&
!raster_caps().use_gpu_rasterization);
UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
}
std::unique_ptr<RasterBufferProvider>
LayerTreeHostImpl::CreateRasterBufferProvider() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
DCHECK(GetTaskRunner());
viz::RasterContextProvider* compositor_context_provider =
layer_tree_frame_sink_->context_provider();
if (!compositor_context_provider) {
return std::make_unique<ZeroCopyRasterBufferProvider>(
layer_tree_frame_sink_->shared_image_interface(),
/*is_software=*/true);
}
const gpu::Capabilities& caps =
compositor_context_provider->ContextCapabilities();
viz::RasterContextProvider* worker_context_provider =
layer_tree_frame_sink_->worker_context_provider();
if (raster_caps().use_gpu_rasterization) {
DCHECK(worker_context_provider);
return std::make_unique<GpuRasterBufferProvider>(
worker_context_provider->SharedImageInterface(),
compositor_context_provider, worker_context_provider,
raster_caps_.tile_overlay_candidate, settings_.max_gpu_raster_tile_size,
pending_raster_queries_.get());
}
bool use_zero_copy = settings_.use_zero_copy;
// TODO(reveman): Remove this when mojo supports worker contexts.
// crbug.com/522440
if (!use_zero_copy && !worker_context_provider) {
LOG(ERROR)
<< "Forcing zero-copy tile initialization as worker context is missing";
use_zero_copy = true;
}
if (use_zero_copy) {
return std::make_unique<ZeroCopyRasterBufferProvider>(
compositor_context_provider->SharedImageInterface(),
/*is_software=*/false);
}
const int max_copy_texture_chromium_size =
caps.max_copy_texture_chromium_size;
return std::make_unique<OneCopyRasterBufferProvider>(
worker_context_provider->SharedImageInterface(), GetTaskRunner(),
compositor_context_provider, worker_context_provider,
max_copy_texture_chromium_size, settings_.use_partial_raster,
settings_.max_staging_buffer_usage_in_bytes,
raster_caps_.tile_overlay_candidate);
}
void LayerTreeHostImpl::SetLayerTreeMutator(
std::unique_ptr<LayerTreeMutator> mutator) {
mutator_host_->SetLayerTreeMutator(std::move(mutator));
}
void LayerTreeHostImpl::SetPaintWorkletLayerPainter(
std::unique_ptr<PaintWorkletLayerPainter> painter) {
paint_worklet_painter_ = std::move(painter);
}
void LayerTreeHostImpl::QueueImageDecode(int request_id,
const DrawImage& image,
bool speculative) {
DCHECK(!settings_.trees_in_viz_in_viz_process);
const PaintImage& paint_image = image.paint_image();
TRACE_EVENT1(
TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::QueueImageDecode", "frame_key",
paint_image.GetKeyForFrame(PaintImage::kDefaultFrameIndex).ToString());
// Optimistically specify the current raster color space, since we assume that
// it won't change.
DrawImage image_copy(
image, /*scale_adjustment=*/1.0,
/*frame_index=*/PaintImage::kDefaultFrameIndex,
GetTargetColorParams(paint_image.GetContentColorUsage()));
tile_manager_.decoded_image_tracker().QueueImageDecode(
image_copy,
base::BindOnce(&LayerTreeHostImpl::ImageDecodeFinished,
weak_factory_.GetWeakPtr(), request_id, speculative),
speculative);
tile_manager_.checker_image_tracker().DisallowCheckeringForImage(paint_image);
}
void LayerTreeHostImpl::ImageDecodeFinished(int request_id,
bool speculative,
bool decode_succeeded) {
DCHECK(!settings_.trees_in_viz_in_viz_process);
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::ImageDecodeFinished");
if (!base::FeatureList::IsEnabled(
features::kSendExplicitDecodeRequestsImmediately)) {
completed_image_decode_requests_.emplace_back(request_id, decode_succeeded);
}
client_->NotifyImageDecodeRequestFinished(request_id, speculative,
decode_succeeded);
}
std::vector<std::pair<int, bool>>
LayerTreeHostImpl::TakeCompletedImageDecodeRequests() {
auto result = std::move(completed_image_decode_requests_);
completed_image_decode_requests_.clear();
return result;
}
std::unique_ptr<MutatorEvents> LayerTreeHostImpl::TakeMutatorEvents() {
std::unique_ptr<MutatorEvents> events = mutator_host_->CreateEvents();
std::swap(events, mutator_events_);
mutator_host_->TakeTimeUpdatedEvents(events.get());
return events;
}
UIResourceChangeMap LayerTreeHostImpl::TakeUIResourceChanges(
bool require_full_sync) {
if (require_full_sync) {
ui_resource_changes_.clear();
if (settings_.TreesInVizInClientProcess()) {
// Mark all ui resources as created in this change set.
for (auto& pair : ui_resource_map_) {
UIResourceId uid = pair.first;
auto [change_it, success] =
ui_resource_changes_.try_emplace(uid, UIResourceChange());
change_it->second.resource_created = true;
}
}
}
return std::move(ui_resource_changes_);
}
void LayerTreeHostImpl::ClearHistory() {
client_->ClearHistory();
}
size_t LayerTreeHostImpl::CommitDurationSampleCountForTesting() const {
return client_->CommitDurationSampleCountForTesting(); // IN-TEST
}
void LayerTreeHostImpl::ClearCaches() {
// It is safe to clear the decode policy tracking on navigations since it
// comes with an invalidation and the image ids are never reused.
bool can_clear_decode_policy_tracking = true;
tile_manager_.ClearCheckerImageTracking(can_clear_decode_policy_tracking);
if (GetImageDecodeCache())
GetImageDecodeCache()->ClearCache();
image_animation_controller_.set_did_navigate();
}
void LayerTreeHostImpl::DidChangeScrollbarVisibility() {
// Need a commit since input handling for scrollbars is handled in Blink so
// we need to communicate to Blink when the compositor shows/hides the
// scrollbars.
client_->SetNeedsCommitOnImplThread();
}
void LayerTreeHostImpl::CleanUpTileManagerResources() {
DCHECK(!settings_.trees_in_viz_in_viz_process);
tile_manager_.FinishTasksAndCleanUp();
single_thread_synchronous_task_graph_runner_ = nullptr;
image_decode_cache_holder_ = nullptr;
raster_buffer_provider_ = nullptr;
pending_raster_queries_ = nullptr;
// Any resources that were allocated previously should be considered not good
// for reuse, as the RasterBufferProvider will be replaced and it may choose
// to allocate future resources differently.
resource_pool_->InvalidateResources();
// We've potentially just freed a large number of resources on our various
// contexts. Flushing now helps ensure these are cleaned up quickly
// preventing driver cache growth. See crbug.com/643251
if (layer_tree_frame_sink_) {
if (auto* worker_context =
layer_tree_frame_sink_->worker_context_provider()) {
viz::RasterContextProvider::ScopedRasterContextLock hold(worker_context);
hold.RasterInterface()->OrderingBarrierCHROMIUM();
}
// There can sometimes be a compositor context with no worker context so use
// it to flush. cc doesn't use the compositor context to issue GPU work so
// it doesn't require an ordering barrier.
if (auto* compositor_context = layer_tree_frame_sink_->context_provider()) {
compositor_context->ContextSupport()->FlushPendingWork();
}
}
}
void LayerTreeHostImpl::ReleaseLayerTreeFrameSink() {
TRACE_EVENT0("cc", "LayerTreeHostImpl::ReleaseLayerTreeFrameSink");
if (!layer_tree_frame_sink_) {
DCHECK(!has_valid_layer_tree_frame_sink_);
return;
}
has_valid_layer_tree_frame_sink_ = false;
ReleaseTreeResources();
if (!settings_.trees_in_viz_in_viz_process) {
CleanUpTileManagerResources();
resource_pool_ = nullptr;
ClearUIResources();
}
bool should_finish = true;
#if BUILDFLAG(IS_WIN)
// Windows does not have stability issues that require calling Finish.
// To minimize risk, only avoid waiting for the UI layer tree.
should_finish = !settings_.is_layer_tree_for_ui;
#endif
if (should_finish && layer_tree_frame_sink_->context_provider()) {
// TODO(kylechar): Exactly where this finish call is still required is not
// obvious. Attempts have been made to remove it which caused problems, eg.
// https://crbug.com/846709. We should test removing it via finch to find
// out if this is still needed on any platforms.
layer_tree_frame_sink_->context_provider()->RasterInterface()->Finish();
}
// Release any context visibility before we destroy the LayerTreeFrameSink.
SetContextVisibility(false);
// Destroy the submit-frame trackers before destroying the frame sink.
frame_trackers_.ClearAll();
// Detach from the old LayerTreeFrameSink and reset |layer_tree_frame_sink_|
// pointer as this surface is going to be destroyed independent of if binding
// the new LayerTreeFrameSink succeeds or not.
layer_tree_frame_sink_->DetachFromClient();
layer_tree_frame_sink_ = nullptr;
layer_context_.reset();
// If gpu compositing, then any resources created with the gpu context in the
// LayerTreeFrameSink were exported to the display compositor may be modified
// by it, and thus we would be unable to determine what state they are in, in
// order to reuse them, so they must be lost. Note that this includes
// resources created using the gpu context associated with
// |layer_tree_frame_sink_| internally by the compositor and any resources
// received from an external source (for instance, TextureLayers). This is
// because the API contract for releasing these external resources requires
// that the compositor return them with a valid sync token and no
// modifications to their GL state. Since that can not be guaranteed, these
// must also be marked lost.
//
// In software compositing, the resources are not modified by the display
// compositor (there is no stateful metadata for shared memory), so we do not
// need to consider them lost.
//
// In both cases, the resources that are exported to the display compositor
// will have no means of being returned to this client without the
// LayerTreeFrameSink, so they should no longer be considered as exported. Do
// this *after* any interactions with the |layer_tree_frame_sink_| in case it
// tries to return resources during destruction.
//
// The assumption being made here is that the display compositor WILL NOT use
// any resources previously exported when the CompositorFrameSink is closed.
// This should be true as the connection is closed when the display compositor
// shuts down/crashes, or when it believes we are a malicious client in which
// case it will not display content from the previous CompositorFrameSink. If
// this assumption is violated, we may modify resources no longer considered
// as exported while the display compositor is still making use of them,
// leading to visual mistakes.
resource_provider_->ReleaseAllExportedResources(/*lose=*/true);
// We don't know if the next LayerTreeFrameSink will support GPU
// rasterization. Make sure to clear the flag so that we force a
// re-computation.
raster_caps_.use_gpu_rasterization = false;
}
bool LayerTreeHostImpl::InitializeFrameSink(
LayerTreeFrameSink* layer_tree_frame_sink) {
TRACE_EVENT0("cc", "LayerTreeHostImpl::InitializeFrameSink");
ReleaseLayerTreeFrameSink();
if (!layer_tree_frame_sink->BindToClient(this)) {
// Avoid recreating tree resources because we might not have enough
// information to do this yet (eg. we don't have a TileManager at this
// point).
return false;
}
layer_tree_frame_sink_ = layer_tree_frame_sink;
has_valid_layer_tree_frame_sink_ = true;
if (settings_.TreesInVizInClientProcess()) {
layer_context_ = layer_tree_frame_sink_->CreateLayerContext(*this);
}
UpdateRasterCapabilities();
// See note in LayerTreeImpl::UpdateDrawProperties, new LayerTreeFrameSink
// means a new max texture size which affects draw properties. Also, if the
// draw properties were up to date, layers still lost resources and we need to
// UpdateDrawProperties() after calling RecreateTreeResources().
active_tree_->set_needs_update_draw_properties();
if (pending_tree_)
pending_tree_->set_needs_update_draw_properties();
if (!settings_.trees_in_viz_in_viz_process) {
resource_pool_ = std::make_unique<ResourcePool>(
resource_provider_.get(), layer_tree_frame_sink_->context_provider(),
GetTaskRunner(), ResourcePool::kDefaultExpirationDelay,
settings_.disallow_non_exact_resource_reuse);
CreateTileManagerResources();
RecreateTileResources();
}
client_->OnCanDrawStateChanged(CanDraw());
SetFullViewportDamage();
// There will not be anything to draw here, so set high res
// to avoid checkerboards, typically when we are recovering
// from lost context.
// TODO(crbug.com/40410467): Replace with RequiresHighResToDraw.
SetRequiresHighResToDraw();
// Always allocate a new viz::LocalSurfaceId when we get a new
// LayerTreeFrameSink to ensure that we do not reuse the same surface after
// it might have been garbage collected.
const viz::LocalSurfaceId& local_surface_id = GetCurrentLocalSurfaceId();
if (local_surface_id.is_valid())
AllocateLocalSurfaceId();
return true;
}
void LayerTreeHostImpl::SetBeginFrameSource(viz::BeginFrameSource* source) {
client_->SetBeginFrameSource(source);
}
const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
return external_transform_;
}
void LayerTreeHostImpl::DidChangeBrowserControlsPosition() {
active_tree_->UpdateViewportContainerSizes();
if (pending_tree_)
pending_tree_->UpdateViewportContainerSizes();
SetNeedsRedraw();
SetNeedsOneBeginImplFrame();
SetFullViewportDamage();
}
void LayerTreeHostImpl::DidObserveScrollDelay(
int source_frame_number,
base::TimeDelta scroll_delay,
base::TimeTicks scroll_timestamp) {
// Record First Scroll Delay.
if (!has_observed_first_scroll_delay_) {
client_->DidObserveFirstScrollDelay(source_frame_number, scroll_delay,
scroll_timestamp);
has_observed_first_scroll_delay_ = true;
}
}
float LayerTreeHostImpl::TopControlsHeight() const {
return active_tree_->top_controls_height();
}
float LayerTreeHostImpl::TopControlsMinHeight() const {
return active_tree_->top_controls_min_height();
}
float LayerTreeHostImpl::BottomControlsHeight() const {
return active_tree_->bottom_controls_height();
}
float LayerTreeHostImpl::BottomControlsMinHeight() const {
return active_tree_->bottom_controls_min_height();
}
void LayerTreeHostImpl::SetCurrentBrowserControlsShownRatio(
float top_ratio,
float bottom_ratio) {
if (active_tree_->SetCurrentBrowserControlsShownRatio(top_ratio,
bottom_ratio))
DidChangeBrowserControlsPosition();
}
float LayerTreeHostImpl::CurrentTopControlsShownRatio() const {
return active_tree_->CurrentTopControlsShownRatio();
}
float LayerTreeHostImpl::CurrentBottomControlsShownRatio() const {
return active_tree_->CurrentBottomControlsShownRatio();
}
gfx::PointF LayerTreeHostImpl::ViewportScrollOffset() const {
return viewport_->TotalScrollOffset();
}
void LayerTreeHostImpl::AutoScrollAnimationCreate(
const ScrollNode& scroll_node,
const gfx::PointF& target_offset,
float autoscroll_velocity) {
// Start the animation one full frame in. Without any offset, the animation
// doesn't start until next frame, increasing latency, and preventing our
// input latency tracking architecture from working.
base::TimeDelta animation_start_offset = CurrentBeginFrameArgs().interval;
const ScrollTree& scroll_tree = active_tree_->property_trees()->scroll_tree();
gfx::PointF current_offset =
scroll_tree.current_scroll_offset(scroll_node.element_id);
mutator_host_->ImplOnlyAutoScrollAnimationCreate(
scroll_node.element_id, target_offset, current_offset,
autoscroll_velocity, animation_start_offset);
SetNeedsOneBeginImplFrame();
}
bool LayerTreeHostImpl::ScrollAnimationCreate(const ScrollNode& scroll_node,
const gfx::Vector2dF& delta,
base::TimeDelta delayed_by) {
ScrollTree& scroll_tree =
active_tree_->property_trees()->scroll_tree_mutable();
const float kEpsilon = 0.1f;
bool scroll_animated =
std::abs(delta.x()) > kEpsilon || std::abs(delta.y()) > kEpsilon;
if (!scroll_animated) {
scroll_tree.ScrollBy(scroll_node, delta, active_tree());
TRACE_EVENT_INSTANT0("cc", "no scroll animation due to small delta",
TRACE_EVENT_SCOPE_THREAD);
return false;
}
gfx::PointF current_offset =
scroll_tree.current_scroll_offset(scroll_node.element_id);
gfx::PointF target_offset = scroll_tree.ClampScrollOffsetToLimits(
current_offset + delta, scroll_node);
// Start the animation one full frame in. Without any offset, the animation
// doesn't start until next frame, increasing latency, and preventing our
// input latency tracking architecture from working.
base::TimeDelta animation_start_offset = CurrentBeginFrameArgs().interval;
mutator_host_->ImplOnlyScrollAnimationCreate(
scroll_node.element_id, target_offset, current_offset, delayed_by,
animation_start_offset);
SetNeedsOneBeginImplFrame();
return true;
}
void LayerTreeHostImpl::UpdateImageDecodingHints(
base::flat_map<PaintImage::Id, PaintImage::DecodingMode>
decoding_mode_map) {
tile_manager_.checker_image_tracker().UpdateImageDecodingHints(
std::move(decoding_mode_map));
}
void LayerTreeHostImpl::RenewTreePriorityForTesting() {
client_->RenewTreePriority();
}
void LayerTreeHostImpl::SetRenderFrameObserver(
std::unique_ptr<RenderFrameMetadataObserver> observer) {
render_frame_metadata_observer_ = std::move(observer);
if (render_frame_metadata_observer_) {
render_frame_metadata_observer_->BindToCurrentSequence();
}
}
void LayerTreeHostImpl::WillScrollContent(ElementId element_id) {
// Flash the overlay scrollbar even if the scroll delta is 0.
if (settings().scrollbar_flash_after_any_scroll_update) {
FlashAllScrollbars(false);
} else {
if (ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id))
animation_controller->WillUpdateScroll();
}
// Whenever we are scrolling, we want to save the metrics. It is possible for
// the event to result in a 0 delta change. However we want to associate it
// with the subsequent frame. Otherwise this event will be attributed to jank.
//
// If there are on going animations, we may still submit a frame.
events_metrics_manager_.SaveActiveEventMetrics();
}
void LayerTreeHostImpl::DidScrollContent(ElementId element_id,
bool animated,
const gfx::Vector2dF& scroll_delta) {
scroll_accumulated_this_frame_ += scroll_delta;
frame_max_scroll_delta_ =
std::max(std::abs(scroll_delta.x()), std::abs(scroll_delta.y()));
if (settings().scrollbar_flash_after_any_scroll_update) {
FlashAllScrollbars(true);
} else {
if (ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id))
animation_controller->DidScrollUpdate();
}
// We may wish to prioritize smoothness over raster when the user is
// interacting with content, but this needs to be evaluated only for direct
// user scrolls, not for programmatic scrolls.
if (input_delegate_->IsCurrentlyScrolling()) {
if (!settings().single_thread_proxy_scheduler) {
client_->SetWaitingForScrollEvent(false);
}
client_->RenewTreePriority();
}
if (!animated) {
// SetNeedsRedraw is only called in non-animated cases since an animation
// won't actually update any scroll offsets until a frame produces a
// tick. Scheduling a redraw here before ticking means the draw gets
// aborted due to no damage and the swap promises broken so a LatencyInfo
// won't be recorded.
SetNeedsRedraw();
}
}
float LayerTreeHostImpl::DeviceScaleFactor() const {
return active_tree_->device_scale_factor();
}
float LayerTreeHostImpl::PageScaleFactor() const {
return active_tree_->page_scale_factor_for_scroll();
}
void LayerTreeHostImpl::BindToInputHandler(
std::unique_ptr<InputDelegateForCompositor> delegate) {
input_delegate_ = std::move(delegate);
input_delegate_->SetPrefersReducedMotion(prefers_reduced_motion_);
}
void LayerTreeHostImpl::DetachInputDelegateAndRenderFrameObserver() {
if (input_delegate_) {
input_delegate_->WillShutdown();
}
input_delegate_ = nullptr;
SetRenderFrameObserver(nullptr);
}
void LayerTreeHostImpl::SetVisualDeviceViewportSize(
const gfx::Size& visual_device_viewport_size) {
visual_device_viewport_size_ = visual_device_viewport_size;
}
gfx::Size LayerTreeHostImpl::VisualDeviceViewportSize() const {
return visual_device_viewport_size_;
}
void LayerTreeHostImpl::SetPrefersReducedMotion(bool prefers_reduced_motion) {
if (prefers_reduced_motion_ == prefers_reduced_motion)
return;
prefers_reduced_motion_ = prefers_reduced_motion;
if (input_delegate_)
input_delegate_->SetPrefersReducedMotion(prefers_reduced_motion_);
}
void LayerTreeHostImpl::SetMayThrottleIfUndrawnFrames(
bool may_throttle_if_undrawn_frames) {
may_throttle_if_undrawn_frames_ = may_throttle_if_undrawn_frames;
}
ScrollTree& LayerTreeHostImpl::GetScrollTree() const {
return active_tree_->property_trees()->scroll_tree_mutable();
}
void LayerTreeHostImpl::ScrollAnimationAbort(ElementId element_id) const {
return mutator_host_->ScrollAnimationAbort(element_id);
}
float LayerTreeHostImpl::GetBrowserControlsTopOffset() const {
return browser_controls_offset_manager_->ControlsTopOffset();
}
void LayerTreeHostImpl::ScrollBegin() const {
return browser_controls_offset_manager_->ScrollBegin();
}
void LayerTreeHostImpl::ScrollEnd() const {
return browser_controls_offset_manager_->ScrollEnd();
}
void LayerTreeHostImpl::StartScrollSequence(
FrameSequenceTrackerType type,
FrameInfo::SmoothEffectDrivingThread scrolling_thread) {
frame_trackers_.StartScrollSequence(type, scrolling_thread);
}
void LayerTreeHostImpl::StopSequence(FrameSequenceTrackerType type) {
return frame_trackers_.StopSequence(type);
}
void LayerTreeHostImpl::PinchBegin() const {
return browser_controls_offset_manager_->PinchBegin();
}
void LayerTreeHostImpl::PinchEnd() const {
return browser_controls_offset_manager_->PinchEnd();
}
void LayerTreeHostImpl::ScrollbarAnimationMouseLeave(
ElementId element_id) const {
ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id);
if (animation_controller) {
animation_controller->DidMouseLeave();
}
}
void LayerTreeHostImpl::ScrollbarAnimationMouseMove(
ElementId element_id,
gfx::PointF device_viewport_point) const {
ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id);
if (animation_controller) {
animation_controller->DidMouseMove(device_viewport_point);
}
}
bool LayerTreeHostImpl::ScrollbarAnimationMouseDown(
ElementId element_id) const {
ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id);
if (animation_controller) {
animation_controller->DidMouseDown();
return true;
}
return false;
}
bool LayerTreeHostImpl::ScrollbarAnimationMouseUp(ElementId element_id) const {
ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id);
if (animation_controller) {
animation_controller->DidMouseUp();
return true;
}
return false;
}
void LayerTreeHostImpl::TickScrollAnimations() const {
return mutator_host_->TickScrollAnimations(CurrentBeginFrameArgs().frame_time,
GetScrollTree());
}
double LayerTreeHostImpl::PredictViewportBoundsDelta(
double current_bounds_delta,
gfx::Vector2dF scroll_distance) const {
return browser_controls_offset_manager_->PredictViewportBoundsDelta(
current_bounds_delta, scroll_distance);
}
bool LayerTreeHostImpl::ElementHasImplOnlyScrollAnimation(
ElementId element_id) const {
return mutator_host_->ElementHasImplOnlyScrollAnimation(element_id);
}
std::optional<gfx::PointF>
LayerTreeHostImpl::UpdateImplAnimationScrollTargetWithDelta(
gfx::Vector2dF adjusted_delta,
int scroll_node_id,
base::TimeDelta delayed_by,
ElementId element_id) const {
return mutator_host_->ImplOnlyScrollAnimationUpdateTarget(
adjusted_delta, GetScrollTree().MaxScrollOffset(scroll_node_id),
CurrentBeginFrameArgs().frame_time, delayed_by, element_id);
}
bool LayerTreeHostImpl::HasAnimatedScrollbars() const {
return !scrollbar_animation_controllers_.empty();
}
void LayerTreeHostImpl::UpdateChildLocalSurfaceId() {
if (!active_tree()->local_surface_id_from_parent().is_valid()) {
return;
}
child_local_surface_id_allocator_.UpdateFromParent(
active_tree()->local_surface_id_from_parent());
if (active_tree()->TakeNewLocalSurfaceIdRequest()) {
AllocateLocalSurfaceId();
}
// We have a newer surface than the evicted one, or the embedding has
// changed, clear eviction state resume drawing.
if (evicted_local_surface_id_.is_valid() &&
GetCurrentLocalSurfaceId().IsNewerThanOrEmbeddingChanged(
evicted_local_surface_id_)) {
evicted_local_surface_id_ = viz::LocalSurfaceId();
if (resource_provider_) {
resource_provider_->SetEvicted(false);
}
}
}
void LayerTreeHostImpl::ReturnResource(
viz::ReturnedResource returned_resource) {
client_->ReturnResource(std::move(returned_resource));
}
void LayerTreeHostImpl::NotifyNewLocalSurfaceIdExpectedWhilePaused() {
if (new_local_surface_id_expected_) {
return;
}
new_local_surface_id_expected_ = true;
if (layer_tree_frame_sink_) {
layer_tree_frame_sink_->NotifyNewLocalSurfaceIdExpectedWhilePaused();
}
}
void LayerTreeHostImpl::CollectScrollbarUpdatesForCommit(
CompositorCommitData* commit_data) const {
commit_data->scrollbars.reserve(scrollbar_animation_controllers_.size());
for (auto& pair : scrollbar_animation_controllers_) {
if (pair.second->visibility_changed()) {
commit_data->scrollbars.push_back(
{pair.first, pair.second->ScrollbarsHidden()});
pair.second->ClearVisibilityChanged();
}
}
}
std::unique_ptr<CompositorCommitData>
LayerTreeHostImpl::ProcessCompositorDeltas(
const MutatorHost* main_thread_mutator_host) {
auto commit_data = std::make_unique<CompositorCommitData>();
if (input_delegate_) {
input_delegate_->ProcessCommitDeltas(commit_data.get(),
main_thread_mutator_host);
}
CollectScrollbarUpdatesForCommit(commit_data.get());
commit_data->page_scale_delta =
active_tree_->page_scale_factor()->PullDeltaForMainThread(
main_thread_mutator_host);
commit_data->is_pinch_gesture_active = active_tree_->PinchGestureActive();
commit_data->is_scroll_active =
input_delegate_ && GetInputHandler().IsCurrentlyScrolling();
// We should never process non-unit page_scale_delta for an OOPIF subframe.
// TODO(wjmaclean): Remove this DCHECK as a pre-condition to closing the bug.
// https://crbug.com/845097
DCHECK(settings().is_for_scalable_page ||
commit_data->page_scale_delta == 1.f);
commit_data->top_controls_delta =
active_tree()->top_controls_shown_ratio()->PullDeltaForMainThread(
main_thread_mutator_host);
commit_data->bottom_controls_delta =
active_tree()->bottom_controls_shown_ratio()->PullDeltaForMainThread(
main_thread_mutator_host);
commit_data->elastic_overscroll_delta =
active_tree_->elastic_overscroll()->PullDeltaForMainThread(
main_thread_mutator_host);
commit_data->swap_promises.swap(swap_promises_for_main_thread_scroll_update_);
commit_data->ongoing_scroll_animation =
mutator_host_->HasImplOnlyScrollAnimatingElement();
commit_data->is_auto_scrolling =
mutator_host_->HasImplOnlyAutoScrollAnimatingElement();
if (browser_controls_manager()) {
commit_data->browser_controls_constraint =
browser_controls_manager()->PullConstraintForMainThread(
&commit_data->browser_controls_constraint_changed);
}
return commit_data;
}
void LayerTreeHostImpl::SetFullViewportDamage() {
// In non-Android-WebView cases, we expect GetDeviceViewport() to be the same
// as internal_device_viewport(), so the full-viewport damage rect is just
// the internal viewport rect. In the case of Android WebView,
// GetDeviceViewport returns the external viewport, but we still want to use
// the internal viewport's origin for setting the damage.
// See https://chromium-review.googlesource.com/c/chromium/src/+/1257555.
SetViewportDamage(gfx::Rect(active_tree_->internal_device_viewport().origin(),
active_tree_->GetDeviceViewport().size()));
}
bool LayerTreeHostImpl::AnimatePageScale(base::TimeTicks monotonic_time) {
if (!page_scale_animation_)
return false;
gfx::PointF scroll_total = active_tree_->TotalScrollOffset();
if (!page_scale_animation_->IsAnimationStarted())
page_scale_animation_->StartAnimation(monotonic_time);
active_tree_->SetPageScaleOnActiveTree(
page_scale_animation_->PageScaleFactorAtTime(monotonic_time));
gfx::PointF next_scroll =
page_scale_animation_->ScrollOffsetAtTime(monotonic_time);
viewport().ScrollByInnerFirst(next_scroll - scroll_total);
if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
page_scale_animation_ = nullptr;
client_->SetNeedsCommitOnImplThread();
client_->RenewTreePriority();
client_->DidCompletePageScaleAnimationOnImplThread();
} else {
SetNeedsOneBeginImplFrame();
}
return true;
}
bool LayerTreeHostImpl::AnimateBrowserControls(base::TimeTicks time) {
if (!browser_controls_offset_manager_->HasAnimation())
return false;
gfx::Vector2dF scroll_delta = browser_controls_offset_manager_->Animate(time);
if (browser_controls_offset_manager_->HasAnimation())
SetNeedsOneBeginImplFrame();
if (active_tree_->TotalScrollOffset().y() == 0.f ||
OnlyExpandTopControlsAtPageTop()) {
return false;
}
if (scroll_delta.IsZero())
return false;
// This counter-scrolls the page to keep the appearance of the page content
// being fixed while the browser controls animate.
viewport().ScrollBy(scroll_delta,
/*viewport_point=*/gfx::Point(),
/*is_direct_manipulation=*/false,
/*affect_browser_controls=*/false,
/*scroll_outer_viewport=*/true);
// If the viewport has scroll snap styling, we may need to snap after
// scrolling it. Browser controls animations may happen after scrollend, so
// it is too late for InputHandler to do the snapping.
viewport().SnapIfNeeded();
client_->SetNeedsCommitOnImplThread();
client_->RenewTreePriority();
return true;
}
bool LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks monotonic_time) {
bool animated = false;
for (auto& pair : scrollbar_animation_controllers_) {
animated |= pair.second->Animate(monotonic_time);
}
return animated;
}
bool LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time,
bool is_active_tree) {
const ScrollTree& scroll_tree =
is_active_tree ? active_tree_->property_trees()->scroll_tree()
: pending_tree_->property_trees()->scroll_tree();
const bool animated = mutator_host_->TickAnimations(
monotonic_time, scroll_tree, is_active_tree);
// TODO(crbug.com/40443202): Only do this if the animations are on the active
// tree, or if they are on the pending tree waiting for some future time to
// start.
// TODO(crbug.com/40443205): We currently have a single signal from the
// animation_host, so on the last frame of an animation we will
// still request an extra SetNeedsAnimate here.
if (animated) {
// TODO(crbug.com/40667010): If only scroll animations present, schedule a
// frame only if scroll changes.
SetNeedsOneBeginImplFrame();
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kCompositorAnimation);
if (mutator_host_->HasInvalidationAnimation()) {
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kCompositorRasterAnimation);
} else {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kCompositorRasterAnimation);
}
if (mutator_host_->HasNativePropertyAnimation()) {
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kCompositorNativeAnimation);
} else {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kCompositorNativeAnimation);
}
} else {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kCompositorAnimation);
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kCompositorRasterAnimation);
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kCompositorNativeAnimation);
}
if (animated && mutator_host_->HasViewTransition()) {
frame_trackers_.StartSequence(
FrameSequenceTrackerType::kSETCompositorAnimation);
} else {
frame_trackers_.StopSequence(
FrameSequenceTrackerType::kSETCompositorAnimation);
}
// TODO(crbug.com/40443205): We could return true only if the animations are
// on the active tree. There's no need to cause a draw to take place from
// animations starting/ticking on the pending tree.
return animated;
}
void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
const bool has_active_animations = mutator_host_->UpdateAnimationState(
start_ready_animations, mutator_events_.get());
if (has_active_animations) {
SetNeedsOneBeginImplFrame();
if (!mutator_events_->IsEmpty())
SetNeedsCommit();
}
}
void LayerTreeHostImpl::ActivateAnimations() {
const bool activated =
mutator_host_->ActivateAnimations(mutator_events_.get());
if (activated) {
// Activating an animation changes layer draw properties, such as
// screen_space_transform_is_animating. So when we see a new animation get
// activated, we need to update the draw properties on the active tree.
active_tree()->set_needs_update_draw_properties();
// Request another frame to run the next tick of the animation.
SetNeedsOneBeginImplFrame();
if (!mutator_events_->IsEmpty())
SetNeedsCommit();
}
}
void LayerTreeHostImpl::RegisterScrollbarAnimationController(
ElementId scroll_element_id,
float scrollbar_opacity) {
if (ScrollbarAnimationControllerForElementId(scroll_element_id))
return;
scrollbar_animation_controllers_[scroll_element_id] =
active_tree_->CreateScrollbarAnimationController(scroll_element_id,
scrollbar_opacity);
}
void LayerTreeHostImpl::DidRegisterScrollbarLayer(
ElementId scroll_element_id,
ScrollbarOrientation orientation) {
if (input_delegate_)
input_delegate_->DidRegisterScrollbar(scroll_element_id, orientation);
}
void LayerTreeHostImpl::DidUnregisterScrollbarLayer(
ElementId scroll_element_id,
ScrollbarOrientation orientation) {
if (ScrollbarsFor(scroll_element_id).empty())
scrollbar_animation_controllers_.erase(scroll_element_id);
if (input_delegate_)
input_delegate_->DidUnregisterScrollbar(scroll_element_id, orientation);
}
ScrollbarAnimationController*
LayerTreeHostImpl::ScrollbarAnimationControllerForElementId(
ElementId scroll_element_id) const {
// The viewport layers have only one set of scrollbars. On Android, these are
// registered with the inner viewport, otherwise they're registered with the
// outer viewport. If a controller for one exists, the other shouldn't.
if (InnerViewportScrollNode()) {
DCHECK(OuterViewportScrollNode());
if (scroll_element_id == InnerViewportScrollNode()->element_id ||
scroll_element_id == OuterViewportScrollNode()->element_id) {
auto itr = scrollbar_animation_controllers_.find(
InnerViewportScrollNode()->element_id);
if (itr != scrollbar_animation_controllers_.end())
return itr->second.get();
itr = scrollbar_animation_controllers_.find(
OuterViewportScrollNode()->element_id);
if (itr != scrollbar_animation_controllers_.end())
return itr->second.get();
return nullptr;
}
}
auto i = scrollbar_animation_controllers_.find(scroll_element_id);
if (i == scrollbar_animation_controllers_.end())
return nullptr;
return i->second.get();
}
void LayerTreeHostImpl::FlashAllScrollbars(bool did_scroll) {
for (auto& pair : scrollbar_animation_controllers_) {
if (did_scroll)
pair.second->DidScrollUpdate();
else
pair.second->WillUpdateScroll();
}
}
void LayerTreeHostImpl::PostDelayedScrollbarAnimationTask(
base::OnceClosure task,
base::TimeDelta delay) {
client_->PostDelayedAnimationTaskOnImplThread(std::move(task), delay);
}
// TODO(danakj): Make this a return value from the Animate() call instead of an
// interface on LTHI. (Also, crbug.com/551138.)
void LayerTreeHostImpl::SetNeedsAnimateForScrollbarAnimation() {
TRACE_EVENT0("cc", "LayerTreeHostImpl::SetNeedsAnimateForScrollbarAnimation");
SetNeedsOneBeginImplFrame();
}
// TODO(danakj): Make this a return value from the Animate() call instead of an
// interface on LTHI. (Also, crbug.com/551138.)
void LayerTreeHostImpl::SetNeedsRedrawForScrollbarAnimation() {
SetNeedsRedraw(/*animation_only*/ true);
}
ScrollbarSet LayerTreeHostImpl::ScrollbarsFor(ElementId id) const {
return active_tree_->ScrollbarsFor(id);
}
bool LayerTreeHostImpl::IsFluentOverlayScrollbar() const {
return settings().enable_fluent_overlay_scrollbar;
}
void LayerTreeHostImpl::AddVideoFrameController(
VideoFrameController* controller) {
bool was_empty = video_frame_controllers_.empty();
video_frame_controllers_.insert(controller);
if (current_begin_frame_tracker_.DangerousMethodHasStarted() &&
!current_begin_frame_tracker_.DangerousMethodHasFinished())
controller->OnBeginFrame(current_begin_frame_tracker_.Current());
if (was_empty)
client_->SetVideoNeedsBeginFrames(true);
}
void LayerTreeHostImpl::RemoveVideoFrameController(
VideoFrameController* controller) {
video_frame_controllers_.erase(controller);
if (video_frame_controllers_.empty())
client_->SetVideoNeedsBeginFrames(false);
}
void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
if (global_tile_state_.tree_priority == priority)
return;
global_tile_state_.tree_priority = priority;
DidModifyTilePriorities(/*pending_update_tiles=*/false);
}
TreePriority LayerTreeHostImpl::GetTreePriority() const {
return global_tile_state_.tree_priority;
}
const viz::BeginFrameArgs& LayerTreeHostImpl::CurrentBeginFrameArgs() const {
// TODO(mithro): Replace call with current_begin_frame_tracker_.Current()
// once all calls which happens outside impl frames are fixed.
return current_begin_frame_tracker_.DangerousMethodCurrentOrLast();
}
base::TimeDelta LayerTreeHostImpl::CurrentBeginFrameInterval() const {
return current_begin_frame_tracker_.Interval();
}
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
LayerTreeHostImpl::AsValueWithFrame(FrameData* frame) const {
std::unique_ptr<base::trace_event::TracedValue> state(
new base::trace_event::TracedValue());
AsValueWithFrameInto(frame, state.get());
return std::move(state);
}
void LayerTreeHostImpl::AsValueWithFrameInto(
FrameData* frame,
base::trace_event::TracedValue* state) const {
if (this->pending_tree_) {
state->BeginDictionary("activation_state");
ActivationStateAsValueInto(state);
state->EndDictionary();
}
MathUtil::AddToTracedValue("device_viewport_size",
active_tree_->GetDeviceViewport().size(), state);
std::vector<PrioritizedTile> prioritized_tiles;
active_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
if (pending_tree_)
pending_tree_->GetAllPrioritizedTilesForTracing(&prioritized_tiles);
state->BeginArray("active_tiles");
for (const auto& prioritized_tile : prioritized_tiles) {
state->BeginDictionary();
prioritized_tile.AsValueInto(state);
state->EndDictionary();
}
state->EndArray();
state->BeginDictionary("tile_manager_basic_state");
tile_manager_.BasicStateAsValueInto(state);
state->EndDictionary();
state->BeginDictionary("active_tree");
active_tree_->AsValueInto(state);
state->EndDictionary();
if (pending_tree_) {
state->BeginDictionary("pending_tree");
pending_tree_->AsValueInto(state);
state->EndDictionary();
}
if (frame) {
state->BeginDictionary("frame");
frame->AsValueInto(state);
state->EndDictionary();
}
}
void LayerTreeHostImpl::ActivationStateAsValueInto(
base::trace_event::TracedValue* state) const {
viz::TracedValue::SetIDRef(this, state, "lthi");
state->BeginDictionary("tile_manager");
tile_manager_.BasicStateAsValueInto(state);
state->EndDictionary();
}
void LayerTreeHostImpl::SetDebugState(
const LayerTreeDebugState& new_debug_state) {
if (debug_state_ == new_debug_state) {
return;
}
debug_state_ = new_debug_state;
UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
SetFullViewportDamage();
}
void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
const UIResourceBitmap& bitmap) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::CreateUIResource");
// We expect only CreateUIResourceFromImportedResource to be used for
// trees_in_viz_in_viz_process mode.
DCHECK(!settings_.trees_in_viz_in_viz_process);
DCHECK_GT(uid, 0);
// Allow for multiple creation requests with the same UIResourceId. The
// previous resource is simply deleted.
viz::ResourceId id = ResourceIdForUIResource(uid);
if (id)
DeleteUIResource(uid);
if (!has_valid_layer_tree_frame_sink_) {
evicted_ui_resources_.insert(uid);
return;
}
viz::SharedImageFormat format;
switch (bitmap.GetFormat()) {
case UIResourceBitmap::RGBA8:
format = raster_caps_.ui_rgba_format;
break;
case UIResourceBitmap::ALPHA_8:
format = viz::SinglePlaneFormat::kALPHA_8;
break;
case UIResourceBitmap::ETC1:
format = viz::SinglePlaneFormat::kETC1;
break;
}
const gfx::Size source_size = bitmap.GetSize();
gfx::Size upload_size = bitmap.GetSize();
bool scaled = false;
// UIResources are assumed to be rastered in SRGB.
const gfx::ColorSpace& color_space = gfx::ColorSpace::CreateSRGB();
if (source_size.width() > raster_caps().max_texture_size ||
source_size.height() > raster_caps().max_texture_size) {
// Must resize the bitmap to fit within the max texture size.
scaled = true;
int edge = std::max(source_size.width(), source_size.height());
float scale = static_cast<float>(raster_caps().max_texture_size - 1) / edge;
DCHECK_LT(scale, 1.f);
upload_size = gfx::ScaleToCeiledSize(source_size, scale, scale);
}
scoped_refptr<gpu::ClientSharedImage> client_shared_image;
gpu::SharedImageUsageSet shared_image_usage =
gpu::SHARED_IMAGE_USAGE_DISPLAY_READ;
// For software compositing, shared memory will be allocated and the
// UIResource will be copied into it.
std::unique_ptr<gpu::ClientSharedImage::ScopedMapping> shared_mapping;
if (layer_tree_frame_sink_->context_provider()) {
viz::RasterContextProvider* context_provider =
layer_tree_frame_sink_->context_provider();
const auto& shared_image_caps =
context_provider->SharedImageInterface()->GetCapabilities();
const bool overlay_candidate =
settings_.use_gpu_memory_buffer_resources &&
shared_image_caps.supports_scanout_shared_images &&
viz::CanCreateGpuMemoryBufferForSinglePlaneSharedImageFormat(format);
if (overlay_candidate) {
shared_image_usage |= gpu::SHARED_IMAGE_USAGE_SCANOUT;
}
} else {
// software composition;
DCHECK_EQ(bitmap.GetFormat(), UIResourceBitmap::RGBA8);
// Must not include gpu::SHARED_IMAGE_USAGE_DISPLAY_READ here because
// DISPLAY_READ means gpu composition.
shared_image_usage = gpu::SHARED_IMAGE_USAGE_CPU_WRITE_ONLY;
auto sii = layer_tree_frame_sink_->shared_image_interface();
CHECK(sii);
client_shared_image = sii->CreateSharedImageForSoftwareCompositor(
{format, upload_size, color_space, shared_image_usage,
"LayerTreeHostUIResource"});
CHECK(client_shared_image);
shared_mapping = client_shared_image->Map();
}
if (!scaled) {
// If not scaled, we can copy the pixels 1:1 from the source bitmap to our
// destination backing of a texture or shared bitmap.
if (layer_tree_frame_sink_->context_provider()) {
viz::RasterContextProvider* context_provider =
layer_tree_frame_sink_->context_provider();
auto* sii = context_provider->SharedImageInterface();
client_shared_image = sii->CreateSharedImage(
{format, upload_size, color_space, shared_image_usage,
"LayerTreeHostUIResource"},
bitmap.GetPixels());
CHECK(client_shared_image);
} else {
DCHECK_EQ(bitmap.GetFormat(), UIResourceBitmap::RGBA8);
SkImageInfo src_info =
SkImageInfo::MakeN32Premul(gfx::SizeToSkISize(source_size));
SkImageInfo dst_info =
SkImageInfo::MakeN32Premul(gfx::SizeToSkISize(upload_size));
sk_sp<SkSurface> surface = SkSurfaces::WrapPixels(
dst_info, shared_mapping->GetMemoryForPlane(0).data(),
dst_info.minRowBytes());
surface->getCanvas()->writePixels(src_info, bitmap.GetPixels().data(),
bitmap.row_bytes(), 0, 0);
}
} else {
// Only support auto-resizing for N32 textures (since this is primarily for
// scrollbars). Users of other types need to ensure they are not too big.
DCHECK_EQ(bitmap.GetFormat(), UIResourceBitmap::RGBA8);
float canvas_scale_x =
upload_size.width() / static_cast<float>(source_size.width());
float canvas_scale_y =
upload_size.height() / static_cast<float>(source_size.height());
// Uses N32Premul since that is what SkBitmap's allocN32Pixels makes, and we
// only support the RGBA8 format here.
SkImageInfo info =
SkImageInfo::MakeN32Premul(gfx::SizeToSkISize(source_size));
SkBitmap source_bitmap;
source_bitmap.setInfo(info, bitmap.row_bytes());
source_bitmap.setPixels(const_cast<uint8_t*>(bitmap.GetPixels().data()));
// This applies the scale to draw the |bitmap| into |scaled_surface|. For
// gpu compositing, we scale into a software bitmap-backed SkSurface here,
// then upload from there into a texture. For software compositing, we scale
// directly into the shared memory backing.
sk_sp<SkSurface> scaled_surface;
if (layer_tree_frame_sink_->context_provider()) {
scaled_surface = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(
upload_size.width(), upload_size.height()));
CHECK(scaled_surface); // This would fail in OOM situations.
} else {
SkImageInfo dst_info =
SkImageInfo::MakeN32Premul(gfx::SizeToSkISize(upload_size));
scaled_surface = SkSurfaces::WrapPixels(
dst_info, shared_mapping->GetMemoryForPlane(0).data(),
dst_info.minRowBytes());
CHECK(scaled_surface); // This could fail on invalid parameters.
}
SkCanvas* scaled_canvas = scaled_surface->getCanvas();
scaled_canvas->scale(canvas_scale_x, canvas_scale_y);
// The |canvas_scale_x| and |canvas_scale_y| may have some floating point
// error for large enough values, causing pixels on the edge to be not
// fully filled by drawBitmap(), so we ensure they start empty. (See
// crbug.com/642011 for an example.)
scaled_canvas->clear(SK_ColorTRANSPARENT);
scaled_canvas->drawImage(source_bitmap.asImage(), 0, 0);
if (layer_tree_frame_sink_->context_provider()) {
SkPixmap pixmap;
scaled_surface->peekPixels(&pixmap);
viz::RasterContextProvider* context_provider =
layer_tree_frame_sink_->context_provider();
auto* sii = context_provider->SharedImageInterface();
client_shared_image = sii->CreateSharedImage(
{format, upload_size, color_space, shared_image_usage,
"LayerTreeHostUIResource"},
gfx::SkPixmapToSpan(pixmap));
CHECK(client_shared_image);
}
}
// Once the backing has the UIResource inside it, we have to prepare it for
// export to the display compositor via ImportResource(). This requires a
// Mailbox+SyncToken as well. The OnUIResourceReleased() method will be called
// once the resource is deleted and the display compositor is no longer using
// it, to free the memory allocated in this method above.
viz::TransferableResource transferable;
if (layer_tree_frame_sink_->context_provider()) {
gpu::SyncToken sync_token = layer_tree_frame_sink_->context_provider()
->SharedImageInterface()
->GenUnverifiedSyncToken();
transferable = viz::TransferableResource::Make(
client_shared_image, viz::TransferableResource::ResourceSource::kUI,
sync_token);
} else {
auto sii = layer_tree_frame_sink_->shared_image_interface();
gpu::SyncToken sync_token = sii->GenVerifiedSyncToken();
transferable = viz::TransferableResource::Make(
client_shared_image, viz::TransferableResource::ResourceSource::kUI,
sync_token);
}
id = resource_provider_->ImportResource(
transferable,
// The OnUIResourceReleased method is bound with a WeakPtr, but the
// resource backing will be deleted when the LayerTreeFrameSink is
// removed before shutdown, so nothing leaks if the WeakPtr is
// invalidated.
base::BindOnce(&LayerTreeHostImpl::OnUIResourceReleased, AsWeakPtr(),
uid));
UIResourceData data;
data.opaque = bitmap.GetOpaque();
data.shared_image = std::move(client_shared_image);
data.resource_id_for_export = id;
ui_resource_map_[uid] = std::move(data);
MarkUIResourceNotEvicted(uid);
if (settings_.TreesInVizInClientProcess()) {
auto [change_it, success] =
ui_resource_changes_.try_emplace(uid, UIResourceChange());
// Mark that a resource was created in this change set.
change_it->second.resource_created = true;
}
}
void LayerTreeHostImpl::CreateUIResourceFromImportedResource(
UIResourceId uid,
viz::ResourceId resource_id,
bool is_opaque) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::CreateUIResourceFromResource");
// We expect only CreateUIResource to be used for
// non-trees_in_viz_in_viz_process mode.
DCHECK(settings_.trees_in_viz_in_viz_process);
DCHECK_GT(uid, 0);
// Allow for multiple creation requests with the same UIResourceId. The
// previous resource is simply deleted.
viz::ResourceId id = ResourceIdForUIResource(uid);
if (id) {
DeleteUIResource(uid);
}
if (!has_valid_layer_tree_frame_sink_) {
evicted_ui_resources_.insert(uid);
return;
}
UIResourceData data;
data.opaque = is_opaque;
data.resource_id_for_export = resource_id;
ui_resource_map_[uid] = std::move(data);
MarkUIResourceNotEvicted(uid);
if (settings_.TreesInVizInClientProcess()) {
auto [change_it, success] =
ui_resource_changes_.try_emplace(uid, UIResourceChange());
// Mark that a resource was created in this change set.
change_it->second.resource_created = true;
}
}
void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHostImpl::DeleteUIResource");
auto it = ui_resource_map_.find(uid);
if (it != ui_resource_map_.end()) {
UIResourceData& data = it->second;
viz::ResourceId id = data.resource_id_for_export;
// Move the |data| to |deleted_ui_resources_| before removing it from the
// viz::ClientResourceProvider, so that the ReleaseCallback can see it
// there.
deleted_ui_resources_[uid] = std::move(data);
ui_resource_map_.erase(it);
resource_provider_->RemoveImportedResource(id);
if (settings_.TreesInVizInClientProcess()) {
auto [change_it, success] =
ui_resource_changes_.try_emplace(uid, UIResourceChange());
// If a resource was marked as created in this change set, unmark it.
// Otherwise, the resource must have been created in a prior change set,
// so we mark it as requiring deletion.
if (change_it->second.resource_created) {
change_it->second.resource_created = false;
} else {
change_it->second.resource_deleted = true;
}
}
}
MarkUIResourceNotEvicted(uid);
}
void LayerTreeHostImpl::DeleteUIResourceBacking(
UIResourceData data,
const gpu::SyncToken& sync_token) {
data.shared_image->UpdateDestructionSyncToken(sync_token);
}
void LayerTreeHostImpl::OnUIResourceReleased(UIResourceId uid,
const gpu::SyncToken& sync_token,
bool lost) {
auto it = deleted_ui_resources_.find(uid);
if (it == deleted_ui_resources_.end()) {
// Backing was already deleted, eg if the context was lost.
return;
}
UIResourceData& data = it->second;
// We don't recycle backings here, so |lost| is not relevant, we always delete
// them.
DeleteUIResourceBacking(std::move(data), sync_token);
deleted_ui_resources_.erase(it);
}
void LayerTreeHostImpl::ClearUIResources() {
for (auto& pair : ui_resource_map_) {
UIResourceId uid = pair.first;
UIResourceData& data = pair.second;
resource_provider_->RemoveImportedResource(data.resource_id_for_export);
// Immediately drop the backing instead of waiting for the resource to be
// returned from the ResourceProvider, as this is called in cases where the
// ability to clean up the backings will go away (context loss, shutdown).
DeleteUIResourceBacking(std::move(data), gpu::SyncToken());
// This resource is not deleted, and its |uid| is still valid, so it moves
// to the evicted list, not the |deleted_ui_resources_| set. Also, its
// backing is gone, so it would not belong in |deleted_ui_resources_|.
evicted_ui_resources_.insert(uid);
}
ui_resource_map_.clear();
for (auto& pair : deleted_ui_resources_) {
UIResourceData& data = pair.second;
// Immediately drop the backing instead of waiting for the resource to be
// returned from the ResourceProvider, as this is called in cases where the
// ability to clean up the backings will go away (context loss, shutdown).
DeleteUIResourceBacking(std::move(data), gpu::SyncToken());
}
deleted_ui_resources_.clear();
}
void LayerTreeHostImpl::EvictAllUIResources() {
if (ui_resource_map_.empty())
return;
while (!ui_resource_map_.empty()) {
UIResourceId uid = ui_resource_map_.begin()->first;
DeleteUIResource(uid);
evicted_ui_resources_.insert(uid);
}
client_->SetNeedsCommitOnImplThread();
client_->OnCanDrawStateChanged(CanDraw());
client_->RenewTreePriority();
}
viz::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
UIResourceId uid) const {
auto iter = ui_resource_map_.find(uid);
if (iter != ui_resource_map_.end())
return iter->second.resource_id_for_export;
return viz::kInvalidResourceId;
}
bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
auto iter = ui_resource_map_.find(uid);
CHECK(iter != ui_resource_map_.end());
return iter->second.opaque;
}
bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
return !evicted_ui_resources_.empty();
}
void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
auto found_in_evicted = evicted_ui_resources_.find(uid);
if (found_in_evicted == evicted_ui_resources_.end())
return;
evicted_ui_resources_.erase(found_in_evicted);
if (evicted_ui_resources_.empty())
client_->OnCanDrawStateChanged(CanDraw());
}
void LayerTreeHostImpl::ScheduleMicroBenchmark(
std::unique_ptr<MicroBenchmarkImpl> benchmark) {
micro_benchmark_controller_.ScheduleRun(std::move(benchmark));
}
void LayerTreeHostImpl::InsertLatencyInfoSwapPromiseMonitor(
LatencyInfoSwapPromiseMonitor* monitor) {
latency_info_swap_promise_monitor_.insert(monitor);
}
void LayerTreeHostImpl::RemoveLatencyInfoSwapPromiseMonitor(
LatencyInfoSwapPromiseMonitor* monitor) {
latency_info_swap_promise_monitor_.erase(monitor);
}
void LayerTreeHostImpl::NotifyLatencyInfoSwapPromiseMonitors() {
for (LatencyInfoSwapPromiseMonitor* monitor :
latency_info_swap_promise_monitor_) {
monitor->OnSetNeedsRedrawOnImpl();
}
}
bool LayerTreeHostImpl::IsOwnerThread() const {
bool result;
if (task_runner_provider_->ImplThreadTaskRunner()) {
result = task_runner_provider_->ImplThreadTaskRunner()
->RunsTasksInCurrentSequence();
} else {
result = task_runner_provider_->MainThreadTaskRunner()
->RunsTasksInCurrentSequence();
// There's no impl thread, and we're not on the main thread; where are we?
DCHECK(result);
}
return result;
}
// LayerTreeHostImpl has no "protected sequence" (yet).
bool LayerTreeHostImpl::InProtectedSequence() const {
return false;
}
void LayerTreeHostImpl::WaitForProtectedSequenceCompletion() const {}
bool LayerTreeHostImpl::IsElementInPropertyTrees(
ElementId element_id,
ElementListType list_type) const {
if (list_type == ElementListType::ACTIVE)
return active_tree() && active_tree()->IsElementInPropertyTree(element_id);
return (pending_tree() &&
pending_tree()->IsElementInPropertyTree(element_id)) ||
(recycle_tree() &&
recycle_tree()->IsElementInPropertyTree(element_id));
}
void LayerTreeHostImpl::SetMutatorsNeedCommit() {}
void LayerTreeHostImpl::SetMutatorsNeedRebuildPropertyTrees() {}
void LayerTreeHostImpl::SetTreeLayerScrollOffsetMutated(
ElementId element_id,
LayerTreeImpl* tree,
const gfx::PointF& scroll_offset) {
if (!tree)
return;
PropertyTrees* property_trees = tree->property_trees();
DCHECK_EQ(1u, property_trees->scroll_tree().element_id_to_node_index().count(
element_id));
const ScrollNode* scroll_node =
property_trees->scroll_tree().FindNodeFromElementId(element_id);
// TODO(crbug.com/40828469): We should aim to prevent this condition from
// happening and either remove this check or make it fatal.
DCHECK(scroll_node);
if (!scroll_node)
return;
property_trees->scroll_tree_mutable().OnScrollOffsetAnimated(
element_id, scroll_node->id, scroll_offset, tree);
}
void LayerTreeHostImpl::SetElementFilterMutated(
ElementId element_id,
ElementListType list_type,
const FilterOperations& filters) {
if (list_type == ElementListType::ACTIVE) {
active_tree()->SetFilterMutated(element_id, filters);
} else {
if (pending_tree())
pending_tree()->SetFilterMutated(element_id, filters);
if (recycle_tree())
recycle_tree()->SetFilterMutated(element_id, filters);
}
}
void LayerTreeHostImpl::OnCustomPropertyMutated(
PaintWorkletInput::PropertyKey property_key,
PaintWorkletInput::PropertyValue property_value) {
paint_worklet_tracker_.OnCustomPropertyMutated(std::move(property_key),
std::move(property_value));
}
bool LayerTreeHostImpl::RunsOnCurrentThread() const {
// If there is no impl thread, then we assume the current thread is ok.
return !task_runner_provider_->HasImplThread() ||
task_runner_provider_->IsImplThread();
}
void LayerTreeHostImpl::SetElementBackdropFilterMutated(
ElementId element_id,
ElementListType list_type,
const FilterOperations& backdrop_filters) {
if (list_type == ElementListType::ACTIVE) {
active_tree()->SetBackdropFilterMutated(element_id, backdrop_filters);
} else {
if (pending_tree())
pending_tree()->SetBackdropFilterMutated(element_id, backdrop_filters);
if (recycle_tree())
recycle_tree()->SetBackdropFilterMutated(element_id, backdrop_filters);
}
}
void LayerTreeHostImpl::SetElementOpacityMutated(ElementId element_id,
ElementListType list_type,
float opacity) {
if (list_type == ElementListType::ACTIVE) {
active_tree()->SetOpacityMutated(element_id, opacity);
} else {
if (pending_tree())
pending_tree()->SetOpacityMutated(element_id, opacity);
if (recycle_tree())
recycle_tree()->SetOpacityMutated(element_id, opacity);
}
}
void LayerTreeHostImpl::SetElementTransformMutated(
ElementId element_id,
ElementListType list_type,
const gfx::Transform& transform) {
if (list_type == ElementListType::ACTIVE) {
active_tree()->SetTransformMutated(element_id, transform);
} else {
if (pending_tree())
pending_tree()->SetTransformMutated(element_id, transform);
if (recycle_tree())
recycle_tree()->SetTransformMutated(element_id, transform);
}
}
void LayerTreeHostImpl::SetElementScrollOffsetMutated(
ElementId element_id,
ElementListType list_type,
const gfx::PointF& scroll_offset) {
if (list_type == ElementListType::ACTIVE) {
SetTreeLayerScrollOffsetMutated(element_id, active_tree(), scroll_offset);
ShowScrollbarsForImplScroll(element_id);
} else {
SetTreeLayerScrollOffsetMutated(element_id, pending_tree(), scroll_offset);
SetTreeLayerScrollOffsetMutated(element_id, recycle_tree(), scroll_offset);
}
}
void LayerTreeHostImpl::ElementIsAnimatingChanged(
const PropertyToElementIdMap& element_id_map,
ElementListType list_type,
const PropertyAnimationState& mask,
const PropertyAnimationState& state) {
LayerTreeImpl* tree =
list_type == ElementListType::ACTIVE ? active_tree() : pending_tree();
// TODO(wkorman): Explore enabling DCHECK in ElementIsAnimatingChanged()
// below. Currently enabling causes batch of unit test failures.
if (tree && tree->property_trees()->ElementIsAnimatingChanged(
element_id_map, mask, state, false))
tree->set_needs_update_draw_properties();
}
void LayerTreeHostImpl::MaximumScaleChanged(ElementId element_id,
ElementListType list_type,
float maximum_scale) {
if (LayerTreeImpl* tree = list_type == ElementListType::ACTIVE
? active_tree()
: pending_tree()) {
tree->property_trees()->MaximumAnimationScaleChanged(element_id,
maximum_scale);
}
}
void LayerTreeHostImpl::ScrollOffsetAnimationFinished(ElementId element_id) {
if (input_delegate_)
input_delegate_->ScrollOffsetAnimationFinished(element_id);
}
void LayerTreeHostImpl::NotifyAnimationWorkletStateChange(
AnimationWorkletMutationState state,
ElementListType tree_type) {
client_->NotifyAnimationWorkletStateChange(state, tree_type);
if (state != AnimationWorkletMutationState::CANCELED) {
// We have at least one active worklet animation. We need to request a new
// frame to keep the animation ticking.
SetNeedsOneBeginImplFrame();
if (state == AnimationWorkletMutationState::COMPLETED_WITH_UPDATE &&
tree_type == ElementListType::ACTIVE) {
SetNeedsRedraw();
}
}
}
bool LayerTreeHostImpl::CommitsToActiveTree() const {
return settings_.commit_to_active_tree;
}
void LayerTreeHostImpl::SetContextVisibility(bool is_visible) {
if (!layer_tree_frame_sink_)
return;
// Update the compositor context. If we are already in the correct visibility
// state, skip. This can happen if we transition invisible/visible rapidly,
// before we get a chance to go invisible in NotifyAllTileTasksComplete.
auto* compositor_context = layer_tree_frame_sink_->context_provider();
if (compositor_context && is_visible != !!compositor_context_visibility_) {
if (is_visible) {
compositor_context_visibility_ =
compositor_context->CacheController()->ClientBecameVisible();
} else {
compositor_context->CacheController()->ClientBecameNotVisible(
std::move(compositor_context_visibility_));
}
}
// Update the worker context. If we are already in the correct visibility
// state, skip. This can happen if we transition invisible/visible rapidly,
// before we get a chance to go invisible in NotifyAllTileTasksComplete.
auto* worker_context = layer_tree_frame_sink_->worker_context_provider();
if (worker_context && is_visible != !!worker_context_visibility_) {
viz::RasterContextProvider::ScopedRasterContextLock hold(worker_context);
if (is_visible) {
worker_context_visibility_ =
worker_context->CacheController()->ClientBecameVisible();
} else {
worker_context->CacheController()->ClientBecameNotVisible(
std::move(worker_context_visibility_));
}
}
}
void LayerTreeHostImpl::ShowScrollbarsForImplScroll(ElementId element_id) {
if (settings_.scrollbar_flash_after_any_scroll_update) {
FlashAllScrollbars(true);
return;
}
if (!element_id)
return;
if (ScrollbarAnimationController* animation_controller =
ScrollbarAnimationControllerForElementId(element_id))
animation_controller->DidScrollUpdate();
}
void LayerTreeHostImpl::InitializeUkm(
std::unique_ptr<ukm::UkmRecorder> recorder) {
compositor_frame_reporting_controller_->InitializeUkmManager(
std::move(recorder));
}
void LayerTreeHostImpl::SetActiveURL(const GURL& url, ukm::SourceId source_id) {
tile_manager_.set_active_url(url);
has_observed_first_scroll_delay_ = false;
// The active tree might still be from content for the previous page when the
// recorder is updated here, since new content will be pushed with the next
// main frame. But we should only get a few impl frames wrong here in that
// case. Also, since checkerboard stats are only recorded with user
// interaction, it must be in progress when the navigation commits for this
// case to occur.
// The source id has already been associated to the URL.
compositor_frame_reporting_controller_->SetSourceId(source_id);
frame_sorter_.Reset(/*reset_fcp=*/true);
}
void LayerTreeHostImpl::SetUkmSmoothnessDestination(
base::WritableSharedMemoryMapping ukm_smoothness_data) {
ukm_smoothness_mapping_ = std::move(ukm_smoothness_data);
}
void LayerTreeHostImpl::SetUkmDroppedFramesDestination(
base::WritableSharedMemoryMapping ukm_dropped_frames_data) {
frame_trackers_.SetUkmDroppedFramesDestination(
ukm_dropped_frames_data.GetMemoryAs<UkmDroppedFramesDataShared>());
ukm_dropped_frames_mapping_ = std::move(ukm_dropped_frames_data);
}
void LayerTreeHostImpl::NotifyDidPresentCompositorFrameOnImplThread(
uint32_t frame_token,
std::vector<PresentationTimeCallbackBuffer::SuccessfulCallback> callbacks,
const viz::FrameTimingDetails& details) {
for (auto& callback : callbacks)
std::move(callback).Run(details.presentation_feedback.timestamp);
}
void LayerTreeHostImpl::AllocateLocalSurfaceId() {
child_local_surface_id_allocator_.GenerateId();
}
void LayerTreeHostImpl::RequestBeginFrameForAnimatedImages() {
SetNeedsOneBeginImplFrame();
}
void LayerTreeHostImpl::RequestInvalidationForAnimatedImages() {
DCHECK_EQ(impl_thread_phase_, ImplThreadPhase::INSIDE_IMPL_FRAME);
// If we are animating an image, we want at least one draw of the active tree
// before a new tree is activated.
bool needs_first_draw_on_activation = true;
client_->SetNeedsImplSideInvalidation(needs_first_draw_on_activation);
}
bool LayerTreeHostImpl::IsInSynchronousComposite() const {
return client_->IsInSynchronousComposite();
}
bool LayerTreeHostImpl::IsReadyToActivate() const {
return client_->IsReadyToActivate();
}
void LayerTreeHostImpl::RequestImplSideInvalidationForRerasterTiling() {
bool needs_first_draw_on_activation = true;
client_->SetNeedsImplSideInvalidation(needs_first_draw_on_activation);
}
void LayerTreeHostImpl::RequestImplSideInvalidationForRasterInducingScroll(
ElementId scroll_element_id) {
client_->SetNeedsImplSideInvalidation(
/*needs_first_draw_on_activation=*/true);
pending_invalidation_raster_inducing_scrolls_.insert(scroll_element_id);
}
base::WeakPtr<LayerTreeHostImpl> LayerTreeHostImpl::AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void LayerTreeHostImpl::ApplyFirstScrollTracking(const ui::LatencyInfo& latency,
uint32_t frame_token) {
base::TimeTicks creation_timestamp;
// If `latency` isn't tracking a scroll, we don't need to do extra
// first-scroll tracking.
if (!latency.FindLatency(
ui::INPUT_EVENT_LATENCY_FIRST_SCROLL_UPDATE_ORIGINAL_COMPONENT,
&creation_timestamp) &&
!latency.FindLatency(
ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT,
&creation_timestamp)) {
return;
}
// Construct a callback that, given a successful presentation timestamp, will
// report the time span between the scroll input-event creation and the
// presentation timestamp.
std::vector<PresentationTimeCallbackBuffer::SuccessfulCallback> callbacks;
callbacks.push_back(base::BindOnce(
[](base::TimeTicks event_creation, int source_frame_number,
LayerTreeHostImpl* layer_tree_host_impl,
base::TimeTicks presentation_timestamp) {
layer_tree_host_impl->DidObserveScrollDelay(
source_frame_number, presentation_timestamp - event_creation,
event_creation);
},
creation_timestamp, active_tree_->source_frame_number(), this));
// Register the callback to run with the presentation timestamp corresponding
// to the given `frame_token`.
presentation_time_callbacks_.RegisterCompositorThreadSuccessfulCallbacks(
frame_token, std::move(callbacks));
}
bool LayerTreeHostImpl::RunningOnRendererProcess() const {
// The browser process uses |SingleThreadProxy| whereas the renderers use
// |ProxyMain|. This is more of an implementation detail, but we can use
// that here to determine the process type.
return !settings().single_thread_proxy_scheduler;
}
void LayerTreeHostImpl::ResetHasInputForFrameInterval() {
has_input_for_frame_interval_ = false;
}
} // namespace cc
|