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
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "SurfaceComposerClient"
#include <semaphore.h>
#include <stdint.h>
#include <sys/types.h>
#include <android/gui/BnWindowInfosReportedListener.h>
#include <android/gui/DisplayState.h>
#include <android/gui/ISurfaceComposerClient.h>
#include <android/gui/IWindowInfosListener.h>
#include <android/gui/TrustedPresentationThresholds.h>
#include <android/os/IInputConstants.h>
#include <gui/FrameRateUtils.h>
#include <gui/TraceUtils.h>
#include <utils/Errors.h>
#include <utils/Log.h>
#include <utils/SortedVector.h>
#include <utils/String8.h>
#include <utils/threads.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/ProcessState.h>
#include <system/graphics.h>
#include <gui/AidlStatusUtil.h>
#include <gui/BufferItemConsumer.h>
#include <gui/CpuConsumer.h>
#include <gui/IGraphicBufferProducer.h>
#include <gui/ISurfaceComposer.h>
#include <gui/LayerState.h>
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <gui/WindowInfo.h>
#include <private/gui/ParcelUtils.h>
#include <ui/DisplayMode.h>
#include <ui/DisplayState.h>
#include <ui/DynamicDisplayInfo.h>
#include <android-base/thread_annotations.h>
#include <gui/LayerStatePermissions.h>
#include <gui/ScreenCaptureResults.h>
#include <private/gui/ComposerService.h>
#include <private/gui/ComposerServiceAIDL.h>
// This server size should always be smaller than the server cache size
#define BUFFER_CACHE_MAX_SIZE 4096
namespace android {
using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
using gui::FocusRequest;
using gui::IRegionSamplingListener;
using gui::TrustedPresentationThresholds;
using gui::WindowInfo;
using gui::WindowInfoHandle;
using gui::WindowInfosListener;
using gui::aidl_utils::statusTFromBinderStatus;
using ui::ColorMode;
// ---------------------------------------------------------------------------
ANDROID_SINGLETON_STATIC_INSTANCE(ComposerService);
ANDROID_SINGLETON_STATIC_INSTANCE(ComposerServiceAIDL);
namespace {
// Initialize transaction id counter used to generate transaction ids
std::atomic<uint32_t> idCounter = 0;
int64_t generateId() {
return (((int64_t)getpid()) << 32) | ++idCounter;
}
void emptyCallback(nsecs_t, const sp<Fence>&, const std::vector<SurfaceControlStats>&) {}
} // namespace
ComposerService::ComposerService()
: Singleton<ComposerService>() {
Mutex::Autolock _l(mLock);
connectLocked();
}
bool ComposerService::connectLocked() {
const String16 name("SurfaceFlinger");
mComposerService = waitForService<ISurfaceComposer>(name);
if (mComposerService == nullptr) {
return false; // fatal error or permission problem
}
// Create the death listener.
class DeathObserver : public IBinder::DeathRecipient {
ComposerService& mComposerService;
virtual void binderDied(const wp<IBinder>& who) {
ALOGW("ComposerService remote (surfaceflinger) died [%p]",
who.unsafe_get());
mComposerService.composerServiceDied();
}
public:
explicit DeathObserver(ComposerService& mgr) : mComposerService(mgr) { }
};
mDeathObserver = new DeathObserver(*const_cast<ComposerService*>(this));
IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
return true;
}
/*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {
ComposerService& instance = ComposerService::getInstance();
Mutex::Autolock _l(instance.mLock);
if (instance.mComposerService == nullptr) {
if (ComposerService::getInstance().connectLocked()) {
ALOGD("ComposerService reconnected");
}
}
return instance.mComposerService;
}
void ComposerService::composerServiceDied()
{
Mutex::Autolock _l(mLock);
mComposerService = nullptr;
mDeathObserver = nullptr;
}
ComposerServiceAIDL::ComposerServiceAIDL() : Singleton<ComposerServiceAIDL>() {
std::scoped_lock lock(mMutex);
connectLocked();
}
bool ComposerServiceAIDL::connectLocked() {
const String16 name("SurfaceFlingerAIDL");
mComposerService = waitForService<gui::ISurfaceComposer>(name);
if (mComposerService == nullptr) {
return false; // fatal error or permission problem
}
// Create the death listener.
class DeathObserver : public IBinder::DeathRecipient {
ComposerServiceAIDL& mComposerService;
virtual void binderDied(const wp<IBinder>& who) {
ALOGW("ComposerService aidl remote (surfaceflinger) died [%p]", who.unsafe_get());
mComposerService.composerServiceDied();
}
public:
explicit DeathObserver(ComposerServiceAIDL& mgr) : mComposerService(mgr) {}
};
mDeathObserver = new DeathObserver(*const_cast<ComposerServiceAIDL*>(this));
IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
return true;
}
/*static*/ sp<gui::ISurfaceComposer> ComposerServiceAIDL::getComposerService() {
ComposerServiceAIDL& instance = ComposerServiceAIDL::getInstance();
std::scoped_lock lock(instance.mMutex);
if (instance.mComposerService == nullptr) {
if (ComposerServiceAIDL::getInstance().connectLocked()) {
ALOGD("ComposerServiceAIDL reconnected");
WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService);
}
}
return instance.mComposerService;
}
void ComposerServiceAIDL::composerServiceDied() {
std::scoped_lock lock(mMutex);
mComposerService = nullptr;
mDeathObserver = nullptr;
}
class DefaultComposerClient: public Singleton<DefaultComposerClient> {
Mutex mLock;
sp<SurfaceComposerClient> mClient;
friend class Singleton<ComposerService>;
public:
static sp<SurfaceComposerClient> getComposerClient() {
DefaultComposerClient& dc = DefaultComposerClient::getInstance();
Mutex::Autolock _l(dc.mLock);
if (dc.mClient == nullptr) {
dc.mClient = new SurfaceComposerClient;
}
return dc.mClient;
}
};
ANDROID_SINGLETON_STATIC_INSTANCE(DefaultComposerClient);
sp<SurfaceComposerClient> SurfaceComposerClient::getDefault() {
return DefaultComposerClient::getComposerClient();
}
JankDataListener::~JankDataListener() {
}
// ---------------------------------------------------------------------------
// TransactionCompletedListener does not use ANDROID_SINGLETON_STATIC_INSTANCE because it needs
// to be able to return a sp<> to its instance to pass to SurfaceFlinger.
// ANDROID_SINGLETON_STATIC_INSTANCE only allows a reference to an instance.
// 0 is an invalid callback id
TransactionCompletedListener::TransactionCompletedListener() : mCallbackIdCounter(1) {}
int64_t TransactionCompletedListener::getNextIdLocked() {
return mCallbackIdCounter++;
}
sp<TransactionCompletedListener> TransactionCompletedListener::sInstance = nullptr;
static std::mutex sListenerInstanceMutex;
void TransactionCompletedListener::setInstance(const sp<TransactionCompletedListener>& listener) {
sInstance = listener;
}
sp<TransactionCompletedListener> TransactionCompletedListener::getInstance() {
std::lock_guard<std::mutex> lock(sListenerInstanceMutex);
if (sInstance == nullptr) {
sInstance = new TransactionCompletedListener;
}
return sInstance;
}
sp<ITransactionCompletedListener> TransactionCompletedListener::getIInstance() {
return static_cast<sp<ITransactionCompletedListener>>(getInstance());
}
void TransactionCompletedListener::startListeningLocked() {
if (mListening) {
return;
}
ProcessState::self()->startThreadPool();
mListening = true;
}
CallbackId TransactionCompletedListener::addCallbackFunction(
const TransactionCompletedCallback& callbackFunction,
const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
surfaceControls,
CallbackId::Type callbackType) {
std::lock_guard<std::mutex> lock(mMutex);
return addCallbackFunctionLocked(callbackFunction, surfaceControls, callbackType);
}
CallbackId TransactionCompletedListener::addCallbackFunctionLocked(
const TransactionCompletedCallback& callbackFunction,
const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
surfaceControls,
CallbackId::Type callbackType) {
startListeningLocked();
CallbackId callbackId(getNextIdLocked(), callbackType);
mCallbacks[callbackId].callbackFunction = callbackFunction;
auto& callbackSurfaceControls = mCallbacks[callbackId].surfaceControls;
for (const auto& surfaceControl : surfaceControls) {
callbackSurfaceControls[surfaceControl->getHandle()] = surfaceControl;
if (callbackType == CallbackId::Type::ON_COMPLETE &&
mJankListeners.count(surfaceControl->getLayerId()) != 0) {
callbackId.includeJankData = true;
}
}
return callbackId;
}
void TransactionCompletedListener::addJankListener(const sp<JankDataListener>& listener,
sp<SurfaceControl> surfaceControl) {
std::lock_guard<std::mutex> lock(mMutex);
mJankListeners.insert({surfaceControl->getLayerId(), listener});
}
void TransactionCompletedListener::removeJankListener(const sp<JankDataListener>& listener) {
std::lock_guard<std::mutex> lock(mMutex);
for (auto it = mJankListeners.begin(); it != mJankListeners.end();) {
if (it->second == listener) {
it = mJankListeners.erase(it);
} else {
it++;
}
}
}
void TransactionCompletedListener::setReleaseBufferCallback(const ReleaseCallbackId& callbackId,
ReleaseBufferCallback listener) {
std::scoped_lock<std::mutex> lock(mMutex);
mReleaseBufferCallbacks[callbackId] = listener;
}
void TransactionCompletedListener::addSurfaceStatsListener(void* context, void* cookie,
sp<SurfaceControl> surfaceControl, SurfaceStatsCallback listener) {
std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
mSurfaceStatsListeners.insert(
{surfaceControl->getLayerId(), SurfaceStatsCallbackEntry(context, cookie, listener)});
}
void TransactionCompletedListener::removeSurfaceStatsListener(void* context, void* cookie) {
std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
for (auto it = mSurfaceStatsListeners.begin(); it != mSurfaceStatsListeners.end();) {
auto [itContext, itCookie, itListener] = it->second;
if (itContext == context && itCookie == cookie) {
it = mSurfaceStatsListeners.erase(it);
} else {
it++;
}
}
}
void TransactionCompletedListener::addSurfaceControlToCallbacks(
SurfaceComposerClient::CallbackInfo& callbackInfo,
const sp<SurfaceControl>& surfaceControl) {
std::lock_guard<std::mutex> lock(mMutex);
bool includingJankData = false;
for (auto callbackId : callbackInfo.callbackIds) {
mCallbacks[callbackId].surfaceControls.emplace(std::piecewise_construct,
std::forward_as_tuple(
surfaceControl->getHandle()),
std::forward_as_tuple(surfaceControl));
includingJankData = includingJankData || callbackId.includeJankData;
}
// If no registered callback is requesting jank data, but there is a jank listener registered
// on the new surface control, add a synthetic callback that requests the jank data.
if (!includingJankData && mJankListeners.count(surfaceControl->getLayerId()) != 0) {
CallbackId callbackId =
addCallbackFunctionLocked(&emptyCallback, callbackInfo.surfaceControls,
CallbackId::Type::ON_COMPLETE);
callbackInfo.callbackIds.emplace(callbackId);
}
}
void TransactionCompletedListener::onTransactionCompleted(ListenerStats listenerStats) {
std::unordered_map<CallbackId, CallbackTranslation, CallbackIdHash> callbacksMap;
std::multimap<int32_t, sp<JankDataListener>> jankListenersMap;
{
std::lock_guard<std::mutex> lock(mMutex);
/* This listener knows all the sp<IBinder> to sp<SurfaceControl> for all its registered
* callbackIds, except for when Transactions are merged together. This probably cannot be
* solved before this point because the Transactions could be merged together and applied in
* a different process.
*
* Fortunately, we get all the callbacks for this listener for the same frame together at
* the same time. This means if any Transactions were merged together, we will get their
* callbacks at the same time. We can combine all the sp<IBinder> to sp<SurfaceControl> maps
* for all the callbackIds to generate one super map that contains all the sp<IBinder> to
* sp<SurfaceControl> that could possibly exist for the callbacks.
*/
callbacksMap = mCallbacks;
jankListenersMap = mJankListeners;
for (const auto& transactionStats : listenerStats.transactionStats) {
for (auto& callbackId : transactionStats.callbackIds) {
mCallbacks.erase(callbackId);
}
}
}
for (const auto& transactionStats : listenerStats.transactionStats) {
// handle on commit callbacks
for (auto callbackId : transactionStats.callbackIds) {
if (callbackId.type != CallbackId::Type::ON_COMMIT) {
continue;
}
auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
if (!callbackFunction) {
continue;
}
std::vector<SurfaceControlStats> surfaceControlStats;
for (const auto& surfaceStats : transactionStats.surfaceStats) {
surfaceControlStats
.emplace_back(callbacksMap[callbackId]
.surfaceControls[surfaceStats.surfaceControl],
transactionStats.latchTime, surfaceStats.acquireTimeOrFence,
transactionStats.presentFence,
surfaceStats.previousReleaseFence, surfaceStats.transformHint,
surfaceStats.eventStats,
surfaceStats.currentMaxAcquiredBufferCount);
}
callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
surfaceControlStats);
// More than one transaction may contain the same callback id. Erase the callback from
// the map to ensure that it is only called once. This can happen if transactions are
// parcelled out of process and applied in both processes.
callbacksMap.erase(callbackId);
}
// handle on complete callbacks
for (auto callbackId : transactionStats.callbackIds) {
if (callbackId.type != CallbackId::Type::ON_COMPLETE) {
continue;
}
auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
if (!callbackFunction) {
ALOGE("cannot call null callback function, skipping");
continue;
}
std::vector<SurfaceControlStats> surfaceControlStats;
for (const auto& surfaceStats : transactionStats.surfaceStats) {
surfaceControlStats
.emplace_back(callbacksMap[callbackId]
.surfaceControls[surfaceStats.surfaceControl],
transactionStats.latchTime, surfaceStats.acquireTimeOrFence,
transactionStats.presentFence,
surfaceStats.previousReleaseFence, surfaceStats.transformHint,
surfaceStats.eventStats,
surfaceStats.currentMaxAcquiredBufferCount);
if (callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl] &&
surfaceStats.transformHint.has_value()) {
callbacksMap[callbackId]
.surfaceControls[surfaceStats.surfaceControl]
->setTransformHint(*surfaceStats.transformHint);
}
// If there is buffer id set, we look up any pending client release buffer callbacks
// and call them. This is a performance optimization when we have a transaction
// callback and a release buffer callback happening at the same time to avoid an
// additional ipc call from the server.
if (surfaceStats.previousReleaseCallbackId != ReleaseCallbackId::INVALID_ID) {
ReleaseBufferCallback callback;
{
std::scoped_lock<std::mutex> lock(mMutex);
callback = popReleaseBufferCallbackLocked(
surfaceStats.previousReleaseCallbackId);
}
if (callback) {
callback(surfaceStats.previousReleaseCallbackId,
surfaceStats.previousReleaseFence
? surfaceStats.previousReleaseFence
: Fence::NO_FENCE,
surfaceStats.currentMaxAcquiredBufferCount);
}
}
}
callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
surfaceControlStats);
}
}
for (const auto& transactionStats : listenerStats.transactionStats) {
for (const auto& surfaceStats : transactionStats.surfaceStats) {
// The callbackMap contains the SurfaceControl object, which we need to look up the
// layerId. Since we don't know which callback contains the SurfaceControl, iterate
// through all until the SC is found.
int32_t layerId = -1;
for (auto callbackId : transactionStats.callbackIds) {
if (callbackId.type != CallbackId::Type::ON_COMPLETE) {
// We only want to run the stats callback for ON_COMPLETE
continue;
}
sp<SurfaceControl> sc =
callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl];
if (sc != nullptr) {
layerId = sc->getLayerId();
break;
}
}
if (layerId != -1) {
// Acquire surface stats listener lock such that we guarantee that after calling
// unregister, there won't be any further callback.
std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
auto listenerRange = mSurfaceStatsListeners.equal_range(layerId);
for (auto it = listenerRange.first; it != listenerRange.second; it++) {
auto entry = it->second;
entry.callback(entry.context, transactionStats.latchTime,
transactionStats.presentFence, surfaceStats);
}
}
if (surfaceStats.jankData.empty()) continue;
auto jankRange = jankListenersMap.equal_range(layerId);
for (auto it = jankRange.first; it != jankRange.second; it++) {
it->second->onJankDataAvailable(surfaceStats.jankData);
}
}
}
}
void TransactionCompletedListener::onTransactionQueueStalled(const String8& reason) {
std::unordered_map<void*, std::function<void(const std::string&)>> callbackCopy;
{
std::scoped_lock<std::mutex> lock(mMutex);
callbackCopy = mQueueStallListeners;
}
for (auto const& it : callbackCopy) {
it.second(reason.c_str());
}
}
void TransactionCompletedListener::addQueueStallListener(
std::function<void(const std::string&)> stallListener, void* id) {
std::scoped_lock<std::mutex> lock(mMutex);
mQueueStallListeners[id] = stallListener;
}
void TransactionCompletedListener::removeQueueStallListener(void* id) {
std::scoped_lock<std::mutex> lock(mMutex);
mQueueStallListeners.erase(id);
}
void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId,
sp<Fence> releaseFence,
uint32_t currentMaxAcquiredBufferCount) {
ReleaseBufferCallback callback;
{
std::scoped_lock<std::mutex> lock(mMutex);
callback = popReleaseBufferCallbackLocked(callbackId);
}
if (!callback) {
ALOGE("Could not call release buffer callback, buffer not found %s",
callbackId.to_string().c_str());
return;
}
std::optional<uint32_t> optionalMaxAcquiredBufferCount =
currentMaxAcquiredBufferCount == UINT_MAX
? std::nullopt
: std::make_optional<uint32_t>(currentMaxAcquiredBufferCount);
callback(callbackId, releaseFence, optionalMaxAcquiredBufferCount);
}
ReleaseBufferCallback TransactionCompletedListener::popReleaseBufferCallbackLocked(
const ReleaseCallbackId& callbackId) {
ReleaseBufferCallback callback;
auto itr = mReleaseBufferCallbacks.find(callbackId);
if (itr == mReleaseBufferCallbacks.end()) {
return nullptr;
}
callback = itr->second;
mReleaseBufferCallbacks.erase(itr);
return callback;
}
void TransactionCompletedListener::removeReleaseBufferCallback(
const ReleaseCallbackId& callbackId) {
{
std::scoped_lock<std::mutex> lock(mMutex);
popReleaseBufferCallbackLocked(callbackId);
}
}
SurfaceComposerClient::PresentationCallbackRAII::PresentationCallbackRAII(
TransactionCompletedListener* tcl, int id) {
mTcl = tcl;
mId = id;
}
SurfaceComposerClient::PresentationCallbackRAII::~PresentationCallbackRAII() {
mTcl->clearTrustedPresentationCallback(mId);
}
sp<SurfaceComposerClient::PresentationCallbackRAII>
TransactionCompletedListener::addTrustedPresentationCallback(TrustedPresentationCallback tpc,
int id, void* context) {
std::scoped_lock<std::mutex> lock(mMutex);
mTrustedPresentationCallbacks[id] =
std::tuple<TrustedPresentationCallback, void*>(tpc, context);
return new SurfaceComposerClient::PresentationCallbackRAII(this, id);
}
void TransactionCompletedListener::clearTrustedPresentationCallback(int id) {
std::scoped_lock<std::mutex> lock(mMutex);
mTrustedPresentationCallbacks.erase(id);
}
void TransactionCompletedListener::onTrustedPresentationChanged(int id,
bool presentedWithinThresholds) {
TrustedPresentationCallback tpc;
void* context;
{
std::scoped_lock<std::mutex> lock(mMutex);
auto it = mTrustedPresentationCallbacks.find(id);
if (it == mTrustedPresentationCallbacks.end()) {
return;
}
std::tie(tpc, context) = it->second;
}
tpc(context, presentedWithinThresholds);
}
// ---------------------------------------------------------------------------
void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId);
/**
* We use the BufferCache to reduce the overhead of exchanging GraphicBuffers with
* the server. If we were to simply parcel the GraphicBuffer we would pay two overheads
* 1. Cost of sending the FD
* 2. Cost of importing the GraphicBuffer with the mapper in the receiving process.
* To ease this cost we implement the following scheme of caching buffers to integers,
* or said-otherwise, naming them with integers. This is the scheme known as slots in
* the legacy BufferQueue system.
* 1. When sending Buffers to SurfaceFlinger we look up the Buffer in the cache.
* 2. If there is a cache-hit we remove the Buffer from the Transaction and instead
* send the cached integer.
* 3. If there is a cache miss, we cache the new buffer and send the integer
* along with the Buffer, SurfaceFlinger on it's side creates a new cache
* entry, and we use the integer for further communication.
* A few details about lifetime:
* 1. The cache evicts by LRU. The server side cache is keyed by BufferCache::getToken
* which is per process Unique. The server side cache is larger than the client side
* cache so that the server will never evict entries before the client.
* 2. When the client evicts an entry it notifies the server via an uncacheBuffer
* transaction.
* 3. The client only references the Buffers by ID, and uses buffer->addDeathCallback
* to auto-evict destroyed buffers.
*/
class BufferCache : public Singleton<BufferCache> {
public:
BufferCache() : token(new BBinder()) {}
sp<IBinder> getToken() {
return IInterface::asBinder(TransactionCompletedListener::getIInstance());
}
status_t getCacheId(const sp<GraphicBuffer>& buffer, uint64_t* cacheId) {
std::lock_guard<std::mutex> lock(mMutex);
auto itr = mBuffers.find(buffer->getId());
if (itr == mBuffers.end()) {
return BAD_VALUE;
}
itr->second = getCounter();
*cacheId = buffer->getId();
return NO_ERROR;
}
uint64_t cache(const sp<GraphicBuffer>& buffer,
std::optional<client_cache_t>& outUncacheBuffer) {
std::lock_guard<std::mutex> lock(mMutex);
if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) {
outUncacheBuffer = findLeastRecentlyUsedBuffer();
mBuffers.erase(outUncacheBuffer->id);
}
buffer->addDeathCallback(removeDeadBufferCallback, nullptr);
mBuffers[buffer->getId()] = getCounter();
return buffer->getId();
}
void uncache(uint64_t cacheId) {
std::lock_guard<std::mutex> lock(mMutex);
if (mBuffers.erase(cacheId)) {
SurfaceComposerClient::doUncacheBufferTransaction(cacheId);
}
}
private:
client_cache_t findLeastRecentlyUsedBuffer() REQUIRES(mMutex) {
auto itr = mBuffers.begin();
uint64_t minCounter = itr->second;
auto minBuffer = itr;
itr++;
while (itr != mBuffers.end()) {
uint64_t counter = itr->second;
if (counter < minCounter) {
minCounter = counter;
minBuffer = itr;
}
itr++;
}
return {.token = getToken(), .id = minBuffer->first};
}
uint64_t getCounter() REQUIRES(mMutex) {
static uint64_t counter = 0;
return counter++;
}
std::mutex mMutex;
std::map<uint64_t /*Cache id*/, uint64_t /*counter*/> mBuffers GUARDED_BY(mMutex);
// Used by ISurfaceComposer to identify which process is sending the cached buffer.
sp<IBinder> token;
};
ANDROID_SINGLETON_STATIC_INSTANCE(BufferCache);
void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId) {
// GraphicBuffer id's are used as the cache ids.
BufferCache::getInstance().uncache(graphicBufferId);
}
// ---------------------------------------------------------------------------
SurfaceComposerClient::Transaction::Transaction() {
mId = generateId();
}
SurfaceComposerClient::Transaction::Transaction(const Transaction& other)
: mId(other.mId),
mTransactionNestCount(other.mTransactionNestCount),
mAnimation(other.mAnimation),
mEarlyWakeupStart(other.mEarlyWakeupStart),
mEarlyWakeupEnd(other.mEarlyWakeupEnd),
mMayContainBuffer(other.mMayContainBuffer),
mDesiredPresentTime(other.mDesiredPresentTime),
mIsAutoTimestamp(other.mIsAutoTimestamp),
mFrameTimelineInfo(other.mFrameTimelineInfo),
mApplyToken(other.mApplyToken) {
mDisplayStates = other.mDisplayStates;
mComposerStates = other.mComposerStates;
mInputWindowCommands = other.mInputWindowCommands;
mListenerCallbacks = other.mListenerCallbacks;
}
void SurfaceComposerClient::Transaction::sanitize(int pid, int uid) {
uint32_t permissions = LayerStatePermissions::getTransactionPermissions(pid, uid);
for (auto & [handle, composerState] : mComposerStates) {
composerState.state.sanitize(permissions);
}
if (!mInputWindowCommands.empty() &&
(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) {
ALOGE("Only privileged callers are allowed to send input commands.");
mInputWindowCommands.clear();
}
}
std::unique_ptr<SurfaceComposerClient::Transaction>
SurfaceComposerClient::Transaction::createFromParcel(const Parcel* parcel) {
auto transaction = std::make_unique<Transaction>();
if (transaction->readFromParcel(parcel) == NO_ERROR) {
return transaction;
}
return nullptr;
}
status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel) {
const uint64_t transactionId = parcel->readUint64();
const uint32_t transactionNestCount = parcel->readUint32();
const bool animation = parcel->readBool();
const bool earlyWakeupStart = parcel->readBool();
const bool earlyWakeupEnd = parcel->readBool();
const int64_t desiredPresentTime = parcel->readInt64();
const bool isAutoTimestamp = parcel->readBool();
FrameTimelineInfo frameTimelineInfo;
frameTimelineInfo.readFromParcel(parcel);
sp<IBinder> applyToken;
parcel->readNullableStrongBinder(&applyToken);
size_t count = static_cast<size_t>(parcel->readUint32());
if (count > parcel->dataSize()) {
return BAD_VALUE;
}
SortedVector<DisplayState> displayStates;
displayStates.setCapacity(count);
for (size_t i = 0; i < count; i++) {
DisplayState displayState;
if (displayState.read(*parcel) == BAD_VALUE) {
return BAD_VALUE;
}
displayStates.add(displayState);
}
count = static_cast<size_t>(parcel->readUint32());
if (count > parcel->dataSize()) {
return BAD_VALUE;
}
std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash> listenerCallbacks;
listenerCallbacks.reserve(count);
for (size_t i = 0; i < count; i++) {
sp<ITransactionCompletedListener> listener =
interface_cast<ITransactionCompletedListener>(parcel->readStrongBinder());
size_t numCallbackIds = parcel->readUint32();
if (numCallbackIds > parcel->dataSize()) {
return BAD_VALUE;
}
for (size_t j = 0; j < numCallbackIds; j++) {
CallbackId id;
parcel->readParcelable(&id);
listenerCallbacks[listener].callbackIds.insert(id);
}
size_t numSurfaces = parcel->readUint32();
if (numSurfaces > parcel->dataSize()) {
return BAD_VALUE;
}
for (size_t j = 0; j < numSurfaces; j++) {
sp<SurfaceControl> surface;
SAFE_PARCEL(SurfaceControl::readFromParcel, *parcel, &surface);
listenerCallbacks[listener].surfaceControls.insert(surface);
}
}
count = static_cast<size_t>(parcel->readUint32());
if (count > parcel->dataSize()) {
return BAD_VALUE;
}
std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> composerStates;
composerStates.reserve(count);
for (size_t i = 0; i < count; i++) {
sp<IBinder> surfaceControlHandle;
SAFE_PARCEL(parcel->readStrongBinder, &surfaceControlHandle);
ComposerState composerState;
if (composerState.read(*parcel) == BAD_VALUE) {
return BAD_VALUE;
}
composerStates[surfaceControlHandle] = composerState;
}
InputWindowCommands inputWindowCommands;
inputWindowCommands.read(*parcel);
count = static_cast<size_t>(parcel->readUint32());
if (count > parcel->dataSize()) {
return BAD_VALUE;
}
std::vector<client_cache_t> uncacheBuffers(count);
for (size_t i = 0; i < count; i++) {
sp<IBinder> tmpBinder;
SAFE_PARCEL(parcel->readStrongBinder, &tmpBinder);
uncacheBuffers[i].token = tmpBinder;
SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id);
}
count = static_cast<size_t>(parcel->readUint32());
if (count > parcel->dataSize()) {
return BAD_VALUE;
}
std::vector<uint64_t> mergedTransactionIds(count);
for (size_t i = 0; i < count; i++) {
SAFE_PARCEL(parcel->readUint64, &mergedTransactionIds[i]);
}
// Parsing was successful. Update the object.
mId = transactionId;
mTransactionNestCount = transactionNestCount;
mAnimation = animation;
mEarlyWakeupStart = earlyWakeupStart;
mEarlyWakeupEnd = earlyWakeupEnd;
mDesiredPresentTime = desiredPresentTime;
mIsAutoTimestamp = isAutoTimestamp;
mFrameTimelineInfo = frameTimelineInfo;
mDisplayStates = displayStates;
mListenerCallbacks = listenerCallbacks;
mComposerStates = composerStates;
mInputWindowCommands = inputWindowCommands;
mApplyToken = applyToken;
mUncacheBuffers = std::move(uncacheBuffers);
mMergedTransactionIds = std::move(mergedTransactionIds);
return NO_ERROR;
}
status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const {
// If we write the Transaction to a parcel, we want to ensure the Buffers are cached
// before crossing the IPC boundary. Otherwise the receiving party will cache the buffers
// but is unlikely to use them again as they are owned by the other process.
// You may be asking yourself, is this const cast safe? Const cast is safe up
// until the point where you try and write to an object that was originally const at which
// point we enter undefined behavior. In this case we are safe though, because there are
// two possibilities:
// 1. The SurfaceComposerClient::Transaction was originally non-const. Safe.
// 2. It was originall const! In this case not only was it useless, but it by definition
// contains no composer states and so cacheBuffers will not perform any writes.
const_cast<SurfaceComposerClient::Transaction*>(this)->cacheBuffers();
parcel->writeUint64(mId);
parcel->writeUint32(mTransactionNestCount);
parcel->writeBool(mAnimation);
parcel->writeBool(mEarlyWakeupStart);
parcel->writeBool(mEarlyWakeupEnd);
parcel->writeInt64(mDesiredPresentTime);
parcel->writeBool(mIsAutoTimestamp);
mFrameTimelineInfo.writeToParcel(parcel);
parcel->writeStrongBinder(mApplyToken);
parcel->writeUint32(static_cast<uint32_t>(mDisplayStates.size()));
for (auto const& displayState : mDisplayStates) {
displayState.write(*parcel);
}
parcel->writeUint32(static_cast<uint32_t>(mListenerCallbacks.size()));
for (auto const& [listener, callbackInfo] : mListenerCallbacks) {
parcel->writeStrongBinder(ITransactionCompletedListener::asBinder(listener));
parcel->writeUint32(static_cast<uint32_t>(callbackInfo.callbackIds.size()));
for (auto callbackId : callbackInfo.callbackIds) {
parcel->writeParcelable(callbackId);
}
parcel->writeUint32(static_cast<uint32_t>(callbackInfo.surfaceControls.size()));
for (auto surfaceControl : callbackInfo.surfaceControls) {
SAFE_PARCEL(surfaceControl->writeToParcel, *parcel);
}
}
parcel->writeUint32(static_cast<uint32_t>(mComposerStates.size()));
for (auto const& [handle, composerState] : mComposerStates) {
SAFE_PARCEL(parcel->writeStrongBinder, handle);
composerState.write(*parcel);
}
mInputWindowCommands.write(*parcel);
SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(mUncacheBuffers.size()));
for (const client_cache_t& uncacheBuffer : mUncacheBuffers) {
SAFE_PARCEL(parcel->writeStrongBinder, uncacheBuffer.token.promote());
SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id);
}
SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(mMergedTransactionIds.size()));
for (auto mergedTransactionId : mMergedTransactionIds) {
SAFE_PARCEL(parcel->writeUint64, mergedTransactionId);
}
return NO_ERROR;
}
void SurfaceComposerClient::Transaction::releaseBufferIfOverwriting(const layer_state_t& state) {
if (!(state.what & layer_state_t::eBufferChanged) || !state.bufferData->hasBuffer()) {
return;
}
auto listener = state.bufferData->releaseBufferListener;
sp<Fence> fence =
state.bufferData->acquireFence ? state.bufferData->acquireFence : Fence::NO_FENCE;
if (state.bufferData->releaseBufferEndpoint ==
IInterface::asBinder(TransactionCompletedListener::getIInstance())) {
// if the callback is in process, run on a different thread to avoid any lock contigency
// issues in the client.
SurfaceComposerClient::getDefault()
->mReleaseCallbackThread
.addReleaseCallback(state.bufferData->generateReleaseCallbackId(), fence);
} else {
listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fence, UINT_MAX);
}
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Transaction&& other) {
while (mMergedTransactionIds.size() + other.mMergedTransactionIds.size() >
MAX_MERGE_HISTORY_LENGTH - 1 &&
mMergedTransactionIds.size() > 0) {
mMergedTransactionIds.pop_back();
}
if (other.mMergedTransactionIds.size() == MAX_MERGE_HISTORY_LENGTH) {
mMergedTransactionIds.insert(mMergedTransactionIds.begin(),
other.mMergedTransactionIds.begin(),
other.mMergedTransactionIds.end() - 1);
} else if (other.mMergedTransactionIds.size() > 0u) {
mMergedTransactionIds.insert(mMergedTransactionIds.begin(),
other.mMergedTransactionIds.begin(),
other.mMergedTransactionIds.end());
}
mMergedTransactionIds.insert(mMergedTransactionIds.begin(), other.mId);
for (auto const& [handle, composerState] : other.mComposerStates) {
if (mComposerStates.count(handle) == 0) {
mComposerStates[handle] = composerState;
} else {
if (composerState.state.what & layer_state_t::eBufferChanged) {
releaseBufferIfOverwriting(mComposerStates[handle].state);
}
mComposerStates[handle].state.merge(composerState.state);
}
}
for (auto const& state : other.mDisplayStates) {
ssize_t index = mDisplayStates.indexOf(state);
if (index < 0) {
mDisplayStates.add(state);
} else {
mDisplayStates.editItemAt(static_cast<size_t>(index)).merge(state);
}
}
for (const auto& [listener, callbackInfo] : other.mListenerCallbacks) {
auto& [callbackIds, surfaceControls] = callbackInfo;
mListenerCallbacks[listener].callbackIds.insert(std::make_move_iterator(
callbackIds.begin()),
std::make_move_iterator(callbackIds.end()));
mListenerCallbacks[listener].surfaceControls.insert(surfaceControls.begin(),
surfaceControls.end());
auto& currentProcessCallbackInfo =
mListenerCallbacks[TransactionCompletedListener::getIInstance()];
currentProcessCallbackInfo.surfaceControls
.insert(std::make_move_iterator(surfaceControls.begin()),
std::make_move_iterator(surfaceControls.end()));
// register all surface controls for all callbackIds for this listener that is merging
for (const auto& surfaceControl : currentProcessCallbackInfo.surfaceControls) {
TransactionCompletedListener::getInstance()
->addSurfaceControlToCallbacks(currentProcessCallbackInfo, surfaceControl);
}
}
for (const auto& cacheId : other.mUncacheBuffers) {
mUncacheBuffers.push_back(cacheId);
}
mInputWindowCommands.merge(other.mInputWindowCommands);
mMayContainBuffer |= other.mMayContainBuffer;
mEarlyWakeupStart = mEarlyWakeupStart || other.mEarlyWakeupStart;
mEarlyWakeupEnd = mEarlyWakeupEnd || other.mEarlyWakeupEnd;
mApplyToken = other.mApplyToken;
mergeFrameTimelineInfo(mFrameTimelineInfo, other.mFrameTimelineInfo);
other.clear();
return *this;
}
void SurfaceComposerClient::Transaction::clear() {
mComposerStates.clear();
mDisplayStates.clear();
mListenerCallbacks.clear();
mInputWindowCommands.clear();
mUncacheBuffers.clear();
mMayContainBuffer = false;
mTransactionNestCount = 0;
mAnimation = false;
mEarlyWakeupStart = false;
mEarlyWakeupEnd = false;
mDesiredPresentTime = 0;
mIsAutoTimestamp = true;
mFrameTimelineInfo = {};
mApplyToken = nullptr;
mMergedTransactionIds.clear();
}
uint64_t SurfaceComposerClient::Transaction::getId() {
return mId;
}
std::vector<uint64_t> SurfaceComposerClient::Transaction::getMergedTransactionIds() {
return mMergedTransactionIds;
}
void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) {
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
client_cache_t uncacheBuffer;
uncacheBuffer.token = BufferCache::getInstance().getToken();
uncacheBuffer.id = cacheId;
Vector<ComposerState> composerStates;
status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {},
ISurfaceComposer::eOneWay,
Transaction::getDefaultApplyToken(), {}, systemTime(),
true, {uncacheBuffer}, false, {}, generateId(), {});
if (status != NO_ERROR) {
ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s",
strerror(-status));
}
}
void SurfaceComposerClient::Transaction::cacheBuffers() {
if (!mMayContainBuffer) {
return;
}
size_t count = 0;
for (auto& [handle, cs] : mComposerStates) {
layer_state_t* s = &(mComposerStates[handle].state);
if (!(s->what & layer_state_t::eBufferChanged)) {
continue;
} else if (s->bufferData &&
s->bufferData->flags.test(BufferData::BufferDataChange::cachedBufferChanged)) {
// If eBufferChanged and eCachedBufferChanged are both trued then that means
// we already cached the buffer in a previous call to cacheBuffers, perhaps
// from writeToParcel on a Transaction that was merged in to this one.
continue;
}
// Don't try to cache a null buffer. Sending null buffers is cheap so we shouldn't waste
// time trying to cache them.
if (!s->bufferData || !s->bufferData->buffer) {
continue;
}
uint64_t cacheId = 0;
status_t ret = BufferCache::getInstance().getCacheId(s->bufferData->buffer, &cacheId);
if (ret == NO_ERROR) {
// Cache-hit. Strip the buffer and send only the id.
s->bufferData->buffer = nullptr;
} else {
// Cache-miss. Include the buffer and send the new cacheId.
std::optional<client_cache_t> uncacheBuffer;
cacheId = BufferCache::getInstance().cache(s->bufferData->buffer, uncacheBuffer);
if (uncacheBuffer) {
mUncacheBuffers.push_back(*uncacheBuffer);
}
}
s->bufferData->flags |= BufferData::BufferDataChange::cachedBufferChanged;
s->bufferData->cachedBuffer.token = BufferCache::getInstance().getToken();
s->bufferData->cachedBuffer.id = cacheId;
// If we have more buffers than the size of the cache, we should stop caching so we don't
// evict other buffers in this transaction
count++;
if (count >= BUFFER_CACHE_MAX_SIZE) {
break;
}
}
}
class SyncCallback {
public:
static auto getCallback(std::shared_ptr<SyncCallback>& callbackContext) {
return [callbackContext](void* /* unused context */, nsecs_t /* latchTime */,
const sp<Fence>& /* presentFence */,
const std::vector<SurfaceControlStats>& /* stats */) {
if (!callbackContext) {
ALOGE("failed to get callback context for SyncCallback");
return;
}
LOG_ALWAYS_FATAL_IF(sem_post(&callbackContext->mSemaphore), "sem_post failed");
};
}
~SyncCallback() {
if (mInitialized) {
LOG_ALWAYS_FATAL_IF(sem_destroy(&mSemaphore), "sem_destroy failed");
}
}
void init() {
LOG_ALWAYS_FATAL_IF(clock_gettime(CLOCK_MONOTONIC, &mTimeoutTimespec) == -1,
"clock_gettime() fail! in SyncCallback::init");
mTimeoutTimespec.tv_sec += 4;
LOG_ALWAYS_FATAL_IF(sem_init(&mSemaphore, 0, 0), "sem_init failed");
mInitialized = true;
}
void wait() {
int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &mTimeoutTimespec);
if (result && errno != ETIMEDOUT && errno != EINTR) {
LOG_ALWAYS_FATAL("sem_clockwait failed(%d)", errno);
} else if (errno == ETIMEDOUT) {
ALOGW("Sync transaction timed out waiting for commit callback.");
}
}
void* getContext() { return static_cast<void*>(this); }
private:
sem_t mSemaphore;
bool mInitialized = false;
timespec mTimeoutTimespec;
};
status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay) {
if (mStatus != NO_ERROR) {
return mStatus;
}
std::shared_ptr<SyncCallback> syncCallback = std::make_shared<SyncCallback>();
if (synchronous) {
syncCallback->init();
addTransactionCommittedCallback(SyncCallback::getCallback(syncCallback),
/*callbackContext=*/nullptr);
}
bool hasListenerCallbacks = !mListenerCallbacks.empty();
std::vector<ListenerCallbacks> listenerCallbacks;
// For every listener with registered callbacks
for (const auto& [listener, callbackInfo] : mListenerCallbacks) {
auto& [callbackIds, surfaceControls] = callbackInfo;
if (callbackIds.empty()) {
continue;
}
if (surfaceControls.empty()) {
listenerCallbacks.emplace_back(IInterface::asBinder(listener), std::move(callbackIds));
} else {
// If the listener has any SurfaceControls set on this Transaction update the surface
// state
for (const auto& surfaceControl : surfaceControls) {
layer_state_t* s = getLayerState(surfaceControl);
if (!s) {
ALOGE("failed to get layer state");
continue;
}
std::vector<CallbackId> callbacks(callbackIds.begin(), callbackIds.end());
s->what |= layer_state_t::eHasListenerCallbacksChanged;
s->listeners.emplace_back(IInterface::asBinder(listener), callbacks);
}
}
}
cacheBuffers();
Vector<ComposerState> composerStates;
Vector<DisplayState> displayStates;
uint32_t flags = 0;
for (auto const& kv : mComposerStates) {
composerStates.add(kv.second);
}
displayStates = std::move(mDisplayStates);
if (mAnimation) {
flags |= ISurfaceComposer::eAnimation;
}
if (oneWay) {
if (synchronous) {
ALOGE("Transaction attempted to set synchronous and one way at the same time"
" this is an invalid request. Synchronous will win for safety");
} else {
flags |= ISurfaceComposer::eOneWay;
}
}
// If both mEarlyWakeupStart and mEarlyWakeupEnd are set
// it is equivalent for none
if (mEarlyWakeupStart && !mEarlyWakeupEnd) {
flags |= ISurfaceComposer::eEarlyWakeupStart;
}
if (mEarlyWakeupEnd && !mEarlyWakeupStart) {
flags |= ISurfaceComposer::eEarlyWakeupEnd;
}
sp<IBinder> applyToken = mApplyToken ? mApplyToken : getDefaultApplyToken();
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId,
mMergedTransactionIds);
mId = generateId();
// Clear the current states and flags
clear();
if (synchronous) {
syncCallback->wait();
}
mStatus = NO_ERROR;
return NO_ERROR;
}
sp<IBinder> SurfaceComposerClient::Transaction::sApplyToken = new BBinder();
std::mutex SurfaceComposerClient::Transaction::sApplyTokenMutex;
sp<IBinder> SurfaceComposerClient::Transaction::getDefaultApplyToken() {
std::scoped_lock lock{sApplyTokenMutex};
return sApplyToken;
}
void SurfaceComposerClient::Transaction::setDefaultApplyToken(sp<IBinder> applyToken) {
std::scoped_lock lock{sApplyTokenMutex};
sApplyToken = applyToken;
}
status_t SurfaceComposerClient::Transaction::sendSurfaceFlushJankDataTransaction(
const sp<SurfaceControl>& sc) {
Transaction t;
layer_state_t* s = t.getLayerState(sc);
if (!s) {
return BAD_INDEX;
}
s->what |= layer_state_t::eFlushJankData;
t.registerSurfaceControlForCallback(sc);
return t.apply(/*sync=*/false, /* oneWay=*/true);
}
// ---------------------------------------------------------------------------
sp<IBinder> SurfaceComposerClient::createDisplay(const String8& displayName, bool secure,
float requestedRefereshRate) {
sp<IBinder> display = nullptr;
binder::Status status =
ComposerServiceAIDL::getComposerService()->createDisplay(std::string(
displayName.c_str()),
secure, requestedRefereshRate,
&display);
return status.isOk() ? display : nullptr;
}
void SurfaceComposerClient::destroyDisplay(const sp<IBinder>& display) {
ComposerServiceAIDL::getComposerService()->destroyDisplay(display);
}
std::vector<PhysicalDisplayId> SurfaceComposerClient::getPhysicalDisplayIds() {
std::vector<int64_t> displayIds;
std::vector<PhysicalDisplayId> physicalDisplayIds;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getPhysicalDisplayIds(&displayIds);
if (status.isOk()) {
physicalDisplayIds.reserve(displayIds.size());
for (auto item : displayIds) {
auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(item));
physicalDisplayIds.push_back(*id);
}
}
return physicalDisplayIds;
}
sp<IBinder> SurfaceComposerClient::getPhysicalDisplayToken(PhysicalDisplayId displayId) {
sp<IBinder> display = nullptr;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getPhysicalDisplayToken(displayId.value,
&display);
return status.isOk() ? display : nullptr;
}
std::optional<gui::StalledTransactionInfo> SurfaceComposerClient::getStalledTransactionInfo(
pid_t pid) {
std::optional<gui::StalledTransactionInfo> result;
ComposerServiceAIDL::getComposerService()->getStalledTransactionInfo(pid, &result);
return result;
}
void SurfaceComposerClient::Transaction::setAnimationTransaction() {
mAnimation = true;
}
void SurfaceComposerClient::Transaction::setEarlyWakeupStart() {
mEarlyWakeupStart = true;
}
void SurfaceComposerClient::Transaction::setEarlyWakeupEnd() {
mEarlyWakeupEnd = true;
}
layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
auto handle = sc->getLayerStateHandle();
if (mComposerStates.count(handle) == 0) {
// we don't have it, add an initialized layer_state to our list
ComposerState s;
s.state.surface = handle;
s.state.layerId = sc->getLayerId();
mComposerStates[handle] = s;
}
return &(mComposerStates[handle].state);
}
void SurfaceComposerClient::Transaction::registerSurfaceControlForCallback(
const sp<SurfaceControl>& sc) {
auto& callbackInfo = mListenerCallbacks[TransactionCompletedListener::getIInstance()];
callbackInfo.surfaceControls.insert(sc);
TransactionCompletedListener::getInstance()->addSurfaceControlToCallbacks(callbackInfo, sc);
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
const sp<SurfaceControl>& sc, float x, float y) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::ePositionChanged;
s->x = x;
s->y = y;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::show(
const sp<SurfaceControl>& sc) {
return setFlags(sc, 0, layer_state_t::eLayerHidden);
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::hide(
const sp<SurfaceControl>& sc) {
return setFlags(sc, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden);
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
const sp<SurfaceControl>& sc, int32_t z) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eLayerChanged;
s->what &= ~layer_state_t::eRelativeLayerChanged;
s->z = z;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setRelativeLayer(
const sp<SurfaceControl>& sc, const sp<SurfaceControl>& relativeTo, int32_t z) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eRelativeLayerChanged;
s->what &= ~layer_state_t::eLayerChanged;
s->relativeLayerSurfaceControl = relativeTo;
s->z = z;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFlags(
const sp<SurfaceControl>& sc, uint32_t flags,
uint32_t mask) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
if ((mask & layer_state_t::eLayerOpaque) || (mask & layer_state_t::eLayerHidden) ||
(mask & layer_state_t::eLayerSecure) || (mask & layer_state_t::eLayerSkipScreenshot) ||
(mask & layer_state_t::eEnableBackpressure) ||
(mask & layer_state_t::eIgnoreDestinationFrame) ||
(mask & layer_state_t::eLayerIsDisplayDecoration) ||
(mask & layer_state_t::eLayerIsRefreshRateIndicator)) {
s->what |= layer_state_t::eFlagsChanged;
}
s->flags &= ~mask;
s->flags |= (flags & mask);
s->mask |= mask;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransparentRegionHint(
const sp<SurfaceControl>& sc,
const Region& transparentRegion) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eTransparentRegionChanged;
s->transparentRegion = transparentRegion;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDimmingEnabled(
const sp<SurfaceControl>& sc, bool dimmingEnabled) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDimmingEnabledChanged;
s->dimmingEnabled = dimmingEnabled;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAlpha(
const sp<SurfaceControl>& sc, float alpha) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
if (alpha < 0.0f || alpha > 1.0f) {
ALOGE("SurfaceComposerClient::Transaction::setAlpha: invalid alpha %f, clamping", alpha);
}
s->what |= layer_state_t::eAlphaChanged;
s->color.a = std::clamp(alpha, 0.f, 1.f);
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayerStack(
const sp<SurfaceControl>& sc, ui::LayerStack layerStack) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eLayerStackChanged;
s->layerStack = layerStack;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMetadata(
const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eMetadataChanged;
s->metadata.mMap[key] = {p.data(), p.data() + p.dataSize()};
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMatrix(
const sp<SurfaceControl>& sc, float dsdx, float dtdx,
float dtdy, float dsdy) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eMatrixChanged;
layer_state_t::matrix22_t matrix;
matrix.dsdx = dsdx;
matrix.dtdx = dtdx;
matrix.dsdy = dsdy;
matrix.dtdy = dtdy;
s->matrix = matrix;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCrop(
const sp<SurfaceControl>& sc, const Rect& crop) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eCropChanged;
s->crop = crop;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCornerRadius(
const sp<SurfaceControl>& sc, float cornerRadius) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eCornerRadiusChanged;
s->cornerRadius = cornerRadius;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundBlurRadius(
const sp<SurfaceControl>& sc, int backgroundBlurRadius) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eBackgroundBlurRadiusChanged;
s->backgroundBlurRadius = backgroundBlurRadius;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBlurRegions(
const sp<SurfaceControl>& sc, const std::vector<BlurRegion>& blurRegions) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eBlurRegionsChanged;
s->blurRegions = blurRegions;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::reparent(
const sp<SurfaceControl>& sc, const sp<SurfaceControl>& newParent) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
if (SurfaceControl::isSameSurface(sc, newParent)) {
return *this;
}
s->what |= layer_state_t::eReparent;
s->parentSurfaceControlForChild = newParent ? newParent->getParentingLayer() : nullptr;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColor(
const sp<SurfaceControl>& sc,
const half3& color) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eColorChanged;
s->color.rgb = color;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundColor(
const sp<SurfaceControl>& sc, const half3& color, float alpha, ui::Dataspace dataspace) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eBackgroundColorChanged;
s->bgColor.rgb = color;
s->bgColor.a = alpha;
s->bgColorDataspace = dataspace;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransform(
const sp<SurfaceControl>& sc, uint32_t transform) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eBufferTransformChanged;
s->bufferTransform = transform;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
bool transformToDisplayInverse) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eTransformToDisplayInverseChanged;
s->transformToDisplayInverse = transformToDisplayInverse;
registerSurfaceControlForCallback(sc);
return *this;
}
std::shared_ptr<BufferData> SurfaceComposerClient::Transaction::getAndClearBuffer(
const sp<SurfaceControl>& sc) {
layer_state_t* s = getLayerState(sc);
if (!s) {
return nullptr;
}
if (!(s->what & layer_state_t::eBufferChanged)) {
return nullptr;
}
std::shared_ptr<BufferData> bufferData = std::move(s->bufferData);
TransactionCompletedListener::getInstance()->removeReleaseBufferCallback(
bufferData->generateReleaseCallbackId());
s->what &= ~layer_state_t::eBufferChanged;
s->bufferData = nullptr;
return bufferData;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBufferHasBarrier(
const sp<SurfaceControl>& sc, uint64_t barrierFrameNumber) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->bufferData->hasBarrier = true;
s->bufferData->barrierFrameNumber = barrierFrameNumber;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBuffer(
const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer,
const std::optional<sp<Fence>>& fence, const std::optional<uint64_t>& optFrameNumber,
uint32_t producerId, ReleaseBufferCallback callback) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
releaseBufferIfOverwriting(*s);
std::shared_ptr<BufferData> bufferData = std::make_shared<BufferData>();
bufferData->buffer = buffer;
if (buffer) {
uint64_t frameNumber = sc->resolveFrameNumber(optFrameNumber);
bufferData->frameNumber = frameNumber;
bufferData->producerId = producerId;
bufferData->flags |= BufferData::BufferDataChange::frameNumberChanged;
if (fence) {
bufferData->acquireFence = *fence;
bufferData->flags |= BufferData::BufferDataChange::fenceChanged;
}
bufferData->releaseBufferEndpoint =
IInterface::asBinder(TransactionCompletedListener::getIInstance());
setReleaseBufferCallback(bufferData.get(), callback);
}
if (mIsAutoTimestamp) {
mDesiredPresentTime = systemTime();
}
s->what |= layer_state_t::eBufferChanged;
s->bufferData = std::move(bufferData);
registerSurfaceControlForCallback(sc);
// With the current infrastructure, a release callback will not be invoked if there's no
// transaction callback in the case when a buffer is latched and not released early. This is
// because the legacy implementation didn't have a release callback and sent releases in the
// transaction callback. Because of this, we need to make sure to have a transaction callback
// set up when a buffer is sent in a transaction to ensure the caller gets the release
// callback, regardless if they set up a transaction callback.
//
// TODO (b/230380821): Remove when release callbacks are separated from transaction callbacks
addTransactionCompletedCallback([](void*, nsecs_t, const sp<Fence>&,
const std::vector<SurfaceControlStats>&) {},
nullptr);
mMayContainBuffer = true;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::unsetBuffer(
const sp<SurfaceControl>& sc) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
if (!(s->what & layer_state_t::eBufferChanged)) {
return *this;
}
releaseBufferIfOverwriting(*s);
s->what &= ~layer_state_t::eBufferChanged;
s->bufferData = nullptr;
return *this;
}
void SurfaceComposerClient::Transaction::setReleaseBufferCallback(BufferData* bufferData,
ReleaseBufferCallback callback) {
if (!callback) {
return;
}
if (!bufferData->buffer) {
ALOGW("Transaction::setReleaseBufferCallback"
"ignored trying to set a callback on a null buffer.");
return;
}
bufferData->releaseBufferListener = TransactionCompletedListener::getIInstance();
auto listener = TransactionCompletedListener::getInstance();
listener->setReleaseBufferCallback(bufferData->generateReleaseCallbackId(), callback);
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDataspace(
const sp<SurfaceControl>& sc, ui::Dataspace dataspace) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDataspaceChanged;
s->dataspace = dataspace;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setExtendedRangeBrightness(
const sp<SurfaceControl>& sc, float currentBufferRatio, float desiredRatio) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eExtendedRangeBrightnessChanged;
s->currentHdrSdrRatio = currentBufferRatio;
s->desiredHdrSdrRatio = desiredRatio;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDesiredHdrHeadroom(
const sp<SurfaceControl>& sc, float desiredRatio) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDesiredHdrHeadroomChanged;
s->desiredHdrSdrRatio = desiredRatio;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCachingHint(
const sp<SurfaceControl>& sc, gui::CachingHint cachingHint) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eCachingHintChanged;
s->cachingHint = cachingHint;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setHdrMetadata(
const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eHdrMetadataChanged;
s->hdrMetadata = hdrMetadata;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSurfaceDamageRegion(
const sp<SurfaceControl>& sc, const Region& surfaceDamageRegion) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eSurfaceDamageRegionChanged;
s->surfaceDamageRegion = surfaceDamageRegion;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApi(
const sp<SurfaceControl>& sc, int32_t api) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eApiChanged;
s->api = api;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSidebandStream(
const sp<SurfaceControl>& sc, const sp<NativeHandle>& sidebandStream) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eSidebandStreamChanged;
s->sidebandStream = sidebandStream;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDesiredPresentTime(
nsecs_t desiredPresentTime) {
mDesiredPresentTime = desiredPresentTime;
mIsAutoTimestamp = false;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorSpaceAgnostic(
const sp<SurfaceControl>& sc, const bool agnostic) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eColorSpaceAgnosticChanged;
s->colorSpaceAgnostic = agnostic;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::setFrameRateSelectionPriority(const sp<SurfaceControl>& sc,
int32_t priority) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eFrameRateSelectionPriority;
s->frameRateSelectionPriority = priority;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::addTransactionCallback(
TransactionCompletedCallbackTakesContext callback, void* callbackContext,
CallbackId::Type callbackType) {
auto listener = TransactionCompletedListener::getInstance();
auto callbackWithContext = std::bind(callback, callbackContext, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
const auto& surfaceControls =
mListenerCallbacks[TransactionCompletedListener::getIInstance()].surfaceControls;
CallbackId callbackId =
listener->addCallbackFunction(callbackWithContext, surfaceControls, callbackType);
mListenerCallbacks[TransactionCompletedListener::getIInstance()].callbackIds.emplace(
callbackId);
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::addTransactionCompletedCallback(
TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMPLETE);
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::addTransactionCommittedCallback(
TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMMIT);
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::notifyProducerDisconnect(
const sp<SurfaceControl>& sc) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eProducerDisconnect;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
const sp<SurfaceControl>& sc, const WindowInfo& info) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->windowInfoHandle = new WindowInfoHandle(info);
s->what |= layer_state_t::eInputInfoChanged;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFocusedWindow(
const FocusRequest& request) {
mInputWindowCommands.focusRequests.push_back(request);
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::addWindowInfosReportedListener(
sp<gui::IWindowInfosReportedListener> windowInfosReportedListener) {
mInputWindowCommands.windowInfosReportedListeners.insert(windowInfosReportedListener);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorTransform(
const sp<SurfaceControl>& sc, const mat3& matrix, const vec3& translation) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eColorTransformChanged;
s->colorTransform = mat4(matrix, translation);
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setGeometry(
const sp<SurfaceControl>& sc, const Rect& source, const Rect& dst, int transform) {
setCrop(sc, source);
int x = dst.left;
int y = dst.top;
float sourceWidth = source.getWidth();
float sourceHeight = source.getHeight();
float xScale = sourceWidth < 0 ? 1.0f : dst.getWidth() / sourceWidth;
float yScale = sourceHeight < 0 ? 1.0f : dst.getHeight() / sourceHeight;
float matrix[4] = {1, 0, 0, 1};
switch (transform) {
case NATIVE_WINDOW_TRANSFORM_FLIP_H:
matrix[0] = -xScale; matrix[1] = 0;
matrix[2] = 0; matrix[3] = yScale;
x += source.getWidth();
break;
case NATIVE_WINDOW_TRANSFORM_FLIP_V:
matrix[0] = xScale; matrix[1] = 0;
matrix[2] = 0; matrix[3] = -yScale;
y += source.getHeight();
break;
case NATIVE_WINDOW_TRANSFORM_ROT_90:
matrix[0] = 0; matrix[1] = -yScale;
matrix[2] = xScale; matrix[3] = 0;
x += source.getHeight();
break;
case NATIVE_WINDOW_TRANSFORM_ROT_180:
matrix[0] = -xScale; matrix[1] = 0;
matrix[2] = 0; matrix[3] = -yScale;
x += source.getWidth();
y += source.getHeight();
break;
case NATIVE_WINDOW_TRANSFORM_ROT_270:
matrix[0] = 0; matrix[1] = yScale;
matrix[2] = -xScale; matrix[3] = 0;
y += source.getWidth();
break;
default:
matrix[0] = xScale; matrix[1] = 0;
matrix[2] = 0; matrix[3] = yScale;
break;
}
setMatrix(sc, matrix[0], matrix[1], matrix[2], matrix[3]);
float offsetX = xScale * source.left;
float offsetY = yScale * source.top;
setPosition(sc, x - offsetX, y - offsetY);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setShadowRadius(
const sp<SurfaceControl>& sc, float shadowRadius) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eShadowRadiusChanged;
s->shadowRadius = shadowRadius;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameRate(
const sp<SurfaceControl>& sc, float frameRate, int8_t compatibility,
int8_t changeFrameRateStrategy) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
// Allow privileged values as well here, those will be ignored by SF if
// the caller is not privileged
if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
"Transaction::setFrameRate",
/*privileged=*/true)) {
mStatus = BAD_VALUE;
return *this;
}
s->what |= layer_state_t::eFrameRateChanged;
s->frameRate = frameRate;
s->frameRateCompatibility = compatibility;
s->changeFrameRateStrategy = changeFrameRateStrategy;
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::setDefaultFrameRateCompatibility(const sp<SurfaceControl>& sc,
int8_t compatibility) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDefaultFrameRateCompatibilityChanged;
s->defaultFrameRateCompatibility = compatibility;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameRateCategory(
const sp<SurfaceControl>& sc, int8_t category, bool smoothSwitchOnly) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eFrameRateCategoryChanged;
s->frameRateCategory = category;
s->frameRateCategorySmoothSwitchOnly = smoothSwitchOnly;
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::setFrameRateSelectionStrategy(const sp<SurfaceControl>& sc,
int8_t strategy) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eFrameRateSelectionStrategyChanged;
s->frameRateSelectionStrategy = strategy;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFixedTransformHint(
const sp<SurfaceControl>& sc, int32_t fixedTransformHint) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
const ui::Transform::RotationFlags transform = fixedTransformHint == -1
? ui::Transform::ROT_INVALID
: ui::Transform::toRotationFlags(static_cast<ui::Rotation>(fixedTransformHint));
s->what |= layer_state_t::eFixedTransformHintChanged;
s->fixedTransformHint = transform;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameTimelineInfo(
const FrameTimelineInfo& frameTimelineInfo) {
mergeFrameTimelineInfo(mFrameTimelineInfo, frameTimelineInfo);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAutoRefresh(
const sp<SurfaceControl>& sc, bool autoRefresh) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eAutoRefreshChanged;
s->autoRefresh = autoRefresh;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTrustedOverlay(
const sp<SurfaceControl>& sc, bool isTrustedOverlay) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eTrustedOverlayChanged;
s->isTrustedOverlay = isTrustedOverlay;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApplyToken(
const sp<IBinder>& applyToken) {
mApplyToken = applyToken;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setStretchEffect(
const sp<SurfaceControl>& sc, const StretchEffect& stretchEffect) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eStretchChanged;
s->stretchEffect = stretchEffect;
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBufferCrop(
const sp<SurfaceControl>& sc, const Rect& bufferCrop) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eBufferCropChanged;
s->bufferCrop = bufferCrop;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDestinationFrame(
const sp<SurfaceControl>& sc, const Rect& destinationFrame) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDestinationFrameChanged;
s->destinationFrame = destinationFrame;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDropInputMode(
const sp<SurfaceControl>& sc, gui::DropInputMode mode) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eDropInputModeChanged;
s->dropInputMode = mode;
registerSurfaceControlForCallback(sc);
return *this;
}
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::enableBorder(
const sp<SurfaceControl>& sc, bool shouldEnable, float width, const half4& color) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eRenderBorderChanged;
s->borderEnabled = shouldEnable;
s->borderWidth = width;
s->borderColor = color;
registerSurfaceControlForCallback(sc);
return *this;
}
// ---------------------------------------------------------------------------
DisplayState& SurfaceComposerClient::Transaction::getDisplayState(const sp<IBinder>& token) {
DisplayState s;
s.token = token;
ssize_t index = mDisplayStates.indexOf(s);
if (index < 0) {
// we don't have it, add an initialized layer_state to our list
s.what = 0;
index = mDisplayStates.add(s);
}
return mDisplayStates.editItemAt(static_cast<size_t>(index));
}
status_t SurfaceComposerClient::Transaction::setDisplaySurface(const sp<IBinder>& token,
const sp<IGraphicBufferProducer>& bufferProducer) {
if (bufferProducer.get() != nullptr) {
// Make sure that composition can never be stalled by a virtual display
// consumer that isn't processing buffers fast enough.
status_t err = bufferProducer->setAsyncMode(true);
if (err != NO_ERROR) {
ALOGE("Composer::setDisplaySurface Failed to enable async mode on the "
"BufferQueue. This BufferQueue cannot be used for virtual "
"display. (%d)", err);
return err;
}
}
DisplayState& s(getDisplayState(token));
s.surface = bufferProducer;
s.what |= DisplayState::eSurfaceChanged;
return NO_ERROR;
}
void SurfaceComposerClient::Transaction::setDisplayLayerStack(const sp<IBinder>& token,
ui::LayerStack layerStack) {
DisplayState& s(getDisplayState(token));
s.layerStack = layerStack;
s.what |= DisplayState::eLayerStackChanged;
}
void SurfaceComposerClient::Transaction::setDisplayFlags(const sp<IBinder>& token, uint32_t flags) {
DisplayState& s(getDisplayState(token));
s.flags = flags;
s.what |= DisplayState::eFlagsChanged;
}
void SurfaceComposerClient::Transaction::setDisplayProjection(const sp<IBinder>& token,
ui::Rotation orientation,
const Rect& layerStackRect,
const Rect& displayRect) {
DisplayState& s(getDisplayState(token));
s.orientation = orientation;
s.layerStackSpaceRect = layerStackRect;
s.orientedDisplaySpaceRect = displayRect;
s.what |= DisplayState::eDisplayProjectionChanged;
}
void SurfaceComposerClient::Transaction::setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height) {
DisplayState& s(getDisplayState(token));
s.width = width;
s.height = height;
s.what |= DisplayState::eDisplaySizeChanged;
}
// copied from FrameTimelineInfo::merge()
void SurfaceComposerClient::Transaction::mergeFrameTimelineInfo(FrameTimelineInfo& t,
const FrameTimelineInfo& other) {
// When merging vsync Ids we take the oldest valid one
if (t.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID &&
other.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
if (other.vsyncId > t.vsyncId) {
t = other;
}
} else if (t.vsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
t = other;
}
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::setTrustedPresentationCallback(
const sp<SurfaceControl>& sc, TrustedPresentationCallback cb,
const TrustedPresentationThresholds& thresholds, void* context,
sp<SurfaceComposerClient::PresentationCallbackRAII>& outCallbackRef) {
auto listener = TransactionCompletedListener::getInstance();
outCallbackRef = listener->addTrustedPresentationCallback(cb, sc->getLayerId(), context);
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eTrustedPresentationInfoChanged;
s->trustedPresentationThresholds = thresholds;
s->trustedPresentationListener.callbackInterface = TransactionCompletedListener::getIInstance();
s->trustedPresentationListener.callbackId = sc->getLayerId();
return *this;
}
SurfaceComposerClient::Transaction&
SurfaceComposerClient::Transaction::clearTrustedPresentationCallback(const sp<SurfaceControl>& sc) {
auto listener = TransactionCompletedListener::getInstance();
listener->clearTrustedPresentationCallback(sc->getLayerId());
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eTrustedPresentationInfoChanged;
s->trustedPresentationThresholds = TrustedPresentationThresholds();
s->trustedPresentationListener.callbackInterface = nullptr;
s->trustedPresentationListener.callbackId = -1;
return *this;
}
// ---------------------------------------------------------------------------
SurfaceComposerClient::SurfaceComposerClient() : mStatus(NO_INIT) {}
SurfaceComposerClient::SurfaceComposerClient(const sp<ISurfaceComposerClient>& client)
: mStatus(NO_ERROR), mClient(client) {}
void SurfaceComposerClient::onFirstRef() {
sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
if (sf != nullptr && mStatus == NO_INIT) {
sp<ISurfaceComposerClient> conn;
binder::Status status = sf->createConnection(&conn);
if (status.isOk() && conn != nullptr) {
mClient = conn;
mStatus = NO_ERROR;
}
}
}
SurfaceComposerClient::~SurfaceComposerClient() {
dispose();
}
status_t SurfaceComposerClient::initCheck() const {
return mStatus;
}
sp<IBinder> SurfaceComposerClient::connection() const {
return IInterface::asBinder(mClient);
}
status_t SurfaceComposerClient::linkToComposerDeath(
const sp<IBinder::DeathRecipient>& recipient,
void* cookie, uint32_t flags) {
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
return IInterface::asBinder(sf)->linkToDeath(recipient, cookie, flags);
}
void SurfaceComposerClient::dispose() {
// this can be called more than once.
sp<ISurfaceComposerClient> client;
Mutex::Autolock _lm(mLock);
if (mClient != nullptr) {
client = mClient; // hold ref while lock is held
mClient.clear();
}
mStatus = NO_INIT;
}
status_t SurfaceComposerClient::bootFinished() {
sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
binder::Status status = sf->bootFinished();
return statusTFromBinderStatus(status);
}
sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
PixelFormat format, int32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
sp<SurfaceControl> s;
createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
outTransformHint);
return s;
}
static std::string toString(const String16& string) {
return std::string(String8(string).c_str());
}
status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
PixelFormat format,
sp<SurfaceControl>* outSurface, int32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
status_t err = mStatus;
if (mStatus == NO_ERROR) {
gui::CreateSurfaceResult result;
binder::Status status = mClient->createSurface(std::string(name.c_str()), flags,
parentHandle, std::move(metadata), &result);
err = statusTFromBinderStatus(status);
if (outTransformHint) {
*outTransformHint = result.transformHint;
}
ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
if (err == NO_ERROR) {
*outSurface = new SurfaceControl(this, result.handle, result.layerId,
toString(result.layerName), w, h, format,
result.transformHint, flags);
}
}
return err;
}
sp<SurfaceControl> SurfaceComposerClient::mirrorSurface(SurfaceControl* mirrorFromSurface) {
if (mirrorFromSurface == nullptr) {
return nullptr;
}
sp<IBinder> mirrorFromHandle = mirrorFromSurface->getHandle();
gui::CreateSurfaceResult result;
const binder::Status status = mClient->mirrorSurface(mirrorFromHandle, &result);
const status_t err = statusTFromBinderStatus(status);
if (err == NO_ERROR) {
return new SurfaceControl(this, result.handle, result.layerId, toString(result.layerName));
}
return nullptr;
}
sp<SurfaceControl> SurfaceComposerClient::mirrorDisplay(DisplayId displayId) {
gui::CreateSurfaceResult result;
const binder::Status status = mClient->mirrorDisplay(displayId.value, &result);
const status_t err = statusTFromBinderStatus(status);
if (err == NO_ERROR) {
return new SurfaceControl(this, result.handle, result.layerId, toString(result.layerName));
}
return nullptr;
}
status_t SurfaceComposerClient::clearLayerFrameStats(const sp<IBinder>& token) const {
if (mStatus != NO_ERROR) {
return mStatus;
}
const binder::Status status = mClient->clearLayerFrameStats(token);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getLayerFrameStats(const sp<IBinder>& token,
FrameStats* outStats) const {
if (mStatus != NO_ERROR) {
return mStatus;
}
gui::FrameStats stats;
const binder::Status status = mClient->getLayerFrameStats(token, &stats);
if (status.isOk()) {
outStats->refreshPeriodNano = stats.refreshPeriodNano;
outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size());
for (const auto& t : stats.desiredPresentTimesNano) {
outStats->desiredPresentTimesNano.add(t);
}
outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size());
for (const auto& t : stats.actualPresentTimesNano) {
outStats->actualPresentTimesNano.add(t);
}
outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size());
for (const auto& t : stats.frameReadyTimesNano) {
outStats->frameReadyTimesNano.add(t);
}
}
return statusTFromBinderStatus(status);
}
// ----------------------------------------------------------------------------
status_t SurfaceComposerClient::getDisplayState(const sp<IBinder>& display,
ui::DisplayState* state) {
gui::DisplayState ds;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDisplayState(display, &ds);
if (status.isOk()) {
state->layerStack = ui::LayerStack::fromValue(ds.layerStack);
state->orientation = static_cast<ui::Rotation>(ds.orientation);
state->layerStackSpaceRect =
ui::Size(ds.layerStackSpaceRect.width, ds.layerStackSpaceRect.height);
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getStaticDisplayInfo(int64_t displayId,
ui::StaticDisplayInfo* outInfo) {
using Tag = android::gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
gui::StaticDisplayInfo ginfo;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getStaticDisplayInfo(displayId, &ginfo);
if (status.isOk()) {
// convert gui::StaticDisplayInfo to ui::StaticDisplayInfo
outInfo->connectionType = static_cast<ui::DisplayConnectionType>(ginfo.connectionType);
outInfo->density = ginfo.density;
outInfo->secure = ginfo.secure;
outInfo->installOrientation = static_cast<ui::Rotation>(ginfo.installOrientation);
if (const std::optional<gui::DeviceProductInfo> dpi = ginfo.deviceProductInfo) {
DeviceProductInfo info;
info.name = dpi->name;
if (dpi->manufacturerPnpId.size() > 0) {
// copid from PnpId = std::array<char, 4> in ui/DeviceProductInfo.h
constexpr int kMaxPnpIdSize = 4;
size_t count = std::max<size_t>(kMaxPnpIdSize, dpi->manufacturerPnpId.size());
std::copy_n(dpi->manufacturerPnpId.begin(), count, info.manufacturerPnpId.begin());
}
if (dpi->relativeAddress.size() > 0) {
std::copy(dpi->relativeAddress.begin(), dpi->relativeAddress.end(),
std::back_inserter(info.relativeAddress));
}
info.productId = dpi->productId;
const gui::DeviceProductInfo::ManufactureOrModelDate& date =
dpi->manufactureOrModelDate;
if (date.getTag() == Tag::modelYear) {
DeviceProductInfo::ModelYear modelYear;
modelYear.year = static_cast<uint32_t>(date.get<Tag::modelYear>().year);
info.manufactureOrModelDate = modelYear;
} else if (date.getTag() == Tag::manufactureYear) {
DeviceProductInfo::ManufactureYear manufactureYear;
manufactureYear.year = date.get<Tag::manufactureYear>().modelYear.year;
info.manufactureOrModelDate = manufactureYear;
} else if (date.getTag() == Tag::manufactureWeekAndYear) {
DeviceProductInfo::ManufactureWeekAndYear weekAndYear;
weekAndYear.year =
date.get<Tag::manufactureWeekAndYear>().manufactureYear.modelYear.year;
weekAndYear.week = date.get<Tag::manufactureWeekAndYear>().week;
info.manufactureOrModelDate = weekAndYear;
}
outInfo->deviceProductInfo = info;
}
}
return statusTFromBinderStatus(status);
}
void SurfaceComposerClient::getDynamicDisplayInfoInternal(gui::DynamicDisplayInfo& ginfo,
ui::DynamicDisplayInfo*& outInfo) {
// convert gui::DynamicDisplayInfo to ui::DynamicDisplayInfo
outInfo->supportedDisplayModes.clear();
outInfo->supportedDisplayModes.reserve(ginfo.supportedDisplayModes.size());
for (const auto& mode : ginfo.supportedDisplayModes) {
ui::DisplayMode outMode;
outMode.id = mode.id;
outMode.resolution.width = mode.resolution.width;
outMode.resolution.height = mode.resolution.height;
outMode.xDpi = mode.xDpi;
outMode.yDpi = mode.yDpi;
outMode.peakRefreshRate = mode.peakRefreshRate;
outMode.vsyncRate = mode.vsyncRate;
outMode.appVsyncOffset = mode.appVsyncOffset;
outMode.sfVsyncOffset = mode.sfVsyncOffset;
outMode.presentationDeadline = mode.presentationDeadline;
outMode.group = mode.group;
std::transform(mode.supportedHdrTypes.begin(), mode.supportedHdrTypes.end(),
std::back_inserter(outMode.supportedHdrTypes),
[](const int32_t& value) { return static_cast<ui::Hdr>(value); });
outInfo->supportedDisplayModes.push_back(outMode);
}
outInfo->activeDisplayModeId = ginfo.activeDisplayModeId;
outInfo->renderFrameRate = ginfo.renderFrameRate;
outInfo->supportedColorModes.clear();
outInfo->supportedColorModes.reserve(ginfo.supportedColorModes.size());
for (const auto& cmode : ginfo.supportedColorModes) {
outInfo->supportedColorModes.push_back(static_cast<ui::ColorMode>(cmode));
}
outInfo->activeColorMode = static_cast<ui::ColorMode>(ginfo.activeColorMode);
std::vector<ui::Hdr> types;
types.reserve(ginfo.hdrCapabilities.supportedHdrTypes.size());
for (const auto& hdr : ginfo.hdrCapabilities.supportedHdrTypes) {
types.push_back(static_cast<ui::Hdr>(hdr));
}
outInfo->hdrCapabilities = HdrCapabilities(types, ginfo.hdrCapabilities.maxLuminance,
ginfo.hdrCapabilities.maxAverageLuminance,
ginfo.hdrCapabilities.minLuminance);
outInfo->autoLowLatencyModeSupported = ginfo.autoLowLatencyModeSupported;
outInfo->gameContentTypeSupported = ginfo.gameContentTypeSupported;
outInfo->preferredBootDisplayMode = ginfo.preferredBootDisplayMode;
}
status_t SurfaceComposerClient::getDynamicDisplayInfoFromId(int64_t displayId,
ui::DynamicDisplayInfo* outInfo) {
gui::DynamicDisplayInfo ginfo;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDynamicDisplayInfoFromId(displayId,
&ginfo);
if (status.isOk()) {
getDynamicDisplayInfoInternal(ginfo, outInfo);
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getDynamicDisplayInfoFromToken(const sp<IBinder>& display,
ui::DynamicDisplayInfo* outInfo) {
gui::DynamicDisplayInfo ginfo;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDynamicDisplayInfoFromToken(display,
&ginfo);
if (status.isOk()) {
getDynamicDisplayInfoInternal(ginfo, outInfo);
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getActiveDisplayMode(const sp<IBinder>& display,
ui::DisplayMode* mode) {
ui::DynamicDisplayInfo info;
status_t result = getDynamicDisplayInfoFromToken(display, &info);
if (result != NO_ERROR) {
return result;
}
if (const auto activeMode = info.getActiveDisplayMode()) {
*mode = *activeMode;
return NO_ERROR;
}
ALOGE("Active display mode not found.");
return NAME_NOT_FOUND;
}
status_t SurfaceComposerClient::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
const gui::DisplayModeSpecs& specs) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->setDesiredDisplayModeSpecs(displayToken,
specs);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
gui::DisplayModeSpecs* outSpecs) {
if (!outSpecs) {
return BAD_VALUE;
}
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDesiredDisplayModeSpecs(displayToken,
outSpecs);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp<IBinder>& display,
ui::DisplayPrimaries& outPrimaries) {
gui::DisplayPrimaries primaries;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDisplayNativePrimaries(display,
&primaries);
if (status.isOk()) {
outPrimaries.red.X = primaries.red.X;
outPrimaries.red.Y = primaries.red.Y;
outPrimaries.red.Z = primaries.red.Z;
outPrimaries.green.X = primaries.green.X;
outPrimaries.green.Y = primaries.green.Y;
outPrimaries.green.Z = primaries.green.Z;
outPrimaries.blue.X = primaries.blue.X;
outPrimaries.blue.Y = primaries.blue.Y;
outPrimaries.blue.Z = primaries.blue.Z;
outPrimaries.white.X = primaries.white.X;
outPrimaries.white.Y = primaries.white.Y;
outPrimaries.white.Z = primaries.white.Z;
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setActiveColorMode(const sp<IBinder>& display,
ColorMode colorMode) {
binder::Status status = ComposerServiceAIDL::getComposerService()
->setActiveColorMode(display, static_cast<int>(colorMode));
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->getBootDisplayModeSupport(support);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getOverlaySupport(gui::OverlayProperties* outProperties) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->getOverlaySupport(outProperties);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setBootDisplayMode(const sp<IBinder>& display,
ui::DisplayModeId displayModeId) {
binder::Status status = ComposerServiceAIDL::getComposerService()
->setBootDisplayMode(display, static_cast<int>(displayModeId));
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::clearBootDisplayMode(const sp<IBinder>& display) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->clearBootDisplayMode(display);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getHdrConversionCapabilities(
std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) {
binder::Status status = ComposerServiceAIDL::getComposerService()->getHdrConversionCapabilities(
hdrConversionCapabilities);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setHdrConversionStrategy(
gui::HdrConversionStrategy hdrConversionStrategy, ui::Hdr* outPreferredHdrOutputType) {
int hdrType;
binder::Status status = ComposerServiceAIDL::getComposerService()
->setHdrConversionStrategy(hdrConversionStrategy, &hdrType);
*outPreferredHdrOutputType = static_cast<ui::Hdr>(hdrType);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getHdrOutputConversionSupport(bool* isSupported) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->getHdrOutputConversionSupport(isSupported);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setGameModeFrameRateOverride(uid_t uid, float frameRate) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->setGameModeFrameRateOverride(uid, frameRate);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setGameDefaultFrameRateOverride(uid_t uid, float frameRate) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->setGameDefaultFrameRateOverride(uid,
frameRate);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::updateSmallAreaDetection(std::vector<int32_t>& appIds,
std::vector<float>& thresholds) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->updateSmallAreaDetection(appIds, thresholds);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->setSmallAreaDetectionThreshold(appId,
threshold);
return statusTFromBinderStatus(status);
}
void SurfaceComposerClient::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
ComposerServiceAIDL::getComposerService()->setAutoLowLatencyMode(display, on);
}
void SurfaceComposerClient::setGameContentType(const sp<IBinder>& display, bool on) {
ComposerServiceAIDL::getComposerService()->setGameContentType(display, on);
}
void SurfaceComposerClient::setDisplayPowerMode(const sp<IBinder>& token,
int mode) {
ComposerServiceAIDL::getComposerService()->setPowerMode(token, mode);
}
status_t SurfaceComposerClient::getCompositionPreference(
ui::Dataspace* defaultDataspace, ui::PixelFormat* defaultPixelFormat,
ui::Dataspace* wideColorGamutDataspace, ui::PixelFormat* wideColorGamutPixelFormat) {
gui::CompositionPreference pref;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getCompositionPreference(&pref);
if (status.isOk()) {
*defaultDataspace = static_cast<ui::Dataspace>(pref.defaultDataspace);
*defaultPixelFormat = static_cast<ui::PixelFormat>(pref.defaultPixelFormat);
*wideColorGamutDataspace = static_cast<ui::Dataspace>(pref.wideColorGamutDataspace);
*wideColorGamutPixelFormat = static_cast<ui::PixelFormat>(pref.wideColorGamutPixelFormat);
}
return statusTFromBinderStatus(status);
}
bool SurfaceComposerClient::getProtectedContentSupport() {
bool supported = false;
ComposerServiceAIDL::getComposerService()->getProtectedContentSupport(&supported);
return supported;
}
status_t SurfaceComposerClient::clearAnimationFrameStats() {
binder::Status status = ComposerServiceAIDL::getComposerService()->clearAnimationFrameStats();
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) {
gui::FrameStats stats;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getAnimationFrameStats(&stats);
if (status.isOk()) {
outStats->refreshPeriodNano = stats.refreshPeriodNano;
outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size());
for (const auto& t : stats.desiredPresentTimesNano) {
outStats->desiredPresentTimesNano.add(t);
}
outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size());
for (const auto& t : stats.actualPresentTimesNano) {
outStats->actualPresentTimesNano.add(t);
}
outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size());
for (const auto& t : stats.frameReadyTimesNano) {
outStats->frameReadyTimesNano.add(t);
}
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::overrideHdrTypes(const sp<IBinder>& display,
const std::vector<ui::Hdr>& hdrTypes) {
std::vector<int32_t> hdrTypesVector;
hdrTypesVector.reserve(hdrTypes.size());
for (auto t : hdrTypes) {
hdrTypesVector.push_back(static_cast<int32_t>(t));
}
binder::Status status =
ComposerServiceAIDL::getComposerService()->overrideHdrTypes(display, hdrTypesVector);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* outData,
bool* success) {
gui::PullAtomData pad;
binder::Status status = ComposerServiceAIDL::getComposerService()->onPullAtom(atomId, &pad);
if (status.isOk()) {
outData->assign(pad.data.begin(), pad.data.end());
*success = pad.success;
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
ui::PixelFormat* outFormat,
ui::Dataspace* outDataspace,
uint8_t* outComponentMask) {
if (!outFormat || !outDataspace || !outComponentMask) {
return BAD_VALUE;
}
gui::ContentSamplingAttributes attrs;
binder::Status status = ComposerServiceAIDL::getComposerService()
->getDisplayedContentSamplingAttributes(display, &attrs);
if (status.isOk()) {
*outFormat = static_cast<ui::PixelFormat>(attrs.format);
*outDataspace = static_cast<ui::Dataspace>(attrs.dataspace);
*outComponentMask = static_cast<uint8_t>(attrs.componentMask);
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
bool enable, uint8_t componentMask,
uint64_t maxFrames) {
binder::Status status =
ComposerServiceAIDL::getComposerService()
->setDisplayContentSamplingEnabled(display, enable,
static_cast<int8_t>(componentMask),
static_cast<int64_t>(maxFrames));
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::getDisplayedContentSample(const sp<IBinder>& display,
uint64_t maxFrames, uint64_t timestamp,
DisplayedFrameStats* outStats) {
if (!outStats) {
return BAD_VALUE;
}
gui::DisplayedFrameStats stats;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDisplayedContentSample(display, maxFrames,
timestamp, &stats);
if (status.isOk()) {
// convert gui::DisplayedFrameStats to ui::DisplayedFrameStats
outStats->numFrames = static_cast<uint64_t>(stats.numFrames);
outStats->component_0_sample.reserve(stats.component_0_sample.size());
for (const auto& s : stats.component_0_sample) {
outStats->component_0_sample.push_back(static_cast<uint64_t>(s));
}
outStats->component_1_sample.reserve(stats.component_1_sample.size());
for (const auto& s : stats.component_1_sample) {
outStats->component_1_sample.push_back(static_cast<uint64_t>(s));
}
outStats->component_2_sample.reserve(stats.component_2_sample.size());
for (const auto& s : stats.component_2_sample) {
outStats->component_2_sample.push_back(static_cast<uint64_t>(s));
}
outStats->component_3_sample.reserve(stats.component_3_sample.size());
for (const auto& s : stats.component_3_sample) {
outStats->component_3_sample.push_back(static_cast<uint64_t>(s));
}
}
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::isWideColorDisplay(const sp<IBinder>& display,
bool* outIsWideColorDisplay) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->isWideColorDisplay(display,
outIsWideColorDisplay);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::addRegionSamplingListener(
const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
const sp<IRegionSamplingListener>& listener) {
gui::ARect rect;
rect.left = samplingArea.left;
rect.top = samplingArea.top;
rect.right = samplingArea.right;
rect.bottom = samplingArea.bottom;
binder::Status status =
ComposerServiceAIDL::getComposerService()->addRegionSamplingListener(rect,
stopLayerHandle,
listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::removeRegionSamplingListener(
const sp<IRegionSamplingListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->removeRegionSamplingListener(listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::addFpsListener(int32_t taskId,
const sp<gui::IFpsListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->addFpsListener(taskId, listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::removeFpsListener(const sp<gui::IFpsListener>& listener) {
binder::Status status = ComposerServiceAIDL::getComposerService()->removeFpsListener(listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::addTunnelModeEnabledListener(
const sp<gui::ITunnelModeEnabledListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->addTunnelModeEnabledListener(listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::removeTunnelModeEnabledListener(
const sp<gui::ITunnelModeEnabledListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->removeTunnelModeEnabledListener(listener);
return statusTFromBinderStatus(status);
}
bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp<IBinder>& displayToken) {
bool support = false;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDisplayBrightnessSupport(displayToken,
&support);
return status.isOk() ? support : false;
}
status_t SurfaceComposerClient::setDisplayBrightness(const sp<IBinder>& displayToken,
const gui::DisplayBrightness& brightness) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->setDisplayBrightness(displayToken,
brightness);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::addHdrLayerInfoListener(
const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->addHdrLayerInfoListener(displayToken,
listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::removeHdrLayerInfoListener(
const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
binder::Status status =
ComposerServiceAIDL::getComposerService()->removeHdrLayerInfoListener(displayToken,
listener);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::notifyPowerBoost(int32_t boostId) {
binder::Status status = ComposerServiceAIDL::getComposerService()->notifyPowerBoost(boostId);
return statusTFromBinderStatus(status);
}
status_t SurfaceComposerClient::setGlobalShadowSettings(const half4& ambientColor,
const half4& spotColor, float lightPosY,
float lightPosZ, float lightRadius) {
gui::Color ambientColorG, spotColorG;
ambientColorG.r = ambientColor.r;
ambientColorG.g = ambientColor.g;
ambientColorG.b = ambientColor.b;
ambientColorG.a = ambientColor.a;
spotColorG.r = spotColor.r;
spotColorG.g = spotColor.g;
spotColorG.b = spotColor.b;
spotColorG.a = spotColor.a;
binder::Status status =
ComposerServiceAIDL::getComposerService()->setGlobalShadowSettings(ambientColorG,
spotColorG,
lightPosY, lightPosZ,
lightRadius);
return statusTFromBinderStatus(status);
}
std::optional<DisplayDecorationSupport> SurfaceComposerClient::getDisplayDecorationSupport(
const sp<IBinder>& displayToken) {
std::optional<gui::DisplayDecorationSupport> gsupport;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getDisplayDecorationSupport(displayToken,
&gsupport);
std::optional<DisplayDecorationSupport> support;
if (status.isOk() && gsupport.has_value()) {
support.emplace(DisplayDecorationSupport{
.format =
static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
gsupport->format),
.alphaInterpretation =
static_cast<aidl::android::hardware::graphics::common::AlphaInterpretation>(
gsupport->alphaInterpretation)
});
}
return support;
}
int SurfaceComposerClient::getGpuContextPriority() {
int priority;
binder::Status status =
ComposerServiceAIDL::getComposerService()->getGpuContextPriority(&priority);
if (!status.isOk()) {
status_t err = statusTFromBinderStatus(status);
ALOGE("getGpuContextPriority failed to read data: %s (%d)", strerror(-err), err);
return 0;
}
return priority;
}
status_t SurfaceComposerClient::addWindowInfosListener(
const sp<WindowInfosListener>& windowInfosListener,
std::pair<std::vector<gui::WindowInfo>, std::vector<gui::DisplayInfo>>* outInitialInfo) {
return WindowInfosListenerReporter::getInstance()
->addWindowInfosListener(windowInfosListener, ComposerServiceAIDL::getComposerService(),
outInitialInfo);
}
status_t SurfaceComposerClient::removeWindowInfosListener(
const sp<WindowInfosListener>& windowInfosListener) {
return WindowInfosListenerReporter::getInstance()
->removeWindowInfosListener(windowInfosListener,
ComposerServiceAIDL::getComposerService());
}
// ----------------------------------------------------------------------------
status_t ScreenshotClient::captureDisplay(const DisplayCaptureArgs& captureArgs,
const sp<IScreenCaptureListener>& captureListener) {
sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
if (s == nullptr) return NO_INIT;
binder::Status status = s->captureDisplay(captureArgs, captureListener);
return statusTFromBinderStatus(status);
}
status_t ScreenshotClient::captureDisplay(DisplayId displayId, const gui::CaptureArgs& captureArgs,
const sp<IScreenCaptureListener>& captureListener) {
sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
if (s == nullptr) return NO_INIT;
binder::Status status = s->captureDisplayById(displayId.value, captureArgs, captureListener);
return statusTFromBinderStatus(status);
}
status_t ScreenshotClient::captureLayers(const LayerCaptureArgs& captureArgs,
const sp<IScreenCaptureListener>& captureListener,
bool sync) {
sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
if (s == nullptr) return NO_INIT;
binder::Status status;
if (sync) {
gui::ScreenCaptureResults captureResults;
status = s->captureLayersSync(captureArgs, &captureResults);
captureListener->onScreenCaptureCompleted(captureResults);
} else {
status = s->captureLayers(captureArgs, captureListener);
}
return statusTFromBinderStatus(status);
}
// ---------------------------------------------------------------------------------
void ReleaseCallbackThread::addReleaseCallback(const ReleaseCallbackId callbackId,
sp<Fence> releaseFence) {
std::scoped_lock<std::mutex> lock(mMutex);
if (!mStarted) {
mThread = std::thread(&ReleaseCallbackThread::threadMain, this);
mStarted = true;
}
mCallbackInfos.emplace(callbackId, std::move(releaseFence));
mReleaseCallbackPending.notify_one();
}
void ReleaseCallbackThread::threadMain() {
const auto listener = TransactionCompletedListener::getInstance();
std::queue<std::tuple<const ReleaseCallbackId, const sp<Fence>>> callbackInfos;
while (true) {
{
std::unique_lock<std::mutex> lock(mMutex);
base::ScopedLockAssertion assumeLocked(mMutex);
callbackInfos = std::move(mCallbackInfos);
mCallbackInfos = {};
}
while (!callbackInfos.empty()) {
auto [callbackId, releaseFence] = callbackInfos.front();
listener->onReleaseBuffer(callbackId, std::move(releaseFence), UINT_MAX);
callbackInfos.pop();
}
{
std::unique_lock<std::mutex> lock(mMutex);
base::ScopedLockAssertion assumeLocked(mMutex);
if (mCallbackInfos.size() == 0) {
mReleaseCallbackPending.wait(lock);
}
}
}
}
} // namespace android
|