SurfaceFlinger.cpp 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803
  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. //#define LOG_NDEBUG 0
  17. #define ATRACE_TAG ATRACE_TAG_GRAPHICS
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include <errno.h>
  21. #include <math.h>
  22. #include <dlfcn.h>
  23. #include <inttypes.h>
  24. #include <stdatomic.h>
  25. #include <EGL/egl.h>
  26. #include <cutils/log.h>
  27. #include <cutils/iosched_policy.h>
  28. #include <cutils/properties.h>
  29. #include <binder/IPCThreadState.h>
  30. #include <binder/IServiceManager.h>
  31. #include <binder/MemoryHeapBase.h>
  32. #include <binder/PermissionCache.h>
  33. #include <ui/DisplayInfo.h>
  34. #include <ui/DisplayStatInfo.h>
  35. #include <gui/BitTube.h>
  36. #include <gui/BufferQueue.h>
  37. #include <gui/GuiConfig.h>
  38. #include <gui/IDisplayEventConnection.h>
  39. #include <gui/Surface.h>
  40. #include <gui/GraphicBufferAlloc.h>
  41. #include <ui/GraphicBufferAllocator.h>
  42. #include <ui/PixelFormat.h>
  43. #include <ui/UiConfig.h>
  44. #include <utils/misc.h>
  45. #include <utils/String8.h>
  46. #include <utils/String16.h>
  47. #include <utils/StopWatch.h>
  48. #include <utils/Trace.h>
  49. #include <private/android_filesystem_config.h>
  50. #include <private/gui/SyncFeatures.h>
  51. #include "Client.h"
  52. #include "clz.h"
  53. #include "Colorizer.h"
  54. #include "DdmConnection.h"
  55. #include "DisplayDevice.h"
  56. #include "DispSync.h"
  57. #include "EventControlThread.h"
  58. #include "EventThread.h"
  59. #include "Layer.h"
  60. #include "LayerDim.h"
  61. #include "LayerBlur.h"
  62. #include "SurfaceFlinger.h"
  63. #include "DisplayHardware/FramebufferSurface.h"
  64. #include "DisplayHardware/HWComposer.h"
  65. #include "ExSurfaceFlinger/ExHWComposer.h"
  66. #include "DisplayHardware/VirtualDisplaySurface.h"
  67. #include "Effects/Daltonizer.h"
  68. #include "RenderEngine/RenderEngine.h"
  69. #include <cutils/compiler.h>
  70. #include "DisplayUtils.h"
  71. #ifdef USES_HWC_SERVICES
  72. #include "ExynosHWCService.h"
  73. #endif
  74. #define DISPLAY_COUNT 1
  75. /*
  76. * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
  77. * black pixels.
  78. */
  79. #define DEBUG_SCREENSHOTS false
  80. EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
  81. namespace android {
  82. // This is the phase offset in nanoseconds of the software vsync event
  83. // relative to the vsync event reported by HWComposer. The software vsync
  84. // event is when SurfaceFlinger and Choreographer-based applications run each
  85. // frame.
  86. //
  87. // This phase offset allows adjustment of the minimum latency from application
  88. // wake-up (by Choregographer) time to the time at which the resulting window
  89. // image is displayed. This value may be either positive (after the HW vsync)
  90. // or negative (before the HW vsync). Setting it to 0 will result in a
  91. // minimum latency of two vsync periods because the app and SurfaceFlinger
  92. // will run just after the HW vsync. Setting it to a positive number will
  93. // result in the minimum latency being:
  94. //
  95. // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
  96. //
  97. // Note that reducing this latency makes it more likely for the applications
  98. // to not have their window content image ready in time. When this happens
  99. // the latency will end up being an additional vsync period, and animations
  100. // will hiccup. Therefore, this latency should be tuned somewhat
  101. // conservatively (or at least with awareness of the trade-off being made).
  102. static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
  103. // This is the phase offset at which SurfaceFlinger's composition runs.
  104. static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
  105. // ---------------------------------------------------------------------------
  106. const String16 sHardwareTest("android.permission.HARDWARE_TEST");
  107. const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
  108. const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
  109. const String16 sDump("android.permission.DUMP");
  110. static sp<Layer> lastSurfaceViewLayer;
  111. // ---------------------------------------------------------------------------
  112. #ifdef USES_HWC_SERVICES
  113. static bool notifyPSRExit = true;
  114. #endif
  115. SurfaceFlinger::SurfaceFlinger()
  116. : BnSurfaceComposer(),
  117. mTransactionFlags(0),
  118. mTransactionPending(false),
  119. mAnimTransactionPending(false),
  120. mLayersRemoved(false),
  121. mRepaintEverything(0),
  122. mRenderEngine(NULL),
  123. mBootTime(systemTime()),
  124. mVisibleRegionsDirty(false),
  125. mHwWorkListDirty(false),
  126. mAnimCompositionPending(false),
  127. mDebugRegion(0),
  128. mDebugDDMS(0),
  129. mDebugDisableHWC(0),
  130. mDebugDisableTransformHint(0),
  131. mDebugInSwapBuffers(0),
  132. mLastSwapBufferTime(0),
  133. mDebugInTransaction(0),
  134. mLastTransactionTime(0),
  135. mBootFinished(false),
  136. mForceFullDamage(false),
  137. mPrimaryHWVsyncEnabled(false),
  138. mHWVsyncAvailable(false),
  139. mDaltonize(false),
  140. mHasColorMatrix(false),
  141. mHasSecondaryColorMatrix(false),
  142. mHasPoweredOff(false),
  143. mFrameBuckets(),
  144. mTotalTime(0),
  145. mLastSwapTime(0),
  146. mActiveFrameSequence(0)
  147. {
  148. ALOGI("SurfaceFlinger is starting");
  149. // debugging stuff...
  150. char value[PROPERTY_VALUE_MAX];
  151. property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
  152. mGpuToCpuSupported = !atoi(value);
  153. property_get("debug.sf.drop_missed_frames", value, "0");
  154. mDropMissedFrames = atoi(value);
  155. property_get("debug.sf.showupdates", value, "0");
  156. mDebugRegion = atoi(value);
  157. property_get("debug.sf.ddms", value, "0");
  158. mDebugDDMS = atoi(value);
  159. if (mDebugDDMS) {
  160. if (!startDdmConnection()) {
  161. // start failed, and DDMS debugging not enabled
  162. mDebugDDMS = 0;
  163. }
  164. }
  165. ALOGI_IF(mDebugRegion, "showupdates enabled");
  166. ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
  167. }
  168. void SurfaceFlinger::onFirstRef()
  169. {
  170. mEventQueue.init(this);
  171. }
  172. SurfaceFlinger::~SurfaceFlinger()
  173. {
  174. EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  175. eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  176. eglTerminate(display);
  177. }
  178. void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
  179. {
  180. // the window manager died on us. prepare its eulogy.
  181. // restore initial conditions (default device unblank, etc)
  182. initializeDisplays();
  183. // restart the boot-animation
  184. startBootAnim();
  185. }
  186. sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
  187. {
  188. sp<ISurfaceComposerClient> bclient;
  189. sp<Client> client(new Client(this));
  190. status_t err = client->initCheck();
  191. if (err == NO_ERROR) {
  192. bclient = client;
  193. }
  194. return bclient;
  195. }
  196. sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
  197. bool secure)
  198. {
  199. class DisplayToken : public BBinder {
  200. sp<SurfaceFlinger> flinger;
  201. virtual ~DisplayToken() {
  202. // no more references, this display must be terminated
  203. Mutex::Autolock _l(flinger->mStateLock);
  204. flinger->mCurrentState.displays.removeItem(this);
  205. flinger->setTransactionFlags(eDisplayTransactionNeeded);
  206. }
  207. public:
  208. DisplayToken(const sp<SurfaceFlinger>& flinger)
  209. : flinger(flinger) {
  210. }
  211. };
  212. sp<BBinder> token = new DisplayToken(this);
  213. Mutex::Autolock _l(mStateLock);
  214. DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
  215. info.displayName = displayName;
  216. info.isSecure = secure;
  217. mCurrentState.displays.add(token, info);
  218. return token;
  219. }
  220. void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
  221. Mutex::Autolock _l(mStateLock);
  222. ssize_t idx = mCurrentState.displays.indexOfKey(display);
  223. if (idx < 0) {
  224. ALOGW("destroyDisplay: invalid display token");
  225. return;
  226. }
  227. const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
  228. if (!info.isVirtualDisplay()) {
  229. ALOGE("destroyDisplay called for non-virtual display");
  230. return;
  231. }
  232. mCurrentState.displays.removeItemsAt(idx);
  233. setTransactionFlags(eDisplayTransactionNeeded);
  234. }
  235. void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
  236. ALOGW_IF(mBuiltinDisplays[type],
  237. "Overwriting display token for display type %d", type);
  238. mBuiltinDisplays[type] = new BBinder();
  239. DisplayDeviceState info(type);
  240. // All non-virtual displays are currently considered secure.
  241. info.isSecure = true;
  242. mCurrentState.displays.add(mBuiltinDisplays[type], info);
  243. }
  244. sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
  245. if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
  246. ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
  247. return NULL;
  248. }
  249. return mBuiltinDisplays[id];
  250. }
  251. sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
  252. {
  253. sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
  254. return gba;
  255. }
  256. void SurfaceFlinger::bootFinished()
  257. {
  258. const nsecs_t now = systemTime();
  259. const nsecs_t duration = now - mBootTime;
  260. ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
  261. mBootFinished = true;
  262. // wait patiently for the window manager death
  263. const String16 name("window");
  264. sp<IBinder> window(defaultServiceManager()->getService(name));
  265. if (window != 0) {
  266. window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
  267. }
  268. // stop boot animation
  269. // formerly we would just kill the process, but we now ask it to exit so it
  270. // can choose where to stop the animation.
  271. property_set("service.bootanim.exit", "1");
  272. #ifdef USES_HWC_SERVICES
  273. sp<IServiceManager> sm = defaultServiceManager();
  274. sp<android::IExynosHWCService> hwc =
  275. interface_cast<android::IExynosHWCService>(sm->getService(String16("Exynos.HWCService")));
  276. ALOGD("boot finished. Inform HWC");
  277. hwc->setBootFinished();
  278. #endif
  279. }
  280. void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
  281. class MessageDestroyGLTexture : public MessageBase {
  282. RenderEngine& engine;
  283. uint32_t texture;
  284. public:
  285. MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
  286. : engine(engine), texture(texture) {
  287. }
  288. virtual bool handler() {
  289. engine.deleteTextures(1, &texture);
  290. return true;
  291. }
  292. };
  293. postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
  294. }
  295. class DispSyncSource : public VSyncSource, private DispSync::Callback {
  296. public:
  297. DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
  298. const char* label) :
  299. mValue(0),
  300. mTraceVsync(traceVsync),
  301. mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
  302. mVsyncEventLabel(String8::format("VSYNC-%s", label)),
  303. mDispSync(dispSync),
  304. mCallbackMutex(),
  305. mCallback(),
  306. mVsyncMutex(),
  307. mPhaseOffset(phaseOffset),
  308. mEnabled(false) {}
  309. virtual ~DispSyncSource() {}
  310. virtual void setVSyncEnabled(bool enable) {
  311. Mutex::Autolock lock(mVsyncMutex);
  312. if (enable) {
  313. status_t err = mDispSync->addEventListener(mPhaseOffset,
  314. static_cast<DispSync::Callback*>(this));
  315. if (err != NO_ERROR) {
  316. ALOGE("error registering vsync callback: %s (%d)",
  317. strerror(-err), err);
  318. }
  319. //ATRACE_INT(mVsyncOnLabel.string(), 1);
  320. } else {
  321. status_t err = mDispSync->removeEventListener(
  322. static_cast<DispSync::Callback*>(this));
  323. if (err != NO_ERROR) {
  324. ALOGE("error unregistering vsync callback: %s (%d)",
  325. strerror(-err), err);
  326. }
  327. //ATRACE_INT(mVsyncOnLabel.string(), 0);
  328. }
  329. mEnabled = enable;
  330. }
  331. virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
  332. Mutex::Autolock lock(mCallbackMutex);
  333. mCallback = callback;
  334. }
  335. virtual void setPhaseOffset(nsecs_t phaseOffset) {
  336. Mutex::Autolock lock(mVsyncMutex);
  337. // Normalize phaseOffset to [0, period)
  338. auto period = mDispSync->getPeriod();
  339. phaseOffset %= period;
  340. if (phaseOffset < 0) {
  341. // If we're here, then phaseOffset is in (-period, 0). After this
  342. // operation, it will be in (0, period)
  343. phaseOffset += period;
  344. }
  345. mPhaseOffset = phaseOffset;
  346. // If we're not enabled, we don't need to mess with the listeners
  347. if (!mEnabled) {
  348. return;
  349. }
  350. // Remove the listener with the old offset
  351. status_t err = mDispSync->removeEventListener(
  352. static_cast<DispSync::Callback*>(this));
  353. if (err != NO_ERROR) {
  354. ALOGE("error unregistering vsync callback: %s (%d)",
  355. strerror(-err), err);
  356. }
  357. // Add a listener with the new offset
  358. err = mDispSync->addEventListener(mPhaseOffset,
  359. static_cast<DispSync::Callback*>(this));
  360. if (err != NO_ERROR) {
  361. ALOGE("error registering vsync callback: %s (%d)",
  362. strerror(-err), err);
  363. }
  364. }
  365. private:
  366. virtual void onDispSyncEvent(nsecs_t when) {
  367. sp<VSyncSource::Callback> callback;
  368. {
  369. Mutex::Autolock lock(mCallbackMutex);
  370. callback = mCallback;
  371. if (mTraceVsync) {
  372. mValue = (mValue + 1) % 2;
  373. ATRACE_INT(mVsyncEventLabel.string(), mValue);
  374. }
  375. }
  376. if (callback != NULL) {
  377. callback->onVSyncEvent(when);
  378. }
  379. }
  380. int mValue;
  381. const bool mTraceVsync;
  382. const String8 mVsyncOnLabel;
  383. const String8 mVsyncEventLabel;
  384. DispSync* mDispSync;
  385. Mutex mCallbackMutex; // Protects the following
  386. sp<VSyncSource::Callback> mCallback;
  387. Mutex mVsyncMutex; // Protects the following
  388. nsecs_t mPhaseOffset;
  389. bool mEnabled;
  390. };
  391. void SurfaceFlinger::init() {
  392. ALOGI( "SurfaceFlinger's main thread ready to run. "
  393. "Initializing graphics H/W...");
  394. Mutex::Autolock _l(mStateLock);
  395. // initialize EGL for the default display
  396. mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  397. eglInitialize(mEGLDisplay, NULL, NULL);
  398. // start the EventThread
  399. if (vsyncPhaseOffsetNs != sfVsyncPhaseOffsetNs) {
  400. sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
  401. vsyncPhaseOffsetNs, true, "app");
  402. mEventThread = new EventThread(vsyncSrc);
  403. sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
  404. sfVsyncPhaseOffsetNs, true, "sf");
  405. mSFEventThread = new EventThread(sfVsyncSrc);
  406. mEventQueue.setEventThread(mSFEventThread);
  407. } else {
  408. sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
  409. vsyncPhaseOffsetNs, true, "sf-app");
  410. mEventThread = new EventThread(vsyncSrc);
  411. mEventQueue.setEventThread(mEventThread);
  412. }
  413. // Initialize the H/W composer object. There may or may not be an
  414. // actual hardware composer underneath.
  415. mHwc = DisplayUtils::getInstance()->getHWCInstance(this,
  416. *static_cast<HWComposer::EventHandler *>(this));
  417. // get a RenderEngine for the given display / config (can't fail)
  418. mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
  419. // retrieve the EGL context that was selected/created
  420. mEGLContext = mRenderEngine->getEGLContext();
  421. LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
  422. "couldn't create EGLContext");
  423. // initialize our non-virtual displays
  424. for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
  425. DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
  426. // set-up the displays that are already connected
  427. if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
  428. // All non-virtual displays are currently considered secure.
  429. bool isSecure = true;
  430. createBuiltinDisplayLocked(type);
  431. wp<IBinder> token = mBuiltinDisplays[i];
  432. sp<IGraphicBufferProducer> producer;
  433. sp<IGraphicBufferConsumer> consumer;
  434. BufferQueue::createBufferQueue(&producer, &consumer,
  435. new GraphicBufferAlloc());
  436. sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
  437. consumer);
  438. int32_t hwcId = allocateHwcDisplayId(type);
  439. sp<DisplayDevice> hw = new DisplayDevice(this,
  440. type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
  441. fbs, producer,
  442. mRenderEngine->getEGLConfig());
  443. if (i > DisplayDevice::DISPLAY_PRIMARY) {
  444. // FIXME: currently we don't get blank/unblank requests
  445. // for displays other than the main display, so we always
  446. // assume a connected display is unblanked.
  447. ALOGD("marking display %zu as acquired/unblanked", i);
  448. hw->setPowerMode(HWC_POWER_MODE_NORMAL);
  449. }
  450. // When a non-virtual display device is added at boot time,
  451. // update the active config by querying HWC otherwise the
  452. // default config (config 0) will be used.
  453. int activeConfig = mHwc->getActiveConfig(hwcId);
  454. if (activeConfig >= 0) {
  455. hw->setActiveConfig(activeConfig);
  456. }
  457. mDisplays.add(token, hw);
  458. }
  459. }
  460. // make the GLContext current so that we can create textures when creating Layers
  461. // (which may happens before we render something)
  462. getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
  463. mEventControlThread = new EventControlThread(this);
  464. mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
  465. android_set_rt_ioprio(mEventControlThread->getTid(), 1);
  466. // set a fake vsync period if there is no HWComposer
  467. if (mHwc->initCheck() != NO_ERROR) {
  468. mPrimaryDispSync.setPeriod(16666667);
  469. }
  470. // initialize our drawing state
  471. mDrawingState = mCurrentState;
  472. // set initial conditions (e.g. unblank default device)
  473. initializeDisplays();
  474. // start boot animation
  475. startBootAnim();
  476. }
  477. int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
  478. return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
  479. type : mHwc->allocateDisplayId();
  480. }
  481. void SurfaceFlinger::startBootAnim() {
  482. // start boot animation
  483. property_set("service.bootanim.exit", "0");
  484. property_set("ctl.start", "bootanim");
  485. }
  486. size_t SurfaceFlinger::getMaxTextureSize() const {
  487. return mRenderEngine->getMaxTextureSize();
  488. }
  489. size_t SurfaceFlinger::getMaxViewportDims() const {
  490. return mRenderEngine->getMaxViewportDims();
  491. }
  492. // ----------------------------------------------------------------------------
  493. bool SurfaceFlinger::authenticateSurfaceTexture(
  494. const sp<IGraphicBufferProducer>& bufferProducer) const {
  495. Mutex::Autolock _l(mStateLock);
  496. sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
  497. return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
  498. }
  499. status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
  500. Vector<DisplayInfo>* configs) {
  501. if ((configs == NULL) || (display.get() == NULL)) {
  502. return BAD_VALUE;
  503. }
  504. if (!display.get())
  505. return NAME_NOT_FOUND;
  506. int32_t type = NAME_NOT_FOUND;
  507. for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
  508. if (display == mBuiltinDisplays[i]) {
  509. type = i;
  510. break;
  511. }
  512. }
  513. if (type < 0) {
  514. return type;
  515. }
  516. // TODO: Not sure if display density should handled by SF any longer
  517. class Density {
  518. static int getDensityFromProperty(char const* propName) {
  519. char property[PROPERTY_VALUE_MAX];
  520. int density = 0;
  521. if (property_get(propName, property, NULL) > 0) {
  522. density = atoi(property);
  523. }
  524. return density;
  525. }
  526. public:
  527. static int getEmuDensity() {
  528. return getDensityFromProperty("qemu.sf.lcd_density"); }
  529. static int getBuildDensity() {
  530. return getDensityFromProperty("ro.sf.lcd_density"); }
  531. };
  532. configs->clear();
  533. const Vector<HWComposer::DisplayConfig>& hwConfigs =
  534. getHwComposer().getConfigs(type);
  535. for (size_t c = 0; c < hwConfigs.size(); ++c) {
  536. const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
  537. DisplayInfo info = DisplayInfo();
  538. float xdpi = hwConfig.xdpi;
  539. float ydpi = hwConfig.ydpi;
  540. if (type == DisplayDevice::DISPLAY_PRIMARY) {
  541. // The density of the device is provided by a build property
  542. float density = Density::getBuildDensity() / 160.0f;
  543. if (density == 0) {
  544. // the build doesn't provide a density -- this is wrong!
  545. // use xdpi instead
  546. ALOGE("ro.sf.lcd_density must be defined as a build property");
  547. density = xdpi / 160.0f;
  548. }
  549. if (Density::getEmuDensity()) {
  550. // if "qemu.sf.lcd_density" is specified, it overrides everything
  551. xdpi = ydpi = density = Density::getEmuDensity();
  552. density /= 160.0f;
  553. }
  554. info.density = density;
  555. // TODO: this needs to go away (currently needed only by webkit)
  556. sp<const DisplayDevice> hw(getDefaultDisplayDevice());
  557. info.orientation = hw->getOrientation();
  558. } else {
  559. // TODO: where should this value come from?
  560. static const int TV_DENSITY = 213;
  561. info.density = TV_DENSITY / 160.0f;
  562. info.orientation = 0;
  563. }
  564. char value[PROPERTY_VALUE_MAX];
  565. property_get("ro.sf.hwrotation", value, "0");
  566. int additionalRot = atoi(value) / 90;
  567. if ((type == DisplayDevice::DISPLAY_PRIMARY) && (additionalRot & DisplayState::eOrientationSwapMask)) {
  568. info.h = hwConfig.width;
  569. info.w = hwConfig.height;
  570. info.xdpi = ydpi;
  571. info.ydpi = xdpi;
  572. }
  573. else {
  574. info.w = hwConfig.width;
  575. info.h = hwConfig.height;
  576. info.xdpi = xdpi;
  577. info.ydpi = ydpi;
  578. }
  579. info.fps = float(1e9 / hwConfig.refresh);
  580. info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
  581. info.colorTransform = hwConfig.colorTransform;
  582. // This is how far in advance a buffer must be queued for
  583. // presentation at a given time. If you want a buffer to appear
  584. // on the screen at time N, you must submit the buffer before
  585. // (N - presentationDeadline).
  586. //
  587. // Normally it's one full refresh period (to give SF a chance to
  588. // latch the buffer), but this can be reduced by configuring a
  589. // DispSync offset. Any additional delays introduced by the hardware
  590. // composer or panel must be accounted for here.
  591. //
  592. // We add an additional 1ms to allow for processing time and
  593. // differences between the ideal and actual refresh rate.
  594. info.presentationDeadline =
  595. hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
  596. // All non-virtual displays are currently considered secure.
  597. info.secure = true;
  598. configs->push_back(info);
  599. }
  600. return NO_ERROR;
  601. }
  602. status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
  603. DisplayStatInfo* stats) {
  604. if (stats == NULL) {
  605. return BAD_VALUE;
  606. }
  607. // FIXME for now we always return stats for the primary display
  608. memset(stats, 0, sizeof(*stats));
  609. stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
  610. stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
  611. return NO_ERROR;
  612. }
  613. int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
  614. sp<DisplayDevice> device(getDisplayDevice(display));
  615. if (device != NULL) {
  616. return device->getActiveConfig();
  617. }
  618. return BAD_VALUE;
  619. }
  620. void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
  621. ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
  622. this);
  623. int32_t type = hw->getDisplayType();
  624. int currentMode = hw->getActiveConfig();
  625. if (mode == currentMode) {
  626. ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
  627. return;
  628. }
  629. if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
  630. ALOGW("Trying to set config for virtual display");
  631. return;
  632. }
  633. status_t status = getHwComposer().setActiveConfig(type, mode);
  634. if (status == NO_ERROR) {
  635. hw->setActiveConfig(mode);
  636. }
  637. }
  638. status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
  639. class MessageSetActiveConfig: public MessageBase {
  640. SurfaceFlinger& mFlinger;
  641. sp<IBinder> mDisplay;
  642. int mMode;
  643. public:
  644. MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
  645. int mode) :
  646. mFlinger(flinger), mDisplay(disp) { mMode = mode; }
  647. virtual bool handler() {
  648. Vector<DisplayInfo> configs;
  649. mFlinger.getDisplayConfigs(mDisplay, &configs);
  650. if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
  651. ALOGE("Attempt to set active config = %d for display with %zu configs",
  652. mMode, configs.size());
  653. }
  654. sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
  655. if (hw == NULL) {
  656. ALOGE("Attempt to set active config = %d for null display %p",
  657. mMode, mDisplay.get());
  658. } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
  659. ALOGW("Attempt to set active config = %d for virtual display",
  660. mMode);
  661. } else {
  662. mFlinger.setActiveConfigInternal(hw, mMode);
  663. }
  664. return true;
  665. }
  666. };
  667. sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
  668. postMessageSync(msg);
  669. return NO_ERROR;
  670. }
  671. status_t SurfaceFlinger::clearAnimationFrameStats() {
  672. Mutex::Autolock _l(mStateLock);
  673. mAnimFrameTracker.clearStats();
  674. return NO_ERROR;
  675. }
  676. status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
  677. Mutex::Autolock _l(mStateLock);
  678. mAnimFrameTracker.getStats(outStats);
  679. return NO_ERROR;
  680. }
  681. // ----------------------------------------------------------------------------
  682. sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
  683. return mEventThread->createEventConnection();
  684. }
  685. // ----------------------------------------------------------------------------
  686. void SurfaceFlinger::waitForEvent() {
  687. mEventQueue.waitMessage();
  688. }
  689. void SurfaceFlinger::signalTransaction() {
  690. mEventQueue.invalidate();
  691. }
  692. void SurfaceFlinger::signalLayerUpdate() {
  693. #ifdef USES_HWC_SERVICES
  694. if (notifyPSRExit) {
  695. notifyPSRExit = false;
  696. sp<IServiceManager> sm = defaultServiceManager();
  697. sp<IExynosHWCService> hwcService =
  698. interface_cast<android::IExynosHWCService>(
  699. sm->getService(String16("Exynos.HWCService")));
  700. if (hwcService != NULL)
  701. hwcService->notifyPSRExit();
  702. else
  703. ALOGE("HWCService::notifyPSRExit failed");
  704. }
  705. #endif
  706. mEventQueue.invalidate();
  707. }
  708. void SurfaceFlinger::signalRefresh() {
  709. mEventQueue.refresh();
  710. }
  711. status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
  712. nsecs_t reltime, uint32_t /* flags */) {
  713. return mEventQueue.postMessage(msg, reltime);
  714. }
  715. status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
  716. nsecs_t reltime, uint32_t /* flags */) {
  717. status_t res = mEventQueue.postMessage(msg, reltime);
  718. if (res == NO_ERROR) {
  719. msg->wait();
  720. }
  721. return res;
  722. }
  723. void SurfaceFlinger::run() {
  724. do {
  725. waitForEvent();
  726. } while (true);
  727. }
  728. void SurfaceFlinger::enableHardwareVsync() {
  729. Mutex::Autolock _l(mHWVsyncLock);
  730. if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
  731. mPrimaryDispSync.beginResync();
  732. //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
  733. mEventControlThread->setVsyncEnabled(true);
  734. mPrimaryHWVsyncEnabled = true;
  735. }
  736. }
  737. void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
  738. Mutex::Autolock _l(mHWVsyncLock);
  739. if (makeAvailable) {
  740. mHWVsyncAvailable = true;
  741. } else if (!mHWVsyncAvailable) {
  742. ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
  743. return;
  744. }
  745. const nsecs_t period =
  746. getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
  747. mPrimaryDispSync.reset();
  748. mPrimaryDispSync.setPeriod(period);
  749. if (!mPrimaryHWVsyncEnabled) {
  750. mPrimaryDispSync.beginResync();
  751. //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
  752. mEventControlThread->setVsyncEnabled(true);
  753. mPrimaryHWVsyncEnabled = true;
  754. }
  755. }
  756. void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
  757. Mutex::Autolock _l(mHWVsyncLock);
  758. if (mPrimaryHWVsyncEnabled) {
  759. //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
  760. mEventControlThread->setVsyncEnabled(false);
  761. mPrimaryDispSync.endResync();
  762. mPrimaryHWVsyncEnabled = false;
  763. }
  764. if (makeUnavailable) {
  765. mHWVsyncAvailable = false;
  766. }
  767. }
  768. void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
  769. bool needsHwVsync = false;
  770. { // Scope for the lock
  771. Mutex::Autolock _l(mHWVsyncLock);
  772. if (type == 0 && mPrimaryHWVsyncEnabled) {
  773. needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
  774. }
  775. }
  776. if (needsHwVsync) {
  777. enableHardwareVsync();
  778. } else {
  779. disableHardwareVsync(false);
  780. }
  781. }
  782. void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
  783. if (mEventThread == NULL) {
  784. // This is a temporary workaround for b/7145521. A non-null pointer
  785. // does not mean EventThread has finished initializing, so this
  786. // is not a correct fix.
  787. ALOGW("WARNING: EventThread not started, ignoring hotplug");
  788. return;
  789. }
  790. if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
  791. Mutex::Autolock _l(mStateLock);
  792. if (connected) {
  793. createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
  794. } else {
  795. mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
  796. mBuiltinDisplays[type].clear();
  797. updateVisibleRegionsDirty();
  798. }
  799. setTransactionFlags(eDisplayTransactionNeeded);
  800. // Defer EventThread notification until SF has updated mDisplays.
  801. }
  802. }
  803. void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
  804. ATRACE_CALL();
  805. getHwComposer().eventControl(disp, event, enabled);
  806. }
  807. void SurfaceFlinger::onMessageReceived(int32_t what) {
  808. ATRACE_CALL();
  809. switch (what) {
  810. case MessageQueue::TRANSACTION: {
  811. handleMessageTransaction();
  812. break;
  813. }
  814. case MessageQueue::INVALIDATE: {
  815. bool refreshNeeded = handleMessageTransaction();
  816. refreshNeeded |= handleMessageInvalidate();
  817. refreshNeeded |= mRepaintEverything;
  818. if (refreshNeeded) {
  819. // Signal a refresh if a transaction modified the window state,
  820. // a new buffer was latched, or if HWC has requested a full
  821. // repaint
  822. signalRefresh();
  823. }
  824. break;
  825. }
  826. case MessageQueue::REFRESH: {
  827. handleMessageRefresh();
  828. break;
  829. }
  830. }
  831. }
  832. bool SurfaceFlinger::handleMessageTransaction() {
  833. uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
  834. if (transactionFlags) {
  835. handleTransaction(transactionFlags);
  836. return true;
  837. }
  838. return false;
  839. }
  840. bool SurfaceFlinger::handleMessageInvalidate() {
  841. ATRACE_CALL();
  842. return handlePageFlip();
  843. }
  844. void SurfaceFlinger::handleMessageRefresh() {
  845. ATRACE_CALL();
  846. static nsecs_t previousExpectedPresent = 0;
  847. nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
  848. static bool previousFrameMissed = false;
  849. bool frameMissed = (expectedPresent == previousExpectedPresent);
  850. if (frameMissed != previousFrameMissed) {
  851. ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
  852. }
  853. previousFrameMissed = frameMissed;
  854. if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
  855. // Latch buffers, but don't send anything to HWC, then signal another
  856. // wakeup for the next vsync
  857. preComposition();
  858. repaintEverything();
  859. } else {
  860. preComposition();
  861. rebuildLayerStacks();
  862. setUpHWComposer();
  863. doDebugFlashRegions();
  864. doComposition();
  865. postComposition();
  866. #ifdef USES_HWC_SERVICES
  867. notifyPSRExit = true;
  868. #endif
  869. }
  870. previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
  871. }
  872. void SurfaceFlinger::doDebugFlashRegions()
  873. {
  874. // is debugging enabled
  875. if (CC_LIKELY(!mDebugRegion))
  876. return;
  877. const bool repaintEverything = mRepaintEverything;
  878. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  879. const sp<DisplayDevice>& hw(mDisplays[dpy]);
  880. if (hw->isDisplayOn()) {
  881. // transform the dirty region into this screen's coordinate space
  882. const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
  883. if (!dirtyRegion.isEmpty()) {
  884. // redraw the whole screen
  885. doComposeSurfaces(hw, Region(hw->bounds()));
  886. // and draw the dirty region
  887. const int32_t height = hw->getHeight();
  888. RenderEngine& engine(getRenderEngine());
  889. engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
  890. hw->compositionComplete();
  891. hw->swapBuffers(getHwComposer());
  892. }
  893. }
  894. }
  895. postFramebuffer();
  896. if (mDebugRegion > 1) {
  897. usleep(mDebugRegion * 1000);
  898. }
  899. HWComposer& hwc(getHwComposer());
  900. if (hwc.initCheck() == NO_ERROR) {
  901. status_t err = hwc.prepare();
  902. ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
  903. }
  904. }
  905. void SurfaceFlinger::preComposition()
  906. {
  907. bool needExtraInvalidate = false;
  908. const LayerVector& layers(mDrawingState.layersSortedByZ);
  909. const size_t count = layers.size();
  910. for (size_t i=0 ; i<count ; i++) {
  911. if (layers[i]->onPreComposition()) {
  912. needExtraInvalidate = true;
  913. }
  914. }
  915. if (needExtraInvalidate) {
  916. signalLayerUpdate();
  917. }
  918. }
  919. void SurfaceFlinger::postComposition()
  920. {
  921. const LayerVector& layers(mDrawingState.layersSortedByZ);
  922. const size_t count = layers.size();
  923. for (size_t i=0 ; i<count ; i++) {
  924. layers[i]->onPostComposition();
  925. }
  926. const HWComposer& hwc = getHwComposer();
  927. sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
  928. if (presentFence->isValid()) {
  929. if (mPrimaryDispSync.addPresentFence(presentFence)) {
  930. enableHardwareVsync();
  931. } else {
  932. disableHardwareVsync(false);
  933. }
  934. }
  935. const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
  936. if (kIgnorePresentFences) {
  937. if (hw->isDisplayOn()) {
  938. enableHardwareVsync();
  939. }
  940. }
  941. if (mAnimCompositionPending) {
  942. mAnimCompositionPending = false;
  943. if (presentFence->isValid()) {
  944. mAnimFrameTracker.setActualPresentFence(presentFence);
  945. } else {
  946. // The HWC doesn't support present fences, so use the refresh
  947. // timestamp instead.
  948. nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
  949. mAnimFrameTracker.setActualPresentTime(presentTime);
  950. }
  951. mAnimFrameTracker.advanceFrame();
  952. }
  953. dumpDrawCycle(false);
  954. if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
  955. return;
  956. }
  957. nsecs_t currentTime = systemTime();
  958. if (mHasPoweredOff) {
  959. mHasPoweredOff = false;
  960. } else {
  961. nsecs_t period = mPrimaryDispSync.getPeriod();
  962. nsecs_t elapsedTime = currentTime - mLastSwapTime;
  963. size_t numPeriods = static_cast<size_t>(elapsedTime / period);
  964. if (numPeriods < NUM_BUCKETS - 1) {
  965. mFrameBuckets[numPeriods] += elapsedTime;
  966. } else {
  967. mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
  968. }
  969. mTotalTime += elapsedTime;
  970. }
  971. mLastSwapTime = currentTime;
  972. }
  973. void SurfaceFlinger::rebuildLayerStacks() {
  974. updateExtendedMode();
  975. // rebuild the visible layer list per screen
  976. if (CC_UNLIKELY(mVisibleRegionsDirty)) {
  977. ATRACE_CALL();
  978. mVisibleRegionsDirty = false;
  979. invalidateHwcGeometry();
  980. const LayerVector& layers(mDrawingState.layersSortedByZ);
  981. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  982. Region opaqueRegion;
  983. Region dirtyRegion;
  984. Vector< sp<Layer> > layersSortedByZ;
  985. const sp<DisplayDevice>& hw(mDisplays[dpy]);
  986. const Transform& tr(hw->getTransform());
  987. const Rect bounds(hw->getBounds());
  988. if (hw->isDisplayOn()) {
  989. computeVisibleRegions(hw->getHwcDisplayId(), layers,
  990. hw->getLayerStack(), dirtyRegion, opaqueRegion);
  991. const size_t count = layers.size();
  992. for (size_t i=0 ; i<count ; i++) {
  993. const sp<Layer>& layer(layers[i]);
  994. {
  995. Region drawRegion(tr.transform(
  996. layer->visibleNonTransparentRegion));
  997. drawRegion.andSelf(bounds);
  998. if (!drawRegion.isEmpty()) {
  999. layersSortedByZ.add(layer);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. hw->setVisibleLayersSortedByZ(layersSortedByZ);
  1005. hw->undefinedRegion.set(bounds);
  1006. hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
  1007. hw->dirtyRegion.orSelf(dirtyRegion);
  1008. }
  1009. }
  1010. }
  1011. void SurfaceFlinger::setUpHWComposer() {
  1012. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1013. bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
  1014. bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
  1015. bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
  1016. // If nothing has changed (!dirty), don't recompose.
  1017. // If something changed, but we don't currently have any visible layers,
  1018. // and didn't when we last did a composition, then skip it this time.
  1019. // The second rule does two things:
  1020. // - When all layers are removed from a display, we'll emit one black
  1021. // frame, then nothing more until we get new layers.
  1022. // - When a display is created with a private layer stack, we won't
  1023. // emit any black frames until a layer is added to the layer stack.
  1024. bool mustRecompose = dirty && !(empty && wasEmpty);
  1025. ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
  1026. "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
  1027. mustRecompose ? "doing" : "skipping",
  1028. dirty ? "+" : "-",
  1029. empty ? "+" : "-",
  1030. wasEmpty ? "+" : "-");
  1031. mDisplays[dpy]->beginFrame(mustRecompose);
  1032. if (mustRecompose) {
  1033. mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
  1034. }
  1035. }
  1036. HWComposer& hwc(getHwComposer());
  1037. if (hwc.initCheck() == NO_ERROR) {
  1038. // build the h/w work list
  1039. if (CC_UNLIKELY(mHwWorkListDirty)) {
  1040. mHwWorkListDirty = false;
  1041. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1042. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1043. const int32_t id = hw->getHwcDisplayId();
  1044. if (id >= 0) {
  1045. const Vector< sp<Layer> >& currentLayers(
  1046. hw->getVisibleLayersSortedByZ());
  1047. const size_t count = currentLayers.size();
  1048. if (hwc.createWorkList(id, count) == NO_ERROR) {
  1049. HWComposer::LayerListIterator cur = hwc.begin(id);
  1050. const HWComposer::LayerListIterator end = hwc.end(id);
  1051. for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
  1052. const sp<Layer>& layer(currentLayers[i]);
  1053. layer->setGeometry(hw, *cur);
  1054. if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix || mHasSecondaryColorMatrix) {
  1055. cur->setSkip(true);
  1056. }
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. // set the per-frame data
  1063. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1064. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1065. const int32_t id = hw->getHwcDisplayId();
  1066. if (id >= 0) {
  1067. bool freezeSurfacePresent = false;
  1068. isfreezeSurfacePresent(freezeSurfacePresent, hw, id);
  1069. const Vector< sp<Layer> >& currentLayers(
  1070. hw->getVisibleLayersSortedByZ());
  1071. const size_t count = currentLayers.size();
  1072. HWComposer::LayerListIterator cur = hwc.begin(id);
  1073. const HWComposer::LayerListIterator end = hwc.end(id);
  1074. for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
  1075. /*
  1076. * update the per-frame h/w composer data for each layer
  1077. * and build the transparent region of the FB
  1078. */
  1079. const sp<Layer>& layer(currentLayers[i]);
  1080. layer->setPerFrameData(hw, *cur);
  1081. setOrientationEventControl(freezeSurfacePresent,id);
  1082. if(!strncmp(layer->getName(), "SurfaceView",
  1083. 11)) {
  1084. lastSurfaceViewLayer = layer;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. // If possible, attempt to use the cursor overlay on each display.
  1090. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1091. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1092. const int32_t id = hw->getHwcDisplayId();
  1093. if (id >= 0) {
  1094. const Vector< sp<Layer> >& currentLayers(
  1095. hw->getVisibleLayersSortedByZ());
  1096. const size_t count = currentLayers.size();
  1097. HWComposer::LayerListIterator cur = hwc.begin(id);
  1098. const HWComposer::LayerListIterator end = hwc.end(id);
  1099. for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
  1100. const sp<Layer>& layer(currentLayers[i]);
  1101. if (layer->isPotentialCursor()) {
  1102. cur->setIsCursorLayerHint();
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. dumpDrawCycle(true);
  1109. status_t err = hwc.prepare();
  1110. ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
  1111. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1112. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1113. hw->prepareFrame(hwc);
  1114. }
  1115. }
  1116. }
  1117. void SurfaceFlinger::doComposition() {
  1118. ATRACE_CALL();
  1119. const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
  1120. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1121. const sp<DisplayDevice>& hw(mDisplays[dpy]);
  1122. if (hw->isDisplayOn()) {
  1123. // transform the dirty region into this screen's coordinate space
  1124. const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
  1125. // repaint the framebuffer (if needed)
  1126. doDisplayComposition(hw, dirtyRegion);
  1127. ++mActiveFrameSequence;
  1128. hw->dirtyRegion.clear();
  1129. hw->flip(hw->swapRegion);
  1130. hw->swapRegion.clear();
  1131. }
  1132. // inform the h/w that we're done compositing
  1133. hw->compositionComplete();
  1134. }
  1135. postFramebuffer();
  1136. }
  1137. void SurfaceFlinger::postFramebuffer()
  1138. {
  1139. ATRACE_CALL();
  1140. const nsecs_t now = systemTime();
  1141. mDebugInSwapBuffers = now;
  1142. HWComposer& hwc(getHwComposer());
  1143. if (hwc.initCheck() == NO_ERROR) {
  1144. if (!hwc.supportsFramebufferTarget()) {
  1145. // EGL spec says:
  1146. // "surface must be bound to the calling thread's current context,
  1147. // for the current rendering API."
  1148. getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
  1149. }
  1150. hwc.commit();
  1151. }
  1152. // make the default display current because the VirtualDisplayDevice code cannot
  1153. // deal with dequeueBuffer() being called outside of the composition loop; however
  1154. // the code below can call glFlush() which is allowed (and does in some case) call
  1155. // dequeueBuffer().
  1156. getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
  1157. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1158. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1159. const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
  1160. hw->onSwapBuffersCompleted(hwc);
  1161. const size_t count = currentLayers.size();
  1162. int32_t id = hw->getHwcDisplayId();
  1163. if (id >=0 && hwc.initCheck() == NO_ERROR) {
  1164. HWComposer::LayerListIterator cur = hwc.begin(id);
  1165. const HWComposer::LayerListIterator end = hwc.end(id);
  1166. for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
  1167. currentLayers[i]->onLayerDisplayed(hw, &*cur);
  1168. }
  1169. } else {
  1170. for (size_t i = 0; i < count; i++) {
  1171. currentLayers[i]->onLayerDisplayed(hw, NULL);
  1172. }
  1173. }
  1174. }
  1175. mLastSwapBufferTime = systemTime() - now;
  1176. mDebugInSwapBuffers = 0;
  1177. uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
  1178. if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
  1179. logFrameStats();
  1180. }
  1181. ALOGV_IF(mFrameRateHelper.update(), "FPS: %d", mFrameRateHelper.get());
  1182. }
  1183. void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
  1184. {
  1185. ATRACE_CALL();
  1186. // here we keep a copy of the drawing state (that is the state that's
  1187. // going to be overwritten by handleTransactionLocked()) outside of
  1188. // mStateLock so that the side-effects of the State assignment
  1189. // don't happen with mStateLock held (which can cause deadlocks).
  1190. State drawingState(mDrawingState);
  1191. Mutex::Autolock _l(mStateLock);
  1192. const nsecs_t now = systemTime();
  1193. mDebugInTransaction = now;
  1194. // Here we're guaranteed that some transaction flags are set
  1195. // so we can call handleTransactionLocked() unconditionally.
  1196. // We call getTransactionFlags(), which will also clear the flags,
  1197. // with mStateLock held to guarantee that mCurrentState won't change
  1198. // until the transaction is committed.
  1199. transactionFlags = getTransactionFlags(eTransactionMask);
  1200. handleTransactionLocked(transactionFlags);
  1201. mLastTransactionTime = systemTime() - now;
  1202. mDebugInTransaction = 0;
  1203. invalidateHwcGeometry();
  1204. // here the transaction has been committed
  1205. }
  1206. void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
  1207. {
  1208. const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
  1209. const size_t count = currentLayers.size();
  1210. /*
  1211. * Traversal of the children
  1212. * (perform the transaction for each of them if needed)
  1213. */
  1214. if (transactionFlags & eTraversalNeeded) {
  1215. for (size_t i=0 ; i<count ; i++) {
  1216. const sp<Layer>& layer(currentLayers[i]);
  1217. uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
  1218. if (!trFlags) continue;
  1219. const uint32_t flags = layer->doTransaction(0);
  1220. if (flags & Layer::eVisibleRegion)
  1221. mVisibleRegionsDirty = true;
  1222. }
  1223. }
  1224. /*
  1225. * Perform display own transactions if needed
  1226. */
  1227. if (transactionFlags & eDisplayTransactionNeeded) {
  1228. // here we take advantage of Vector's copy-on-write semantics to
  1229. // improve performance by skipping the transaction entirely when
  1230. // know that the lists are identical
  1231. const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
  1232. const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
  1233. if (!curr.isIdenticalTo(draw)) {
  1234. mVisibleRegionsDirty = true;
  1235. const size_t cc = curr.size();
  1236. size_t dc = draw.size();
  1237. // find the displays that were removed
  1238. // (ie: in drawing state but not in current state)
  1239. // also handle displays that changed
  1240. // (ie: displays that are in both lists)
  1241. for (size_t i=0 ; i<dc ; i++) {
  1242. const ssize_t j = curr.indexOfKey(draw.keyAt(i));
  1243. if (j < 0) {
  1244. // in drawing state but not in current state
  1245. if (!draw[i].isMainDisplay()) {
  1246. // Call makeCurrent() on the primary display so we can
  1247. // be sure that nothing associated with this display
  1248. // is current.
  1249. const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
  1250. defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
  1251. sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
  1252. if (hw != NULL)
  1253. hw->disconnect(getHwComposer());
  1254. if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
  1255. mEventThread->onHotplugReceived(draw[i].type, false);
  1256. mDisplays.removeItem(draw.keyAt(i));
  1257. } else {
  1258. ALOGW("trying to remove the main display");
  1259. }
  1260. } else {
  1261. // this display is in both lists. see if something changed.
  1262. const DisplayDeviceState& state(curr[j]);
  1263. const wp<IBinder>& display(curr.keyAt(j));
  1264. const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
  1265. const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
  1266. if (state_binder != draw_binder) {
  1267. // changing the surface is like destroying and
  1268. // recreating the DisplayDevice, so we just remove it
  1269. // from the drawing state, so that it get re-added
  1270. // below.
  1271. sp<DisplayDevice> hw(getDisplayDevice(display));
  1272. if (hw != NULL)
  1273. hw->disconnect(getHwComposer());
  1274. mDisplays.removeItem(display);
  1275. mDrawingState.displays.removeItemsAt(i);
  1276. dc--; i--;
  1277. // at this point we must loop to the next item
  1278. continue;
  1279. }
  1280. const sp<DisplayDevice> disp(getDisplayDevice(display));
  1281. if (disp != NULL) {
  1282. if (state.layerStack != draw[i].layerStack) {
  1283. disp->setLayerStack(state.layerStack);
  1284. }
  1285. if ((state.orientation != draw[i].orientation)
  1286. || (state.viewport != draw[i].viewport)
  1287. || (state.frame != draw[i].frame))
  1288. {
  1289. disp->setProjection(state.orientation,
  1290. state.viewport, state.frame);
  1291. }
  1292. if (state.width != draw[i].width || state.height != draw[i].height) {
  1293. disp->setDisplaySize(state.width, state.height);
  1294. }
  1295. }
  1296. }
  1297. }
  1298. // find displays that were added
  1299. // (ie: in current state but not in drawing state)
  1300. for (size_t i=0 ; i<cc ; i++) {
  1301. if (draw.indexOfKey(curr.keyAt(i)) < 0) {
  1302. const DisplayDeviceState& state(curr[i]);
  1303. sp<DisplaySurface> dispSurface;
  1304. sp<IGraphicBufferProducer> producer;
  1305. sp<IGraphicBufferProducer> bqProducer;
  1306. sp<IGraphicBufferConsumer> bqConsumer;
  1307. BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
  1308. new GraphicBufferAlloc());
  1309. int32_t hwcDisplayId = -1;
  1310. if (state.isVirtualDisplay()) {
  1311. // Virtual displays without a surface are dormant:
  1312. // they have external state (layer stack, projection,
  1313. // etc.) but no internal state (i.e. a DisplayDevice).
  1314. if (state.surface != NULL) {
  1315. int width = 0;
  1316. DisplayUtils* displayUtils = DisplayUtils::getInstance();
  1317. int status = state.surface->query(
  1318. NATIVE_WINDOW_WIDTH, &width);
  1319. ALOGE_IF(status != NO_ERROR,
  1320. "Unable to query width (%d)", status);
  1321. int height = 0;
  1322. status = state.surface->query(
  1323. NATIVE_WINDOW_HEIGHT, &height);
  1324. ALOGE_IF(status != NO_ERROR,
  1325. "Unable to query height (%d)", status);
  1326. if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
  1327. (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
  1328. height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
  1329. int usage = 0;
  1330. status = state.surface->query(
  1331. NATIVE_WINDOW_CONSUMER_USAGE_BITS, &usage);
  1332. ALOGW_IF(status != NO_ERROR,
  1333. "Unable to query usage (%d)", status);
  1334. if ( (status == NO_ERROR) &&
  1335. displayUtils->canAllocateHwcDisplayIdForVDS(usage)) {
  1336. hwcDisplayId = allocateHwcDisplayId(state.type);
  1337. }
  1338. }
  1339. displayUtils->initVDSInstance(mHwc, hwcDisplayId, state.surface,
  1340. dispSurface, producer, bqProducer, bqConsumer,
  1341. state.displayName, state.isSecure, state.type);
  1342. }
  1343. } else {
  1344. ALOGE_IF(state.surface!=NULL,
  1345. "adding a supported display, but rendering "
  1346. "surface is provided (%p), ignoring it",
  1347. state.surface.get());
  1348. hwcDisplayId = allocateHwcDisplayId(state.type);
  1349. // for supported (by hwc) displays we provide our
  1350. // own rendering surface
  1351. dispSurface = new FramebufferSurface(*mHwc, state.type,
  1352. bqConsumer);
  1353. producer = bqProducer;
  1354. }
  1355. const wp<IBinder>& display(curr.keyAt(i));
  1356. if (dispSurface != NULL && producer != NULL) {
  1357. sp<DisplayDevice> hw = new DisplayDevice(this,
  1358. state.type, hwcDisplayId,
  1359. mHwc->getFormat(hwcDisplayId), state.isSecure,
  1360. display, dispSurface, producer,
  1361. mRenderEngine->getEGLConfig());
  1362. hw->setLayerStack(state.layerStack);
  1363. hw->setProjection(state.orientation,
  1364. state.viewport, state.frame);
  1365. hw->setDisplayName(state.displayName);
  1366. // When a new display device is added update the active
  1367. // config by querying HWC otherwise the default config
  1368. // (config 0) will be used.
  1369. if (hwcDisplayId >= DisplayDevice::DISPLAY_PRIMARY &&
  1370. hwcDisplayId < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
  1371. int activeConfig = mHwc->getActiveConfig(hwcDisplayId);
  1372. if (activeConfig >= 0) {
  1373. hw->setActiveConfig(activeConfig);
  1374. }
  1375. }
  1376. mDisplays.add(display, hw);
  1377. if (state.isVirtualDisplay()) {
  1378. if (hwcDisplayId >= 0) {
  1379. mHwc->setVirtualDisplayProperties(hwcDisplayId,
  1380. hw->getWidth(), hw->getHeight(),
  1381. hw->getFormat());
  1382. }
  1383. } else {
  1384. mEventThread->onHotplugReceived(state.type, true);
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
  1392. // The transform hint might have changed for some layers
  1393. // (either because a display has changed, or because a layer
  1394. // as changed).
  1395. //
  1396. // Walk through all the layers in currentLayers,
  1397. // and update their transform hint.
  1398. //
  1399. // If a layer is visible only on a single display, then that
  1400. // display is used to calculate the hint, otherwise we use the
  1401. // default display.
  1402. //
  1403. // NOTE: we do this here, rather than in rebuildLayerStacks() so that
  1404. // the hint is set before we acquire a buffer from the surface texture.
  1405. //
  1406. // NOTE: layer transactions have taken place already, so we use their
  1407. // drawing state. However, SurfaceFlinger's own transaction has not
  1408. // happened yet, so we must use the current state layer list
  1409. // (soon to become the drawing state list).
  1410. //
  1411. sp<const DisplayDevice> disp;
  1412. uint32_t currentlayerStack = 0;
  1413. for (size_t i=0; i<count; i++) {
  1414. // NOTE: we rely on the fact that layers are sorted by
  1415. // layerStack first (so we don't have to traverse the list
  1416. // of displays for every layer).
  1417. const sp<Layer>& layer(currentLayers[i]);
  1418. uint32_t layerStack = layer->getDrawingState().layerStack;
  1419. if (i==0 || currentlayerStack != layerStack) {
  1420. currentlayerStack = layerStack;
  1421. // figure out if this layerstack is mirrored
  1422. // (more than one display) if so, pick the default display,
  1423. // if not, pick the only display it's on.
  1424. disp.clear();
  1425. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1426. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1427. if (hw->getLayerStack() == currentlayerStack) {
  1428. if (disp == NULL) {
  1429. disp = hw;
  1430. } else {
  1431. disp = NULL;
  1432. break;
  1433. }
  1434. }
  1435. }
  1436. }
  1437. if (disp == NULL) {
  1438. // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
  1439. // redraw after transform hint changes. See bug 8508397.
  1440. // could be null when this layer is using a layerStack
  1441. // that is not visible on any display. Also can occur at
  1442. // screen off/on times.
  1443. disp = getDefaultDisplayDevice();
  1444. }
  1445. layer->updateTransformHint(disp);
  1446. }
  1447. }
  1448. /*
  1449. * Perform our own transaction if needed
  1450. */
  1451. const LayerVector& layers(mDrawingState.layersSortedByZ);
  1452. if (currentLayers.size() > layers.size()) {
  1453. // layers have been added
  1454. mVisibleRegionsDirty = true;
  1455. }
  1456. // some layers might have been removed, so
  1457. // we need to update the regions they're exposing.
  1458. if (mLayersRemoved) {
  1459. mLayersRemoved = false;
  1460. mVisibleRegionsDirty = true;
  1461. const size_t count = layers.size();
  1462. for (size_t i=0 ; i<count ; i++) {
  1463. const sp<Layer>& layer(layers[i]);
  1464. if (currentLayers.indexOf(layer) < 0) {
  1465. // this layer is not visible anymore
  1466. // TODO: we could traverse the tree from front to back and
  1467. // compute the actual visible region
  1468. // TODO: we could cache the transformed region
  1469. const Layer::State& s(layer->getDrawingState());
  1470. Region visibleReg = s.transform.transform(
  1471. Region(Rect(s.active.w, s.active.h)));
  1472. invalidateLayerStack(s.layerStack, visibleReg);
  1473. }
  1474. }
  1475. }
  1476. commitTransaction();
  1477. updateCursorAsync();
  1478. }
  1479. void SurfaceFlinger::updateCursorAsync()
  1480. {
  1481. HWComposer& hwc(getHwComposer());
  1482. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1483. sp<const DisplayDevice> hw(mDisplays[dpy]);
  1484. const int32_t id = hw->getHwcDisplayId();
  1485. if (id < 0) {
  1486. continue;
  1487. }
  1488. const Vector< sp<Layer> >& currentLayers(
  1489. hw->getVisibleLayersSortedByZ());
  1490. const size_t count = currentLayers.size();
  1491. HWComposer::LayerListIterator cur = hwc.begin(id);
  1492. const HWComposer::LayerListIterator end = hwc.end(id);
  1493. for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
  1494. if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
  1495. continue;
  1496. }
  1497. const sp<Layer>& layer(currentLayers[i]);
  1498. Rect cursorPos = layer->getPosition(hw);
  1499. hwc.setCursorPositionAsync(id, cursorPos);
  1500. break;
  1501. }
  1502. }
  1503. }
  1504. void SurfaceFlinger::commitTransaction()
  1505. {
  1506. if (!mLayersPendingRemoval.isEmpty()) {
  1507. // Notify removed layers now that they can't be drawn from
  1508. for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
  1509. mLayersPendingRemoval[i]->onRemoved();
  1510. }
  1511. mLayersPendingRemoval.clear();
  1512. }
  1513. // If this transaction is part of a window animation then the next frame
  1514. // we composite should be considered an animation as well.
  1515. mAnimCompositionPending = mAnimTransactionPending;
  1516. mDrawingState = mCurrentState;
  1517. mTransactionPending = false;
  1518. mAnimTransactionPending = false;
  1519. mTransactionCV.broadcast();
  1520. }
  1521. void SurfaceFlinger::computeVisibleRegions(size_t dpy,
  1522. const LayerVector& currentLayers, uint32_t layerStack,
  1523. Region& outDirtyRegion, Region& outOpaqueRegion)
  1524. {
  1525. ATRACE_CALL();
  1526. Region aboveOpaqueLayers;
  1527. Region aboveCoveredLayers;
  1528. Region dirty;
  1529. outDirtyRegion.clear();
  1530. bool bIgnoreLayers = false;
  1531. int indexLOI = -1;
  1532. getIndexLOI(dpy, currentLayers, bIgnoreLayers, indexLOI);
  1533. size_t i = currentLayers.size();
  1534. while (i--) {
  1535. const sp<Layer>& layer = currentLayers[i];
  1536. // start with the whole surface at its current location
  1537. const Layer::State& s(layer->getDrawingState());
  1538. if(updateLayerVisibleNonTransparentRegion(dpy, layer,
  1539. bIgnoreLayers, indexLOI,
  1540. layerStack, i))
  1541. continue;
  1542. /*
  1543. * opaqueRegion: area of a surface that is fully opaque.
  1544. */
  1545. Region opaqueRegion;
  1546. /*
  1547. * visibleRegion: area of a surface that is visible on screen
  1548. * and not fully transparent. This is essentially the layer's
  1549. * footprint minus the opaque regions above it.
  1550. * Areas covered by a translucent surface are considered visible.
  1551. */
  1552. Region visibleRegion;
  1553. /*
  1554. * coveredRegion: area of a surface that is covered by all
  1555. * visible regions above it (which includes the translucent areas).
  1556. */
  1557. Region coveredRegion;
  1558. /*
  1559. * transparentRegion: area of a surface that is hinted to be completely
  1560. * transparent. This is only used to tell when the layer has no visible
  1561. * non-transparent regions and can be removed from the layer list. It
  1562. * does not affect the visibleRegion of this layer or any layers
  1563. * beneath it. The hint may not be correct if apps don't respect the
  1564. * SurfaceView restrictions (which, sadly, some don't).
  1565. */
  1566. Region transparentRegion;
  1567. // handle hidden surfaces by setting the visible region to empty
  1568. if (CC_LIKELY(layer->isVisible())) {
  1569. const bool translucent = !layer->isOpaque(s);
  1570. Rect bounds(s.transform.transform(layer->computeBounds()));
  1571. visibleRegion.set(bounds);
  1572. if (!visibleRegion.isEmpty()) {
  1573. // Remove the transparent area from the visible region
  1574. if (translucent) {
  1575. const Transform tr(s.transform);
  1576. if (tr.transformed()) {
  1577. if (tr.preserveRects()) {
  1578. // transform the transparent region
  1579. transparentRegion = tr.transform(s.activeTransparentRegion);
  1580. } else {
  1581. // transformation too complex, can't do the
  1582. // transparent region optimization.
  1583. transparentRegion.clear();
  1584. }
  1585. } else {
  1586. transparentRegion = s.activeTransparentRegion;
  1587. }
  1588. }
  1589. // compute the opaque region
  1590. const int32_t layerOrientation = s.transform.getOrientation();
  1591. if (s.alpha==255 && !translucent &&
  1592. ((layerOrientation & Transform::ROT_INVALID) == false)) {
  1593. // the opaque region is the layer's footprint
  1594. opaqueRegion = visibleRegion;
  1595. }
  1596. }
  1597. }
  1598. // Clip the covered region to the visible region
  1599. coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
  1600. // Update aboveCoveredLayers for next (lower) layer
  1601. aboveCoveredLayers.orSelf(visibleRegion);
  1602. // subtract the opaque region covered by the layers above us
  1603. visibleRegion.subtractSelf(aboveOpaqueLayers);
  1604. // compute this layer's dirty region
  1605. if (layer->contentDirty) {
  1606. // we need to invalidate the whole region
  1607. dirty = visibleRegion;
  1608. // as well, as the old visible region
  1609. dirty.orSelf(layer->visibleRegion);
  1610. layer->contentDirty = false;
  1611. } else {
  1612. /* compute the exposed region:
  1613. * the exposed region consists of two components:
  1614. * 1) what's VISIBLE now and was COVERED before
  1615. * 2) what's EXPOSED now less what was EXPOSED before
  1616. *
  1617. * note that (1) is conservative, we start with the whole
  1618. * visible region but only keep what used to be covered by
  1619. * something -- which mean it may have been exposed.
  1620. *
  1621. * (2) handles areas that were not covered by anything but got
  1622. * exposed because of a resize.
  1623. */
  1624. const Region newExposed = visibleRegion - coveredRegion;
  1625. const Region oldVisibleRegion = layer->visibleRegion;
  1626. const Region oldCoveredRegion = layer->coveredRegion;
  1627. const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
  1628. dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
  1629. }
  1630. dirty.subtractSelf(aboveOpaqueLayers);
  1631. // accumulate to the screen dirty region
  1632. outDirtyRegion.orSelf(dirty);
  1633. // Update aboveOpaqueLayers for next (lower) layer
  1634. aboveOpaqueLayers.orSelf(opaqueRegion);
  1635. // Store the visible region in screen space
  1636. layer->setVisibleRegion(visibleRegion);
  1637. layer->setCoveredRegion(coveredRegion);
  1638. layer->setVisibleNonTransparentRegion(
  1639. visibleRegion.subtract(transparentRegion));
  1640. }
  1641. outOpaqueRegion = aboveOpaqueLayers;
  1642. }
  1643. void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
  1644. const Region& dirty) {
  1645. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  1646. const sp<DisplayDevice>& hw(mDisplays[dpy]);
  1647. if (hw->getLayerStack() == layerStack) {
  1648. hw->dirtyRegion.orSelf(dirty);
  1649. }
  1650. }
  1651. }
  1652. bool SurfaceFlinger::handlePageFlip()
  1653. {
  1654. Region dirtyRegion;
  1655. bool visibleRegions = false;
  1656. const LayerVector& layers(mDrawingState.layersSortedByZ);
  1657. bool frameQueued = false;
  1658. // Store the set of layers that need updates. This set must not change as
  1659. // buffers are being latched, as this could result in a deadlock.
  1660. // Example: Two producers share the same command stream and:
  1661. // 1.) Layer 0 is latched
  1662. // 2.) Layer 0 gets a new frame
  1663. // 2.) Layer 1 gets a new frame
  1664. // 3.) Layer 1 is latched.
  1665. // Display is now waiting on Layer 1's frame, which is behind layer 0's
  1666. // second frame. But layer 0's second frame could be waiting on display.
  1667. Vector<Layer*> layersWithQueuedFrames;
  1668. for (size_t i = 0, count = layers.size(); i<count ; i++) {
  1669. const sp<Layer>& layer(layers[i]);
  1670. if (layer->hasQueuedFrame()) {
  1671. frameQueued = true;
  1672. if (layer->shouldPresentNow(mPrimaryDispSync)) {
  1673. layersWithQueuedFrames.push_back(layer.get());
  1674. } else {
  1675. layer->useEmptyDamage();
  1676. }
  1677. } else {
  1678. layer->useEmptyDamage();
  1679. }
  1680. }
  1681. for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
  1682. Layer* layer = layersWithQueuedFrames[i];
  1683. const Region dirty(layer->latchBuffer(visibleRegions));
  1684. layer->useSurfaceDamage();
  1685. const Layer::State& s(layer->getDrawingState());
  1686. invalidateLayerStack(s.layerStack, dirty);
  1687. }
  1688. mVisibleRegionsDirty |= visibleRegions;
  1689. // If we will need to wake up at some time in the future to deal with a
  1690. // queued frame that shouldn't be displayed during this vsync period, wake
  1691. // up during the next vsync period to check again.
  1692. if (frameQueued && layersWithQueuedFrames.empty()) {
  1693. signalLayerUpdate();
  1694. }
  1695. // Only continue with the refresh if there is actually new work to do
  1696. return !layersWithQueuedFrames.empty();
  1697. }
  1698. void SurfaceFlinger::invalidateHwcGeometry()
  1699. {
  1700. mHwWorkListDirty = true;
  1701. }
  1702. void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
  1703. const Region& inDirtyRegion)
  1704. {
  1705. // We only need to actually compose the display if:
  1706. // 1) It is being handled by hardware composer, which may need this to
  1707. // keep its virtual display state machine in sync, or
  1708. // 2) There is work to be done (the dirty region isn't empty)
  1709. bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
  1710. if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
  1711. return;
  1712. }
  1713. Region dirtyRegion(inDirtyRegion);
  1714. // compute the invalid region
  1715. hw->swapRegion.orSelf(dirtyRegion);
  1716. uint32_t flags = hw->getFlags();
  1717. if (flags & DisplayDevice::SWAP_RECTANGLE) {
  1718. // we can redraw only what's dirty, but since SWAP_RECTANGLE only
  1719. // takes a rectangle, we must make sure to update that whole
  1720. // rectangle in that case
  1721. dirtyRegion.set(hw->swapRegion.bounds());
  1722. } else {
  1723. if (flags & DisplayDevice::PARTIAL_UPDATES) {
  1724. // We need to redraw the rectangle that will be updated
  1725. // (pushed to the framebuffer).
  1726. // This is needed because PARTIAL_UPDATES only takes one
  1727. // rectangle instead of a region (see DisplayDevice::flip())
  1728. dirtyRegion.set(hw->swapRegion.bounds());
  1729. } else {
  1730. // we need to redraw everything (the whole screen)
  1731. dirtyRegion.set(hw->bounds());
  1732. hw->swapRegion = dirtyRegion;
  1733. }
  1734. }
  1735. if (CC_LIKELY(!mDaltonize && !mHasColorMatrix && !mHasSecondaryColorMatrix)) {
  1736. if (!doComposeSurfaces(hw, dirtyRegion)) return;
  1737. } else {
  1738. RenderEngine& engine(getRenderEngine());
  1739. mat4 colorMatrix = mColorMatrix;
  1740. if (mHasSecondaryColorMatrix) {
  1741. colorMatrix = mHasColorMatrix ? (colorMatrix * mSecondaryColorMatrix) : mSecondaryColorMatrix;
  1742. }
  1743. if (mDaltonize) {
  1744. colorMatrix = colorMatrix * mDaltonizer();
  1745. }
  1746. mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
  1747. doComposeSurfaces(hw, dirtyRegion);
  1748. engine.setupColorTransform(oldMatrix);
  1749. }
  1750. // update the swap region and clear the dirty region
  1751. hw->swapRegion.orSelf(dirtyRegion);
  1752. // swap buffers (presentation)
  1753. hw->swapBuffers(getHwComposer());
  1754. }
  1755. bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
  1756. {
  1757. RenderEngine& engine(getRenderEngine());
  1758. const int32_t id = hw->getHwcDisplayId();
  1759. HWComposer& hwc(getHwComposer());
  1760. HWComposer::LayerListIterator cur = hwc.begin(id);
  1761. const HWComposer::LayerListIterator end = hwc.end(id);
  1762. bool hasGlesComposition = hwc.hasGlesComposition(id);
  1763. if (hasGlesComposition) {
  1764. if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
  1765. ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
  1766. hw->getDisplayName().string());
  1767. eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  1768. if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
  1769. ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
  1770. }
  1771. return false;
  1772. }
  1773. // Never touch the framebuffer if we don't have any framebuffer layers
  1774. #if defined(QTI_BSP) && defined(SDM_TARGET)
  1775. const bool hasHwcComposition = hwc.hasHwcComposition(id) |
  1776. (reinterpret_cast<ExHWComposer*>(&hwc))->getS3DFlag(id);
  1777. #else
  1778. const bool hasHwcComposition = hwc.hasHwcComposition(id);
  1779. #endif
  1780. if (hasHwcComposition) {
  1781. // when using overlays, we assume a fully transparent framebuffer
  1782. // NOTE: we could reduce how much we need to clear, for instance
  1783. // remove where there are opaque FB layers. however, on some
  1784. // GPUs doing a "clean slate" clear might be more efficient.
  1785. // We'll revisit later if needed.
  1786. engine.clearWithColor(0, 0, 0, 0);
  1787. } else {
  1788. // we start with the whole screen area
  1789. const Region bounds(hw->getBounds());
  1790. // we remove the scissor part
  1791. // we're left with the letterbox region
  1792. // (common case is that letterbox ends-up being empty)
  1793. const Region letterbox(bounds.subtract(hw->getScissor()));
  1794. // compute the area to clear
  1795. Region region(hw->undefinedRegion.merge(letterbox));
  1796. // but limit it to the dirty region
  1797. region.andSelf(dirty);
  1798. // screen is already cleared here
  1799. if (!region.isEmpty()) {
  1800. // can happen with SurfaceView
  1801. drawWormHoleIfRequired(cur, end, hw, region);
  1802. }
  1803. }
  1804. if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
  1805. // just to be on the safe side, we don't set the
  1806. // scissor on the main display. It should never be needed
  1807. // anyways (though in theory it could since the API allows it).
  1808. const Rect& bounds(hw->getBounds());
  1809. const Rect& scissor(hw->getScissor());
  1810. if (scissor != bounds) {
  1811. // scissor doesn't match the screen's dimensions, so we
  1812. // need to clear everything outside of it and enable
  1813. // the GL scissor so we don't draw anything where we shouldn't
  1814. // enable scissor for this frame
  1815. const uint32_t height = hw->getHeight();
  1816. engine.setScissor(scissor.left, height - scissor.bottom,
  1817. scissor.getWidth(), scissor.getHeight());
  1818. }
  1819. }
  1820. }
  1821. /*
  1822. * and then, render the layers targeted at the framebuffer
  1823. */
  1824. const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
  1825. const size_t count = layers.size();
  1826. const Transform& tr = hw->getTransform();
  1827. if (cur != end) {
  1828. // we're using h/w composer
  1829. for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
  1830. const sp<Layer>& layer(layers[i]);
  1831. const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
  1832. if (!clip.isEmpty()) {
  1833. switch (cur->getCompositionType()) {
  1834. case HWC_CURSOR_OVERLAY:
  1835. case HWC_OVERLAY: {
  1836. const Layer::State& state(layer->getDrawingState());
  1837. if ((cur->getHints() & HWC_HINT_CLEAR_FB)
  1838. && i
  1839. && layer->isOpaque(state) && (state.alpha == 0xFF)
  1840. && hasGlesComposition) {
  1841. // never clear the very first layer since we're
  1842. // guaranteed the FB is already cleared
  1843. layer->clearWithOpenGL(hw, clip);
  1844. }
  1845. break;
  1846. }
  1847. case HWC_FRAMEBUFFER: {
  1848. layer->draw(hw, clip);
  1849. break;
  1850. }
  1851. case HWC_FRAMEBUFFER_TARGET: {
  1852. // this should not happen as the iterator shouldn't
  1853. // let us get there.
  1854. ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. layer->setAcquireFence(hw, *cur);
  1860. }
  1861. } else {
  1862. // we're not using h/w composer
  1863. for (size_t i=0 ; i<count ; ++i) {
  1864. const sp<Layer>& layer(layers[i]);
  1865. const Region clip(dirty.intersect(
  1866. tr.transform(layer->visibleRegion)));
  1867. if (!clip.isEmpty()) {
  1868. layer->draw(hw, clip);
  1869. }
  1870. }
  1871. }
  1872. // disable scissor at the end of the frame
  1873. engine.disableScissor();
  1874. return true;
  1875. }
  1876. void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
  1877. const int32_t height = hw->getHeight();
  1878. RenderEngine& engine(getRenderEngine());
  1879. engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
  1880. }
  1881. status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
  1882. const sp<IBinder>& handle,
  1883. const sp<IGraphicBufferProducer>& gbc,
  1884. const sp<Layer>& lbc)
  1885. {
  1886. // add this layer to the current state list
  1887. {
  1888. Mutex::Autolock _l(mStateLock);
  1889. if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
  1890. return NO_MEMORY;
  1891. }
  1892. mCurrentState.layersSortedByZ.add(lbc);
  1893. mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
  1894. }
  1895. // attach this layer to the client
  1896. client->attachLayer(handle, lbc);
  1897. return NO_ERROR;
  1898. }
  1899. status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
  1900. Mutex::Autolock _l(mStateLock);
  1901. ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
  1902. if (index >= 0) {
  1903. mLayersPendingRemoval.push(layer);
  1904. mLayersRemoved = true;
  1905. setTransactionFlags(eTransactionNeeded);
  1906. return NO_ERROR;
  1907. }
  1908. return status_t(index);
  1909. }
  1910. uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
  1911. return android_atomic_release_load(&mTransactionFlags);
  1912. }
  1913. uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
  1914. return android_atomic_and(~flags, &mTransactionFlags) & flags;
  1915. }
  1916. uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
  1917. uint32_t old = android_atomic_or(flags, &mTransactionFlags);
  1918. if ((old & flags)==0) { // wake the server up
  1919. signalTransaction();
  1920. }
  1921. return old;
  1922. }
  1923. void SurfaceFlinger::setTransactionState(
  1924. const Vector<ComposerState>& state,
  1925. const Vector<DisplayState>& displays,
  1926. uint32_t flags)
  1927. {
  1928. ATRACE_CALL();
  1929. delayDPTransactionIfNeeded(displays);
  1930. Mutex::Autolock _l(mStateLock);
  1931. uint32_t transactionFlags = 0;
  1932. if (flags & eAnimation) {
  1933. // For window updates that are part of an animation we must wait for
  1934. // previous animation "frames" to be handled.
  1935. while (mAnimTransactionPending) {
  1936. status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
  1937. if (CC_UNLIKELY(err != NO_ERROR)) {
  1938. // just in case something goes wrong in SF, return to the
  1939. // caller after a few seconds.
  1940. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
  1941. "waiting for previous animation frame");
  1942. mAnimTransactionPending = false;
  1943. break;
  1944. }
  1945. }
  1946. }
  1947. size_t count = displays.size();
  1948. for (size_t i=0 ; i<count ; i++) {
  1949. const DisplayState& s(displays[i]);
  1950. transactionFlags |= setDisplayStateLocked(s);
  1951. }
  1952. count = state.size();
  1953. for (size_t i=0 ; i<count ; i++) {
  1954. const ComposerState& s(state[i]);
  1955. // Here we need to check that the interface we're given is indeed
  1956. // one of our own. A malicious client could give us a NULL
  1957. // IInterface, or one of its own or even one of our own but a
  1958. // different type. All these situations would cause us to crash.
  1959. //
  1960. // NOTE: it would be better to use RTTI as we could directly check
  1961. // that we have a Client*. however, RTTI is disabled in Android.
  1962. if (s.client != NULL) {
  1963. sp<IBinder> binder = IInterface::asBinder(s.client);
  1964. if (binder != NULL) {
  1965. if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
  1966. sp<Client> client( static_cast<Client *>(s.client.get()) );
  1967. transactionFlags |= setClientStateLocked(client, s.state);
  1968. }
  1969. }
  1970. }
  1971. }
  1972. if (transactionFlags) {
  1973. // this triggers the transaction
  1974. setTransactionFlags(transactionFlags);
  1975. // if this is a synchronous transaction, wait for it to take effect
  1976. // before returning.
  1977. if (flags & eSynchronous) {
  1978. mTransactionPending = true;
  1979. }
  1980. if (flags & eAnimation) {
  1981. mAnimTransactionPending = true;
  1982. }
  1983. while (mTransactionPending) {
  1984. status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
  1985. if (CC_UNLIKELY(err != NO_ERROR)) {
  1986. // just in case something goes wrong in SF, return to the
  1987. // called after a few seconds.
  1988. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
  1989. mTransactionPending = false;
  1990. break;
  1991. }
  1992. }
  1993. }
  1994. }
  1995. uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
  1996. {
  1997. ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
  1998. if (dpyIdx < 0)
  1999. return 0;
  2000. uint32_t flags = 0;
  2001. DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
  2002. if (disp.isValid()) {
  2003. const uint32_t what = s.what;
  2004. if (what & DisplayState::eSurfaceChanged) {
  2005. if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
  2006. disp.surface = s.surface;
  2007. flags |= eDisplayTransactionNeeded;
  2008. }
  2009. }
  2010. if (what & DisplayState::eLayerStackChanged) {
  2011. if (disp.layerStack != s.layerStack) {
  2012. disp.layerStack = s.layerStack;
  2013. flags |= eDisplayTransactionNeeded;
  2014. }
  2015. }
  2016. if (what & DisplayState::eDisplayProjectionChanged) {
  2017. if (disp.orientation != s.orientation) {
  2018. disp.orientation = s.orientation;
  2019. flags |= eDisplayTransactionNeeded;
  2020. }
  2021. if (disp.frame != s.frame) {
  2022. disp.frame = s.frame;
  2023. flags |= eDisplayTransactionNeeded;
  2024. }
  2025. if (disp.viewport != s.viewport) {
  2026. disp.viewport = s.viewport;
  2027. flags |= eDisplayTransactionNeeded;
  2028. }
  2029. }
  2030. if (what & DisplayState::eDisplaySizeChanged) {
  2031. if (disp.width != s.width) {
  2032. disp.width = s.width;
  2033. flags |= eDisplayTransactionNeeded;
  2034. }
  2035. if (disp.height != s.height) {
  2036. disp.height = s.height;
  2037. flags |= eDisplayTransactionNeeded;
  2038. }
  2039. }
  2040. }
  2041. return flags;
  2042. }
  2043. uint32_t SurfaceFlinger::setClientStateLocked(
  2044. const sp<Client>& client,
  2045. const layer_state_t& s)
  2046. {
  2047. uint32_t flags = 0;
  2048. sp<Layer> layer(client->getLayerUser(s.surface));
  2049. if (layer != 0) {
  2050. const uint32_t what = s.what;
  2051. if (what & layer_state_t::ePositionChanged) {
  2052. if (layer->setPosition(s.x, s.y))
  2053. flags |= eTraversalNeeded;
  2054. }
  2055. if (what & layer_state_t::eLayerChanged) {
  2056. // NOTE: index needs to be calculated before we update the state
  2057. ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
  2058. if (layer->setLayer(s.z)) {
  2059. mCurrentState.layersSortedByZ.removeAt(idx);
  2060. mCurrentState.layersSortedByZ.add(layer);
  2061. // we need traversal (state changed)
  2062. // AND transaction (list changed)
  2063. flags |= eTransactionNeeded|eTraversalNeeded;
  2064. }
  2065. }
  2066. if (what & layer_state_t::eBlurChanged) {
  2067. ALOGV("eBlurChanged");
  2068. if (layer->setBlur(uint8_t(255.0f*s.blur+0.5f))) {
  2069. flags |= eTraversalNeeded;
  2070. }
  2071. }
  2072. if (what & layer_state_t::eBlurMaskSurfaceChanged) {
  2073. ALOGV("eBlurMaskSurfaceChanged");
  2074. sp<Layer> maskLayer = 0;
  2075. if (s.blurMaskSurface != 0) {
  2076. maskLayer = client->getLayerUser(s.blurMaskSurface);
  2077. }
  2078. if (maskLayer == 0) {
  2079. ALOGV("eBlurMaskSurfaceChanged. maskLayer == 0");
  2080. } else {
  2081. ALOGV("eBlurMaskSurfaceChagned. maskLayer.z == %d", maskLayer->getCurrentState().z);
  2082. if (maskLayer->isBlurLayer()) {
  2083. ALOGE("Blur layer can not be used as blur mask surface");
  2084. maskLayer = 0;
  2085. }
  2086. }
  2087. if (layer->setBlurMaskLayer(maskLayer)) {
  2088. flags |= eTraversalNeeded;
  2089. }
  2090. }
  2091. if (what & layer_state_t::eBlurMaskSamplingChanged) {
  2092. if (layer->setBlurMaskSampling(s.blurMaskSampling)) {
  2093. flags |= eTraversalNeeded;
  2094. }
  2095. }
  2096. if (what & layer_state_t::eBlurMaskAlphaThresholdChanged) {
  2097. if (layer->setBlurMaskAlphaThreshold(s.blurMaskAlphaThreshold)) {
  2098. flags |= eTraversalNeeded;
  2099. }
  2100. }
  2101. if (what & layer_state_t::eSizeChanged) {
  2102. if (layer->setSize(s.w, s.h)) {
  2103. flags |= eTraversalNeeded;
  2104. }
  2105. }
  2106. if (what & layer_state_t::eAlphaChanged) {
  2107. if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
  2108. flags |= eTraversalNeeded;
  2109. }
  2110. if (what & layer_state_t::eMatrixChanged) {
  2111. if (layer->setMatrix(s.matrix))
  2112. flags |= eTraversalNeeded;
  2113. }
  2114. if (what & layer_state_t::eTransparentRegionChanged) {
  2115. if (layer->setTransparentRegionHint(s.transparentRegion))
  2116. flags |= eTraversalNeeded;
  2117. }
  2118. if (what & layer_state_t::eFlagsChanged) {
  2119. if (layer->setFlags(s.flags, s.mask))
  2120. flags |= eTraversalNeeded;
  2121. }
  2122. if (what & layer_state_t::eCropChanged) {
  2123. if (layer->setCrop(s.crop))
  2124. flags |= eTraversalNeeded;
  2125. }
  2126. if (what & layer_state_t::eLayerStackChanged) {
  2127. // NOTE: index needs to be calculated before we update the state
  2128. ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
  2129. if (layer->setLayerStack(s.layerStack)) {
  2130. mCurrentState.layersSortedByZ.removeAt(idx);
  2131. mCurrentState.layersSortedByZ.add(layer);
  2132. // we need traversal (state changed)
  2133. // AND transaction (list changed)
  2134. flags |= eTransactionNeeded|eTraversalNeeded;
  2135. }
  2136. }
  2137. }
  2138. return flags;
  2139. }
  2140. status_t SurfaceFlinger::createLayer(
  2141. const String8& name,
  2142. const sp<Client>& client,
  2143. uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
  2144. sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
  2145. {
  2146. //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
  2147. if (int32_t(w|h) < 0) {
  2148. ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
  2149. int(w), int(h));
  2150. return BAD_VALUE;
  2151. }
  2152. status_t result = NO_ERROR;
  2153. sp<Layer> layer;
  2154. switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
  2155. case ISurfaceComposerClient::eFXSurfaceNormal:
  2156. result = createNormalLayer(client,
  2157. name, w, h, flags, format,
  2158. handle, gbp, &layer);
  2159. break;
  2160. case ISurfaceComposerClient::eFXSurfaceDim:
  2161. result = createDimLayer(client,
  2162. name, w, h, flags,
  2163. handle, gbp, &layer);
  2164. break;
  2165. case ISurfaceComposerClient::eFXSurfaceBlur:
  2166. result = createBlurLayer(client,
  2167. name, w, h, flags,
  2168. handle, gbp, &layer);
  2169. break;
  2170. default:
  2171. result = BAD_VALUE;
  2172. break;
  2173. }
  2174. if (result != NO_ERROR) {
  2175. return result;
  2176. }
  2177. result = addClientLayer(client, *handle, *gbp, layer);
  2178. if (result != NO_ERROR) {
  2179. return result;
  2180. }
  2181. setTransactionFlags(eTransactionNeeded);
  2182. return result;
  2183. }
  2184. status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
  2185. const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
  2186. sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
  2187. {
  2188. // initialize the surfaces
  2189. switch (format) {
  2190. case PIXEL_FORMAT_TRANSPARENT:
  2191. case PIXEL_FORMAT_TRANSLUCENT:
  2192. format = PIXEL_FORMAT_RGBA_8888;
  2193. break;
  2194. case PIXEL_FORMAT_OPAQUE:
  2195. format = PIXEL_FORMAT_RGBX_8888;
  2196. break;
  2197. }
  2198. *outLayer = DisplayUtils::getInstance()->getLayerInstance(this, client, name, w, h, flags);
  2199. status_t err = (*outLayer)->setBuffers(w, h, format, flags);
  2200. if (err == NO_ERROR) {
  2201. *handle = (*outLayer)->getHandle();
  2202. *gbp = (*outLayer)->getProducer();
  2203. }
  2204. ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
  2205. return err;
  2206. }
  2207. status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
  2208. const String8& name, uint32_t w, uint32_t h, uint32_t flags,
  2209. sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
  2210. {
  2211. *outLayer = new LayerDim(this, client, name, w, h, flags);
  2212. *handle = (*outLayer)->getHandle();
  2213. *gbp = (*outLayer)->getProducer();
  2214. return NO_ERROR;
  2215. }
  2216. status_t SurfaceFlinger::createBlurLayer(const sp<Client>& client,
  2217. const String8& name, uint32_t w, uint32_t h, uint32_t flags,
  2218. sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
  2219. {
  2220. *outLayer = new LayerBlur(this, client, name, w, h, flags);
  2221. *handle = (*outLayer)->getHandle();
  2222. *gbp = (*outLayer)->getProducer();
  2223. return NO_ERROR;
  2224. }
  2225. status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
  2226. {
  2227. // called by the window manager when it wants to remove a Layer
  2228. status_t err = NO_ERROR;
  2229. sp<Layer> l(client->getLayerUser(handle));
  2230. if (l != NULL) {
  2231. err = removeLayer(l);
  2232. ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
  2233. "error removing layer=%p (%s)", l.get(), strerror(-err));
  2234. }
  2235. return err;
  2236. }
  2237. status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
  2238. {
  2239. // called by ~LayerCleaner() when all references to the IBinder (handle)
  2240. // are gone
  2241. status_t err = NO_ERROR;
  2242. sp<Layer> l(layer.promote());
  2243. if (l != NULL) {
  2244. err = removeLayer(l);
  2245. ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
  2246. "error removing layer=%p (%s)", l.get(), strerror(-err));
  2247. }
  2248. return err;
  2249. }
  2250. // ---------------------------------------------------------------------------
  2251. void SurfaceFlinger::onInitializeDisplays() {
  2252. // reset screen orientation and use primary layer stack
  2253. Vector<ComposerState> state;
  2254. Vector<DisplayState> displays;
  2255. DisplayState d;
  2256. d.what = DisplayState::eDisplayProjectionChanged |
  2257. DisplayState::eLayerStackChanged;
  2258. d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
  2259. d.layerStack = 0;
  2260. d.orientation = DisplayState::eOrientationDefault;
  2261. d.frame.makeInvalid();
  2262. d.viewport.makeInvalid();
  2263. d.width = 0;
  2264. d.height = 0;
  2265. displays.add(d);
  2266. setTransactionState(state, displays, 0);
  2267. setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
  2268. const nsecs_t period =
  2269. getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
  2270. mAnimFrameTracker.setDisplayRefreshPeriod(period);
  2271. }
  2272. void SurfaceFlinger::initializeDisplays() {
  2273. class MessageScreenInitialized : public MessageBase {
  2274. SurfaceFlinger* flinger;
  2275. public:
  2276. MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
  2277. virtual bool handler() {
  2278. flinger->onInitializeDisplays();
  2279. return true;
  2280. }
  2281. };
  2282. sp<MessageBase> msg = new MessageScreenInitialized(this);
  2283. postMessageAsync(msg); // we may be called from main thread, use async message
  2284. }
  2285. void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
  2286. int mode) {
  2287. ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
  2288. this);
  2289. int32_t type = hw->getDisplayType();
  2290. int currentMode = hw->getPowerMode();
  2291. if (mode == currentMode) {
  2292. ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
  2293. return;
  2294. }
  2295. hw->setPowerMode(mode);
  2296. if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
  2297. ALOGW("Trying to set power mode for virtual display");
  2298. return;
  2299. }
  2300. if (currentMode == HWC_POWER_MODE_OFF) {
  2301. getHwComposer().setPowerMode(type, mode);
  2302. if (type == DisplayDevice::DISPLAY_PRIMARY) {
  2303. // FIXME: eventthread only knows about the main display right now
  2304. mEventThread->onScreenAcquired();
  2305. resyncToHardwareVsync(true);
  2306. }
  2307. mVisibleRegionsDirty = true;
  2308. mHasPoweredOff = true;
  2309. repaintEverything();
  2310. } else if (mode == HWC_POWER_MODE_OFF) {
  2311. if (type == DisplayDevice::DISPLAY_PRIMARY) {
  2312. disableHardwareVsync(true); // also cancels any in-progress resync
  2313. // FIXME: eventthread only knows about the main display right now
  2314. mEventThread->onScreenReleased();
  2315. }
  2316. getHwComposer().setPowerMode(type, mode);
  2317. mVisibleRegionsDirty = true;
  2318. // from this point on, SF will stop drawing on this display
  2319. } else {
  2320. getHwComposer().setPowerMode(type, mode);
  2321. }
  2322. }
  2323. void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
  2324. class MessageSetPowerMode: public MessageBase {
  2325. SurfaceFlinger& mFlinger;
  2326. sp<IBinder> mDisplay;
  2327. int mMode;
  2328. public:
  2329. MessageSetPowerMode(SurfaceFlinger& flinger,
  2330. const sp<IBinder>& disp, int mode) : mFlinger(flinger),
  2331. mDisplay(disp) { mMode = mode; }
  2332. virtual bool handler() {
  2333. sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
  2334. if (hw == NULL) {
  2335. ALOGE("Attempt to set power mode = %d for null display %p",
  2336. mMode, mDisplay.get());
  2337. } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
  2338. ALOGW("Attempt to set power mode = %d for virtual display",
  2339. mMode);
  2340. } else {
  2341. mFlinger.setPowerModeInternal(hw, mMode);
  2342. }
  2343. return true;
  2344. }
  2345. };
  2346. sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
  2347. postMessageSync(msg);
  2348. }
  2349. // ---------------------------------------------------------------------------
  2350. status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
  2351. {
  2352. String8 result;
  2353. IPCThreadState* ipc = IPCThreadState::self();
  2354. const int pid = ipc->getCallingPid();
  2355. const int uid = ipc->getCallingUid();
  2356. if ((uid != AID_SHELL) &&
  2357. !PermissionCache::checkPermission(sDump, pid, uid)) {
  2358. result.appendFormat("Permission Denial: "
  2359. "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
  2360. } else {
  2361. // Try to get the main lock, but give up after one second
  2362. // (this would indicate SF is stuck, but we want to be able to
  2363. // print something in dumpsys).
  2364. status_t err = mStateLock.timedLock(s2ns(1));
  2365. bool locked = (err == NO_ERROR);
  2366. if (!locked) {
  2367. result.appendFormat(
  2368. "SurfaceFlinger appears to be unresponsive (%s [%d]), "
  2369. "dumping anyways (no locks held)\n", strerror(-err), err);
  2370. }
  2371. bool dumpAll = true;
  2372. size_t index = 0;
  2373. size_t numArgs = args.size();
  2374. if (numArgs) {
  2375. if ((index < numArgs) &&
  2376. (args[index] == String16("--list"))) {
  2377. index++;
  2378. listLayersLocked(args, index, result);
  2379. dumpAll = false;
  2380. }
  2381. if ((index < numArgs) &&
  2382. (args[index] == String16("--latency"))) {
  2383. index++;
  2384. dumpStatsLocked(args, index, result);
  2385. dumpAll = false;
  2386. }
  2387. if ((index < numArgs) &&
  2388. (args[index] == String16("--latency-clear"))) {
  2389. index++;
  2390. clearStatsLocked(args, index, result);
  2391. dumpAll = false;
  2392. }
  2393. if ((index < numArgs) &&
  2394. (args[index] == String16("--dispsync"))) {
  2395. index++;
  2396. mPrimaryDispSync.dump(result);
  2397. dumpAll = false;
  2398. }
  2399. if ((index < numArgs) &&
  2400. (args[index] == String16("--static-screen"))) {
  2401. index++;
  2402. dumpStaticScreenStats(result);
  2403. dumpAll = false;
  2404. }
  2405. }
  2406. if (dumpAll) {
  2407. dumpAllLocked(args, index, result);
  2408. }
  2409. if (locked) {
  2410. mStateLock.unlock();
  2411. }
  2412. }
  2413. write(fd, result.string(), result.size());
  2414. return NO_ERROR;
  2415. }
  2416. void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
  2417. size_t& /* index */, String8& result) const
  2418. {
  2419. const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
  2420. const size_t count = currentLayers.size();
  2421. for (size_t i=0 ; i<count ; i++) {
  2422. const sp<Layer>& layer(currentLayers[i]);
  2423. result.appendFormat("%s\n", layer->getName().string());
  2424. }
  2425. }
  2426. void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
  2427. String8& result) const
  2428. {
  2429. String8 name;
  2430. if (index < args.size()) {
  2431. name = String8(args[index]);
  2432. index++;
  2433. }
  2434. const nsecs_t period =
  2435. getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
  2436. result.appendFormat("%" PRId64 "\n", period);
  2437. if (name.isEmpty()) {
  2438. mAnimFrameTracker.dumpStats(result);
  2439. } else {
  2440. bool found = false;
  2441. const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
  2442. const size_t count = currentLayers.size();
  2443. for (size_t i=0 ; i<count ; i++) {
  2444. const sp<Layer>& layer(currentLayers[i]);
  2445. if (name == layer->getName()) {
  2446. found = true;
  2447. layer->dumpFrameStats(result);
  2448. }
  2449. }
  2450. if (!found && !strncmp(name.string(), "SurfaceView", 11)) {
  2451. lastSurfaceViewLayer->dumpFrameStats(result);
  2452. }
  2453. }
  2454. }
  2455. void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
  2456. String8& /* result */)
  2457. {
  2458. String8 name;
  2459. if (index < args.size()) {
  2460. name = String8(args[index]);
  2461. index++;
  2462. }
  2463. const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
  2464. const size_t count = currentLayers.size();
  2465. for (size_t i=0 ; i<count ; i++) {
  2466. const sp<Layer>& layer(currentLayers[i]);
  2467. if (name.isEmpty() || (name == layer->getName())) {
  2468. layer->clearFrameStats();
  2469. }
  2470. }
  2471. mAnimFrameTracker.clearStats();
  2472. }
  2473. // This should only be called from the main thread. Otherwise it would need
  2474. // the lock and should use mCurrentState rather than mDrawingState.
  2475. void SurfaceFlinger::logFrameStats() {
  2476. const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
  2477. const size_t count = drawingLayers.size();
  2478. for (size_t i=0 ; i<count ; i++) {
  2479. const sp<Layer>& layer(drawingLayers[i]);
  2480. layer->logFrameStats();
  2481. }
  2482. mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
  2483. }
  2484. /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
  2485. {
  2486. static const char* config =
  2487. " [sf"
  2488. #ifdef HAS_CONTEXT_PRIORITY
  2489. " HAS_CONTEXT_PRIORITY"
  2490. #endif
  2491. #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
  2492. " NEVER_DEFAULT_TO_ASYNC_MODE"
  2493. #endif
  2494. #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
  2495. " TARGET_DISABLE_TRIPLE_BUFFERING"
  2496. #endif
  2497. "]";
  2498. result.append(config);
  2499. }
  2500. void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
  2501. {
  2502. result.appendFormat("Static screen stats:\n");
  2503. for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
  2504. float bucketTimeSec = mFrameBuckets[b] / 1e9;
  2505. float percent = 100.0f *
  2506. static_cast<float>(mFrameBuckets[b]) / mTotalTime;
  2507. result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
  2508. b + 1, bucketTimeSec, percent);
  2509. }
  2510. float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
  2511. float percent = 100.0f *
  2512. static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
  2513. result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
  2514. NUM_BUCKETS - 1, bucketTimeSec, percent);
  2515. }
  2516. void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
  2517. String8& result) const
  2518. {
  2519. bool colorize = false;
  2520. if (index < args.size()
  2521. && (args[index] == String16("--color"))) {
  2522. colorize = true;
  2523. index++;
  2524. }
  2525. Colorizer colorizer(colorize);
  2526. // figure out if we're stuck somewhere
  2527. const nsecs_t now = systemTime();
  2528. const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
  2529. const nsecs_t inTransaction(mDebugInTransaction);
  2530. nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
  2531. nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
  2532. /*
  2533. * Dump library configuration.
  2534. */
  2535. colorizer.bold(result);
  2536. result.append("Build configuration:");
  2537. colorizer.reset(result);
  2538. appendSfConfigString(result);
  2539. appendUiConfigString(result);
  2540. appendGuiConfigString(result);
  2541. result.append("\n");
  2542. colorizer.bold(result);
  2543. result.append("Sync configuration: ");
  2544. colorizer.reset(result);
  2545. result.append(SyncFeatures::getInstance().toString());
  2546. result.append("\n");
  2547. colorizer.bold(result);
  2548. result.append("DispSync configuration: ");
  2549. colorizer.reset(result);
  2550. result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
  2551. "present offset %d ns (refresh %" PRId64 " ns)",
  2552. vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
  2553. mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
  2554. result.append("\n");
  2555. // Dump static screen stats
  2556. result.append("\n");
  2557. dumpStaticScreenStats(result);
  2558. result.append("\n");
  2559. /*
  2560. * Dump the visible layer list
  2561. */
  2562. const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
  2563. const size_t count = currentLayers.size();
  2564. colorizer.bold(result);
  2565. result.appendFormat("Visible layers (count = %zu)\n", count);
  2566. colorizer.reset(result);
  2567. for (size_t i=0 ; i<count ; i++) {
  2568. const sp<Layer>& layer(currentLayers[i]);
  2569. layer->dump(result, colorizer);
  2570. }
  2571. /*
  2572. * Dump Display state
  2573. */
  2574. colorizer.bold(result);
  2575. result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
  2576. colorizer.reset(result);
  2577. for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
  2578. const sp<const DisplayDevice>& hw(mDisplays[dpy]);
  2579. hw->dump(result);
  2580. }
  2581. /*
  2582. * Dump SurfaceFlinger global state
  2583. */
  2584. colorizer.bold(result);
  2585. result.append("SurfaceFlinger global state:\n");
  2586. colorizer.reset(result);
  2587. HWComposer& hwc(getHwComposer());
  2588. sp<const DisplayDevice> hw(getDefaultDisplayDevice());
  2589. colorizer.bold(result);
  2590. result.appendFormat("EGL implementation : %s\n",
  2591. eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
  2592. colorizer.reset(result);
  2593. result.appendFormat("%s\n",
  2594. eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
  2595. mRenderEngine->dump(result);
  2596. hw->undefinedRegion.dump(result, "undefinedRegion");
  2597. result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
  2598. hw->getOrientation(), hw->isDisplayOn());
  2599. result.appendFormat(
  2600. " last eglSwapBuffers() time: %f us\n"
  2601. " last transaction time : %f us\n"
  2602. " transaction-flags : %08x\n"
  2603. " refresh-rate : %f fps\n"
  2604. " x-dpi : %f\n"
  2605. " y-dpi : %f\n"
  2606. " gpu_to_cpu_unsupported : %d\n"
  2607. ,
  2608. mLastSwapBufferTime/1000.0,
  2609. mLastTransactionTime/1000.0,
  2610. mTransactionFlags,
  2611. 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
  2612. hwc.getDpiX(HWC_DISPLAY_PRIMARY),
  2613. hwc.getDpiY(HWC_DISPLAY_PRIMARY),
  2614. !mGpuToCpuSupported);
  2615. result.appendFormat(" eglSwapBuffers time: %f us\n",
  2616. inSwapBuffersDuration/1000.0);
  2617. result.appendFormat(" transaction time: %f us\n",
  2618. inTransactionDuration/1000.0);
  2619. /*
  2620. * VSYNC state
  2621. */
  2622. mEventThread->dump(result);
  2623. /*
  2624. * Dump HWComposer state
  2625. */
  2626. colorizer.bold(result);
  2627. result.append("h/w composer state:\n");
  2628. colorizer.reset(result);
  2629. result.appendFormat(" h/w composer %s and %s\n",
  2630. hwc.initCheck()==NO_ERROR ? "present" : "not present",
  2631. (mDebugDisableHWC || mDebugRegion || mDaltonize
  2632. || mHasColorMatrix
  2633. || mHasSecondaryColorMatrix) ? "disabled" : "enabled");
  2634. hwc.dump(result);
  2635. /*
  2636. * Dump gralloc state
  2637. */
  2638. const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
  2639. alloc.dump(result);
  2640. }
  2641. const Vector< sp<Layer> >&
  2642. SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
  2643. // Note: mStateLock is held here
  2644. wp<IBinder> dpy;
  2645. for (size_t i=0 ; i<mDisplays.size() ; i++) {
  2646. if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
  2647. dpy = mDisplays.keyAt(i);
  2648. break;
  2649. }
  2650. }
  2651. if (dpy == NULL) {
  2652. ALOGW("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
  2653. // Just use the primary display so we have something to return
  2654. dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
  2655. }
  2656. return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
  2657. }
  2658. bool SurfaceFlinger::startDdmConnection()
  2659. {
  2660. void* libddmconnection_dso =
  2661. dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
  2662. if (!libddmconnection_dso) {
  2663. return false;
  2664. }
  2665. void (*DdmConnection_start)(const char* name);
  2666. DdmConnection_start =
  2667. (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
  2668. if (!DdmConnection_start) {
  2669. dlclose(libddmconnection_dso);
  2670. return false;
  2671. }
  2672. (*DdmConnection_start)(getServiceName());
  2673. return true;
  2674. }
  2675. status_t SurfaceFlinger::onTransact(
  2676. uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
  2677. {
  2678. switch (code) {
  2679. case CREATE_CONNECTION:
  2680. case CREATE_DISPLAY:
  2681. case SET_TRANSACTION_STATE:
  2682. case BOOT_FINISHED:
  2683. case CLEAR_ANIMATION_FRAME_STATS:
  2684. case GET_ANIMATION_FRAME_STATS:
  2685. case SET_POWER_MODE:
  2686. {
  2687. // codes that require permission check
  2688. IPCThreadState* ipc = IPCThreadState::self();
  2689. const int pid = ipc->getCallingPid();
  2690. const int uid = ipc->getCallingUid();
  2691. if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
  2692. !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
  2693. ALOGE("Permission Denial: "
  2694. "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
  2695. return PERMISSION_DENIED;
  2696. }
  2697. break;
  2698. }
  2699. case CAPTURE_SCREEN:
  2700. {
  2701. // codes that require permission check
  2702. IPCThreadState* ipc = IPCThreadState::self();
  2703. const int pid = ipc->getCallingPid();
  2704. const int uid = ipc->getCallingUid();
  2705. if ((uid != AID_GRAPHICS) &&
  2706. !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
  2707. ALOGE("Permission Denial: "
  2708. "can't read framebuffer pid=%d, uid=%d", pid, uid);
  2709. return PERMISSION_DENIED;
  2710. }
  2711. break;
  2712. }
  2713. }
  2714. status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
  2715. if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
  2716. CHECK_INTERFACE(ISurfaceComposer, data, reply);
  2717. if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
  2718. IPCThreadState* ipc = IPCThreadState::self();
  2719. const int pid = ipc->getCallingPid();
  2720. const int uid = ipc->getCallingUid();
  2721. ALOGE("Permission Denial: "
  2722. "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
  2723. return PERMISSION_DENIED;
  2724. }
  2725. int n;
  2726. switch (code) {
  2727. case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
  2728. case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
  2729. return NO_ERROR;
  2730. case 1002: // SHOW_UPDATES
  2731. n = data.readInt32();
  2732. mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
  2733. invalidateHwcGeometry();
  2734. repaintEverything();
  2735. return NO_ERROR;
  2736. case 1004:{ // repaint everything
  2737. repaintEverything();
  2738. return NO_ERROR;
  2739. }
  2740. case 1005:{ // force transaction
  2741. setTransactionFlags(
  2742. eTransactionNeeded|
  2743. eDisplayTransactionNeeded|
  2744. eTraversalNeeded);
  2745. return NO_ERROR;
  2746. }
  2747. case 1006:{ // send empty update
  2748. signalRefresh();
  2749. return NO_ERROR;
  2750. }
  2751. case 1008: // toggle use of hw composer
  2752. n = data.readInt32();
  2753. mDebugDisableHWC = n ? 1 : 0;
  2754. invalidateHwcGeometry();
  2755. repaintEverything();
  2756. return NO_ERROR;
  2757. case 1009: // toggle use of transform hint
  2758. n = data.readInt32();
  2759. mDebugDisableTransformHint = n ? 1 : 0;
  2760. invalidateHwcGeometry();
  2761. repaintEverything();
  2762. return NO_ERROR;
  2763. case 1010: // interrogate.
  2764. reply->writeInt32(0);
  2765. reply->writeInt32(0);
  2766. reply->writeInt32(mDebugRegion);
  2767. reply->writeInt32(0);
  2768. reply->writeInt32(mDebugDisableHWC);
  2769. return NO_ERROR;
  2770. case 1013: {
  2771. Mutex::Autolock _l(mStateLock);
  2772. sp<const DisplayDevice> hw(getDefaultDisplayDevice());
  2773. reply->writeInt32(hw->getPageFlipCount());
  2774. return NO_ERROR;
  2775. }
  2776. case 1014: {
  2777. // daltonize
  2778. n = data.readInt32();
  2779. switch (n % 10) {
  2780. case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
  2781. case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
  2782. case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
  2783. }
  2784. if (n >= 10) {
  2785. mDaltonizer.setMode(Daltonizer::correction);
  2786. } else {
  2787. mDaltonizer.setMode(Daltonizer::simulation);
  2788. }
  2789. mDaltonize = n > 0;
  2790. invalidateHwcGeometry();
  2791. repaintEverything();
  2792. return NO_ERROR;
  2793. }
  2794. case 1015: {
  2795. // apply a color matrix
  2796. n = data.readInt32();
  2797. mHasColorMatrix = n ? 1 : 0;
  2798. if (n) {
  2799. // color matrix is sent as mat3 matrix followed by vec3
  2800. // offset, then packed into a mat4 where the last row is
  2801. // the offset and extra values are 0
  2802. for (size_t i = 0 ; i < 4; i++) {
  2803. for (size_t j = 0; j < 4; j++) {
  2804. mColorMatrix[i][j] = data.readFloat();
  2805. }
  2806. }
  2807. } else {
  2808. mColorMatrix = mat4();
  2809. }
  2810. invalidateHwcGeometry();
  2811. repaintEverything();
  2812. return NO_ERROR;
  2813. }
  2814. // This is an experimental interface
  2815. // Needs to be shifted to proper binder interface when we productize
  2816. case 1016: {
  2817. n = data.readInt32();
  2818. mPrimaryDispSync.setRefreshSkipCount(n);
  2819. return NO_ERROR;
  2820. }
  2821. case 1017: {
  2822. n = data.readInt32();
  2823. mForceFullDamage = static_cast<bool>(n);
  2824. return NO_ERROR;
  2825. }
  2826. case 1018: { // Modify Choreographer's phase offset
  2827. n = data.readInt32();
  2828. if (mEventThread != NULL)
  2829. mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
  2830. return NO_ERROR;
  2831. }
  2832. case 1019: { // Modify SurfaceFlinger's phase offset
  2833. n = data.readInt32();
  2834. if (mSFEventThread != NULL)
  2835. mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
  2836. return NO_ERROR;
  2837. }
  2838. case 1030: {
  2839. // apply a secondary color matrix
  2840. // this will be combined with any other transformations
  2841. n = data.readInt32();
  2842. mHasSecondaryColorMatrix = n ? 1 : 0;
  2843. if (n) {
  2844. // color matrix is sent as mat3 matrix followed by vec3
  2845. // offset, then packed into a mat4 where the last row is
  2846. // the offset and extra values are 0
  2847. for (size_t i = 0 ; i < 4; i++) {
  2848. for (size_t j = 0; j < 4; j++) {
  2849. mSecondaryColorMatrix[i][j] = data.readFloat();
  2850. }
  2851. }
  2852. } else {
  2853. mSecondaryColorMatrix = mat4();
  2854. }
  2855. invalidateHwcGeometry();
  2856. repaintEverything();
  2857. return NO_ERROR;
  2858. }
  2859. }
  2860. }
  2861. return err;
  2862. }
  2863. void SurfaceFlinger::repaintEverything() {
  2864. android_atomic_or(1, &mRepaintEverything);
  2865. signalTransaction();
  2866. }
  2867. // ---------------------------------------------------------------------------
  2868. // Capture screen into an IGraphiBufferProducer
  2869. // ---------------------------------------------------------------------------
  2870. /* The code below is here to handle b/8734824
  2871. *
  2872. * We create a IGraphicBufferProducer wrapper that forwards all calls
  2873. * from the surfaceflinger thread to the calling binder thread, where they
  2874. * are executed. This allows the calling thread in the calling process to be
  2875. * reused and not depend on having "enough" binder threads to handle the
  2876. * requests.
  2877. */
  2878. class GraphicProducerWrapper : public BBinder, public MessageHandler {
  2879. /* Parts of GraphicProducerWrapper are run on two different threads,
  2880. * communicating by sending messages via Looper but also by shared member
  2881. * data. Coherence maintenance is subtle and in places implicit (ugh).
  2882. *
  2883. * Don't rely on Looper's sendMessage/handleMessage providing
  2884. * release/acquire semantics for any data not actually in the Message.
  2885. * Data going from surfaceflinger to binder threads needs to be
  2886. * synchronized explicitly.
  2887. *
  2888. * Barrier open/wait do provide release/acquire semantics. This provides
  2889. * implicit synchronization for data coming back from binder to
  2890. * surfaceflinger threads.
  2891. */
  2892. sp<IGraphicBufferProducer> impl;
  2893. sp<Looper> looper;
  2894. status_t result;
  2895. bool exitPending;
  2896. bool exitRequested;
  2897. Barrier barrier;
  2898. uint32_t code;
  2899. Parcel const* data;
  2900. Parcel* reply;
  2901. enum {
  2902. MSG_API_CALL,
  2903. MSG_EXIT
  2904. };
  2905. /*
  2906. * Called on surfaceflinger thread. This is called by our "fake"
  2907. * BpGraphicBufferProducer. We package the data and reply Parcel and
  2908. * forward them to the binder thread.
  2909. */
  2910. virtual status_t transact(uint32_t code,
  2911. const Parcel& data, Parcel* reply, uint32_t /* flags */) {
  2912. this->code = code;
  2913. this->data = &data;
  2914. this->reply = reply;
  2915. if (exitPending) {
  2916. // if we've exited, we run the message synchronously right here.
  2917. // note (JH): as far as I can tell from looking at the code, this
  2918. // never actually happens. if it does, i'm not sure if it happens
  2919. // on the surfaceflinger or binder thread.
  2920. handleMessage(Message(MSG_API_CALL));
  2921. } else {
  2922. barrier.close();
  2923. // Prevent stores to this->{code, data, reply} from being
  2924. // reordered later than the construction of Message.
  2925. atomic_thread_fence(memory_order_release);
  2926. looper->sendMessage(this, Message(MSG_API_CALL));
  2927. barrier.wait();
  2928. }
  2929. return result;
  2930. }
  2931. /*
  2932. * here we run on the binder thread. All we've got to do is
  2933. * call the real BpGraphicBufferProducer.
  2934. */
  2935. virtual void handleMessage(const Message& message) {
  2936. int what = message.what;
  2937. // Prevent reads below from happening before the read from Message
  2938. atomic_thread_fence(memory_order_acquire);
  2939. if (what == MSG_API_CALL) {
  2940. result = IInterface::asBinder(impl)->transact(code, data[0], reply);
  2941. barrier.open();
  2942. } else if (what == MSG_EXIT) {
  2943. exitRequested = true;
  2944. }
  2945. }
  2946. public:
  2947. GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
  2948. : impl(impl),
  2949. looper(new Looper(true)),
  2950. exitPending(false),
  2951. exitRequested(false)
  2952. {}
  2953. // Binder thread
  2954. status_t waitForResponse() {
  2955. do {
  2956. looper->pollOnce(-1);
  2957. } while (!exitRequested);
  2958. return result;
  2959. }
  2960. // Client thread
  2961. void exit(status_t result) {
  2962. this->result = result;
  2963. exitPending = true;
  2964. // Ensure this->result is visible to the binder thread before it
  2965. // handles the message.
  2966. atomic_thread_fence(memory_order_release);
  2967. looper->sendMessage(this, Message(MSG_EXIT));
  2968. }
  2969. };
  2970. status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
  2971. const sp<IGraphicBufferProducer>& producer,
  2972. Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
  2973. uint32_t minLayerZ, uint32_t maxLayerZ,
  2974. bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
  2975. bool useReadPixels) {
  2976. if (CC_UNLIKELY(display == 0))
  2977. return BAD_VALUE;
  2978. if (CC_UNLIKELY(producer == 0))
  2979. return BAD_VALUE;
  2980. // if we have secure windows on this display, never allow the screen capture
  2981. // unless the producer interface is local (i.e.: we can take a screenshot for
  2982. // ourselves).
  2983. if (!IInterface::asBinder(producer)->localBinder()) {
  2984. Mutex::Autolock _l(mStateLock);
  2985. sp<const DisplayDevice> hw(getDisplayDevice(display));
  2986. if (hw->getSecureLayerVisible()) {
  2987. ALOGW("FB is protected: PERMISSION_DENIED");
  2988. return PERMISSION_DENIED;
  2989. }
  2990. }
  2991. // Convert to surfaceflinger's internal rotation type.
  2992. Transform::orientation_flags rotationFlags;
  2993. switch (rotation) {
  2994. case ISurfaceComposer::eRotateNone:
  2995. rotationFlags = Transform::ROT_0;
  2996. break;
  2997. case ISurfaceComposer::eRotate90:
  2998. rotationFlags = Transform::ROT_90;
  2999. break;
  3000. case ISurfaceComposer::eRotate180:
  3001. rotationFlags = Transform::ROT_180;
  3002. break;
  3003. case ISurfaceComposer::eRotate270:
  3004. rotationFlags = Transform::ROT_270;
  3005. break;
  3006. default:
  3007. rotationFlags = Transform::ROT_0;
  3008. ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
  3009. break;
  3010. }
  3011. class MessageCaptureScreen : public MessageBase {
  3012. SurfaceFlinger* flinger;
  3013. sp<IBinder> display;
  3014. sp<IGraphicBufferProducer> producer;
  3015. Rect sourceCrop;
  3016. uint32_t reqWidth, reqHeight;
  3017. uint32_t minLayerZ,maxLayerZ;
  3018. bool useIdentityTransform;
  3019. Transform::orientation_flags rotation;
  3020. bool useReadPixels;
  3021. status_t result;
  3022. public:
  3023. MessageCaptureScreen(SurfaceFlinger* flinger,
  3024. const sp<IBinder>& display,
  3025. const sp<IGraphicBufferProducer>& producer,
  3026. Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
  3027. uint32_t minLayerZ, uint32_t maxLayerZ,
  3028. bool useIdentityTransform, Transform::orientation_flags rotation,
  3029. bool useReadPixels)
  3030. : flinger(flinger), display(display), producer(producer),
  3031. sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
  3032. minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
  3033. useIdentityTransform(useIdentityTransform),
  3034. rotation(rotation),
  3035. useReadPixels(useReadPixels),
  3036. result(PERMISSION_DENIED)
  3037. {
  3038. }
  3039. status_t getResult() const {
  3040. return result;
  3041. }
  3042. virtual bool handler() {
  3043. Mutex::Autolock _l(flinger->mStateLock);
  3044. sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
  3045. bool useReadPixels = this->useReadPixels && !flinger->mGpuToCpuSupported;
  3046. result = flinger->captureScreenImplLocked(hw, producer,
  3047. sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
  3048. useIdentityTransform, rotation, useReadPixels);
  3049. static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
  3050. return true;
  3051. }
  3052. };
  3053. // make sure to process transactions before screenshots -- a transaction
  3054. // might already be pending but scheduled for VSYNC; this guarantees we
  3055. // will handle it before the screenshot. When VSYNC finally arrives
  3056. // the scheduled transaction will be a no-op. If no transactions are
  3057. // scheduled at this time, this will end-up being a no-op as well.
  3058. mEventQueue.invalidateTransactionNow();
  3059. // this creates a "fake" BBinder which will serve as a "fake" remote
  3060. // binder to receive the marshaled calls and forward them to the
  3061. // real remote (a BpGraphicBufferProducer)
  3062. sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
  3063. // the asInterface() call below creates our "fake" BpGraphicBufferProducer
  3064. // which does the marshaling work forwards to our "fake remote" above.
  3065. sp<MessageBase> msg = new MessageCaptureScreen(this,
  3066. display, IGraphicBufferProducer::asInterface( wrapper ),
  3067. sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
  3068. useIdentityTransform, rotationFlags, useReadPixels);
  3069. status_t res = postMessageAsync(msg);
  3070. if (res == NO_ERROR) {
  3071. res = wrapper->waitForResponse();
  3072. }
  3073. return res;
  3074. }
  3075. void SurfaceFlinger::renderScreenImplLocked(
  3076. const sp<const DisplayDevice>& hw,
  3077. Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
  3078. uint32_t minLayerZ, uint32_t maxLayerZ,
  3079. bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
  3080. {
  3081. ATRACE_CALL();
  3082. RenderEngine& engine(getRenderEngine());
  3083. // get screen geometry
  3084. const int32_t hw_w = hw->getWidth();
  3085. const int32_t hw_h = hw->getHeight();
  3086. const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
  3087. static_cast<int32_t>(reqHeight) != hw_h;
  3088. // if a default or invalid sourceCrop is passed in, set reasonable values
  3089. if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
  3090. !sourceCrop.isValid()) {
  3091. sourceCrop.setLeftTop(Point(0, 0));
  3092. sourceCrop.setRightBottom(Point(hw_w, hw_h));
  3093. }
  3094. // ensure that sourceCrop is inside screen
  3095. if (sourceCrop.left < 0) {
  3096. ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
  3097. }
  3098. if (sourceCrop.right > hw_w) {
  3099. ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
  3100. }
  3101. if (sourceCrop.top < 0) {
  3102. ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
  3103. }
  3104. if (sourceCrop.bottom > hw_h) {
  3105. ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
  3106. }
  3107. // make sure to clear all GL error flags
  3108. engine.checkErrors();
  3109. if (DisplayDevice::DISPLAY_PRIMARY == hw->getDisplayType()) {
  3110. rotation = (Transform::orientation_flags)
  3111. (rotation ^ hw->getPanelMountFlip());
  3112. }
  3113. // set-up our viewport
  3114. engine.setViewportAndProjection(
  3115. reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
  3116. engine.disableTexturing();
  3117. // redraw the screen entirely...
  3118. engine.clearWithColor(0, 0, 0, 1);
  3119. const LayerVector& layers( mDrawingState.layersSortedByZ );
  3120. const size_t count = layers.size();
  3121. for (size_t i=0 ; i<count ; ++i) {
  3122. const sp<Layer>& layer(layers[i]);
  3123. const Layer::State& state(layer->getDrawingState());
  3124. if (state.layerStack == hw->getLayerStack()) {
  3125. if (state.z >= minLayerZ && state.z <= maxLayerZ) {
  3126. if (canDrawLayerinScreenShot(hw,layer)) {
  3127. if (filtering) layer->setFiltering(true);
  3128. layer->draw(hw, useIdentityTransform);
  3129. if (filtering) layer->setFiltering(false);
  3130. }
  3131. }
  3132. }
  3133. }
  3134. // compositionComplete is needed for older driver
  3135. hw->compositionComplete();
  3136. hw->setViewportAndProjection();
  3137. }
  3138. status_t SurfaceFlinger::captureScreenImplLocked(
  3139. const sp<const DisplayDevice>& hw,
  3140. const sp<IGraphicBufferProducer>& producer,
  3141. Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
  3142. uint32_t minLayerZ, uint32_t maxLayerZ,
  3143. bool useIdentityTransform, Transform::orientation_flags rotation,
  3144. bool useReadPixels)
  3145. {
  3146. ATRACE_CALL();
  3147. // get screen geometry
  3148. uint32_t hw_w = hw->getWidth();
  3149. uint32_t hw_h = hw->getHeight();
  3150. if (rotation & Transform::ROT_90) {
  3151. std::swap(hw_w, hw_h);
  3152. }
  3153. if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
  3154. ALOGE("size mismatch (%d, %d) > (%d, %d)",
  3155. reqWidth, reqHeight, hw_w, hw_h);
  3156. return BAD_VALUE;
  3157. }
  3158. ++mActiveFrameSequence;
  3159. reqWidth = (!reqWidth) ? hw_w : reqWidth;
  3160. reqHeight = (!reqHeight) ? hw_h : reqHeight;
  3161. // create a surface (because we're a producer, and we need to
  3162. // dequeue/queue a buffer)
  3163. sp<Surface> sur = new Surface(producer, false);
  3164. ANativeWindow* window = sur.get();
  3165. status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
  3166. if (result == NO_ERROR) {
  3167. uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
  3168. GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
  3169. int err = 0;
  3170. err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
  3171. err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
  3172. err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
  3173. err |= native_window_set_usage(window, usage);
  3174. if (err == NO_ERROR) {
  3175. ANativeWindowBuffer* buffer;
  3176. /* TODO: Once we have the sync framework everywhere this can use
  3177. * server-side waits on the fence that dequeueBuffer returns.
  3178. */
  3179. result = native_window_dequeue_buffer_and_wait(window, &buffer);
  3180. if (result == NO_ERROR) {
  3181. int syncFd = -1;
  3182. // create an EGLImage from the buffer so we can later
  3183. // turn it into a texture
  3184. EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
  3185. EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
  3186. if (image != EGL_NO_IMAGE_KHR) {
  3187. // this binds the given EGLImage as a framebuffer for the
  3188. // duration of this scope.
  3189. RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image,
  3190. useReadPixels, reqWidth, reqHeight);
  3191. if (imageBond.getStatus() == NO_ERROR) {
  3192. // this will in fact render into our dequeued buffer
  3193. // via an FBO, which means we didn't have to create
  3194. // an EGLSurface and therefore we're not
  3195. // dependent on the context's EGLConfig.
  3196. renderScreenImplLocked(
  3197. hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
  3198. useIdentityTransform, rotation);
  3199. // Attempt to create a sync khr object that can produce a sync point. If that
  3200. // isn't available, create a non-dupable sync object in the fallback path and
  3201. // wait on it directly.
  3202. EGLSyncKHR sync;
  3203. if (!DEBUG_SCREENSHOTS) {
  3204. sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
  3205. // native fence fd will not be populated until flush() is done.
  3206. getRenderEngine().flush();
  3207. } else {
  3208. sync = EGL_NO_SYNC_KHR;
  3209. }
  3210. if (sync != EGL_NO_SYNC_KHR) {
  3211. // get the sync fd
  3212. syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
  3213. if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
  3214. ALOGW("captureScreen: failed to dup sync khr object");
  3215. syncFd = -1;
  3216. }
  3217. eglDestroySyncKHR(mEGLDisplay, sync);
  3218. } else {
  3219. // fallback path
  3220. sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
  3221. if (sync != EGL_NO_SYNC_KHR) {
  3222. EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
  3223. EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
  3224. EGLint eglErr = eglGetError();
  3225. if (result == EGL_TIMEOUT_EXPIRED_KHR) {
  3226. ALOGW("captureScreen: fence wait timed out");
  3227. } else {
  3228. ALOGW_IF(eglErr != EGL_SUCCESS,
  3229. "captureScreen: error waiting on EGL fence: %#x", eglErr);
  3230. }
  3231. eglDestroySyncKHR(mEGLDisplay, sync);
  3232. } else {
  3233. ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
  3234. }
  3235. }
  3236. if (useReadPixels) {
  3237. sp<GraphicBuffer> buf = static_cast<GraphicBuffer*>(buffer);
  3238. void* vaddr;
  3239. if (buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, &vaddr) == NO_ERROR) {
  3240. getRenderEngine().readPixels(0, 0, buffer->stride, reqHeight,
  3241. (uint32_t *)vaddr);
  3242. buf->unlock();
  3243. }
  3244. }
  3245. if (DEBUG_SCREENSHOTS) {
  3246. uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
  3247. getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
  3248. checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
  3249. hw, minLayerZ, maxLayerZ);
  3250. delete [] pixels;
  3251. }
  3252. } else {
  3253. ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
  3254. result = INVALID_OPERATION;
  3255. }
  3256. // destroy our image
  3257. eglDestroyImageKHR(mEGLDisplay, image);
  3258. } else {
  3259. result = BAD_VALUE;
  3260. }
  3261. // queueBuffer takes ownership of syncFd
  3262. result = window->queueBuffer(window, buffer, syncFd);
  3263. }
  3264. } else {
  3265. result = BAD_VALUE;
  3266. }
  3267. native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
  3268. }
  3269. return result;
  3270. }
  3271. void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
  3272. const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
  3273. if (DEBUG_SCREENSHOTS) {
  3274. for (size_t y=0 ; y<h ; y++) {
  3275. uint32_t const * p = (uint32_t const *)vaddr + y*s;
  3276. for (size_t x=0 ; x<w ; x++) {
  3277. if (p[x] != 0xFF000000) return;
  3278. }
  3279. }
  3280. ALOGE("*** we just took a black screenshot ***\n"
  3281. "requested minz=%d, maxz=%d, layerStack=%d",
  3282. minLayerZ, maxLayerZ, hw->getLayerStack());
  3283. const LayerVector& layers( mDrawingState.layersSortedByZ );
  3284. const size_t count = layers.size();
  3285. for (size_t i=0 ; i<count ; ++i) {
  3286. const sp<Layer>& layer(layers[i]);
  3287. const Layer::State& state(layer->getDrawingState());
  3288. const bool visible = (state.layerStack == hw->getLayerStack())
  3289. && (state.z >= minLayerZ && state.z <= maxLayerZ)
  3290. && (layer->isVisible());
  3291. ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
  3292. visible ? '+' : '-',
  3293. i, layer->getName().string(), state.layerStack, state.z,
  3294. layer->isVisible(), state.flags, state.alpha);
  3295. }
  3296. }
  3297. }
  3298. /* ------------------------------------------------------------------------
  3299. * Extensions
  3300. */
  3301. bool SurfaceFlinger::updateLayerVisibleNonTransparentRegion(const int& /*dpy*/,
  3302. const sp<Layer>& layer, bool& /*bIgnoreLayers*/, int& /*indexLOI*/,
  3303. uint32_t layerStack, const int& /*i*/) {
  3304. const Layer::State& s(layer->getDrawingState());
  3305. // only consider the layers on the given layer stack
  3306. if (s.layerStack != layerStack) {
  3307. /* set the visible region as empty since we have removed the
  3308. * layerstack check in rebuildLayerStack() function
  3309. */
  3310. Region visibleNonTransRegion;
  3311. visibleNonTransRegion.set(Rect(0,0));
  3312. layer->setVisibleNonTransparentRegion(visibleNonTransRegion);
  3313. return true;
  3314. }
  3315. return false;
  3316. }
  3317. bool SurfaceFlinger::canDrawLayerinScreenShot(
  3318. const sp<const DisplayDevice>& /*hw*/,
  3319. const sp<Layer>& layer) {
  3320. return layer->isVisible();
  3321. }
  3322. void SurfaceFlinger::drawWormHoleIfRequired(HWComposer::LayerListIterator& /*cur*/,
  3323. const HWComposer::LayerListIterator& /*end*/,
  3324. const sp<const DisplayDevice>& hw,
  3325. const Region& region) {
  3326. drawWormhole(hw, region);
  3327. }
  3328. // ---------------------------------------------------------------------------
  3329. SurfaceFlinger::LayerVector::LayerVector() {
  3330. }
  3331. SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
  3332. : SortedVector<sp<Layer> >(rhs) {
  3333. }
  3334. int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
  3335. const void* rhs) const
  3336. {
  3337. // sort layers per layer-stack, then by z-order and finally by sequence
  3338. const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
  3339. const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
  3340. uint32_t ls = l->getCurrentState().layerStack;
  3341. uint32_t rs = r->getCurrentState().layerStack;
  3342. if (ls != rs)
  3343. return ls - rs;
  3344. uint32_t lz = l->getCurrentState().z;
  3345. uint32_t rz = r->getCurrentState().z;
  3346. if (lz != rz)
  3347. return lz - rz;
  3348. return l->sequence - r->sequence;
  3349. }
  3350. // ---------------------------------------------------------------------------
  3351. SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
  3352. : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
  3353. }
  3354. SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
  3355. : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
  3356. viewport.makeInvalid();
  3357. frame.makeInvalid();
  3358. }
  3359. // ---------------------------------------------------------------------------
  3360. }; // namespace android
  3361. #if defined(__gl_h_)
  3362. #error "don't include gl/gl.h in this file"
  3363. #endif
  3364. #if defined(__gl2_h_)
  3365. #error "don't include gl2/gl2.h in this file"
  3366. #endif