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
|
/*
* 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 ATRACE_TAG ATRACE_TAG_GRAPHICS
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <cutils/log.h>
#include <cutils/properties.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/MemoryHeapBase.h>
#include <binder/PermissionCache.h>
#include <gui/IDisplayEventConnection.h>
#include <utils/String8.h>
#include <utils/String16.h>
#include <utils/StopWatch.h>
#include <utils/Trace.h>
#include <ui/GraphicBufferAllocator.h>
#include <ui/PixelFormat.h>
#include <GLES/gl.h>
#include "clz.h"
#include "DdmConnection.h"
#include "EventThread.h"
#include "GLExtensions.h"
#include "Layer.h"
#include "LayerDim.h"
#include "LayerScreenshot.h"
#include "SurfaceFlinger.h"
#include "DisplayHardware/DisplayHardware.h"
#include "DisplayHardware/HWComposer.h"
#include <private/android_filesystem_config.h>
#include <private/gui/SharedBufferStack.h>
#include <gui/BitTube.h>
#define EGL_VERSION_HW_ANDROID 0x3143
#define DISPLAY_COUNT 1
namespace android {
// ---------------------------------------------------------------------------
const String16 sHardwareTest("android.permission.HARDWARE_TEST");
const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
const String16 sDump("android.permission.DUMP");
// ---------------------------------------------------------------------------
SurfaceFlinger::SurfaceFlinger()
: BnSurfaceComposer(), Thread(false),
mTransactionFlags(0),
mTransationPending(false),
mLayersRemoved(false),
mBootTime(systemTime()),
mVisibleRegionsDirty(false),
mHwWorkListDirty(false),
mElectronBeamAnimationMode(0),
mDebugRegion(0),
mDebugDDMS(0),
mDebugDisableHWC(0),
mDebugDisableTransformHint(0),
mDebugInSwapBuffers(0),
mLastSwapBufferTime(0),
mDebugInTransaction(0),
mLastTransactionTime(0),
mBootFinished(false),
mSecureFrameBuffer(0)
{
init();
}
void SurfaceFlinger::init()
{
ALOGI("SurfaceFlinger is starting");
// debugging stuff...
char value[PROPERTY_VALUE_MAX];
property_get("debug.sf.showupdates", value, "0");
mDebugRegion = atoi(value);
#ifdef DDMS_DEBUGGING
property_get("debug.sf.ddms", value, "0");
mDebugDDMS = atoi(value);
if (mDebugDDMS) {
DdmConnection::start(getServiceName());
}
#endif
ALOGI_IF(mDebugRegion, "showupdates enabled");
ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
}
void SurfaceFlinger::onFirstRef()
{
mEventQueue.init(this);
run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
// Wait for the main thread to be done with its initialization
mReadyToRunBarrier.wait();
}
SurfaceFlinger::~SurfaceFlinger()
{
glDeleteTextures(1, &mWormholeTexName);
}
void SurfaceFlinger::binderDied(const wp<IBinder>& who)
{
// the window manager died on us. prepare its eulogy.
// reset screen orientation
Vector<ComposerState> state;
setTransactionState(state, eOrientationDefault, 0);
// restart the boot-animation
startBootAnim();
}
sp<IMemoryHeap> SurfaceFlinger::getCblk() const
{
return mServerHeap;
}
sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
{
sp<ISurfaceComposerClient> bclient;
sp<Client> client(new Client(this));
status_t err = client->initCheck();
if (err == NO_ERROR) {
bclient = client;
}
return bclient;
}
sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
{
sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
return gba;
}
const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
{
ALOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
const GraphicPlane& plane(mGraphicPlanes[dpy]);
return plane;
}
GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
{
return const_cast<GraphicPlane&>(
const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
}
void SurfaceFlinger::bootFinished()
{
const nsecs_t now = systemTime();
const nsecs_t duration = now - mBootTime;
ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
mBootFinished = true;
// wait patiently for the window manager death
const String16 name("window");
sp<IBinder> window(defaultServiceManager()->getService(name));
if (window != 0) {
window->linkToDeath(this);
}
// stop boot animation
// formerly we would just kill the process, but we now ask it to exit so it
// can choose where to stop the animation.
property_set("service.bootanim.exit", "1");
}
static inline uint16_t pack565(int r, int g, int b) {
return (r<<11)|(g<<5)|b;
}
status_t SurfaceFlinger::readyToRun()
{
ALOGI( "SurfaceFlinger's main thread ready to run. "
"Initializing graphics H/W...");
// we only support one display currently
int dpy = 0;
{
// initialize the main display
GraphicPlane& plane(graphicPlane(dpy));
DisplayHardware* const hw = new DisplayHardware(this, dpy);
plane.setDisplayHardware(hw);
}
// create the shared control-block
mServerHeap = new MemoryHeapBase(4096,
MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
ALOGE_IF(mServerHeap==0, "can't create shared memory dealer");
mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
ALOGE_IF(mServerCblk==0, "can't get to shared control block's address");
new(mServerCblk) surface_flinger_cblk_t;
// initialize primary screen
// (other display should be initialized in the same manner, but
// asynchronously, as they could come and go. None of this is supported
// yet).
const GraphicPlane& plane(graphicPlane(dpy));
const DisplayHardware& hw = plane.displayHardware();
const uint32_t w = hw.getWidth();
const uint32_t h = hw.getHeight();
const uint32_t f = hw.getFormat();
hw.makeCurrent();
// initialize the shared control block
mServerCblk->connected |= 1<<dpy;
display_cblk_t* dcblk = mServerCblk->displays + dpy;
memset(dcblk, 0, sizeof(display_cblk_t));
dcblk->w = plane.getWidth();
dcblk->h = plane.getHeight();
dcblk->format = f;
dcblk->orientation = ISurfaceComposer::eOrientationDefault;
dcblk->xdpi = hw.getDpiX();
dcblk->ydpi = hw.getDpiY();
dcblk->fps = hw.getRefreshRate();
dcblk->density = hw.getDensity();
// Initialize OpenGL|ES
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glEnableClientState(GL_VERTEX_ARRAY);
glShadeModel(GL_FLAT);
glDisable(GL_DITHER);
glDisable(GL_CULL_FACE);
const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
const uint16_t g1 = pack565(0x17,0x2f,0x17);
const uint16_t wormholeTexData[4] = { g0, g1, g1, g0 };
glGenTextures(1, &mWormholeTexName);
glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
GL_RGB, GL_UNSIGNED_SHORT_5_6_5, wormholeTexData);
const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
glGenTextures(1, &mProtectedTexName);
glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// put the origin in the left-bottom corner
glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
// start the EventThread
mEventThread = new EventThread(this);
mEventQueue.setEventThread(mEventThread);
hw.startSleepManagement();
/*
* We're now ready to accept clients...
*/
mReadyToRunBarrier.open();
// start boot animation
startBootAnim();
return NO_ERROR;
}
void SurfaceFlinger::startBootAnim() {
// start boot animation
property_set("service.bootanim.exit", "0");
property_set("ctl.start", "bootanim");
}
// ----------------------------------------------------------------------------
bool SurfaceFlinger::authenticateSurfaceTexture(
const sp<ISurfaceTexture>& surfaceTexture) const {
Mutex::Autolock _l(mStateLock);
sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
// Check the visible layer list for the ISurface
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
if (lbc != NULL) {
wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
if (lbcBinder == surfaceTextureBinder) {
return true;
}
}
}
// Check the layers in the purgatory. This check is here so that if a
// SurfaceTexture gets destroyed before all the clients are done using it,
// the error will not be reported as "surface XYZ is not authenticated", but
// will instead fail later on when the client tries to use the surface,
// which should be reported as "surface XYZ returned an -ENODEV". The
// purgatorized layers are no less authentic than the visible ones, so this
// should not cause any harm.
size_t purgatorySize = mLayerPurgatory.size();
for (size_t i=0 ; i<purgatorySize ; i++) {
const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
if (lbc != NULL) {
wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
if (lbcBinder == surfaceTextureBinder) {
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
return mEventThread->createEventConnection();
}
// ----------------------------------------------------------------------------
void SurfaceFlinger::waitForEvent() {
mEventQueue.waitMessage();
}
void SurfaceFlinger::signalTransaction() {
mEventQueue.invalidate();
}
void SurfaceFlinger::signalLayerUpdate() {
mEventQueue.invalidate();
}
void SurfaceFlinger::signalRefresh() {
mEventQueue.refresh();
}
status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
nsecs_t reltime, uint32_t flags) {
return mEventQueue.postMessage(msg, reltime);
}
status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
nsecs_t reltime, uint32_t flags) {
status_t res = mEventQueue.postMessage(msg, reltime);
if (res == NO_ERROR) {
msg->wait();
}
return res;
}
bool SurfaceFlinger::threadLoop()
{
waitForEvent();
return true;
}
void SurfaceFlinger::onMessageReceived(int32_t what)
{
ATRACE_CALL();
switch (what) {
case MessageQueue::REFRESH: {
// case MessageQueue::INVALIDATE: {
// if we're in a global transaction, don't do anything.
const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
uint32_t transactionFlags = peekTransactionFlags(mask);
if (CC_UNLIKELY(transactionFlags)) {
handleTransaction(transactionFlags);
}
// post surfaces (if needed)
handlePageFlip();
// signalRefresh();
//
// } break;
//
// case MessageQueue::REFRESH: {
handleRefresh();
const DisplayHardware& hw(graphicPlane(0).displayHardware());
// if (mDirtyRegion.isEmpty()) {
// return;
// }
if (CC_UNLIKELY(mHwWorkListDirty)) {
// build the h/w work list
handleWorkList();
}
if (CC_LIKELY(hw.canDraw())) {
// repaint the framebuffer (if needed)
handleRepaint();
// inform the h/w that we're done compositing
hw.compositionComplete();
postFramebuffer();
} else {
// pretend we did the post
hw.compositionComplete();
}
} break;
}
}
void SurfaceFlinger::postFramebuffer()
{
ATRACE_CALL();
// mSwapRegion can be empty here is some cases, for instance if a hidden
// or fully transparent window is updating.
// in that case, we need to flip anyways to not risk a deadlock with
// h/w composer.
const DisplayHardware& hw(graphicPlane(0).displayHardware());
const nsecs_t now = systemTime();
mDebugInSwapBuffers = now;
hw.flip(mSwapRegion);
size_t numLayers = mVisibleLayersSortedByZ.size();
for (size_t i = 0; i < numLayers; i++) {
mVisibleLayersSortedByZ[i]->onLayerDisplayed();
}
mLastSwapBufferTime = systemTime() - now;
mDebugInSwapBuffers = 0;
mSwapRegion.clear();
}
void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
{
ATRACE_CALL();
Mutex::Autolock _l(mStateLock);
const nsecs_t now = systemTime();
mDebugInTransaction = now;
// Here we're guaranteed that some transaction flags are set
// so we can call handleTransactionLocked() unconditionally.
// We call getTransactionFlags(), which will also clear the flags,
// with mStateLock held to guarantee that mCurrentState won't change
// until the transaction is committed.
const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
transactionFlags = getTransactionFlags(mask);
handleTransactionLocked(transactionFlags);
mLastTransactionTime = systemTime() - now;
mDebugInTransaction = 0;
invalidateHwcGeometry();
// here the transaction has been committed
}
void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
{
const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
const size_t count = currentLayers.size();
/*
* Traversal of the children
* (perform the transaction for each of them if needed)
*/
const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
if (layersNeedTransaction) {
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer = currentLayers[i];
uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
if (!trFlags) continue;
const uint32_t flags = layer->doTransaction(0);
if (flags & Layer::eVisibleRegion)
mVisibleRegionsDirty = true;
}
}
/*
* Perform our own transaction if needed
*/
if (transactionFlags & eTransactionNeeded) {
if (mCurrentState.orientation != mDrawingState.orientation) {
// the orientation has changed, recompute all visible regions
// and invalidate everything.
const int dpy = 0;
const int orientation = mCurrentState.orientation;
// Currently unused: const uint32_t flags = mCurrentState.orientationFlags;
GraphicPlane& plane(graphicPlane(dpy));
plane.setOrientation(orientation);
// update the shared control block
const DisplayHardware& hw(plane.displayHardware());
volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
dcblk->orientation = orientation;
dcblk->w = plane.getWidth();
dcblk->h = plane.getHeight();
mVisibleRegionsDirty = true;
mDirtyRegion.set(hw.bounds());
}
if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
// layers have been added
mVisibleRegionsDirty = true;
}
// some layers might have been removed, so
// we need to update the regions they're exposing.
if (mLayersRemoved) {
mLayersRemoved = false;
mVisibleRegionsDirty = true;
const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
const size_t count = previousLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(previousLayers[i]);
if (currentLayers.indexOf( layer ) < 0) {
// this layer is not visible anymore
mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
}
}
}
}
commitTransaction();
}
void SurfaceFlinger::computeVisibleRegions(
const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
{
ATRACE_CALL();
const GraphicPlane& plane(graphicPlane(0));
const Transform& planeTransform(plane.transform());
const DisplayHardware& hw(plane.displayHardware());
const Region screenRegion(hw.bounds());
Region aboveOpaqueLayers;
Region aboveCoveredLayers;
Region dirty;
bool secureFrameBuffer = false;
size_t i = currentLayers.size();
while (i--) {
const sp<LayerBase>& layer = currentLayers[i];
layer->validateVisibility(planeTransform);
// start with the whole surface at its current location
const Layer::State& s(layer->drawingState());
/*
* opaqueRegion: area of a surface that is fully opaque.
*/
Region opaqueRegion;
/*
* visibleRegion: area of a surface that is visible on screen
* and not fully transparent. This is essentially the layer's
* footprint minus the opaque regions above it.
* Areas covered by a translucent surface are considered visible.
*/
Region visibleRegion;
/*
* coveredRegion: area of a surface that is covered by all
* visible regions above it (which includes the translucent areas).
*/
Region coveredRegion;
/*
* transparentRegion: area of a surface that is hinted to be completely
* transparent. This is only used to tell when the layer has no visible
* non-transparent regions and can be removed from the layer list. It
* does not affect the visibleRegion of this layer or any layers
* beneath it. The hint may not be correct if apps don't respect the
* SurfaceView restrictions (which, sadly, some don't).
*/
Region transparentRegion;
// handle hidden surfaces by setting the visible region to empty
if (CC_LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
const bool translucent = !layer->isOpaque();
const Rect bounds(layer->visibleBounds());
visibleRegion.set(bounds);
visibleRegion.andSelf(screenRegion);
if (!visibleRegion.isEmpty()) {
// Remove the transparent area from the visible region
if (translucent) {
transparentRegion = layer->transparentRegionScreen;
}
// compute the opaque region
const int32_t layerOrientation = layer->getOrientation();
if (s.alpha==255 && !translucent &&
((layerOrientation & Transform::ROT_INVALID) == false)) {
// the opaque region is the layer's footprint
opaqueRegion = visibleRegion;
}
}
}
// Clip the covered region to the visible region
coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
// Update aboveCoveredLayers for next (lower) layer
aboveCoveredLayers.orSelf(visibleRegion);
// subtract the opaque region covered by the layers above us
visibleRegion.subtractSelf(aboveOpaqueLayers);
// compute this layer's dirty region
if (layer->contentDirty) {
// we need to invalidate the whole region
dirty = visibleRegion;
// as well, as the old visible region
dirty.orSelf(layer->visibleRegionScreen);
layer->contentDirty = false;
} else {
/* compute the exposed region:
* the exposed region consists of two components:
* 1) what's VISIBLE now and was COVERED before
* 2) what's EXPOSED now less what was EXPOSED before
*
* note that (1) is conservative, we start with the whole
* visible region but only keep what used to be covered by
* something -- which mean it may have been exposed.
*
* (2) handles areas that were not covered by anything but got
* exposed because of a resize.
*/
const Region newExposed = visibleRegion - coveredRegion;
const Region oldVisibleRegion = layer->visibleRegionScreen;
const Region oldCoveredRegion = layer->coveredRegionScreen;
const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
}
dirty.subtractSelf(aboveOpaqueLayers);
// accumulate to the screen dirty region
dirtyRegion.orSelf(dirty);
// Update aboveOpaqueLayers for next (lower) layer
aboveOpaqueLayers.orSelf(opaqueRegion);
// Store the visible region is screen space
layer->setVisibleRegion(visibleRegion);
layer->setCoveredRegion(coveredRegion);
layer->setVisibleNonTransparentRegion(
visibleRegion.subtract(transparentRegion));
// If a secure layer is partially visible, lock-down the screen!
if (layer->isSecure() && !visibleRegion.isEmpty()) {
secureFrameBuffer = true;
}
}
// invalidate the areas where a layer was removed
dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
mDirtyRegionRemovedLayer.clear();
mSecureFrameBuffer = secureFrameBuffer;
opaqueRegion = aboveOpaqueLayers;
}
void SurfaceFlinger::commitTransaction()
{
if (!mLayersPendingRemoval.isEmpty()) {
// Notify removed layers now that they can't be drawn from
for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
mLayersPendingRemoval[i]->onRemoved();
}
mLayersPendingRemoval.clear();
}
mDrawingState = mCurrentState;
mTransationPending = false;
mTransactionCV.broadcast();
}
void SurfaceFlinger::handlePageFlip()
{
ATRACE_CALL();
const DisplayHardware& hw = graphicPlane(0).displayHardware();
const Region screenRegion(hw.bounds());
const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
const bool visibleRegions = lockPageFlip(currentLayers);
if (visibleRegions || mVisibleRegionsDirty) {
Region opaqueRegion;
computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
/*
* rebuild the visible layer list
*/
const size_t count = currentLayers.size();
mVisibleLayersSortedByZ.clear();
mVisibleLayersSortedByZ.setCapacity(count);
for (size_t i=0 ; i<count ; i++) {
if (!currentLayers[i]->visibleNonTransparentRegion.isEmpty())
mVisibleLayersSortedByZ.add(currentLayers[i]);
}
mWormholeRegion = screenRegion.subtract(opaqueRegion);
mVisibleRegionsDirty = false;
invalidateHwcGeometry();
}
unlockPageFlip(currentLayers);
mDirtyRegion.orSelf(getAndClearInvalidateRegion());
mDirtyRegion.andSelf(screenRegion);
}
void SurfaceFlinger::invalidateHwcGeometry()
{
mHwWorkListDirty = true;
}
bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
{
bool recomputeVisibleRegions = false;
size_t count = currentLayers.size();
sp<LayerBase> const* layers = currentLayers.array();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(layers[i]);
layer->lockPageFlip(recomputeVisibleRegions);
}
return recomputeVisibleRegions;
}
void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
{
const GraphicPlane& plane(graphicPlane(0));
const Transform& planeTransform(plane.transform());
const size_t count = currentLayers.size();
sp<LayerBase> const* layers = currentLayers.array();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(layers[i]);
layer->unlockPageFlip(planeTransform, mDirtyRegion);
}
}
void SurfaceFlinger::handleRefresh()
{
bool needInvalidate = false;
const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
const size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
if (layer->onPreComposition()) {
needInvalidate = true;
}
}
if (needInvalidate) {
signalLayerUpdate();
}
}
void SurfaceFlinger::handleWorkList()
{
mHwWorkListDirty = false;
HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
if (hwc.initCheck() == NO_ERROR) {
const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
const size_t count = currentLayers.size();
hwc.createWorkList(count);
hwc_layer_t* const cur(hwc.getLayers());
for (size_t i=0 ; cur && i<count ; i++) {
currentLayers[i]->setGeometry(&cur[i]);
if (mDebugDisableHWC || mDebugRegion) {
cur[i].compositionType = HWC_FRAMEBUFFER;
cur[i].flags |= HWC_SKIP_LAYER;
}
}
}
}
void SurfaceFlinger::handleRepaint()
{
ATRACE_CALL();
// compute the invalid region
mSwapRegion.orSelf(mDirtyRegion);
if (CC_UNLIKELY(mDebugRegion)) {
debugFlashRegions();
}
// set the frame buffer
const DisplayHardware& hw(graphicPlane(0).displayHardware());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
uint32_t flags = hw.getFlags();
if (flags & DisplayHardware::SWAP_RECTANGLE) {
// we can redraw only what's dirty, but since SWAP_RECTANGLE only
// takes a rectangle, we must make sure to update that whole
// rectangle in that case
mDirtyRegion.set(mSwapRegion.bounds());
} else {
if (flags & DisplayHardware::PARTIAL_UPDATES) {
// We need to redraw the rectangle that will be updated
// (pushed to the framebuffer).
// This is needed because PARTIAL_UPDATES only takes one
// rectangle instead of a region (see DisplayHardware::flip())
mDirtyRegion.set(mSwapRegion.bounds());
} else {
// we need to redraw everything (the whole screen)
mDirtyRegion.set(hw.bounds());
mSwapRegion = mDirtyRegion;
}
}
setupHardwareComposer();
composeSurfaces(mDirtyRegion);
// update the swap region and clear the dirty region
mSwapRegion.orSelf(mDirtyRegion);
mDirtyRegion.clear();
}
void SurfaceFlinger::setupHardwareComposer()
{
const DisplayHardware& hw(graphicPlane(0).displayHardware());
HWComposer& hwc(hw.getHwComposer());
hwc_layer_t* const cur(hwc.getLayers());
if (!cur) {
return;
}
const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
size_t count = layers.size();
ALOGE_IF(hwc.getNumLayers() != count,
"HAL number of layers (%d) doesn't match surfaceflinger (%d)",
hwc.getNumLayers(), count);
// just to be extra-safe, use the smallest count
if (hwc.initCheck() == NO_ERROR) {
count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
}
/*
* update the per-frame h/w composer data for each layer
* and build the transparent region of the FB
*/
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(layers[i]);
layer->setPerFrameData(&cur[i]);
}
status_t err = hwc.prepare();
ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
}
void SurfaceFlinger::composeSurfaces(const Region& dirty)
{
const DisplayHardware& hw(graphicPlane(0).displayHardware());
HWComposer& hwc(hw.getHwComposer());
hwc_layer_t* const cur(hwc.getLayers());
const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);
if (!cur || fbLayerCount) {
// Never touch the framebuffer if we don't have any framebuffer layers
if (hwc.getLayerCount(HWC_OVERLAY)) {
// when using overlays, we assume a fully transparent framebuffer
// NOTE: we could reduce how much we need to clear, for instance
// remove where there are opaque FB layers. however, on some
// GPUs doing a "clean slate" glClear might be more efficient.
// We'll revisit later if needed.
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
} else {
// screen is already cleared here
if (!mWormholeRegion.isEmpty()) {
// can happen with SurfaceView
drawWormhole();
}
}
/*
* and then, render the layers targeted at the framebuffer
*/
const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
const size_t count = layers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(layers[i]);
const Region clip(dirty.intersect(layer->visibleRegionScreen));
if (!clip.isEmpty()) {
if (cur && (cur[i].compositionType == HWC_OVERLAY)) {
if (i && (cur[i].hints & HWC_HINT_CLEAR_FB)
&& layer->isOpaque()) {
// never clear the very first layer since we're
// guaranteed the FB is already cleared
layer->clearWithOpenGL(clip);
}
continue;
}
// render the layer
layer->draw(clip);
}
}
}
}
void SurfaceFlinger::debugFlashRegions()
{
const DisplayHardware& hw(graphicPlane(0).displayHardware());
const uint32_t flags = hw.getFlags();
const int32_t height = hw.getHeight();
if (mSwapRegion.isEmpty()) {
return;
}
if (!(flags & DisplayHardware::SWAP_RECTANGLE)) {
const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
mDirtyRegion.bounds() : hw.bounds());
composeSurfaces(repaint);
}
glDisable(GL_TEXTURE_EXTERNAL_OES);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
static int toggle = 0;
toggle = 1 - toggle;
if (toggle) {
glColor4f(1, 0, 1, 1);
} else {
glColor4f(1, 1, 0, 1);
}
Region::const_iterator it = mDirtyRegion.begin();
Region::const_iterator const end = mDirtyRegion.end();
while (it != end) {
const Rect& r = *it++;
GLfloat vertices[][2] = {
{ r.left, height - r.top },
{ r.left, height - r.bottom },
{ r.right, height - r.bottom },
{ r.right, height - r.top }
};
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
hw.flip(mSwapRegion);
if (mDebugRegion > 1)
usleep(mDebugRegion * 1000);
}
void SurfaceFlinger::drawWormhole() const
{
const Region region(mWormholeRegion.intersect(mDirtyRegion));
if (region.isEmpty())
return;
glDisable(GL_TEXTURE_EXTERNAL_OES);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glColor4f(0,0,0,0);
GLfloat vertices[4][2];
glVertexPointer(2, GL_FLOAT, 0, vertices);
Region::const_iterator it = region.begin();
Region::const_iterator const end = region.end();
while (it != end) {
const Rect& r = *it++;
vertices[0][0] = r.left;
vertices[0][1] = r.top;
vertices[1][0] = r.right;
vertices[1][1] = r.top;
vertices[2][0] = r.right;
vertices[2][1] = r.bottom;
vertices[3][0] = r.left;
vertices[3][1] = r.bottom;
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
}
status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
{
Mutex::Autolock _l(mStateLock);
addLayer_l(layer);
setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
return NO_ERROR;
}
status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
{
ssize_t i = mCurrentState.layersSortedByZ.add(layer);
return (i < 0) ? status_t(i) : status_t(NO_ERROR);
}
ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
const sp<LayerBaseClient>& lbc)
{
// attach this layer to the client
size_t name = client->attachLayer(lbc);
Mutex::Autolock _l(mStateLock);
// add this layer to the current state list
addLayer_l(lbc);
return ssize_t(name);
}
status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
{
Mutex::Autolock _l(mStateLock);
status_t err = purgatorizeLayer_l(layer);
if (err == NO_ERROR)
setTransactionFlags(eTransactionNeeded);
return err;
}
status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
{
sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
if (lbc != 0) {
mLayerMap.removeItem( lbc->getSurfaceBinder() );
}
ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
if (index >= 0) {
mLayersRemoved = true;
return NO_ERROR;
}
return status_t(index);
}
status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
{
// First add the layer to the purgatory list, which makes sure it won't
// go away, then remove it from the main list (through a transaction).
ssize_t err = removeLayer_l(layerBase);
if (err >= 0) {
mLayerPurgatory.add(layerBase);
}
mLayersPendingRemoval.push(layerBase);
// it's possible that we don't find a layer, because it might
// have been destroyed already -- this is not technically an error
// from the user because there is a race between Client::destroySurface(),
// ~Client() and ~ISurface().
return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
}
status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
{
layer->forceVisibilityTransaction();
setTransactionFlags(eTraversalNeeded);
return NO_ERROR;
}
uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
{
return android_atomic_release_load(&mTransactionFlags);
}
uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
{
return android_atomic_and(~flags, &mTransactionFlags) & flags;
}
uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
{
uint32_t old = android_atomic_or(flags, &mTransactionFlags);
if ((old & flags)==0) { // wake the server up
signalTransaction();
}
return old;
}
void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state,
int orientation, uint32_t flags) {
Mutex::Autolock _l(mStateLock);
uint32_t transactionFlags = 0;
if (mCurrentState.orientation != orientation) {
if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
mCurrentState.orientation = orientation;
transactionFlags |= eTransactionNeeded;
} else if (orientation != eOrientationUnchanged) {
ALOGW("setTransactionState: ignoring unrecognized orientation: %d",
orientation);
}
}
const size_t count = state.size();
for (size_t i=0 ; i<count ; i++) {
const ComposerState& s(state[i]);
sp<Client> client( static_cast<Client *>(s.client.get()) );
transactionFlags |= setClientStateLocked(client, s.state);
}
if (transactionFlags) {
// this triggers the transaction
setTransactionFlags(transactionFlags);
// if this is a synchronous transaction, wait for it to take effect
// before returning.
if (flags & eSynchronous) {
mTransationPending = true;
}
while (mTransationPending) {
status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
if (CC_UNLIKELY(err != NO_ERROR)) {
// just in case something goes wrong in SF, return to the
// called after a few seconds.
ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
mTransationPending = false;
break;
}
}
}
}
sp<ISurface> SurfaceFlinger::createSurface(
ISurfaceComposerClient::surface_data_t* params,
const String8& name,
const sp<Client>& client,
DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags)
{
sp<LayerBaseClient> layer;
sp<ISurface> surfaceHandle;
if (int32_t(w|h) < 0) {
ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
int(w), int(h));
return surfaceHandle;
}
//ALOGD("createSurface for (%d x %d), name=%s", w, h, name.string());
sp<Layer> normalLayer;
switch (flags & eFXSurfaceMask) {
case eFXSurfaceNormal:
normalLayer = createNormalSurface(client, d, w, h, flags, format);
layer = normalLayer;
break;
case eFXSurfaceBlur:
// for now we treat Blur as Dim, until we can implement it
// efficiently.
case eFXSurfaceDim:
layer = createDimSurface(client, d, w, h, flags);
break;
case eFXSurfaceScreenshot:
layer = createScreenshotSurface(client, d, w, h, flags);
break;
}
if (layer != 0) {
layer->initStates(w, h, flags);
layer->setName(name);
ssize_t token = addClientLayer(client, layer);
surfaceHandle = layer->getSurface();
if (surfaceHandle != 0) {
params->token = token;
params->identity = layer->getIdentity();
if (normalLayer != 0) {
Mutex::Autolock _l(mStateLock);
mLayerMap.add(layer->getSurfaceBinder(), normalLayer);
}
}
setTransactionFlags(eTransactionNeeded);
}
return surfaceHandle;
}
sp<Layer> SurfaceFlinger::createNormalSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags,
PixelFormat& format)
{
// initialize the surfaces
switch (format) { // TODO: take h/w into account
case PIXEL_FORMAT_TRANSPARENT:
case PIXEL_FORMAT_TRANSLUCENT:
format = PIXEL_FORMAT_RGBA_8888;
break;
case PIXEL_FORMAT_OPAQUE:
#ifdef NO_RGBX_8888
format = PIXEL_FORMAT_RGB_565;
#else
format = PIXEL_FORMAT_RGBX_8888;
#endif
break;
}
#ifdef NO_RGBX_8888
if (format == PIXEL_FORMAT_RGBX_8888)
format = PIXEL_FORMAT_RGBA_8888;
#endif
sp<Layer> layer = new Layer(this, display, client);
status_t err = layer->setBuffers(w, h, format, flags);
if (CC_LIKELY(err != NO_ERROR)) {
ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
layer.clear();
}
return layer;
}
sp<LayerDim> SurfaceFlinger::createDimSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags)
{
sp<LayerDim> layer = new LayerDim(this, display, client);
return layer;
}
sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags)
{
sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client);
return layer;
}
status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
{
/*
* called by the window manager, when a surface should be marked for
* destruction.
*
* The surface is removed from the current and drawing lists, but placed
* in the purgatory queue, so it's not destroyed right-away (we need
* to wait for all client's references to go away first).
*/
status_t err = NAME_NOT_FOUND;
Mutex::Autolock _l(mStateLock);
sp<LayerBaseClient> layer = client->getLayerUser(sid);
if (layer != 0) {
err = purgatorizeLayer_l(layer);
if (err == NO_ERROR) {
setTransactionFlags(eTransactionNeeded);
}
}
return err;
}
status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer)
{
// called by ~ISurface() when all references are gone
status_t err = NO_ERROR;
sp<LayerBaseClient> l(layer.promote());
if (l != NULL) {
Mutex::Autolock _l(mStateLock);
err = removeLayer_l(l);
if (err == NAME_NOT_FOUND) {
// The surface wasn't in the current list, which means it was
// removed already, which means it is in the purgatory,
// and need to be removed from there.
ssize_t idx = mLayerPurgatory.remove(l);
ALOGE_IF(idx < 0,
"layer=%p is not in the purgatory list", l.get());
}
ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
"error removing layer=%p (%s)", l.get(), strerror(-err));
}
return err;
}
uint32_t SurfaceFlinger::setClientStateLocked(
const sp<Client>& client,
const layer_state_t& s)
{
uint32_t flags = 0;
sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
if (layer != 0) {
const uint32_t what = s.what;
if (what & ePositionChanged) {
if (layer->setPosition(s.x, s.y))
flags |= eTraversalNeeded;
}
if (what & eLayerChanged) {
ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
if (layer->setLayer(s.z)) {
mCurrentState.layersSortedByZ.removeAt(idx);
mCurrentState.layersSortedByZ.add(layer);
// we need traversal (state changed)
// AND transaction (list changed)
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
if (what & eSizeChanged) {
if (layer->setSize(s.w, s.h)) {
flags |= eTraversalNeeded;
}
}
if (what & eAlphaChanged) {
if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
flags |= eTraversalNeeded;
}
if (what & eMatrixChanged) {
if (layer->setMatrix(s.matrix))
flags |= eTraversalNeeded;
}
if (what & eTransparentRegionChanged) {
if (layer->setTransparentRegionHint(s.transparentRegion))
flags |= eTraversalNeeded;
}
if (what & eVisibilityChanged) {
if (layer->setFlags(s.flags, s.mask))
flags |= eTraversalNeeded;
}
if (what & eCropChanged) {
if (layer->setCrop(s.crop))
flags |= eTraversalNeeded;
}
}
return flags;
}
// ---------------------------------------------------------------------------
void SurfaceFlinger::onScreenAcquired() {
const DisplayHardware& hw(graphicPlane(0).displayHardware());
hw.acquireScreen();
mEventThread->onScreenAcquired();
// this is a temporary work-around, eventually this should be called
// by the power-manager
SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
// from this point on, SF will process updates again
repaintEverything();
}
void SurfaceFlinger::onScreenReleased() {
const DisplayHardware& hw(graphicPlane(0).displayHardware());
if (hw.isScreenAcquired()) {
mEventThread->onScreenReleased();
hw.releaseScreen();
// from this point on, SF will stop drawing
}
}
void SurfaceFlinger::screenAcquired() {
class MessageScreenAcquired : public MessageBase {
SurfaceFlinger* flinger;
public:
MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
virtual bool handler() {
flinger->onScreenAcquired();
return true;
}
};
sp<MessageBase> msg = new MessageScreenAcquired(this);
postMessageSync(msg);
}
void SurfaceFlinger::screenReleased() {
class MessageScreenReleased : public MessageBase {
SurfaceFlinger* flinger;
public:
MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
virtual bool handler() {
flinger->onScreenReleased();
return true;
}
};
sp<MessageBase> msg = new MessageScreenReleased(this);
postMessageSync(msg);
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
{
const size_t SIZE = 4096;
char buffer[SIZE];
String8 result;
if (!PermissionCache::checkCallingPermission(sDump)) {
snprintf(buffer, SIZE, "Permission Denial: "
"can't dump SurfaceFlinger from pid=%d, uid=%d\n",
IPCThreadState::self()->getCallingPid(),
IPCThreadState::self()->getCallingUid());
result.append(buffer);
} else {
// Try to get the main lock, but don't insist if we can't
// (this would indicate SF is stuck, but we want to be able to
// print something in dumpsys).
int retry = 3;
while (mStateLock.tryLock()<0 && --retry>=0) {
usleep(1000000);
}
const bool locked(retry >= 0);
if (!locked) {
snprintf(buffer, SIZE,
"SurfaceFlinger appears to be unresponsive, "
"dumping anyways (no locks held)\n");
result.append(buffer);
}
bool dumpAll = true;
size_t index = 0;
size_t numArgs = args.size();
if (numArgs) {
if ((index < numArgs) &&
(args[index] == String16("--list"))) {
index++;
listLayersLocked(args, index, result, buffer, SIZE);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--latency"))) {
index++;
dumpStatsLocked(args, index, result, buffer, SIZE);
dumpAll = false;
}
if ((index < numArgs) &&
(args[index] == String16("--latency-clear"))) {
index++;
clearStatsLocked(args, index, result, buffer, SIZE);
dumpAll = false;
}
}
if (dumpAll) {
dumpAllLocked(result, buffer, SIZE);
}
if (locked) {
mStateLock.unlock();
}
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
String8& result, char* buffer, size_t SIZE) const
{
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
snprintf(buffer, SIZE, "%s\n", layer->getName().string());
result.append(buffer);
}
}
void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
String8& result, char* buffer, size_t SIZE) const
{
String8 name;
if (index < args.size()) {
name = String8(args[index]);
index++;
}
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
if (name.isEmpty()) {
snprintf(buffer, SIZE, "%s\n", layer->getName().string());
result.append(buffer);
}
if (name.isEmpty() || (name == layer->getName())) {
layer->dumpStats(result, buffer, SIZE);
}
}
}
void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
String8& result, char* buffer, size_t SIZE) const
{
String8 name;
if (index < args.size()) {
name = String8(args[index]);
index++;
}
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
if (name.isEmpty() || (name == layer->getName())) {
layer->clearStats();
}
}
}
void SurfaceFlinger::dumpAllLocked(
String8& result, char* buffer, size_t SIZE) const
{
// figure out if we're stuck somewhere
const nsecs_t now = systemTime();
const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
const nsecs_t inTransaction(mDebugInTransaction);
nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
/*
* Dump the visible layer list
*/
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
result.append(buffer);
for (size_t i=0 ; i<count ; i++) {
const sp<LayerBase>& layer(currentLayers[i]);
layer->dump(result, buffer, SIZE);
}
/*
* Dump the layers in the purgatory
*/
const size_t purgatorySize = mLayerPurgatory.size();
snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
result.append(buffer);
for (size_t i=0 ; i<purgatorySize ; i++) {
const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
layer->shortDump(result, buffer, SIZE);
}
/*
* Dump SurfaceFlinger global state
*/
snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
result.append(buffer);
const GLExtensions& extensions(GLExtensions::getInstance());
snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
extensions.getVendor(),
extensions.getRenderer(),
extensions.getVersion());
result.append(buffer);
snprintf(buffer, SIZE, "EGL : %s\n",
eglQueryString(graphicPlane(0).getEGLDisplay(),
EGL_VERSION_HW_ANDROID));
result.append(buffer);
snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
result.append(buffer);
mWormholeRegion.dump(result, "WormholeRegion");
const DisplayHardware& hw(graphicPlane(0).displayHardware());
snprintf(buffer, SIZE,
" orientation=%d, canDraw=%d\n",
mCurrentState.orientation, hw.canDraw());
result.append(buffer);
snprintf(buffer, SIZE,
" last eglSwapBuffers() time: %f us\n"
" last transaction time : %f us\n"
" transaction-flags : %08x\n"
" refresh-rate : %f fps\n"
" x-dpi : %f\n"
" y-dpi : %f\n"
" density : %f\n",
mLastSwapBufferTime/1000.0,
mLastTransactionTime/1000.0,
mTransactionFlags,
hw.getRefreshRate(),
hw.getDpiX(),
hw.getDpiY(),
hw.getDensity());
result.append(buffer);
snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
inSwapBuffersDuration/1000.0);
result.append(buffer);
snprintf(buffer, SIZE, " transaction time: %f us\n",
inTransactionDuration/1000.0);
result.append(buffer);
/*
* VSYNC state
*/
mEventThread->dump(result, buffer, SIZE);
/*
* Dump HWComposer state
*/
HWComposer& hwc(hw.getHwComposer());
snprintf(buffer, SIZE, "h/w composer state:\n");
result.append(buffer);
snprintf(buffer, SIZE, " h/w composer %s and %s\n",
hwc.initCheck()==NO_ERROR ? "present" : "not present",
(mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
result.append(buffer);
hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ);
/*
* Dump gralloc state
*/
const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
alloc.dump(result);
hw.dump(result);
}
status_t SurfaceFlinger::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch (code) {
case CREATE_CONNECTION:
case SET_TRANSACTION_STATE:
case SET_ORIENTATION:
case BOOT_FINISHED:
case TURN_ELECTRON_BEAM_OFF:
case TURN_ELECTRON_BEAM_ON:
{
// codes that require permission check
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS) &&
!PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
ALOGE("Permission Denial: "
"can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
break;
}
case CAPTURE_SCREEN:
{
// codes that require permission check
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS) &&
!PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
ALOGE("Permission Denial: "
"can't read framebuffer pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
break;
}
}
status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
CHECK_INTERFACE(ISurfaceComposer, data, reply);
if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
ALOGE("Permission Denial: "
"can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
int n;
switch (code) {
case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
return NO_ERROR;
case 1002: // SHOW_UPDATES
n = data.readInt32();
mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1004:{ // repaint everything
repaintEverything();
return NO_ERROR;
}
case 1005:{ // force transaction
setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
return NO_ERROR;
}
case 1006:{ // send empty update
signalRefresh();
return NO_ERROR;
}
case 1008: // toggle use of hw composer
n = data.readInt32();
mDebugDisableHWC = n ? 1 : 0;
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1009: // toggle use of transform hint
n = data.readInt32();
mDebugDisableTransformHint = n ? 1 : 0;
invalidateHwcGeometry();
repaintEverything();
return NO_ERROR;
case 1010: // interrogate.
reply->writeInt32(0);
reply->writeInt32(0);
reply->writeInt32(mDebugRegion);
reply->writeInt32(0);
reply->writeInt32(mDebugDisableHWC);
return NO_ERROR;
case 1013: {
Mutex::Autolock _l(mStateLock);
const DisplayHardware& hw(graphicPlane(0).displayHardware());
reply->writeInt32(hw.getPageFlipCount());
}
return NO_ERROR;
}
}
return err;
}
void SurfaceFlinger::repaintEverything() {
const DisplayHardware& hw(graphicPlane(0).displayHardware());
const Rect bounds(hw.getBounds());
setInvalidateRegion(Region(bounds));
signalTransaction();
}
void SurfaceFlinger::setInvalidateRegion(const Region& reg) {
Mutex::Autolock _l(mInvalidateLock);
mInvalidateRegion = reg;
}
Region SurfaceFlinger::getAndClearInvalidateRegion() {
Mutex::Autolock _l(mInvalidateLock);
Region reg(mInvalidateRegion);
mInvalidateRegion.clear();
return reg;
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
{
Mutex::Autolock _l(mStateLock);
return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
}
status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
{
ATRACE_CALL();
if (!GLExtensions::getInstance().haveFramebufferObject())
return INVALID_OPERATION;
// get screen geometry
const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
const uint32_t hw_w = hw.getWidth();
const uint32_t hw_h = hw.getHeight();
GLfloat u = 1;
GLfloat v = 1;
// make sure to clear all GL error flags
while ( glGetError() != GL_NO_ERROR ) ;
// create a FBO
GLuint name, tname;
glGenTextures(1, &tname);
glBindTexture(GL_TEXTURE_2D, tname);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
if (glGetError() != GL_NO_ERROR) {
while ( glGetError() != GL_NO_ERROR ) ;
GLint tw = (2 << (31 - clz(hw_w)));
GLint th = (2 << (31 - clz(hw_h)));
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
u = GLfloat(hw_w) / tw;
v = GLfloat(hw_h) / th;
}
glGenFramebuffersOES(1, &name);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
// redraw the screen entirely...
glDisable(GL_TEXTURE_EXTERNAL_OES);
glDisable(GL_TEXTURE_2D);
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
const size_t count = layers.size();
for (size_t i=0 ; i<count ; ++i) {
const sp<LayerBase>& layer(layers[i]);
layer->drawForSreenShot();
}
hw.compositionComplete();
// back to main framebuffer
glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
glDeleteFramebuffersOES(1, &name);
*textureName = tname;
*uOut = u;
*vOut = v;
return NO_ERROR;
}
// ---------------------------------------------------------------------------
class VSyncWaiter {
DisplayEventReceiver::Event buffer[4];
sp<Looper> looper;
sp<IDisplayEventConnection> events;
sp<BitTube> eventTube;
public:
VSyncWaiter(const sp<EventThread>& eventThread) {
looper = new Looper(true);
events = eventThread->createEventConnection();
eventTube = events->getDataChannel();
looper->addFd(eventTube->getFd(), 0, ALOOPER_EVENT_INPUT, 0, 0);
events->requestNextVsync();
}
void wait() {
ssize_t n;
looper->pollOnce(-1);
// we don't handle any errors here, it doesn't matter
// and we don't want to take the risk to get stuck.
// drain the events...
while ((n = DisplayEventReceiver::getEvents(
eventTube, buffer, 4)) > 0) ;
events->requestNextVsync();
}
};
status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
{
// get screen geometry
const DisplayHardware& hw(graphicPlane(0).displayHardware());
const uint32_t hw_w = hw.getWidth();
const uint32_t hw_h = hw.getHeight();
const Region screenBounds(hw.getBounds());
GLfloat u, v;
GLuint tname;
status_t result = renderScreenToTextureLocked(0, &tname, &u, &v);
if (result != NO_ERROR) {
return result;
}
GLfloat vtx[8];
const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} };
glBindTexture(GL_TEXTURE_2D, tname);
glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vtx);
/*
* Texture coordinate mapping
*
* u
* 1 +----------+---+
* | | | | image is inverted
* | V | | w.r.t. the texture
* 1-v +----------+ | coordinates
* | |
* | |
* | |
* 0 +--------------+
* 0 1
*
*/
class s_curve_interpolator {
const float nbFrames, s, v;
public:
s_curve_interpolator(int nbFrames, float s)
: nbFrames(1.0f / (nbFrames-1)), s(s),
v(1.0f + expf(-s + 0.5f*s)) {
}
float operator()(int f) {
const float x = f * nbFrames;
return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
}
};
class v_stretch {
const GLfloat hw_w, hw_h;
public:
v_stretch(uint32_t hw_w, uint32_t hw_h)
: hw_w(hw_w), hw_h(hw_h) {
}
void operator()(GLfloat* vtx, float v) {
const GLfloat w = hw_w + (hw_w * v);
const GLfloat h = hw_h - (hw_h * v);
const GLfloat x = (hw_w - w) * 0.5f;
const GLfloat y = (hw_h - h) * 0.5f;
vtx[0] = x; vtx[1] = y;
vtx[2] = x; vtx[3] = y + h;
vtx[4] = x + w; vtx[5] = y + h;
vtx[6] = x + w; vtx[7] = y;
}
};
class h_stretch {
const GLfloat hw_w, hw_h;
public:
h_stretch(uint32_t hw_w, uint32_t hw_h)
: hw_w(hw_w), hw_h(hw_h) {
}
void operator()(GLfloat* vtx, float v) {
const GLfloat w = hw_w - (hw_w * v);
const GLfloat h = 1.0f;
const GLfloat x = (hw_w - w) * 0.5f;
const GLfloat y = (hw_h - h) * 0.5f;
vtx[0] = x; vtx[1] = y;
vtx[2] = x; vtx[3] = y + h;
vtx[4] = x + w; vtx[5] = y + h;
vtx[6] = x + w; vtx[7] = y;
}
};
VSyncWaiter vsync(mEventThread);
// the full animation is 24 frames
char value[PROPERTY_VALUE_MAX];
property_get("debug.sf.electron_frames", value, "24");
int nbFrames = (atoi(value) + 1) >> 1;
if (nbFrames <= 0) // just in case
nbFrames = 24;
s_curve_interpolator itr(nbFrames, 7.5f);
s_curve_interpolator itg(nbFrames, 8.0f);
s_curve_interpolator itb(nbFrames, 8.5f);
v_stretch vverts(hw_w, hw_h);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
for (int i=0 ; i<nbFrames ; i++) {
float x, y, w, h;
const float vr = itr(i);
const float vg = itg(i);
const float vb = itb(i);
// wait for vsync
vsync.wait();
// clear screen
glColorMask(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
// draw the red plane
vverts(vtx, vr);
glColorMask(1,0,0,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// draw the green plane
vverts(vtx, vg);
glColorMask(0,1,0,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// draw the blue plane
vverts(vtx, vb);
glColorMask(0,0,1,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// draw the white highlight (we use the last vertices)
glDisable(GL_TEXTURE_2D);
glColorMask(1,1,1,1);
glColor4f(vg, vg, vg, 1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
hw.flip(screenBounds);
}
h_stretch hverts(hw_w, hw_h);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glColorMask(1,1,1,1);
for (int i=0 ; i<nbFrames ; i++) {
const float v = itg(i);
hverts(vtx, v);
// wait for vsync
vsync.wait();
glClear(GL_COLOR_BUFFER_BIT);
glColor4f(1-v, 1-v, 1-v, 1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
hw.flip(screenBounds);
}
glColorMask(1,1,1,1);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDeleteTextures(1, &tname);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
return NO_ERROR;
}
status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
{
status_t result = PERMISSION_DENIED;
if (!GLExtensions::getInstance().haveFramebufferObject())
return INVALID_OPERATION;
// get screen geometry
const DisplayHardware& hw(graphicPlane(0).displayHardware());
const uint32_t hw_w = hw.getWidth();
const uint32_t hw_h = hw.getHeight();
const Region screenBounds(hw.bounds());
GLfloat u, v;
GLuint tname;
result = renderScreenToTextureLocked(0, &tname, &u, &v);
if (result != NO_ERROR) {
return result;
}
GLfloat vtx[8];
const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
glBindTexture(GL_TEXTURE_2D, tname);
glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vtx);
class s_curve_interpolator {
const float nbFrames, s, v;
public:
s_curve_interpolator(int nbFrames, float s)
: nbFrames(1.0f / (nbFrames-1)), s(s),
v(1.0f + expf(-s + 0.5f*s)) {
}
float operator()(int f) {
const float x = f * nbFrames;
return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
}
};
class v_stretch {
const GLfloat hw_w, hw_h;
public:
v_stretch(uint32_t hw_w, uint32_t hw_h)
: hw_w(hw_w), hw_h(hw_h) {
}
void operator()(GLfloat* vtx, float v) {
const GLfloat w = hw_w + (hw_w * v);
const GLfloat h = hw_h - (hw_h * v);
const GLfloat x = (hw_w - w) * 0.5f;
const GLfloat y = (hw_h - h) * 0.5f;
vtx[0] = x; vtx[1] = y;
vtx[2] = x; vtx[3] = y + h;
vtx[4] = x + w; vtx[5] = y + h;
vtx[6] = x + w; vtx[7] = y;
}
};
class h_stretch {
const GLfloat hw_w, hw_h;
public:
h_stretch(uint32_t hw_w, uint32_t hw_h)
: hw_w(hw_w), hw_h(hw_h) {
}
void operator()(GLfloat* vtx, float v) {
const GLfloat w = hw_w - (hw_w * v);
const GLfloat h = 1.0f;
const GLfloat x = (hw_w - w) * 0.5f;
const GLfloat y = (hw_h - h) * 0.5f;
vtx[0] = x; vtx[1] = y;
vtx[2] = x; vtx[3] = y + h;
vtx[4] = x + w; vtx[5] = y + h;
vtx[6] = x + w; vtx[7] = y;
}
};
VSyncWaiter vsync(mEventThread);
// the full animation is 12 frames
int nbFrames = 8;
s_curve_interpolator itr(nbFrames, 7.5f);
s_curve_interpolator itg(nbFrames, 8.0f);
s_curve_interpolator itb(nbFrames, 8.5f);
h_stretch hverts(hw_w, hw_h);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glColorMask(1,1,1,1);
for (int i=nbFrames-1 ; i>=0 ; i--) {
const float v = itg(i);
hverts(vtx, v);
// wait for vsync
vsync.wait();
glClear(GL_COLOR_BUFFER_BIT);
glColor4f(1-v, 1-v, 1-v, 1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
hw.flip(screenBounds);
}
nbFrames = 4;
v_stretch vverts(hw_w, hw_h);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
for (int i=nbFrames-1 ; i>=0 ; i--) {
float x, y, w, h;
const float vr = itr(i);
const float vg = itg(i);
const float vb = itb(i);
// wait for vsync
vsync.wait();
// clear screen
glColorMask(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
// draw the red plane
vverts(vtx, vr);
glColorMask(1,0,0,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// draw the green plane
vverts(vtx, vg);
glColorMask(0,1,0,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// draw the blue plane
vverts(vtx, vb);
glColorMask(0,0,1,1);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
hw.flip(screenBounds);
}
glColorMask(1,1,1,1);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDeleteTextures(1, &tname);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
return NO_ERROR;
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
{
ATRACE_CALL();
DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
if (!hw.canDraw()) {
// we're already off
return NO_ERROR;
}
// turn off hwc while we're doing the animation
hw.getHwComposer().disable();
// and make sure to turn it back on (if needed) next time we compose
invalidateHwcGeometry();
if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
electronBeamOffAnimationImplLocked();
}
// always clear the whole screen at the end of the animation
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);
hw.flip( Region(hw.bounds()) );
return NO_ERROR;
}
status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
{
class MessageTurnElectronBeamOff : public MessageBase {
SurfaceFlinger* flinger;
int32_t mode;
status_t result;
public:
MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
: flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
}
status_t getResult() const {
return result;
}
virtual bool handler() {
Mutex::Autolock _l(flinger->mStateLock);
result = flinger->turnElectronBeamOffImplLocked(mode);
return true;
}
};
sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
status_t res = postMessageSync(msg);
if (res == NO_ERROR) {
res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
// work-around: when the power-manager calls us we activate the
// animation. eventually, the "on" animation will be called
// by the power-manager itself
mElectronBeamAnimationMode = mode;
}
return res;
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
{
DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
if (hw.canDraw()) {
// we're already on
return NO_ERROR;
}
if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
electronBeamOnAnimationImplLocked();
}
// make sure to redraw the whole screen when the animation is done
mDirtyRegion.set(hw.bounds());
signalTransaction();
return NO_ERROR;
}
status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
{
class MessageTurnElectronBeamOn : public MessageBase {
SurfaceFlinger* flinger;
int32_t mode;
status_t result;
public:
MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
: flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
}
status_t getResult() const {
return result;
}
virtual bool handler() {
Mutex::Autolock _l(flinger->mStateLock);
result = flinger->turnElectronBeamOnImplLocked(mode);
return true;
}
};
postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
return NO_ERROR;
}
// ---------------------------------------------------------------------------
status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
sp<IMemoryHeap>* heap,
uint32_t* w, uint32_t* h, PixelFormat* f,
uint32_t sw, uint32_t sh,
uint32_t minLayerZ, uint32_t maxLayerZ)
{
ATRACE_CALL();
status_t result = PERMISSION_DENIED;
// only one display supported for now
if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
return BAD_VALUE;
if (!GLExtensions::getInstance().haveFramebufferObject())
return INVALID_OPERATION;
// get screen geometry
const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
const uint32_t hw_w = hw.getWidth();
const uint32_t hw_h = hw.getHeight();
if ((sw > hw_w) || (sh > hw_h))
return BAD_VALUE;
sw = (!sw) ? hw_w : sw;
sh = (!sh) ? hw_h : sh;
const size_t size = sw * sh * 4;
//ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
// sw, sh, minLayerZ, maxLayerZ);
// make sure to clear all GL error flags
while ( glGetError() != GL_NO_ERROR ) ;
// create a FBO
GLuint name, tname;
glGenRenderbuffersOES(1, &tname);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
glGenFramebuffersOES(1, &name);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
// invert everything, b/c glReadPixel() below will invert the FB
glViewport(0, 0, sw, sh);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrthof(0, hw_w, hw_h, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
// redraw the screen entirely...
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT);
const LayerVector& layers(mDrawingState.layersSortedByZ);
const size_t count = layers.size();
for (size_t i=0 ; i<count ; ++i) {
const sp<LayerBase>& layer(layers[i]);
const uint32_t flags = layer->drawingState().flags;
if (!(flags & ISurfaceComposer::eLayerHidden)) {
const uint32_t z = layer->drawingState().z;
if (z >= minLayerZ && z <= maxLayerZ) {
layer->drawForSreenShot();
}
}
}
// check for errors and return screen capture
if (glGetError() != GL_NO_ERROR) {
// error while rendering
result = INVALID_OPERATION;
} else {
// allocate shared memory large enough to hold the
// screen capture
sp<MemoryHeapBase> base(
new MemoryHeapBase(size, 0, "screen-capture") );
void* const ptr = base->getBase();
if (ptr) {
// capture the screen with glReadPixels()
ScopedTrace _t(ATRACE_TAG, "glReadPixels");
glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
if (glGetError() == GL_NO_ERROR) {
*heap = base;
*w = sw;
*h = sh;
*f = PIXEL_FORMAT_RGBA_8888;
result = NO_ERROR;
}
} else {
result = NO_MEMORY;
}
}
glViewport(0, 0, hw_w, hw_h);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
} else {
result = BAD_VALUE;
}
// release FBO resources
glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
glDeleteRenderbuffersOES(1, &tname);
glDeleteFramebuffersOES(1, &name);
hw.compositionComplete();
// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
return result;
}
status_t SurfaceFlinger::captureScreen(DisplayID dpy,
sp<IMemoryHeap>* heap,
uint32_t* width, uint32_t* height, PixelFormat* format,
uint32_t sw, uint32_t sh,
uint32_t minLayerZ, uint32_t maxLayerZ)
{
// only one display supported for now
if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
return BAD_VALUE;
if (!GLExtensions::getInstance().haveFramebufferObject())
return INVALID_OPERATION;
class MessageCaptureScreen : public MessageBase {
SurfaceFlinger* flinger;
DisplayID dpy;
sp<IMemoryHeap>* heap;
uint32_t* w;
uint32_t* h;
PixelFormat* f;
uint32_t sw;
uint32_t sh;
uint32_t minLayerZ;
uint32_t maxLayerZ;
status_t result;
public:
MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
uint32_t sw, uint32_t sh,
uint32_t minLayerZ, uint32_t maxLayerZ)
: flinger(flinger), dpy(dpy),
heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
result(PERMISSION_DENIED)
{
}
status_t getResult() const {
return result;
}
virtual bool handler() {
Mutex::Autolock _l(flinger->mStateLock);
// if we have secure windows, never allow the screen capture
if (flinger->mSecureFrameBuffer)
return true;
result = flinger->captureScreenImplLocked(dpy,
heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
return true;
}
};
sp<MessageBase> msg = new MessageCaptureScreen(this,
dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
status_t res = postMessageSync(msg);
if (res == NO_ERROR) {
res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
}
return res;
}
// ---------------------------------------------------------------------------
sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
{
sp<Layer> result;
Mutex::Autolock _l(mStateLock);
result = mLayerMap.valueFor( sur->asBinder() ).promote();
return result;
}
// ---------------------------------------------------------------------------
Client::Client(const sp<SurfaceFlinger>& flinger)
: mFlinger(flinger), mNameGenerator(1)
{
}
Client::~Client()
{
const size_t count = mLayers.size();
for (size_t i=0 ; i<count ; i++) {
sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
if (layer != 0) {
mFlinger->removeLayer(layer);
}
}
}
status_t Client::initCheck() const {
return NO_ERROR;
}
size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
{
Mutex::Autolock _l(mLock);
size_t name = mNameGenerator++;
mLayers.add(name, layer);
return name;
}
void Client::detachLayer(const LayerBaseClient* layer)
{
Mutex::Autolock _l(mLock);
// we do a linear search here, because this doesn't happen often
const size_t count = mLayers.size();
for (size_t i=0 ; i<count ; i++) {
if (mLayers.valueAt(i) == layer) {
mLayers.removeItemsAt(i, 1);
break;
}
}
}
sp<LayerBaseClient> Client::getLayerUser(int32_t i) const
{
Mutex::Autolock _l(mLock);
sp<LayerBaseClient> lbc;
wp<LayerBaseClient> layer(mLayers.valueFor(i));
if (layer != 0) {
lbc = layer.promote();
ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
}
return lbc;
}
status_t Client::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
// these must be checked
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
const int self_pid = getpid();
if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) {
// we're called from a different process, do the real check
if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
{
ALOGE("Permission Denial: "
"can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
}
return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
}
sp<ISurface> Client::createSurface(
ISurfaceComposerClient::surface_data_t* params,
const String8& name,
DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags)
{
/*
* createSurface must be called from the GL thread so that it can
* have access to the GL context.
*/
class MessageCreateSurface : public MessageBase {
sp<ISurface> result;
SurfaceFlinger* flinger;
ISurfaceComposerClient::surface_data_t* params;
Client* client;
const String8& name;
DisplayID display;
uint32_t w, h;
PixelFormat format;
uint32_t flags;
public:
MessageCreateSurface(SurfaceFlinger* flinger,
ISurfaceComposerClient::surface_data_t* params,
const String8& name, Client* client,
DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags)
: flinger(flinger), params(params), client(client), name(name),
display(display), w(w), h(h), format(format), flags(flags)
{
}
sp<ISurface> getResult() const { return result; }
virtual bool handler() {
result = flinger->createSurface(params, name, client,
display, w, h, format, flags);
return true;
}
};
sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),
params, name, this, display, w, h, format, flags);
mFlinger->postMessageSync(msg);
return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
}
status_t Client::destroySurface(SurfaceID sid) {
return mFlinger->removeSurface(this, sid);
}
// ---------------------------------------------------------------------------
GraphicBufferAlloc::GraphicBufferAlloc() {}
GraphicBufferAlloc::~GraphicBufferAlloc() {}
sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
PixelFormat format, uint32_t usage, status_t* error) {
sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
status_t err = graphicBuffer->initCheck();
*error = err;
if (err != 0 || graphicBuffer->handle == 0) {
if (err == NO_MEMORY) {
GraphicBuffer::dumpAllocationsToSystemLog();
}
ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
"failed (%s), handle=%p",
w, h, strerror(-err), graphicBuffer->handle);
return 0;
}
return graphicBuffer;
}
// ---------------------------------------------------------------------------
GraphicPlane::GraphicPlane()
: mHw(0)
{
}
GraphicPlane::~GraphicPlane() {
delete mHw;
}
bool GraphicPlane::initialized() const {
return mHw ? true : false;
}
int GraphicPlane::getWidth() const {
return mWidth;
}
int GraphicPlane::getHeight() const {
return mHeight;
}
void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
{
mHw = hw;
// initialize the display orientation transform.
// it's a constant that should come from the display driver.
int displayOrientation = ISurfaceComposer::eOrientationDefault;
char property[PROPERTY_VALUE_MAX];
if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
//displayOrientation
switch (atoi(property)) {
case 90:
displayOrientation = ISurfaceComposer::eOrientation90;
break;
case 270:
displayOrientation = ISurfaceComposer::eOrientation270;
break;
}
}
const float w = hw->getWidth();
const float h = hw->getHeight();
GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
&mDisplayTransform);
if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
mDisplayWidth = h;
mDisplayHeight = w;
} else {
mDisplayWidth = w;
mDisplayHeight = h;
}
setOrientation(ISurfaceComposer::eOrientationDefault);
}
status_t GraphicPlane::orientationToTransfrom(
int orientation, int w, int h, Transform* tr)
{
uint32_t flags = 0;
switch (orientation) {
case ISurfaceComposer::eOrientationDefault:
flags = Transform::ROT_0;
break;
case ISurfaceComposer::eOrientation90:
flags = Transform::ROT_90;
break;
case ISurfaceComposer::eOrientation180:
flags = Transform::ROT_180;
break;
case ISurfaceComposer::eOrientation270:
flags = Transform::ROT_270;
break;
default:
return BAD_VALUE;
}
tr->set(flags, w, h);
return NO_ERROR;
}
status_t GraphicPlane::setOrientation(int orientation)
{
// If the rotation can be handled in hardware, this is where
// the magic should happen.
const DisplayHardware& hw(displayHardware());
const float w = mDisplayWidth;
const float h = mDisplayHeight;
mWidth = int(w);
mHeight = int(h);
Transform orientationTransform;
GraphicPlane::orientationToTransfrom(orientation, w, h,
&orientationTransform);
if (orientation & ISurfaceComposer::eOrientationSwapMask) {
mWidth = int(h);
mHeight = int(w);
}
mOrientation = orientation;
mGlobalTransform = mDisplayTransform * orientationTransform;
return NO_ERROR;
}
const DisplayHardware& GraphicPlane::displayHardware() const {
return *mHw;
}
DisplayHardware& GraphicPlane::editDisplayHardware() {
return *mHw;
}
const Transform& GraphicPlane::transform() const {
return mGlobalTransform;
}
EGLDisplay GraphicPlane::getEGLDisplay() const {
return mHw->getEGLDisplay();
}
// ---------------------------------------------------------------------------
}; // namespace android
|