SurfaceFlinger.cpp 246 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337
  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 <sys/types.h>
  19. #include <errno.h>
  20. #include <dlfcn.h>
  21. #include <algorithm>
  22. #include <cinttypes>
  23. #include <cmath>
  24. #include <cstdint>
  25. #include <functional>
  26. #include <mutex>
  27. #include <optional>
  28. #include <unordered_map>
  29. #include <cutils/properties.h>
  30. #include <log/log.h>
  31. #include <binder/IPCThreadState.h>
  32. #include <binder/IServiceManager.h>
  33. #include <binder/PermissionCache.h>
  34. #include <compositionengine/CompositionEngine.h>
  35. #include <compositionengine/Display.h>
  36. #include <compositionengine/DisplayColorProfile.h>
  37. #include <compositionengine/Layer.h>
  38. #include <compositionengine/OutputLayer.h>
  39. #include <compositionengine/RenderSurface.h>
  40. #include <compositionengine/impl/LayerCompositionState.h>
  41. #include <compositionengine/impl/OutputCompositionState.h>
  42. #include <compositionengine/impl/OutputLayerCompositionState.h>
  43. #include <dvr/vr_flinger.h>
  44. #include <gui/BufferQueue.h>
  45. #include <gui/DebugEGLImageTracker.h>
  46. #include <gui/GuiConfig.h>
  47. #include <gui/IDisplayEventConnection.h>
  48. #include <gui/IProducerListener.h>
  49. #include <gui/LayerDebugInfo.h>
  50. #include <gui/Surface.h>
  51. #include <input/IInputFlinger.h>
  52. #include <renderengine/RenderEngine.h>
  53. #include <ui/ColorSpace.h>
  54. #include <ui/DebugUtils.h>
  55. #include <ui/DisplayInfo.h>
  56. #include <ui/DisplayStatInfo.h>
  57. #include <ui/GraphicBufferAllocator.h>
  58. #include <ui/PixelFormat.h>
  59. #include <ui/UiConfig.h>
  60. #include <utils/StopWatch.h>
  61. #include <utils/String16.h>
  62. #include <utils/String8.h>
  63. #include <utils/Timers.h>
  64. #include <utils/Trace.h>
  65. #include <utils/misc.h>
  66. #include <private/android_filesystem_config.h>
  67. #include <private/gui/SyncFeatures.h>
  68. #include "BufferLayer.h"
  69. #include "BufferQueueLayer.h"
  70. #include "BufferStateLayer.h"
  71. #include "Client.h"
  72. #include "ColorLayer.h"
  73. #include "Colorizer.h"
  74. #include "ContainerLayer.h"
  75. #include "DisplayDevice.h"
  76. #include "Layer.h"
  77. #include "LayerVector.h"
  78. #include "MonitoredProducer.h"
  79. #include "NativeWindowSurface.h"
  80. #include "RefreshRateOverlay.h"
  81. #include "StartPropertySetThread.h"
  82. #include "SurfaceFlinger.h"
  83. #include "SurfaceInterceptor.h"
  84. #include "DisplayHardware/ComposerHal.h"
  85. #include "DisplayHardware/DisplayIdentification.h"
  86. #include "DisplayHardware/FramebufferSurface.h"
  87. #include "DisplayHardware/HWComposer.h"
  88. #include "DisplayHardware/VirtualDisplaySurface.h"
  89. #include "Effects/Daltonizer.h"
  90. #include "RegionSamplingThread.h"
  91. #include "Scheduler/DispSync.h"
  92. #include "Scheduler/DispSyncSource.h"
  93. #include "Scheduler/EventControlThread.h"
  94. #include "Scheduler/EventThread.h"
  95. #include "Scheduler/InjectVSyncSource.h"
  96. #include "Scheduler/MessageQueue.h"
  97. #include "Scheduler/PhaseOffsets.h"
  98. #include "Scheduler/Scheduler.h"
  99. #include "TimeStats/TimeStats.h"
  100. #include <cutils/compiler.h>
  101. #include "android-base/stringprintf.h"
  102. #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
  103. #include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
  104. #include <android/hardware/configstore/1.1/types.h>
  105. #include <android/hardware/power/1.0/IPower.h>
  106. #include <configstore/Utils.h>
  107. #include <layerproto/LayerProtoParser.h>
  108. #include "SurfaceFlingerProperties.h"
  109. namespace android {
  110. using namespace android::hardware::configstore;
  111. using namespace android::hardware::configstore::V1_0;
  112. using namespace android::sysprop;
  113. using android::hardware::power::V1_0::PowerHint;
  114. using base::StringAppendF;
  115. using ui::ColorMode;
  116. using ui::Dataspace;
  117. using ui::DisplayPrimaries;
  118. using ui::Hdr;
  119. using ui::RenderIntent;
  120. namespace {
  121. #pragma clang diagnostic push
  122. #pragma clang diagnostic error "-Wswitch-enum"
  123. bool isWideColorMode(const ColorMode colorMode) {
  124. switch (colorMode) {
  125. case ColorMode::DISPLAY_P3:
  126. case ColorMode::ADOBE_RGB:
  127. case ColorMode::DCI_P3:
  128. case ColorMode::BT2020:
  129. case ColorMode::DISPLAY_BT2020:
  130. case ColorMode::BT2100_PQ:
  131. case ColorMode::BT2100_HLG:
  132. return true;
  133. case ColorMode::NATIVE:
  134. case ColorMode::STANDARD_BT601_625:
  135. case ColorMode::STANDARD_BT601_625_UNADJUSTED:
  136. case ColorMode::STANDARD_BT601_525:
  137. case ColorMode::STANDARD_BT601_525_UNADJUSTED:
  138. case ColorMode::STANDARD_BT709:
  139. case ColorMode::SRGB:
  140. return false;
  141. }
  142. return false;
  143. }
  144. bool isHdrColorMode(const ColorMode colorMode) {
  145. switch (colorMode) {
  146. case ColorMode::BT2100_PQ:
  147. case ColorMode::BT2100_HLG:
  148. return true;
  149. case ColorMode::DISPLAY_P3:
  150. case ColorMode::ADOBE_RGB:
  151. case ColorMode::DCI_P3:
  152. case ColorMode::BT2020:
  153. case ColorMode::DISPLAY_BT2020:
  154. case ColorMode::NATIVE:
  155. case ColorMode::STANDARD_BT601_625:
  156. case ColorMode::STANDARD_BT601_625_UNADJUSTED:
  157. case ColorMode::STANDARD_BT601_525:
  158. case ColorMode::STANDARD_BT601_525_UNADJUSTED:
  159. case ColorMode::STANDARD_BT709:
  160. case ColorMode::SRGB:
  161. return false;
  162. }
  163. return false;
  164. }
  165. ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
  166. switch (rotation) {
  167. case ISurfaceComposer::eRotateNone:
  168. return ui::Transform::ROT_0;
  169. case ISurfaceComposer::eRotate90:
  170. return ui::Transform::ROT_90;
  171. case ISurfaceComposer::eRotate180:
  172. return ui::Transform::ROT_180;
  173. case ISurfaceComposer::eRotate270:
  174. return ui::Transform::ROT_270;
  175. }
  176. ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
  177. return ui::Transform::ROT_0;
  178. }
  179. #pragma clang diagnostic pop
  180. class ConditionalLock {
  181. public:
  182. ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
  183. if (lock) {
  184. mMutex.lock();
  185. }
  186. }
  187. ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
  188. private:
  189. Mutex& mMutex;
  190. bool mLocked;
  191. };
  192. // Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
  193. bool validateCompositionDataspace(Dataspace dataspace) {
  194. return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
  195. }
  196. } // namespace anonymous
  197. // ---------------------------------------------------------------------------
  198. const String16 sHardwareTest("android.permission.HARDWARE_TEST");
  199. const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
  200. const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
  201. const String16 sDump("android.permission.DUMP");
  202. // ---------------------------------------------------------------------------
  203. int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
  204. bool SurfaceFlinger::useHwcForRgbToYuv;
  205. uint64_t SurfaceFlinger::maxVirtualDisplaySize;
  206. bool SurfaceFlinger::hasSyncFramework;
  207. bool SurfaceFlinger::useVrFlinger;
  208. int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
  209. bool SurfaceFlinger::hasWideColorDisplay;
  210. int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
  211. bool SurfaceFlinger::useColorManagement;
  212. bool SurfaceFlinger::useContextPriority;
  213. Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
  214. ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
  215. Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
  216. ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
  217. std::string getHwcServiceName() {
  218. char value[PROPERTY_VALUE_MAX] = {};
  219. property_get("debug.sf.hwc_service_name", value, "default");
  220. ALOGI("Using HWComposer service: '%s'", value);
  221. return std::string(value);
  222. }
  223. bool useTrebleTestingOverride() {
  224. char value[PROPERTY_VALUE_MAX] = {};
  225. property_get("debug.sf.treble_testing_override", value, "false");
  226. ALOGI("Treble testing override: '%s'", value);
  227. return std::string(value) == "true";
  228. }
  229. std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
  230. switch(displayColorSetting) {
  231. case DisplayColorSetting::MANAGED:
  232. return std::string("Managed");
  233. case DisplayColorSetting::UNMANAGED:
  234. return std::string("Unmanaged");
  235. case DisplayColorSetting::ENHANCED:
  236. return std::string("Enhanced");
  237. default:
  238. return std::string("Unknown ") +
  239. std::to_string(static_cast<int>(displayColorSetting));
  240. }
  241. }
  242. SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
  243. SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
  244. : mFactory(factory),
  245. mPhaseOffsets(mFactory.createPhaseOffsets()),
  246. mInterceptor(mFactory.createSurfaceInterceptor(this)),
  247. mTimeStats(mFactory.createTimeStats()),
  248. mEventQueue(mFactory.createMessageQueue()),
  249. mCompositionEngine(mFactory.createCompositionEngine()) {}
  250. SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
  251. ALOGI("SurfaceFlinger is starting");
  252. hasSyncFramework = running_without_sync_framework(true);
  253. dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
  254. useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
  255. maxVirtualDisplaySize = max_virtual_display_dimension(0);
  256. // Vr flinger is only enabled on Daydream ready devices.
  257. useVrFlinger = use_vr_flinger(false);
  258. maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
  259. hasWideColorDisplay = has_wide_color_display(false);
  260. useColorManagement = use_color_management(false);
  261. mDefaultCompositionDataspace =
  262. static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
  263. mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
  264. hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
  265. defaultCompositionDataspace = mDefaultCompositionDataspace;
  266. wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
  267. defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
  268. default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
  269. wideColorGamutCompositionPixelFormat =
  270. static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
  271. mColorSpaceAgnosticDataspace =
  272. static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
  273. useContextPriority = use_context_priority(true);
  274. auto tmpPrimaryDisplayOrientation = primary_display_orientation(
  275. SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
  276. switch (tmpPrimaryDisplayOrientation) {
  277. case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
  278. SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
  279. break;
  280. case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
  281. SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
  282. break;
  283. case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
  284. SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
  285. break;
  286. default:
  287. SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
  288. break;
  289. }
  290. ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
  291. mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
  292. // debugging stuff...
  293. char value[PROPERTY_VALUE_MAX];
  294. property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
  295. mGpuToCpuSupported = !atoi(value);
  296. property_get("debug.sf.showupdates", value, "0");
  297. mDebugRegion = atoi(value);
  298. ALOGI_IF(mDebugRegion, "showupdates enabled");
  299. // DDMS debugging deprecated (b/120782499)
  300. property_get("debug.sf.ddms", value, "0");
  301. int debugDdms = atoi(value);
  302. ALOGI_IF(debugDdms, "DDMS debugging not supported");
  303. property_get("debug.sf.disable_backpressure", value, "0");
  304. mPropagateBackpressure = !atoi(value);
  305. ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
  306. property_get("debug.sf.enable_gl_backpressure", value, "0");
  307. mPropagateBackpressureClientComposition = atoi(value);
  308. ALOGI_IF(mPropagateBackpressureClientComposition,
  309. "Enabling backpressure propagation for Client Composition");
  310. property_get("debug.sf.enable_hwc_vds", value, "0");
  311. mUseHwcVirtualDisplays = atoi(value);
  312. ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
  313. property_get("ro.sf.disable_triple_buffer", value, "0");
  314. mLayerTripleBufferingDisabled = atoi(value);
  315. ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
  316. const size_t defaultListSize = MAX_LAYERS;
  317. auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
  318. mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
  319. mUseSmart90ForVideo = use_smart_90_for_video(false);
  320. property_get("debug.sf.use_smart_90_for_video", value, "0");
  321. int int_value = atoi(value);
  322. if (int_value) {
  323. mUseSmart90ForVideo = true;
  324. }
  325. property_get("debug.sf.luma_sampling", value, "1");
  326. mLumaSampling = atoi(value);
  327. const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
  328. mVsyncModulator.setPhaseOffsets(early, gl, late,
  329. mPhaseOffsets->getOffsetThresholdForNextVsync());
  330. // We should be reading 'persist.sys.sf.color_saturation' here
  331. // but since /data may be encrypted, we need to wait until after vold
  332. // comes online to attempt to read the property. The property is
  333. // instead read after the boot animation
  334. if (useTrebleTestingOverride()) {
  335. // Without the override SurfaceFlinger cannot connect to HIDL
  336. // services that are not listed in the manifests. Considered
  337. // deriving the setting from the set service name, but it
  338. // would be brittle if the name that's not 'default' is used
  339. // for production purposes later on.
  340. setenv("TREBLE_TESTING_OVERRIDE", "true", true);
  341. }
  342. }
  343. void SurfaceFlinger::onFirstRef()
  344. {
  345. mEventQueue->init(this);
  346. }
  347. SurfaceFlinger::~SurfaceFlinger() = default;
  348. void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
  349. {
  350. // the window manager died on us. prepare its eulogy.
  351. // restore initial conditions (default device unblank, etc)
  352. initializeDisplays();
  353. // restart the boot-animation
  354. startBootAnim();
  355. }
  356. static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
  357. status_t err = client->initCheck();
  358. if (err == NO_ERROR) {
  359. return client;
  360. }
  361. return nullptr;
  362. }
  363. sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
  364. return initClient(new Client(this));
  365. }
  366. sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
  367. bool secure)
  368. {
  369. class DisplayToken : public BBinder {
  370. sp<SurfaceFlinger> flinger;
  371. virtual ~DisplayToken() {
  372. // no more references, this display must be terminated
  373. Mutex::Autolock _l(flinger->mStateLock);
  374. flinger->mCurrentState.displays.removeItem(this);
  375. flinger->setTransactionFlags(eDisplayTransactionNeeded);
  376. }
  377. public:
  378. explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
  379. : flinger(flinger) {
  380. }
  381. };
  382. sp<BBinder> token = new DisplayToken(this);
  383. Mutex::Autolock _l(mStateLock);
  384. // Display ID is assigned when virtual display is allocated by HWC.
  385. DisplayDeviceState state;
  386. state.isSecure = secure;
  387. state.displayName = displayName;
  388. mCurrentState.displays.add(token, state);
  389. mInterceptor->saveDisplayCreation(state);
  390. return token;
  391. }
  392. void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
  393. Mutex::Autolock _l(mStateLock);
  394. ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
  395. if (index < 0) {
  396. ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
  397. return;
  398. }
  399. const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
  400. if (!state.isVirtual()) {
  401. ALOGE("destroyDisplay called for non-virtual display");
  402. return;
  403. }
  404. mInterceptor->saveDisplayDeletion(state.sequenceId);
  405. mCurrentState.displays.removeItemsAt(index);
  406. setTransactionFlags(eDisplayTransactionNeeded);
  407. }
  408. std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
  409. Mutex::Autolock lock(mStateLock);
  410. const auto internalDisplayId = getInternalDisplayIdLocked();
  411. if (!internalDisplayId) {
  412. return {};
  413. }
  414. std::vector<PhysicalDisplayId> displayIds;
  415. displayIds.reserve(mPhysicalDisplayTokens.size());
  416. displayIds.push_back(internalDisplayId->value);
  417. for (const auto& [id, token] : mPhysicalDisplayTokens) {
  418. if (id != *internalDisplayId) {
  419. displayIds.push_back(id.value);
  420. }
  421. }
  422. return displayIds;
  423. }
  424. sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
  425. Mutex::Autolock lock(mStateLock);
  426. return getPhysicalDisplayTokenLocked(DisplayId{displayId});
  427. }
  428. status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
  429. if (!outGetColorManagement) {
  430. return BAD_VALUE;
  431. }
  432. *outGetColorManagement = useColorManagement;
  433. return NO_ERROR;
  434. }
  435. HWComposer& SurfaceFlinger::getHwComposer() const {
  436. return mCompositionEngine->getHwComposer();
  437. }
  438. renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
  439. return mCompositionEngine->getRenderEngine();
  440. }
  441. compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
  442. return *mCompositionEngine.get();
  443. }
  444. void SurfaceFlinger::bootFinished()
  445. {
  446. if (mStartPropertySetThread->join() != NO_ERROR) {
  447. ALOGE("Join StartPropertySetThread failed!");
  448. }
  449. const nsecs_t now = systemTime();
  450. const nsecs_t duration = now - mBootTime;
  451. ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
  452. // wait patiently for the window manager death
  453. const String16 name("window");
  454. sp<IBinder> window(defaultServiceManager()->getService(name));
  455. if (window != 0) {
  456. window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
  457. }
  458. sp<IBinder> input(defaultServiceManager()->getService(
  459. String16("inputflinger")));
  460. if (input == nullptr) {
  461. ALOGE("Failed to link to input service");
  462. } else {
  463. mInputFlinger = interface_cast<IInputFlinger>(input);
  464. }
  465. if (mVrFlinger) {
  466. mVrFlinger->OnBootFinished();
  467. }
  468. // stop boot animation
  469. // formerly we would just kill the process, but we now ask it to exit so it
  470. // can choose where to stop the animation.
  471. property_set("service.bootanim.exit", "1");
  472. const int LOGTAG_SF_STOP_BOOTANIM = 60110;
  473. LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
  474. ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
  475. postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
  476. readPersistentProperties();
  477. mBootStage = BootStage::FINISHED;
  478. // set the refresh rate according to the policy
  479. const auto& performanceRefreshRate =
  480. mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
  481. if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
  482. setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
  483. } else {
  484. setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
  485. }
  486. }));
  487. }
  488. uint32_t SurfaceFlinger::getNewTexture() {
  489. {
  490. std::lock_guard lock(mTexturePoolMutex);
  491. if (!mTexturePool.empty()) {
  492. uint32_t name = mTexturePool.back();
  493. mTexturePool.pop_back();
  494. ATRACE_INT("TexturePoolSize", mTexturePool.size());
  495. return name;
  496. }
  497. // The pool was too small, so increase it for the future
  498. ++mTexturePoolSize;
  499. }
  500. // The pool was empty, so we need to get a new texture name directly using a
  501. // blocking call to the main thread
  502. uint32_t name = 0;
  503. postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
  504. return name;
  505. }
  506. void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
  507. std::lock_guard lock(mTexturePoolMutex);
  508. // We don't change the pool size, so the fix-up logic in postComposition will decide whether
  509. // to actually delete this or not based on mTexturePoolSize
  510. mTexturePool.push_back(texture);
  511. ATRACE_INT("TexturePoolSize", mTexturePool.size());
  512. }
  513. // Do not call property_set on main thread which will be blocked by init
  514. // Use StartPropertySetThread instead.
  515. void SurfaceFlinger::init() {
  516. ALOGI( "SurfaceFlinger's main thread ready to run. "
  517. "Initializing graphics H/W...");
  518. ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
  519. Mutex::Autolock _l(mStateLock);
  520. // start the EventThread
  521. mScheduler =
  522. getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
  523. mRefreshRateConfigs);
  524. auto resyncCallback =
  525. mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
  526. mAppConnectionHandle =
  527. mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
  528. mPhaseOffsets->getOffsetThresholdForNextVsync(),
  529. resyncCallback,
  530. impl::EventThread::InterceptVSyncsCallback());
  531. mSfConnectionHandle =
  532. mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
  533. mPhaseOffsets->getOffsetThresholdForNextVsync(),
  534. resyncCallback, [this](nsecs_t timestamp) {
  535. mInterceptor->saveVSyncEvent(timestamp);
  536. });
  537. mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
  538. mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
  539. mSfConnectionHandle.get());
  540. mRegionSamplingThread =
  541. new RegionSamplingThread(*this, *mScheduler,
  542. RegionSamplingThread::EnvironmentTimingTunables());
  543. // Get a RenderEngine for the given display / config (can't fail)
  544. int32_t renderEngineFeature = 0;
  545. renderEngineFeature |= (useColorManagement ?
  546. renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
  547. renderEngineFeature |= (useContextPriority ?
  548. renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
  549. renderEngineFeature |=
  550. (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
  551. : 0);
  552. // TODO(b/77156734): We need to stop casting and use HAL types when possible.
  553. // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
  554. mCompositionEngine->setRenderEngine(
  555. renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
  556. renderEngineFeature, maxFrameBufferAcquiredBuffers));
  557. LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
  558. "Starting with vr flinger active is not currently supported.");
  559. mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
  560. mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
  561. // Process any initial hotplug and resulting display changes.
  562. processDisplayHotplugEventsLocked();
  563. const auto display = getDefaultDisplayDeviceLocked();
  564. LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
  565. LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
  566. "Internal display is disconnected.");
  567. if (useVrFlinger) {
  568. auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
  569. // This callback is called from the vr flinger dispatch thread. We
  570. // need to call signalTransaction(), which requires holding
  571. // mStateLock when we're not on the main thread. Acquiring
  572. // mStateLock from the vr flinger dispatch thread might trigger a
  573. // deadlock in surface flinger (see b/66916578), so post a message
  574. // to be handled on the main thread instead.
  575. postMessageAsync(new LambdaMessage([=] {
  576. ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
  577. mVrFlingerRequestsDisplay = requestDisplay;
  578. signalTransaction();
  579. }));
  580. };
  581. mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
  582. getHwComposer()
  583. .fromPhysicalDisplayId(*display->getId())
  584. .value_or(0),
  585. vrFlingerRequestDisplayCallback);
  586. if (!mVrFlinger) {
  587. ALOGE("Failed to start vrflinger");
  588. }
  589. }
  590. // initialize our drawing state
  591. mDrawingState = mCurrentState;
  592. // set initial conditions (e.g. unblank default device)
  593. initializeDisplays();
  594. getRenderEngine().primeCache();
  595. // Inform native graphics APIs whether the present timestamp is supported:
  596. const bool presentFenceReliable =
  597. !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
  598. mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
  599. if (mStartPropertySetThread->Start() != NO_ERROR) {
  600. ALOGE("Run StartPropertySetThread failed!");
  601. }
  602. mScheduler->setChangeRefreshRateCallback(
  603. [this](RefreshRateType type, Scheduler::ConfigEvent event) {
  604. Mutex::Autolock lock(mStateLock);
  605. setRefreshRateTo(type, event);
  606. });
  607. mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
  608. Mutex::Autolock lock(mStateLock);
  609. const auto display = getDefaultDisplayDeviceLocked();
  610. if (!display) {
  611. // If we don't have a default display the fallback to the default
  612. // refresh rate type
  613. return RefreshRateType::DEFAULT;
  614. }
  615. const int configId = display->getActiveConfig();
  616. for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
  617. if (refresh && refresh->configId == configId) {
  618. return type;
  619. }
  620. }
  621. // This should never happen, but just gracefully fallback to default.
  622. return RefreshRateType::DEFAULT;
  623. });
  624. mScheduler->setGetVsyncPeriodCallback([this] {
  625. Mutex::Autolock lock(mStateLock);
  626. return getVsyncPeriod();
  627. });
  628. mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
  629. mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
  630. ALOGV("Done initializing");
  631. }
  632. void SurfaceFlinger::readPersistentProperties() {
  633. Mutex::Autolock _l(mStateLock);
  634. char value[PROPERTY_VALUE_MAX];
  635. property_get("persist.sys.sf.color_saturation", value, "1.0");
  636. mGlobalSaturationFactor = atof(value);
  637. updateColorMatrixLocked();
  638. ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
  639. property_get("persist.sys.sf.native_mode", value, "0");
  640. mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
  641. property_get("persist.sys.sf.color_mode", value, "0");
  642. mForceColorMode = static_cast<ColorMode>(atoi(value));
  643. }
  644. void SurfaceFlinger::startBootAnim() {
  645. // Start boot animation service by setting a property mailbox
  646. // if property setting thread is already running, Start() will be just a NOP
  647. mStartPropertySetThread->Start();
  648. // Wait until property was set
  649. if (mStartPropertySetThread->join() != NO_ERROR) {
  650. ALOGE("Join StartPropertySetThread failed!");
  651. }
  652. }
  653. size_t SurfaceFlinger::getMaxTextureSize() const {
  654. return getRenderEngine().getMaxTextureSize();
  655. }
  656. size_t SurfaceFlinger::getMaxViewportDims() const {
  657. return getRenderEngine().getMaxViewportDims();
  658. }
  659. // ----------------------------------------------------------------------------
  660. bool SurfaceFlinger::authenticateSurfaceTexture(
  661. const sp<IGraphicBufferProducer>& bufferProducer) const {
  662. Mutex::Autolock _l(mStateLock);
  663. return authenticateSurfaceTextureLocked(bufferProducer);
  664. }
  665. bool SurfaceFlinger::authenticateSurfaceTextureLocked(
  666. const sp<IGraphicBufferProducer>& bufferProducer) const {
  667. sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
  668. return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
  669. }
  670. status_t SurfaceFlinger::getSupportedFrameTimestamps(
  671. std::vector<FrameEvent>* outSupported) const {
  672. *outSupported = {
  673. FrameEvent::REQUESTED_PRESENT,
  674. FrameEvent::ACQUIRE,
  675. FrameEvent::LATCH,
  676. FrameEvent::FIRST_REFRESH_START,
  677. FrameEvent::LAST_REFRESH_START,
  678. FrameEvent::GPU_COMPOSITION_DONE,
  679. FrameEvent::DEQUEUE_READY,
  680. FrameEvent::RELEASE,
  681. };
  682. ConditionalLock _l(mStateLock,
  683. std::this_thread::get_id() != mMainThreadId);
  684. if (!getHwComposer().hasCapability(
  685. HWC2::Capability::PresentFenceIsNotReliable)) {
  686. outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
  687. }
  688. return NO_ERROR;
  689. }
  690. status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
  691. Vector<DisplayInfo>* configs) {
  692. if (!displayToken || !configs) {
  693. return BAD_VALUE;
  694. }
  695. Mutex::Autolock lock(mStateLock);
  696. const auto displayId = getPhysicalDisplayIdLocked(displayToken);
  697. if (!displayId) {
  698. return NAME_NOT_FOUND;
  699. }
  700. // TODO: Not sure if display density should handled by SF any longer
  701. class Density {
  702. static float getDensityFromProperty(char const* propName) {
  703. char property[PROPERTY_VALUE_MAX];
  704. float density = 0.0f;
  705. if (property_get(propName, property, nullptr) > 0) {
  706. density = strtof(property, nullptr);
  707. }
  708. return density;
  709. }
  710. public:
  711. static float getEmuDensity() {
  712. return getDensityFromProperty("qemu.sf.lcd_density"); }
  713. static float getBuildDensity() {
  714. return getDensityFromProperty("ro.sf.lcd_density"); }
  715. };
  716. configs->clear();
  717. for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
  718. DisplayInfo info = DisplayInfo();
  719. float xdpi = hwConfig->getDpiX();
  720. float ydpi = hwConfig->getDpiY();
  721. info.w = hwConfig->getWidth();
  722. info.h = hwConfig->getHeight();
  723. // Default display viewport to display width and height
  724. info.viewportW = info.w;
  725. info.viewportH = info.h;
  726. if (displayId == getInternalDisplayIdLocked()) {
  727. // The density of the device is provided by a build property
  728. float density = Density::getBuildDensity() / 160.0f;
  729. if (density == 0) {
  730. // the build doesn't provide a density -- this is wrong!
  731. // use xdpi instead
  732. ALOGE("ro.sf.lcd_density must be defined as a build property");
  733. density = xdpi / 160.0f;
  734. }
  735. if (Density::getEmuDensity()) {
  736. // if "qemu.sf.lcd_density" is specified, it overrides everything
  737. xdpi = ydpi = density = Density::getEmuDensity();
  738. density /= 160.0f;
  739. }
  740. info.density = density;
  741. // TODO: this needs to go away (currently needed only by webkit)
  742. const auto display = getDefaultDisplayDeviceLocked();
  743. info.orientation = display ? display->getOrientation() : 0;
  744. // This is for screenrecord
  745. const Rect viewport = display->getViewport();
  746. if (viewport.isValid()) {
  747. info.viewportW = uint32_t(viewport.getWidth());
  748. info.viewportH = uint32_t(viewport.getHeight());
  749. }
  750. } else {
  751. // TODO: where should this value come from?
  752. static const int TV_DENSITY = 213;
  753. info.density = TV_DENSITY / 160.0f;
  754. info.orientation = 0;
  755. }
  756. info.xdpi = xdpi;
  757. info.ydpi = ydpi;
  758. info.fps = 1e9 / hwConfig->getVsyncPeriod();
  759. const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
  760. const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
  761. info.appVsyncOffset = offset.late.app;
  762. // This is how far in advance a buffer must be queued for
  763. // presentation at a given time. If you want a buffer to appear
  764. // on the screen at time N, you must submit the buffer before
  765. // (N - presentationDeadline).
  766. //
  767. // Normally it's one full refresh period (to give SF a chance to
  768. // latch the buffer), but this can be reduced by configuring a
  769. // DispSync offset. Any additional delays introduced by the hardware
  770. // composer or panel must be accounted for here.
  771. //
  772. // We add an additional 1ms to allow for processing time and
  773. // differences between the ideal and actual refresh rate.
  774. info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
  775. // All non-virtual displays are currently considered secure.
  776. info.secure = true;
  777. if (displayId == getInternalDisplayIdLocked() &&
  778. primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
  779. std::swap(info.w, info.h);
  780. }
  781. configs->push_back(info);
  782. }
  783. return NO_ERROR;
  784. }
  785. status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
  786. if (!stats) {
  787. return BAD_VALUE;
  788. }
  789. mScheduler->getDisplayStatInfo(stats);
  790. return NO_ERROR;
  791. }
  792. int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
  793. const auto display = getDisplayDevice(displayToken);
  794. if (!display) {
  795. ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
  796. return BAD_VALUE;
  797. }
  798. return display->getActiveConfig();
  799. }
  800. void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
  801. ATRACE_CALL();
  802. // Don't check against the current mode yet. Worst case we set the desired
  803. // config twice. However event generation config might have changed so we need to update it
  804. // accordingly
  805. std::lock_guard<std::mutex> lock(mActiveConfigLock);
  806. const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
  807. mDesiredActiveConfig = info;
  808. mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
  809. if (!mDesiredActiveConfigChanged) {
  810. // This will trigger HWC refresh without resetting the idle timer.
  811. repaintEverythingForHWC();
  812. // Start receiving vsync samples now, so that we can detect a period
  813. // switch.
  814. mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
  815. // As we called to set period, we will call to onRefreshRateChangeCompleted once
  816. // DispSync model is locked.
  817. mVsyncModulator.onRefreshRateChangeInitiated();
  818. mPhaseOffsets->setRefreshRateType(info.type);
  819. const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
  820. mVsyncModulator.setPhaseOffsets(early, gl, late,
  821. mPhaseOffsets->getOffsetThresholdForNextVsync());
  822. }
  823. mDesiredActiveConfigChanged = true;
  824. ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
  825. if (mRefreshRateOverlay) {
  826. mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
  827. }
  828. }
  829. status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
  830. ATRACE_CALL();
  831. std::vector<int32_t> allowedConfig;
  832. allowedConfig.push_back(mode);
  833. return setAllowedDisplayConfigs(displayToken, allowedConfig);
  834. }
  835. void SurfaceFlinger::setActiveConfigInternal() {
  836. ATRACE_CALL();
  837. const auto display = getDefaultDisplayDeviceLocked();
  838. if (!display) {
  839. return;
  840. }
  841. std::lock_guard<std::mutex> lock(mActiveConfigLock);
  842. mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
  843. display->setActiveConfig(mUpcomingActiveConfig.configId);
  844. mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
  845. const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
  846. mVsyncModulator.setPhaseOffsets(early, gl, late,
  847. mPhaseOffsets->getOffsetThresholdForNextVsync());
  848. ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
  849. if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
  850. mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
  851. mUpcomingActiveConfig.configId);
  852. }
  853. }
  854. void SurfaceFlinger::desiredActiveConfigChangeDone() {
  855. std::lock_guard<std::mutex> lock(mActiveConfigLock);
  856. mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
  857. mDesiredActiveConfigChanged = false;
  858. ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
  859. mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
  860. mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
  861. const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
  862. mVsyncModulator.setPhaseOffsets(early, gl, late,
  863. mPhaseOffsets->getOffsetThresholdForNextVsync());
  864. }
  865. bool SurfaceFlinger::performSetActiveConfig() {
  866. ATRACE_CALL();
  867. if (mCheckPendingFence) {
  868. if (previousFrameMissed()) {
  869. // fence has not signaled yet. wait for the next invalidate
  870. mEventQueue->invalidate();
  871. return true;
  872. }
  873. // We received the present fence from the HWC, so we assume it successfully updated
  874. // the config, hence we update SF.
  875. mCheckPendingFence = false;
  876. setActiveConfigInternal();
  877. }
  878. // Store the local variable to release the lock.
  879. ActiveConfigInfo desiredActiveConfig;
  880. {
  881. std::lock_guard<std::mutex> lock(mActiveConfigLock);
  882. if (!mDesiredActiveConfigChanged) {
  883. return false;
  884. }
  885. desiredActiveConfig = mDesiredActiveConfig;
  886. }
  887. const auto display = getDefaultDisplayDeviceLocked();
  888. if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
  889. // display is not valid or we are already in the requested mode
  890. // on both cases there is nothing left to do
  891. desiredActiveConfigChangeDone();
  892. return false;
  893. }
  894. // Desired active config was set, it is different than the config currently in use, however
  895. // allowed configs might have change by the time we process the refresh.
  896. // Make sure the desired config is still allowed
  897. if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
  898. desiredActiveConfigChangeDone();
  899. return false;
  900. }
  901. mUpcomingActiveConfig = desiredActiveConfig;
  902. const auto displayId = display->getId();
  903. LOG_ALWAYS_FATAL_IF(!displayId);
  904. ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
  905. getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
  906. // we need to submit an empty frame to HWC to start the process
  907. mCheckPendingFence = true;
  908. mEventQueue->invalidate();
  909. return false;
  910. }
  911. status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
  912. Vector<ColorMode>* outColorModes) {
  913. if (!displayToken || !outColorModes) {
  914. return BAD_VALUE;
  915. }
  916. std::vector<ColorMode> modes;
  917. bool isInternalDisplay = false;
  918. {
  919. ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
  920. const auto displayId = getPhysicalDisplayIdLocked(displayToken);
  921. if (!displayId) {
  922. return NAME_NOT_FOUND;
  923. }
  924. modes = getHwComposer().getColorModes(*displayId);
  925. isInternalDisplay = displayId == getInternalDisplayIdLocked();
  926. }
  927. outColorModes->clear();
  928. // If it's built-in display and the configuration claims it's not wide color capable,
  929. // filter out all wide color modes. The typical reason why this happens is that the
  930. // hardware is not good enough to support GPU composition of wide color, and thus the
  931. // OEMs choose to disable this capability.
  932. if (isInternalDisplay && !hasWideColorDisplay) {
  933. std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
  934. isWideColorMode);
  935. } else {
  936. std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
  937. }
  938. return NO_ERROR;
  939. }
  940. status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
  941. ui::DisplayPrimaries &primaries) {
  942. if (!displayToken) {
  943. return BAD_VALUE;
  944. }
  945. // Currently we only support this API for a single internal display.
  946. if (getInternalDisplayToken() != displayToken) {
  947. return BAD_VALUE;
  948. }
  949. memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
  950. return NO_ERROR;
  951. }
  952. ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
  953. if (const auto display = getDisplayDevice(displayToken)) {
  954. return display->getCompositionDisplay()->getState().colorMode;
  955. }
  956. return static_cast<ColorMode>(BAD_VALUE);
  957. }
  958. status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
  959. postMessageSync(new LambdaMessage([&] {
  960. Vector<ColorMode> modes;
  961. getDisplayColorModes(displayToken, &modes);
  962. bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
  963. if (mode < ColorMode::NATIVE || !exists) {
  964. ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
  965. decodeColorMode(mode).c_str(), mode, displayToken.get());
  966. return;
  967. }
  968. const auto display = getDisplayDevice(displayToken);
  969. if (!display) {
  970. ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
  971. decodeColorMode(mode).c_str(), mode, displayToken.get());
  972. } else if (display->isVirtual()) {
  973. ALOGW("Attempt to set active color mode %s (%d) for virtual display",
  974. decodeColorMode(mode).c_str(), mode);
  975. } else {
  976. display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
  977. RenderIntent::COLORIMETRIC);
  978. }
  979. }));
  980. return NO_ERROR;
  981. }
  982. status_t SurfaceFlinger::clearAnimationFrameStats() {
  983. Mutex::Autolock _l(mStateLock);
  984. mAnimFrameTracker.clearStats();
  985. return NO_ERROR;
  986. }
  987. status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
  988. Mutex::Autolock _l(mStateLock);
  989. mAnimFrameTracker.getStats(outStats);
  990. return NO_ERROR;
  991. }
  992. status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
  993. HdrCapabilities* outCapabilities) const {
  994. Mutex::Autolock _l(mStateLock);
  995. const auto display = getDisplayDeviceLocked(displayToken);
  996. if (!display) {
  997. ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
  998. return BAD_VALUE;
  999. }
  1000. // At this point the DisplayDeivce should already be set up,
  1001. // meaning the luminance information is already queried from
  1002. // hardware composer and stored properly.
  1003. const HdrCapabilities& capabilities = display->getHdrCapabilities();
  1004. *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
  1005. capabilities.getDesiredMaxLuminance(),
  1006. capabilities.getDesiredMaxAverageLuminance(),
  1007. capabilities.getDesiredMinLuminance());
  1008. return NO_ERROR;
  1009. }
  1010. status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
  1011. ui::PixelFormat* outFormat,
  1012. ui::Dataspace* outDataspace,
  1013. uint8_t* outComponentMask) const {
  1014. if (!outFormat || !outDataspace || !outComponentMask) {
  1015. return BAD_VALUE;
  1016. }
  1017. const auto display = getDisplayDevice(displayToken);
  1018. if (!display || !display->getId()) {
  1019. ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
  1020. return BAD_VALUE;
  1021. }
  1022. return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
  1023. outDataspace, outComponentMask);
  1024. }
  1025. status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
  1026. bool enable, uint8_t componentMask,
  1027. uint64_t maxFrames) const {
  1028. const auto display = getDisplayDevice(displayToken);
  1029. if (!display || !display->getId()) {
  1030. ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
  1031. return BAD_VALUE;
  1032. }
  1033. return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
  1034. componentMask, maxFrames);
  1035. }
  1036. status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
  1037. uint64_t maxFrames, uint64_t timestamp,
  1038. DisplayedFrameStats* outStats) const {
  1039. const auto display = getDisplayDevice(displayToken);
  1040. if (!display || !display->getId()) {
  1041. ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
  1042. return BAD_VALUE;
  1043. }
  1044. return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
  1045. outStats);
  1046. }
  1047. status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
  1048. if (!outSupported) {
  1049. return BAD_VALUE;
  1050. }
  1051. *outSupported = getRenderEngine().supportsProtectedContent();
  1052. return NO_ERROR;
  1053. }
  1054. status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
  1055. bool* outIsWideColorDisplay) const {
  1056. if (!displayToken || !outIsWideColorDisplay) {
  1057. return BAD_VALUE;
  1058. }
  1059. Mutex::Autolock _l(mStateLock);
  1060. const auto display = getDisplayDeviceLocked(displayToken);
  1061. if (!display) {
  1062. return BAD_VALUE;
  1063. }
  1064. // Use hasWideColorDisplay to override built-in display.
  1065. const auto displayId = display->getId();
  1066. if (displayId && displayId == getInternalDisplayIdLocked()) {
  1067. *outIsWideColorDisplay = hasWideColorDisplay;
  1068. return NO_ERROR;
  1069. }
  1070. *outIsWideColorDisplay = display->hasWideColorGamut();
  1071. return NO_ERROR;
  1072. }
  1073. status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
  1074. postMessageSync(new LambdaMessage([&] {
  1075. Mutex::Autolock _l(mStateLock);
  1076. if (mInjectVSyncs == enable) {
  1077. return;
  1078. }
  1079. auto resyncCallback =
  1080. mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
  1081. // TODO(b/128863962): Part of the Injector should be refactored, so that it
  1082. // can be passed to Scheduler.
  1083. if (enable) {
  1084. ALOGV("VSync Injections enabled");
  1085. if (mVSyncInjector.get() == nullptr) {
  1086. mVSyncInjector = std::make_unique<InjectVSyncSource>();
  1087. mInjectorEventThread = std::make_unique<
  1088. impl::EventThread>(mVSyncInjector.get(),
  1089. impl::EventThread::InterceptVSyncsCallback(),
  1090. "injEventThread");
  1091. }
  1092. mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
  1093. } else {
  1094. ALOGV("VSync Injections disabled");
  1095. mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
  1096. std::move(resyncCallback));
  1097. }
  1098. mInjectVSyncs = enable;
  1099. }));
  1100. return NO_ERROR;
  1101. }
  1102. status_t SurfaceFlinger::injectVSync(nsecs_t when) {
  1103. Mutex::Autolock _l(mStateLock);
  1104. if (!mInjectVSyncs) {
  1105. ALOGE("VSync Injections not enabled");
  1106. return BAD_VALUE;
  1107. }
  1108. if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
  1109. ALOGV("Injecting VSync inside SurfaceFlinger");
  1110. mVSyncInjector->onInjectSyncEvent(when);
  1111. }
  1112. return NO_ERROR;
  1113. }
  1114. status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
  1115. NO_THREAD_SAFETY_ANALYSIS {
  1116. // Try to acquire a lock for 1s, fail gracefully
  1117. const status_t err = mStateLock.timedLock(s2ns(1));
  1118. const bool locked = (err == NO_ERROR);
  1119. if (!locked) {
  1120. ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
  1121. return TIMED_OUT;
  1122. }
  1123. outLayers->clear();
  1124. mCurrentState.traverseInZOrder([&](Layer* layer) {
  1125. outLayers->push_back(layer->getLayerDebugInfo());
  1126. });
  1127. mStateLock.unlock();
  1128. return NO_ERROR;
  1129. }
  1130. status_t SurfaceFlinger::getCompositionPreference(
  1131. Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
  1132. Dataspace* outWideColorGamutDataspace,
  1133. ui::PixelFormat* outWideColorGamutPixelFormat) const {
  1134. *outDataspace = mDefaultCompositionDataspace;
  1135. *outPixelFormat = defaultCompositionPixelFormat;
  1136. *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
  1137. *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
  1138. return NO_ERROR;
  1139. }
  1140. status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
  1141. const sp<IBinder>& stopLayerHandle,
  1142. const sp<IRegionSamplingListener>& listener) {
  1143. if (!listener || samplingArea == Rect::INVALID_RECT) {
  1144. return BAD_VALUE;
  1145. }
  1146. mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
  1147. return NO_ERROR;
  1148. }
  1149. status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
  1150. if (!listener) {
  1151. return BAD_VALUE;
  1152. }
  1153. mRegionSamplingThread->removeListener(listener);
  1154. return NO_ERROR;
  1155. }
  1156. status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
  1157. bool* outSupport) const {
  1158. if (!displayToken || !outSupport) {
  1159. return BAD_VALUE;
  1160. }
  1161. const auto displayId = getPhysicalDisplayIdLocked(displayToken);
  1162. if (!displayId) {
  1163. return NAME_NOT_FOUND;
  1164. }
  1165. *outSupport =
  1166. getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
  1167. return NO_ERROR;
  1168. }
  1169. status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
  1170. float brightness) const {
  1171. if (!displayToken) {
  1172. return BAD_VALUE;
  1173. }
  1174. const auto displayId = getPhysicalDisplayIdLocked(displayToken);
  1175. if (!displayId) {
  1176. return NAME_NOT_FOUND;
  1177. }
  1178. return getHwComposer().setDisplayBrightness(*displayId, brightness);
  1179. }
  1180. status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
  1181. PowerHint powerHint = static_cast<PowerHint>(hintId);
  1182. if (powerHint == PowerHint::INTERACTION) {
  1183. mScheduler->notifyTouchEvent();
  1184. }
  1185. return NO_ERROR;
  1186. }
  1187. // ----------------------------------------------------------------------------
  1188. sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
  1189. ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
  1190. auto resyncCallback = mScheduler->makeResyncCallback([this] {
  1191. Mutex::Autolock lock(mStateLock);
  1192. return getVsyncPeriod();
  1193. });
  1194. const auto& handle =
  1195. vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
  1196. return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
  1197. configChanged);
  1198. }
  1199. // ----------------------------------------------------------------------------
  1200. void SurfaceFlinger::waitForEvent() {
  1201. mEventQueue->waitMessage();
  1202. }
  1203. void SurfaceFlinger::signalTransaction() {
  1204. mScheduler->resetIdleTimer();
  1205. mEventQueue->invalidate();
  1206. }
  1207. void SurfaceFlinger::signalLayerUpdate() {
  1208. mScheduler->resetIdleTimer();
  1209. mEventQueue->invalidate();
  1210. }
  1211. void SurfaceFlinger::signalRefresh() {
  1212. mRefreshPending = true;
  1213. mEventQueue->refresh();
  1214. }
  1215. status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
  1216. nsecs_t reltime, uint32_t /* flags */) {
  1217. return mEventQueue->postMessage(msg, reltime);
  1218. }
  1219. status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
  1220. nsecs_t reltime, uint32_t /* flags */) {
  1221. status_t res = mEventQueue->postMessage(msg, reltime);
  1222. if (res == NO_ERROR) {
  1223. msg->wait();
  1224. }
  1225. return res;
  1226. }
  1227. void SurfaceFlinger::run() {
  1228. do {
  1229. waitForEvent();
  1230. } while (true);
  1231. }
  1232. nsecs_t SurfaceFlinger::getVsyncPeriod() const {
  1233. const auto displayId = getInternalDisplayIdLocked();
  1234. if (!displayId || !getHwComposer().isConnected(*displayId)) {
  1235. return 0;
  1236. }
  1237. const auto config = getHwComposer().getActiveConfig(*displayId);
  1238. return config ? config->getVsyncPeriod() : 0;
  1239. }
  1240. void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
  1241. int64_t timestamp) {
  1242. ATRACE_NAME("SF onVsync");
  1243. Mutex::Autolock lock(mStateLock);
  1244. // Ignore any vsyncs from a previous hardware composer.
  1245. if (sequenceId != getBE().mComposerSequenceId) {
  1246. return;
  1247. }
  1248. if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
  1249. return;
  1250. }
  1251. if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
  1252. // For now, we don't do anything with external display vsyncs.
  1253. return;
  1254. }
  1255. bool periodFlushed = false;
  1256. mScheduler->addResyncSample(timestamp, &periodFlushed);
  1257. if (periodFlushed) {
  1258. mVsyncModulator.onRefreshRateChangeCompleted();
  1259. }
  1260. }
  1261. void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
  1262. std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
  1263. *compositorTiming = getBE().mCompositorTiming;
  1264. }
  1265. bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
  1266. return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
  1267. }
  1268. void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
  1269. const auto display = getDefaultDisplayDeviceLocked();
  1270. if (!display || mBootStage != BootStage::FINISHED) {
  1271. return;
  1272. }
  1273. ATRACE_CALL();
  1274. // Don't do any updating if the current fps is the same as the new one.
  1275. const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
  1276. if (!refreshRateConfig) {
  1277. ALOGV("Skipping refresh rate change request for unsupported rate.");
  1278. return;
  1279. }
  1280. const int desiredConfigId = refreshRateConfig->configId;
  1281. if (!isDisplayConfigAllowed(desiredConfigId)) {
  1282. ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
  1283. return;
  1284. }
  1285. setDesiredActiveConfig({refreshRate, desiredConfigId, event});
  1286. }
  1287. void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
  1288. HWC2::Connection connection) {
  1289. ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
  1290. connection == HWC2::Connection::Connected ? "connected" : "disconnected");
  1291. // Ignore events that do not have the right sequenceId.
  1292. if (sequenceId != getBE().mComposerSequenceId) {
  1293. return;
  1294. }
  1295. // Only lock if we're not on the main thread. This function is normally
  1296. // called on a hwbinder thread, but for the primary display it's called on
  1297. // the main thread with the state lock already held, so don't attempt to
  1298. // acquire it here.
  1299. ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
  1300. mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
  1301. if (std::this_thread::get_id() == mMainThreadId) {
  1302. // Process all pending hot plug events immediately if we are on the main thread.
  1303. processDisplayHotplugEventsLocked();
  1304. }
  1305. setTransactionFlags(eDisplayTransactionNeeded);
  1306. }
  1307. void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
  1308. Mutex::Autolock lock(mStateLock);
  1309. if (sequenceId != getBE().mComposerSequenceId) {
  1310. return;
  1311. }
  1312. repaintEverythingForHWC();
  1313. }
  1314. void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
  1315. ATRACE_CALL();
  1316. // Enable / Disable HWVsync from the main thread to avoid race conditions with
  1317. // display power state.
  1318. postMessageAsync(new LambdaMessage(
  1319. [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
  1320. }
  1321. void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
  1322. ATRACE_CALL();
  1323. mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
  1324. if (const auto displayId = getInternalDisplayIdLocked()) {
  1325. sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
  1326. if (display && display->isPoweredOn()) {
  1327. setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
  1328. }
  1329. }
  1330. }
  1331. // Note: it is assumed the caller holds |mStateLock| when this is called
  1332. void SurfaceFlinger::resetDisplayState() {
  1333. mScheduler->disableHardwareVsync(true);
  1334. // Clear the drawing state so that the logic inside of
  1335. // handleTransactionLocked will fire. It will determine the delta between
  1336. // mCurrentState and mDrawingState and re-apply all changes when we make the
  1337. // transition.
  1338. mDrawingState.displays.clear();
  1339. mDisplays.clear();
  1340. }
  1341. void SurfaceFlinger::updateVrFlinger() {
  1342. ATRACE_CALL();
  1343. if (!mVrFlinger)
  1344. return;
  1345. bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
  1346. if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
  1347. return;
  1348. }
  1349. if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
  1350. ALOGE("Vr flinger is only supported for remote hardware composer"
  1351. " service connections. Ignoring request to transition to vr"
  1352. " flinger.");
  1353. mVrFlingerRequestsDisplay = false;
  1354. return;
  1355. }
  1356. Mutex::Autolock _l(mStateLock);
  1357. sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
  1358. LOG_ALWAYS_FATAL_IF(!display);
  1359. const int currentDisplayPowerMode = display->getPowerMode();
  1360. // Clear out all the output layers from the composition engine for all
  1361. // displays before destroying the hardware composer interface. This ensures
  1362. // any HWC layers are destroyed through that interface before it becomes
  1363. // invalid.
  1364. for (const auto& [token, displayDevice] : mDisplays) {
  1365. displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
  1366. compositionengine::Output::OutputLayers());
  1367. }
  1368. // This DisplayDevice will no longer be relevant once resetDisplayState() is
  1369. // called below. Clear the reference now so we don't accidentally use it
  1370. // later.
  1371. display.clear();
  1372. if (!vrFlingerRequestsDisplay) {
  1373. mVrFlinger->SeizeDisplayOwnership();
  1374. }
  1375. resetDisplayState();
  1376. // Delete the current instance before creating the new one
  1377. mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
  1378. mCompositionEngine->setHwComposer(getFactory().createHWComposer(
  1379. vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
  1380. getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
  1381. LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
  1382. "Switched to non-remote hardware composer");
  1383. if (vrFlingerRequestsDisplay) {
  1384. mVrFlinger->GrantDisplayOwnership();
  1385. }
  1386. mVisibleRegionsDirty = true;
  1387. invalidateHwcGeometry();
  1388. // Re-enable default display.
  1389. display = getDefaultDisplayDeviceLocked();
  1390. LOG_ALWAYS_FATAL_IF(!display);
  1391. setPowerModeInternal(display, currentDisplayPowerMode);
  1392. // Reset the timing values to account for the period of the swapped in HWC
  1393. const nsecs_t vsyncPeriod = getVsyncPeriod();
  1394. mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
  1395. // The present fences returned from vr_hwc are not an accurate
  1396. // representation of vsync times.
  1397. mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
  1398. // Use phase of 0 since phase is not known.
  1399. // Use latency of 0, which will snap to the ideal latency.
  1400. DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
  1401. setCompositorTimingSnapped(stats, 0);
  1402. mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
  1403. mRepaintEverything = true;
  1404. setTransactionFlags(eDisplayTransactionNeeded);
  1405. }
  1406. bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
  1407. ATRACE_CALL();
  1408. // We are storing the last 2 present fences. If sf's phase offset is to be
  1409. // woken up before the actual vsync but targeting the next vsync, we need to check
  1410. // fence N-2
  1411. const sp<Fence>& fence =
  1412. mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
  1413. ? mPreviousPresentFences[0]
  1414. : mPreviousPresentFences[1];
  1415. if (fence == Fence::NO_FENCE) {
  1416. return false;
  1417. }
  1418. if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
  1419. fence->wait(graceTimeMs);
  1420. }
  1421. return (fence->getStatus() == Fence::Status::Unsignaled);
  1422. }
  1423. void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
  1424. DisplayStatInfo stats;
  1425. mScheduler->getDisplayStatInfo(&stats);
  1426. const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
  1427. // Inflate the expected present time if we're targetting the next vsync.
  1428. mExpectedPresentTime =
  1429. mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
  1430. ? presentTime
  1431. : presentTime + stats.vsyncPeriod;
  1432. }
  1433. void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
  1434. ATRACE_CALL();
  1435. switch (what) {
  1436. case MessageQueue::INVALIDATE: {
  1437. // calculate the expected present time once and use the cached
  1438. // value throughout this frame to make sure all layers are
  1439. // seeing this same value.
  1440. populateExpectedPresentTime();
  1441. // When Backpressure propagation is enabled we want to give a small grace period
  1442. // for the present fence to fire instead of just giving up on this frame to handle cases
  1443. // where present fence is just about to get signaled.
  1444. const int graceTimeForPresentFenceMs =
  1445. (mPropagateBackpressure &&
  1446. (mPropagateBackpressureClientComposition || !mHadClientComposition))
  1447. ? 1
  1448. : 0;
  1449. bool frameMissed = previousFrameMissed(graceTimeForPresentFenceMs);
  1450. bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
  1451. bool gpuFrameMissed = mHadClientComposition && frameMissed;
  1452. ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
  1453. ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
  1454. ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
  1455. if (frameMissed) {
  1456. mFrameMissedCount++;
  1457. mTimeStats->incrementMissedFrames();
  1458. }
  1459. if (hwcFrameMissed) {
  1460. mHwcFrameMissedCount++;
  1461. }
  1462. if (gpuFrameMissed) {
  1463. mGpuFrameMissedCount++;
  1464. }
  1465. if (mUseSmart90ForVideo) {
  1466. // This call is made each time SF wakes up and creates a new frame. It is part
  1467. // of video detection feature.
  1468. mScheduler->updateFpsBasedOnContent();
  1469. }
  1470. if (performSetActiveConfig()) {
  1471. break;
  1472. }
  1473. if (frameMissed && mPropagateBackpressure) {
  1474. if ((hwcFrameMissed && !gpuFrameMissed) ||
  1475. mPropagateBackpressureClientComposition) {
  1476. signalLayerUpdate();
  1477. break;
  1478. }
  1479. }
  1480. // Now that we're going to make it to the handleMessageTransaction()
  1481. // call below it's safe to call updateVrFlinger(), which will
  1482. // potentially trigger a display handoff.
  1483. updateVrFlinger();
  1484. bool refreshNeeded = handleMessageTransaction();
  1485. refreshNeeded |= handleMessageInvalidate();
  1486. updateCursorAsync();
  1487. updateInputFlinger();
  1488. refreshNeeded |= mRepaintEverything;
  1489. if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
  1490. // Signal a refresh if a transaction modified the window state,
  1491. // a new buffer was latched, or if HWC has requested a full
  1492. // repaint
  1493. signalRefresh();
  1494. }
  1495. break;
  1496. }
  1497. case MessageQueue::REFRESH: {
  1498. handleMessageRefresh();
  1499. break;
  1500. }
  1501. }
  1502. }
  1503. bool SurfaceFlinger::handleMessageTransaction() {
  1504. ATRACE_CALL();
  1505. uint32_t transactionFlags = peekTransactionFlags();
  1506. bool flushedATransaction = flushTransactionQueues();
  1507. bool runHandleTransaction = transactionFlags &&
  1508. ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
  1509. if (runHandleTransaction) {
  1510. handleTransaction(eTransactionMask);
  1511. } else {
  1512. getTransactionFlags(eTransactionFlushNeeded);
  1513. }
  1514. if (transactionFlushNeeded()) {
  1515. setTransactionFlags(eTransactionFlushNeeded);
  1516. }
  1517. return runHandleTransaction;
  1518. }
  1519. void SurfaceFlinger::handleMessageRefresh() {
  1520. ATRACE_CALL();
  1521. mRefreshPending = false;
  1522. const bool repaintEverything = mRepaintEverything.exchange(false);
  1523. preComposition();
  1524. rebuildLayerStacks();
  1525. calculateWorkingSet();
  1526. for (const auto& [token, display] : mDisplays) {
  1527. beginFrame(display);
  1528. prepareFrame(display);
  1529. doDebugFlashRegions(display, repaintEverything);
  1530. doComposition(display, repaintEverything);
  1531. }
  1532. logLayerStats();
  1533. postFrame();
  1534. postComposition();
  1535. mHadClientComposition = false;
  1536. mHadDeviceComposition = false;
  1537. for (const auto& [token, displayDevice] : mDisplays) {
  1538. auto display = displayDevice->getCompositionDisplay();
  1539. const auto displayId = display->getId();
  1540. mHadClientComposition =
  1541. mHadClientComposition || getHwComposer().hasClientComposition(displayId);
  1542. mHadDeviceComposition =
  1543. mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
  1544. }
  1545. mVsyncModulator.onRefreshed(mHadClientComposition);
  1546. mLayersWithQueuedFrames.clear();
  1547. }
  1548. bool SurfaceFlinger::handleMessageInvalidate() {
  1549. ATRACE_CALL();
  1550. bool refreshNeeded = handlePageFlip();
  1551. if (mVisibleRegionsDirty) {
  1552. computeLayerBounds();
  1553. if (mTracingEnabled) {
  1554. mTracing.notify("visibleRegionsDirty");
  1555. }
  1556. }
  1557. for (auto& layer : mLayersPendingRefresh) {
  1558. Region visibleReg;
  1559. visibleReg.set(layer->getScreenBounds());
  1560. invalidateLayerStack(layer, visibleReg);
  1561. }
  1562. mLayersPendingRefresh.clear();
  1563. return refreshNeeded;
  1564. }
  1565. void SurfaceFlinger::calculateWorkingSet() {
  1566. ATRACE_CALL();
  1567. ALOGV(__FUNCTION__);
  1568. // build the h/w work list
  1569. if (CC_UNLIKELY(mGeometryInvalid)) {
  1570. mGeometryInvalid = false;
  1571. for (const auto& [token, displayDevice] : mDisplays) {
  1572. auto display = displayDevice->getCompositionDisplay();
  1573. uint32_t zOrder = 0;
  1574. for (auto& layer : display->getOutputLayersOrderedByZ()) {
  1575. auto& compositionState = layer->editState();
  1576. compositionState.forceClientComposition = false;
  1577. if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
  1578. compositionState.forceClientComposition = true;
  1579. }
  1580. // The output Z order is set here based on a simple counter.
  1581. compositionState.z = zOrder++;
  1582. // Update the display independent composition state. This goes
  1583. // to the general composition layer state structure.
  1584. // TODO: Do this once per compositionengine::CompositionLayer.
  1585. layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
  1586. true);
  1587. // Recalculate the geometry state of the output layer.
  1588. layer->updateCompositionState(true);
  1589. // Write the updated geometry state to the HWC
  1590. layer->writeStateToHWC(true);
  1591. }
  1592. }
  1593. }
  1594. // Set the per-frame data
  1595. for (const auto& [token, displayDevice] : mDisplays) {
  1596. auto display = displayDevice->getCompositionDisplay();
  1597. const auto displayId = display->getId();
  1598. if (!displayId) {
  1599. continue;
  1600. }
  1601. auto* profile = display->getDisplayColorProfile();
  1602. if (mDrawingState.colorMatrixChanged) {
  1603. display->setColorTransform(mDrawingState.colorMatrix);
  1604. }
  1605. Dataspace targetDataspace = Dataspace::UNKNOWN;
  1606. if (useColorManagement) {
  1607. ColorMode colorMode;
  1608. RenderIntent renderIntent;
  1609. pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
  1610. display->setColorMode(colorMode, targetDataspace, renderIntent);
  1611. if (isHdrColorMode(colorMode)) {
  1612. targetDataspace = Dataspace::UNKNOWN;
  1613. } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
  1614. targetDataspace = mColorSpaceAgnosticDataspace;
  1615. }
  1616. }
  1617. for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
  1618. if (layer->isHdrY410()) {
  1619. layer->forceClientComposition(displayDevice);
  1620. } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
  1621. layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
  1622. !profile->hasHDR10Support()) {
  1623. layer->forceClientComposition(displayDevice);
  1624. } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
  1625. layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
  1626. !profile->hasHLGSupport()) {
  1627. layer->forceClientComposition(displayDevice);
  1628. }
  1629. if (layer->getRoundedCornerState().radius > 0.0f) {
  1630. layer->forceClientComposition(displayDevice);
  1631. }
  1632. if (layer->getForceClientComposition(displayDevice)) {
  1633. ALOGV("[%s] Requesting Client composition", layer->getName().string());
  1634. layer->setCompositionType(displayDevice,
  1635. Hwc2::IComposerClient::Composition::CLIENT);
  1636. continue;
  1637. }
  1638. const auto& displayState = display->getState();
  1639. layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
  1640. displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
  1641. }
  1642. }
  1643. mDrawingState.colorMatrixChanged = false;
  1644. for (const auto& [token, displayDevice] : mDisplays) {
  1645. auto display = displayDevice->getCompositionDisplay();
  1646. for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
  1647. auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
  1648. layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
  1649. layer->getCompositionType(displayDevice));
  1650. }
  1651. }
  1652. }
  1653. void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
  1654. bool repaintEverything) {
  1655. auto display = displayDevice->getCompositionDisplay();
  1656. const auto& displayState = display->getState();
  1657. // is debugging enabled
  1658. if (CC_LIKELY(!mDebugRegion))
  1659. return;
  1660. if (displayState.isEnabled) {
  1661. // transform the dirty region into this screen's coordinate space
  1662. const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
  1663. if (!dirtyRegion.isEmpty()) {
  1664. base::unique_fd readyFence;
  1665. // redraw the whole screen
  1666. doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
  1667. display->getRenderSurface()->queueBuffer(std::move(readyFence));
  1668. }
  1669. }
  1670. postFramebuffer(displayDevice);
  1671. if (mDebugRegion > 1) {
  1672. usleep(mDebugRegion * 1000);
  1673. }
  1674. prepareFrame(displayDevice);
  1675. }
  1676. void SurfaceFlinger::logLayerStats() {
  1677. ATRACE_CALL();
  1678. if (CC_UNLIKELY(mLayerStats.isEnabled())) {
  1679. for (const auto& [token, display] : mDisplays) {
  1680. if (display->isPrimary()) {
  1681. mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
  1682. return;
  1683. }
  1684. }
  1685. ALOGE("logLayerStats: no primary display");
  1686. }
  1687. }
  1688. void SurfaceFlinger::preComposition()
  1689. {
  1690. ATRACE_CALL();
  1691. ALOGV("preComposition");
  1692. mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
  1693. bool needExtraInvalidate = false;
  1694. mDrawingState.traverseInZOrder([&](Layer* layer) {
  1695. if (layer->onPreComposition(mRefreshStartTime)) {
  1696. needExtraInvalidate = true;
  1697. }
  1698. });
  1699. if (needExtraInvalidate) {
  1700. signalLayerUpdate();
  1701. }
  1702. }
  1703. void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
  1704. std::shared_ptr<FenceTime>& presentFenceTime) {
  1705. // Update queue of past composite+present times and determine the
  1706. // most recently known composite to present latency.
  1707. getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
  1708. nsecs_t compositeToPresentLatency = -1;
  1709. while (!getBE().mCompositePresentTimes.empty()) {
  1710. SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
  1711. // Cached values should have been updated before calling this method,
  1712. // which helps avoid duplicate syscalls.
  1713. nsecs_t displayTime = cpt.display->getCachedSignalTime();
  1714. if (displayTime == Fence::SIGNAL_TIME_PENDING) {
  1715. break;
  1716. }
  1717. compositeToPresentLatency = displayTime - cpt.composite;
  1718. getBE().mCompositePresentTimes.pop();
  1719. }
  1720. // Don't let mCompositePresentTimes grow unbounded, just in case.
  1721. while (getBE().mCompositePresentTimes.size() > 16) {
  1722. getBE().mCompositePresentTimes.pop();
  1723. }
  1724. setCompositorTimingSnapped(stats, compositeToPresentLatency);
  1725. }
  1726. void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
  1727. nsecs_t compositeToPresentLatency) {
  1728. // Integer division and modulo round toward 0 not -inf, so we need to
  1729. // treat negative and positive offsets differently.
  1730. nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
  1731. ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
  1732. : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
  1733. // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
  1734. if (idealLatency <= 0) {
  1735. idealLatency = stats.vsyncPeriod;
  1736. }
  1737. // Snap the latency to a value that removes scheduling jitter from the
  1738. // composition and present times, which often have >1ms of jitter.
  1739. // Reducing jitter is important if an app attempts to extrapolate
  1740. // something (such as user input) to an accurate diasplay time.
  1741. // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
  1742. // with (presentLatency % interval).
  1743. nsecs_t bias = stats.vsyncPeriod / 2;
  1744. int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
  1745. nsecs_t snappedCompositeToPresentLatency =
  1746. (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
  1747. std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
  1748. getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
  1749. getBE().mCompositorTiming.interval = stats.vsyncPeriod;
  1750. getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
  1751. }
  1752. void SurfaceFlinger::postComposition()
  1753. {
  1754. ATRACE_CALL();
  1755. ALOGV("postComposition");
  1756. // Release any buffers which were replaced this frame
  1757. nsecs_t dequeueReadyTime = systemTime();
  1758. for (auto& layer : mLayersWithQueuedFrames) {
  1759. layer->releasePendingBuffer(dequeueReadyTime);
  1760. }
  1761. // |mStateLock| not needed as we are on the main thread
  1762. const auto displayDevice = getDefaultDisplayDeviceLocked();
  1763. getBE().mGlCompositionDoneTimeline.updateSignalTimes();
  1764. std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
  1765. if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
  1766. glCompositionDoneFenceTime =
  1767. std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
  1768. ->getRenderSurface()
  1769. ->getClientTargetAcquireFence());
  1770. getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
  1771. } else {
  1772. glCompositionDoneFenceTime = FenceTime::NO_FENCE;
  1773. }
  1774. getBE().mDisplayTimeline.updateSignalTimes();
  1775. mPreviousPresentFences[1] = mPreviousPresentFences[0];
  1776. mPreviousPresentFences[0] = displayDevice
  1777. ? getHwComposer().getPresentFence(*displayDevice->getId())
  1778. : Fence::NO_FENCE;
  1779. auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
  1780. getBE().mDisplayTimeline.push(presentFenceTime);
  1781. DisplayStatInfo stats;
  1782. mScheduler->getDisplayStatInfo(&stats);
  1783. // We use the mRefreshStartTime which might be sampled a little later than
  1784. // when we started doing work for this frame, but that should be okay
  1785. // since updateCompositorTiming has snapping logic.
  1786. updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
  1787. CompositorTiming compositorTiming;
  1788. {
  1789. std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
  1790. compositorTiming = getBE().mCompositorTiming;
  1791. }
  1792. mDrawingState.traverseInZOrder([&](Layer* layer) {
  1793. bool frameLatched =
  1794. layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
  1795. presentFenceTime, compositorTiming);
  1796. if (frameLatched) {
  1797. recordBufferingStats(layer->getName().string(),
  1798. layer->getOccupancyHistory(false));
  1799. }
  1800. });
  1801. if (presentFenceTime->isValid()) {
  1802. mScheduler->addPresentFence(presentFenceTime);
  1803. }
  1804. if (!hasSyncFramework) {
  1805. if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
  1806. displayDevice->isPoweredOn()) {
  1807. mScheduler->enableHardwareVsync();
  1808. }
  1809. }
  1810. if (mAnimCompositionPending) {
  1811. mAnimCompositionPending = false;
  1812. if (presentFenceTime->isValid()) {
  1813. mAnimFrameTracker.setActualPresentFence(
  1814. std::move(presentFenceTime));
  1815. } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
  1816. // The HWC doesn't support present fences, so use the refresh
  1817. // timestamp instead.
  1818. const nsecs_t presentTime =
  1819. getHwComposer().getRefreshTimestamp(*displayDevice->getId());
  1820. mAnimFrameTracker.setActualPresentTime(presentTime);
  1821. }
  1822. mAnimFrameTracker.advanceFrame();
  1823. }
  1824. mTimeStats->incrementTotalFrames();
  1825. if (mHadClientComposition) {
  1826. mTimeStats->incrementClientCompositionFrames();
  1827. }
  1828. mTimeStats->setPresentFenceGlobal(presentFenceTime);
  1829. if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
  1830. !displayDevice->isPoweredOn()) {
  1831. return;
  1832. }
  1833. nsecs_t currentTime = systemTime();
  1834. if (mHasPoweredOff) {
  1835. mHasPoweredOff = false;
  1836. } else {
  1837. nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
  1838. size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
  1839. if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
  1840. getBE().mFrameBuckets[numPeriods] += elapsedTime;
  1841. } else {
  1842. getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
  1843. }
  1844. getBE().mTotalTime += elapsedTime;
  1845. }
  1846. getBE().mLastSwapTime = currentTime;
  1847. {
  1848. std::lock_guard lock(mTexturePoolMutex);
  1849. if (mTexturePool.size() < mTexturePoolSize) {
  1850. const size_t refillCount = mTexturePoolSize - mTexturePool.size();
  1851. const size_t offset = mTexturePool.size();
  1852. mTexturePool.resize(mTexturePoolSize);
  1853. getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
  1854. ATRACE_INT("TexturePoolSize", mTexturePool.size());
  1855. } else if (mTexturePool.size() > mTexturePoolSize) {
  1856. const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
  1857. const size_t offset = mTexturePoolSize;
  1858. getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
  1859. mTexturePool.resize(mTexturePoolSize);
  1860. ATRACE_INT("TexturePoolSize", mTexturePool.size());
  1861. }
  1862. }
  1863. mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
  1864. // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
  1865. // If we do not lock here, a callback could be sent without all of its SurfaceControls and
  1866. // metrics.
  1867. {
  1868. Mutex::Autolock _l(mStateLock);
  1869. mTransactionCompletedThread.sendCallbacks();
  1870. }
  1871. if (mLumaSampling && mRegionSamplingThread) {
  1872. mRegionSamplingThread->notifyNewContent();
  1873. }
  1874. // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
  1875. // side-effect of getTotalSize(), so we check that again here
  1876. if (ATRACE_ENABLED()) {
  1877. ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
  1878. }
  1879. }
  1880. void SurfaceFlinger::computeLayerBounds() {
  1881. for (const auto& pair : mDisplays) {
  1882. const auto& displayDevice = pair.second;
  1883. const auto display = displayDevice->getCompositionDisplay();
  1884. for (const auto& layer : mDrawingState.layersSortedByZ) {
  1885. // only consider the layers on the given layer stack
  1886. if (!display->belongsInOutput(layer->getLayerStack(), displayDevice->getActiveSystemName(), layer->getSystemName(), layer->getPrimaryDisplayOnly())) {
  1887. continue;
  1888. }
  1889. layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
  1890. }
  1891. }
  1892. }
  1893. void SurfaceFlinger::rebuildLayerStacks() {
  1894. ATRACE_CALL();
  1895. ALOGV("rebuildLayerStacks");
  1896. // rebuild the visible layer list per screen
  1897. if (CC_UNLIKELY(mVisibleRegionsDirty)) {
  1898. ATRACE_NAME("rebuildLayerStacks VR Dirty");
  1899. mVisibleRegionsDirty = false;
  1900. invalidateHwcGeometry();
  1901. for (const auto& pair : mDisplays) {
  1902. const auto& displayDevice = pair.second;
  1903. auto display = displayDevice->getCompositionDisplay();
  1904. const auto& displayState = display->getState();
  1905. Region opaqueRegion;
  1906. Region dirtyRegion;
  1907. compositionengine::Output::OutputLayers layersSortedByZ;
  1908. Vector<sp<Layer>> deprecated_layersSortedByZ;
  1909. Vector<sp<Layer>> layersNeedingFences;
  1910. const ui::Transform& tr = displayState.transform;
  1911. const Rect bounds = displayState.bounds;
  1912. if (displayState.isEnabled) {
  1913. computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
  1914. mDrawingState.traverseInZOrder([&](Layer* layer) {
  1915. auto compositionLayer = layer->getCompositionLayer();
  1916. if (compositionLayer == nullptr) {
  1917. return;
  1918. }
  1919. const auto displayId = displayDevice->getId();
  1920. sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
  1921. LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
  1922. bool needsOutputLayer = false;
  1923. if (display->belongsInOutput(layer->getLayerStack(), displayDevice->getActiveSystemName(), layer->getSystemName(),
  1924. layer->getPrimaryDisplayOnly())) {
  1925. Region drawRegion(tr.transform(
  1926. layer->visibleNonTransparentRegion));
  1927. drawRegion.andSelf(bounds);
  1928. if (!drawRegion.isEmpty()) {
  1929. needsOutputLayer = true;
  1930. }
  1931. }
  1932. if (needsOutputLayer) {
  1933. layersSortedByZ.emplace_back(
  1934. display->getOrCreateOutputLayer(displayId, compositionLayer,
  1935. layerFE));
  1936. deprecated_layersSortedByZ.add(layer);
  1937. auto& outputLayerState = layersSortedByZ.back()->editState();
  1938. outputLayerState.visibleRegion =
  1939. tr.transform(layer->visibleRegion.intersect(displayState.viewport));
  1940. } else if (displayId) {
  1941. // For layers that are being removed from a HWC display,
  1942. // and that have queued frames, add them to a a list of
  1943. // released layers so we can properly set a fence.
  1944. bool hasExistingOutputLayer =
  1945. display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
  1946. bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
  1947. mLayersWithQueuedFrames.cend(),
  1948. layer) != mLayersWithQueuedFrames.cend();
  1949. if (hasExistingOutputLayer && hasQueuedFrames) {
  1950. layersNeedingFences.add(layer);
  1951. }
  1952. }
  1953. });
  1954. }
  1955. display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
  1956. displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
  1957. displayDevice->setLayersNeedingFences(layersNeedingFences);
  1958. Region undefinedRegion{bounds};
  1959. undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
  1960. display->editState().undefinedRegion = undefinedRegion;
  1961. display->editState().dirtyRegion.orSelf(dirtyRegion);
  1962. }
  1963. }
  1964. }
  1965. // Returns a data space that fits all visible layers. The returned data space
  1966. // can only be one of
  1967. // - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
  1968. // - Dataspace::DISPLAY_P3
  1969. // - Dataspace::DISPLAY_BT2020
  1970. // The returned HDR data space is one of
  1971. // - Dataspace::UNKNOWN
  1972. // - Dataspace::BT2020_HLG
  1973. // - Dataspace::BT2020_PQ
  1974. Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
  1975. Dataspace* outHdrDataSpace,
  1976. bool* outIsHdrClientComposition) const {
  1977. Dataspace bestDataSpace = Dataspace::V0_SRGB;
  1978. *outHdrDataSpace = Dataspace::UNKNOWN;
  1979. for (const auto& layer : display->getVisibleLayersSortedByZ()) {
  1980. switch (layer->getDataSpace()) {
  1981. case Dataspace::V0_SCRGB:
  1982. case Dataspace::V0_SCRGB_LINEAR:
  1983. case Dataspace::BT2020:
  1984. case Dataspace::BT2020_ITU:
  1985. case Dataspace::BT2020_LINEAR:
  1986. case Dataspace::DISPLAY_BT2020:
  1987. bestDataSpace = Dataspace::DISPLAY_BT2020;
  1988. break;
  1989. case Dataspace::DISPLAY_P3:
  1990. bestDataSpace = Dataspace::DISPLAY_P3;
  1991. break;
  1992. case Dataspace::BT2020_PQ:
  1993. case Dataspace::BT2020_ITU_PQ:
  1994. bestDataSpace = Dataspace::DISPLAY_P3;
  1995. *outHdrDataSpace = Dataspace::BT2020_PQ;
  1996. *outIsHdrClientComposition = layer->getForceClientComposition(display);
  1997. break;
  1998. case Dataspace::BT2020_HLG:
  1999. case Dataspace::BT2020_ITU_HLG:
  2000. bestDataSpace = Dataspace::DISPLAY_P3;
  2001. // When there's mixed PQ content and HLG content, we set the HDR
  2002. // data space to be BT2020_PQ and convert HLG to PQ.
  2003. if (*outHdrDataSpace == Dataspace::UNKNOWN) {
  2004. *outHdrDataSpace = Dataspace::BT2020_HLG;
  2005. }
  2006. break;
  2007. default:
  2008. break;
  2009. }
  2010. }
  2011. return bestDataSpace;
  2012. }
  2013. // Pick the ColorMode / Dataspace for the display device.
  2014. void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
  2015. Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
  2016. if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
  2017. *outMode = ColorMode::NATIVE;
  2018. *outDataSpace = Dataspace::UNKNOWN;
  2019. *outRenderIntent = RenderIntent::COLORIMETRIC;
  2020. return;
  2021. }
  2022. Dataspace hdrDataSpace;
  2023. bool isHdrClientComposition = false;
  2024. Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
  2025. auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
  2026. switch (mForceColorMode) {
  2027. case ColorMode::SRGB:
  2028. bestDataSpace = Dataspace::V0_SRGB;
  2029. break;
  2030. case ColorMode::DISPLAY_P3:
  2031. bestDataSpace = Dataspace::DISPLAY_P3;
  2032. break;
  2033. default:
  2034. break;
  2035. }
  2036. // respect hdrDataSpace only when there is no legacy HDR support
  2037. const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
  2038. !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
  2039. if (isHdr) {
  2040. bestDataSpace = hdrDataSpace;
  2041. }
  2042. RenderIntent intent;
  2043. switch (mDisplayColorSetting) {
  2044. case DisplayColorSetting::MANAGED:
  2045. case DisplayColorSetting::UNMANAGED:
  2046. intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
  2047. break;
  2048. case DisplayColorSetting::ENHANCED:
  2049. intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
  2050. break;
  2051. default: // vendor display color setting
  2052. intent = static_cast<RenderIntent>(mDisplayColorSetting);
  2053. break;
  2054. }
  2055. profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
  2056. }
  2057. void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
  2058. auto display = displayDevice->getCompositionDisplay();
  2059. const auto& displayState = display->getState();
  2060. bool dirty = !display->getDirtyRegion(false).isEmpty();
  2061. bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
  2062. bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
  2063. // If nothing has changed (!dirty), don't recompose.
  2064. // If something changed, but we don't currently have any visible layers,
  2065. // and didn't when we last did a composition, then skip it this time.
  2066. // The second rule does two things:
  2067. // - When all layers are removed from a display, we'll emit one black
  2068. // frame, then nothing more until we get new layers.
  2069. // - When a display is created with a private layer stack, we won't
  2070. // emit any black frames until a layer is added to the layer stack.
  2071. bool mustRecompose = dirty && !(empty && wasEmpty);
  2072. const char flagPrefix[] = {'-', '+'};
  2073. static_cast<void>(flagPrefix);
  2074. ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
  2075. __FUNCTION__, mustRecompose ? "doing" : "skipping",
  2076. displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
  2077. flagPrefix[wasEmpty]);
  2078. display->getRenderSurface()->beginFrame(mustRecompose);
  2079. if (mustRecompose) {
  2080. display->editState().lastCompositionHadVisibleLayers = !empty;
  2081. }
  2082. }
  2083. void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
  2084. auto display = displayDevice->getCompositionDisplay();
  2085. const auto& displayState = display->getState();
  2086. if (!displayState.isEnabled) {
  2087. return;
  2088. }
  2089. status_t result = display->getRenderSurface()->prepareFrame();
  2090. ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
  2091. displayDevice->getDebugName().c_str(), result, strerror(-result));
  2092. }
  2093. void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
  2094. ATRACE_CALL();
  2095. ALOGV("doComposition");
  2096. auto display = displayDevice->getCompositionDisplay();
  2097. const auto& displayState = display->getState();
  2098. if (displayState.isEnabled) {
  2099. // transform the dirty region into this screen's coordinate space
  2100. const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
  2101. // repaint the framebuffer (if needed)
  2102. doDisplayComposition(displayDevice, dirtyRegion);
  2103. display->editState().dirtyRegion.clear();
  2104. display->getRenderSurface()->flip();
  2105. }
  2106. postFramebuffer(displayDevice);
  2107. }
  2108. void SurfaceFlinger::postFrame()
  2109. {
  2110. // |mStateLock| not needed as we are on the main thread
  2111. const auto display = getDefaultDisplayDeviceLocked();
  2112. if (display && getHwComposer().isConnected(*display->getId())) {
  2113. uint32_t flipCount = display->getPageFlipCount();
  2114. if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
  2115. logFrameStats();
  2116. }
  2117. }
  2118. }
  2119. void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
  2120. ATRACE_CALL();
  2121. ALOGV("postFramebuffer");
  2122. auto display = displayDevice->getCompositionDisplay();
  2123. const auto& displayState = display->getState();
  2124. const auto displayId = display->getId();
  2125. if (displayState.isEnabled) {
  2126. if (displayId) {
  2127. getHwComposer().presentAndGetReleaseFences(*displayId);
  2128. }
  2129. display->getRenderSurface()->onPresentDisplayCompleted();
  2130. for (auto& layer : display->getOutputLayersOrderedByZ()) {
  2131. sp<Fence> releaseFence = Fence::NO_FENCE;
  2132. bool usedClientComposition = true;
  2133. // The layer buffer from the previous frame (if any) is released
  2134. // by HWC only when the release fence from this frame (if any) is
  2135. // signaled. Always get the release fence from HWC first.
  2136. if (layer->getState().hwc) {
  2137. const auto& hwcState = *layer->getState().hwc;
  2138. releaseFence =
  2139. getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
  2140. usedClientComposition =
  2141. hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
  2142. }
  2143. // If the layer was client composited in the previous frame, we
  2144. // need to merge with the previous client target acquire fence.
  2145. // Since we do not track that, always merge with the current
  2146. // client target acquire fence when it is available, even though
  2147. // this is suboptimal.
  2148. if (usedClientComposition) {
  2149. releaseFence =
  2150. Fence::merge("LayerRelease", releaseFence,
  2151. display->getRenderSurface()->getClientTargetAcquireFence());
  2152. }
  2153. layer->getLayerFE().onLayerDisplayed(releaseFence);
  2154. }
  2155. // We've got a list of layers needing fences, that are disjoint with
  2156. // display->getVisibleLayersSortedByZ. The best we can do is to
  2157. // supply them with the present fence.
  2158. if (!displayDevice->getLayersNeedingFences().isEmpty()) {
  2159. sp<Fence> presentFence =
  2160. displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
  2161. for (auto& layer : displayDevice->getLayersNeedingFences()) {
  2162. layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
  2163. }
  2164. }
  2165. if (displayId) {
  2166. getHwComposer().clearReleaseFences(*displayId);
  2167. }
  2168. }
  2169. }
  2170. void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
  2171. {
  2172. ATRACE_CALL();
  2173. // here we keep a copy of the drawing state (that is the state that's
  2174. // going to be overwritten by handleTransactionLocked()) outside of
  2175. // mStateLock so that the side-effects of the State assignment
  2176. // don't happen with mStateLock held (which can cause deadlocks).
  2177. State drawingState(mDrawingState);
  2178. Mutex::Autolock _l(mStateLock);
  2179. mDebugInTransaction = systemTime();
  2180. // Here we're guaranteed that some transaction flags are set
  2181. // so we can call handleTransactionLocked() unconditionally.
  2182. // We call getTransactionFlags(), which will also clear the flags,
  2183. // with mStateLock held to guarantee that mCurrentState won't change
  2184. // until the transaction is committed.
  2185. mVsyncModulator.onTransactionHandled();
  2186. transactionFlags = getTransactionFlags(eTransactionMask);
  2187. handleTransactionLocked(transactionFlags);
  2188. mDebugInTransaction = 0;
  2189. invalidateHwcGeometry();
  2190. // here the transaction has been committed
  2191. }
  2192. void SurfaceFlinger::processDisplayHotplugEventsLocked() {
  2193. for (const auto& event : mPendingHotplugEvents) {
  2194. const std::optional<DisplayIdentificationInfo> info =
  2195. getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
  2196. if (!info) {
  2197. continue;
  2198. }
  2199. if (event.connection == HWC2::Connection::Connected) {
  2200. if (!mPhysicalDisplayTokens.count(info->id)) {
  2201. ALOGV("Creating display %s", to_string(info->id).c_str());
  2202. mPhysicalDisplayTokens[info->id] = new BBinder();
  2203. DisplayDeviceState state;
  2204. state.displayId = info->id;
  2205. state.isSecure = true; // All physical displays are currently considered secure.
  2206. state.displayName = info->name;
  2207. mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
  2208. mInterceptor->saveDisplayCreation(state);
  2209. }
  2210. } else {
  2211. ALOGV("Removing display %s", to_string(info->id).c_str());
  2212. ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
  2213. if (index >= 0) {
  2214. const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
  2215. mInterceptor->saveDisplayDeletion(state.sequenceId);
  2216. mCurrentState.displays.removeItemsAt(index);
  2217. }
  2218. mPhysicalDisplayTokens.erase(info->id);
  2219. }
  2220. processDisplayChangesLocked();
  2221. }
  2222. mPendingHotplugEvents.clear();
  2223. }
  2224. void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
  2225. mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
  2226. mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
  2227. }
  2228. sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
  2229. const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
  2230. const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
  2231. const sp<IGraphicBufferProducer>& producer) {
  2232. DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
  2233. creationArgs.sequenceId = state.sequenceId;
  2234. creationArgs.isVirtual = state.isVirtual();
  2235. creationArgs.isSecure = state.isSecure;
  2236. creationArgs.displaySurface = dispSurface;
  2237. creationArgs.hasWideColorGamut = false;
  2238. creationArgs.supportedPerFrameMetadata = 0;
  2239. const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
  2240. creationArgs.isPrimary = isInternalDisplay;
  2241. if (useColorManagement && displayId) {
  2242. std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
  2243. for (ColorMode colorMode : modes) {
  2244. if (isWideColorMode(colorMode)) {
  2245. creationArgs.hasWideColorGamut = true;
  2246. }
  2247. std::vector<RenderIntent> renderIntents =
  2248. getHwComposer().getRenderIntents(*displayId, colorMode);
  2249. creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
  2250. }
  2251. }
  2252. if (displayId) {
  2253. getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
  2254. creationArgs.supportedPerFrameMetadata =
  2255. getHwComposer().getSupportedPerFrameMetadata(*displayId);
  2256. }
  2257. auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
  2258. auto nativeWindow = nativeWindowSurface->getNativeWindow();
  2259. creationArgs.nativeWindow = nativeWindow;
  2260. // Make sure that composition can never be stalled by a virtual display
  2261. // consumer that isn't processing buffers fast enough. We have to do this
  2262. // here, in case the display is composed entirely by HWC.
  2263. if (state.isVirtual()) {
  2264. nativeWindow->setSwapInterval(nativeWindow.get(), 0);
  2265. }
  2266. creationArgs.displayInstallOrientation =
  2267. isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
  2268. // virtual displays are always considered enabled
  2269. creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
  2270. sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
  2271. if (maxFrameBufferAcquiredBuffers >= 3) {
  2272. nativeWindowSurface->preallocateBuffers();
  2273. }
  2274. ColorMode defaultColorMode = ColorMode::NATIVE;
  2275. Dataspace defaultDataSpace = Dataspace::UNKNOWN;
  2276. if (display->hasWideColorGamut()) {
  2277. defaultColorMode = ColorMode::SRGB;
  2278. defaultDataSpace = Dataspace::V0_SRGB;
  2279. }
  2280. display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
  2281. RenderIntent::COLORIMETRIC);
  2282. if (!state.isVirtual()) {
  2283. LOG_ALWAYS_FATAL_IF(!displayId);
  2284. display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
  2285. }
  2286. display->setLayerStack(state.layerStack);
  2287. display->setProjection(state.orientation, state.viewport, state.frame);
  2288. display->setDisplayName(state.displayName);
  2289. return display;
  2290. }
  2291. void SurfaceFlinger::processDisplayChangesLocked() {
  2292. // here we take advantage of Vector's copy-on-write semantics to
  2293. // improve performance by skipping the transaction entirely when
  2294. // know that the lists are identical
  2295. const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
  2296. const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
  2297. if (!curr.isIdenticalTo(draw)) {
  2298. mVisibleRegionsDirty = true;
  2299. const size_t cc = curr.size();
  2300. size_t dc = draw.size();
  2301. // find the displays that were removed
  2302. // (ie: in drawing state but not in current state)
  2303. // also handle displays that changed
  2304. // (ie: displays that are in both lists)
  2305. for (size_t i = 0; i < dc;) {
  2306. const ssize_t j = curr.indexOfKey(draw.keyAt(i));
  2307. if (j < 0) {
  2308. // in drawing state but not in current state
  2309. if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
  2310. // Save display ID before disconnecting.
  2311. const auto displayId = display->getId();
  2312. display->disconnect();
  2313. if (!display->isVirtual()) {
  2314. LOG_ALWAYS_FATAL_IF(!displayId);
  2315. dispatchDisplayHotplugEvent(displayId->value, false);
  2316. }
  2317. }
  2318. mDisplays.erase(draw.keyAt(i));
  2319. } else {
  2320. // this display is in both lists. see if something changed.
  2321. const DisplayDeviceState& state(curr[j]);
  2322. const wp<IBinder>& displayToken = curr.keyAt(j);
  2323. const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
  2324. const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
  2325. if (state_binder != draw_binder) {
  2326. // changing the surface is like destroying and
  2327. // recreating the DisplayDevice, so we just remove it
  2328. // from the drawing state, so that it get re-added
  2329. // below.
  2330. if (const auto display = getDisplayDeviceLocked(displayToken)) {
  2331. display->disconnect();
  2332. }
  2333. mDisplays.erase(displayToken);
  2334. mDrawingState.displays.removeItemsAt(i);
  2335. dc--;
  2336. // at this point we must loop to the next item
  2337. continue;
  2338. }
  2339. if (const auto display = getDisplayDeviceLocked(displayToken)) {
  2340. if (state.layerStack != draw[i].layerStack) {
  2341. display->setLayerStack(state.layerStack);
  2342. }
  2343. if ((state.orientation != draw[i].orientation) ||
  2344. (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
  2345. display->setProjection(state.orientation, state.viewport, state.frame);
  2346. }
  2347. if (state.width != draw[i].width || state.height != draw[i].height) {
  2348. display->setDisplaySize(state.width, state.height);
  2349. }
  2350. }
  2351. }
  2352. ++i;
  2353. }
  2354. // find displays that were added
  2355. // (ie: in current state but not in drawing state)
  2356. for (size_t i = 0; i < cc; i++) {
  2357. if (draw.indexOfKey(curr.keyAt(i)) < 0) {
  2358. const DisplayDeviceState& state(curr[i]);
  2359. sp<compositionengine::DisplaySurface> dispSurface;
  2360. sp<IGraphicBufferProducer> producer;
  2361. sp<IGraphicBufferProducer> bqProducer;
  2362. sp<IGraphicBufferConsumer> bqConsumer;
  2363. getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
  2364. std::optional<DisplayId> displayId;
  2365. if (state.isVirtual()) {
  2366. // Virtual displays without a surface are dormant:
  2367. // they have external state (layer stack, projection,
  2368. // etc.) but no internal state (i.e. a DisplayDevice).
  2369. if (state.surface != nullptr) {
  2370. // Allow VR composer to use virtual displays.
  2371. if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
  2372. int width = 0;
  2373. int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
  2374. ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
  2375. int height = 0;
  2376. status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
  2377. ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
  2378. int intFormat = 0;
  2379. status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
  2380. ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
  2381. auto format = static_cast<ui::PixelFormat>(intFormat);
  2382. displayId =
  2383. getHwComposer().allocateVirtualDisplay(width, height, &format);
  2384. }
  2385. // TODO: Plumb requested format back up to consumer
  2386. sp<VirtualDisplaySurface> vds =
  2387. new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
  2388. bqProducer, bqConsumer,
  2389. state.displayName);
  2390. dispSurface = vds;
  2391. producer = vds;
  2392. }
  2393. } else {
  2394. ALOGE_IF(state.surface != nullptr,
  2395. "adding a supported display, but rendering "
  2396. "surface is provided (%p), ignoring it",
  2397. state.surface.get());
  2398. displayId = state.displayId;
  2399. LOG_ALWAYS_FATAL_IF(!displayId);
  2400. dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
  2401. producer = bqProducer;
  2402. }
  2403. const wp<IBinder>& displayToken = curr.keyAt(i);
  2404. if (dispSurface != nullptr) {
  2405. mDisplays.emplace(displayToken,
  2406. setupNewDisplayDeviceInternal(displayToken, displayId, state,
  2407. dispSurface, producer));
  2408. if (!state.isVirtual()) {
  2409. LOG_ALWAYS_FATAL_IF(!displayId);
  2410. dispatchDisplayHotplugEvent(displayId->value, true);
  2411. }
  2412. }
  2413. }
  2414. }
  2415. }
  2416. mDrawingState.displays = mCurrentState.displays;
  2417. }
  2418. void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
  2419. {
  2420. // Notify all layers of available frames
  2421. mCurrentState.traverseInZOrder([](Layer* layer) {
  2422. layer->notifyAvailableFrames();
  2423. });
  2424. /*
  2425. * Traversal of the children
  2426. * (perform the transaction for each of them if needed)
  2427. */
  2428. if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
  2429. mCurrentState.traverseInZOrder([&](Layer* layer) {
  2430. uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
  2431. if (!trFlags) return;
  2432. const uint32_t flags = layer->doTransaction(0);
  2433. if (flags & Layer::eVisibleRegion)
  2434. mVisibleRegionsDirty = true;
  2435. if (flags & Layer::eInputInfoChanged) {
  2436. mInputInfoChanged = true;
  2437. }
  2438. });
  2439. mTraversalNeededMainThread = false;
  2440. }
  2441. /*
  2442. * Perform display own transactions if needed
  2443. */
  2444. if (transactionFlags & eDisplayTransactionNeeded) {
  2445. processDisplayChangesLocked();
  2446. processDisplayHotplugEventsLocked();
  2447. }
  2448. if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
  2449. // The transform hint might have changed for some layers
  2450. // (either because a display has changed, or because a layer
  2451. // as changed).
  2452. //
  2453. // Walk through all the layers in currentLayers,
  2454. // and update their transform hint.
  2455. //
  2456. // If a layer is visible only on a single display, then that
  2457. // display is used to calculate the hint, otherwise we use the
  2458. // default display.
  2459. //
  2460. // NOTE: we do this here, rather than in rebuildLayerStacks() so that
  2461. // the hint is set before we acquire a buffer from the surface texture.
  2462. //
  2463. // NOTE: layer transactions have taken place already, so we use their
  2464. // drawing state. However, SurfaceFlinger's own transaction has not
  2465. // happened yet, so we must use the current state layer list
  2466. // (soon to become the drawing state list).
  2467. //
  2468. sp<const DisplayDevice> hintDisplay;
  2469. uint32_t currentlayerStack = 0;
  2470. bool first = true;
  2471. mCurrentState.traverseInZOrder([&](Layer* layer) {
  2472. // NOTE: we rely on the fact that layers are sorted by
  2473. // layerStack first (so we don't have to traverse the list
  2474. // of displays for every layer).
  2475. uint32_t layerStack = layer->getLayerStack();
  2476. if (first || currentlayerStack != layerStack) {
  2477. currentlayerStack = layerStack;
  2478. // figure out if this layerstack is mirrored
  2479. // (more than one display) if so, pick the default display,
  2480. // if not, pick the only display it's on.
  2481. hintDisplay = nullptr;
  2482. for (const auto& [token, display] : mDisplays) {
  2483. if (display->getCompositionDisplay()
  2484. ->belongsInOutput(layer->getLayerStack(), display->getActiveSystemName(), layer->getSystemName(),
  2485. layer->getPrimaryDisplayOnly())) {
  2486. if (hintDisplay) {
  2487. hintDisplay = nullptr;
  2488. break;
  2489. } else {
  2490. hintDisplay = display;
  2491. }
  2492. }
  2493. }
  2494. }
  2495. if (!hintDisplay) {
  2496. // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
  2497. // redraw after transform hint changes. See bug 8508397.
  2498. // could be null when this layer is using a layerStack
  2499. // that is not visible on any display. Also can occur at
  2500. // screen off/on times.
  2501. hintDisplay = getDefaultDisplayDeviceLocked();
  2502. }
  2503. // could be null if there is no display available at all to get
  2504. // the transform hint from.
  2505. if (hintDisplay) {
  2506. layer->updateTransformHint(hintDisplay);
  2507. }
  2508. first = false;
  2509. });
  2510. }
  2511. /*
  2512. * Perform our own transaction if needed
  2513. */
  2514. if (mLayersAdded) {
  2515. mLayersAdded = false;
  2516. // Layers have been added.
  2517. mVisibleRegionsDirty = true;
  2518. }
  2519. // some layers might have been removed, so
  2520. // we need to update the regions they're exposing.
  2521. if (mLayersRemoved) {
  2522. mLayersRemoved = false;
  2523. mVisibleRegionsDirty = true;
  2524. mDrawingState.traverseInZOrder([&](Layer* layer) {
  2525. if (mLayersPendingRemoval.indexOf(layer) >= 0) {
  2526. // this layer is not visible anymore
  2527. Region visibleReg;
  2528. visibleReg.set(layer->getScreenBounds());
  2529. invalidateLayerStack(layer, visibleReg);
  2530. }
  2531. });
  2532. }
  2533. commitInputWindowCommands();
  2534. commitTransaction();
  2535. }
  2536. void SurfaceFlinger::updateInputFlinger() {
  2537. ATRACE_CALL();
  2538. if (!mInputFlinger) {
  2539. return;
  2540. }
  2541. if (mVisibleRegionsDirty || mInputInfoChanged) {
  2542. mInputInfoChanged = false;
  2543. updateInputWindowInfo();
  2544. } else if (mInputWindowCommands.syncInputWindows) {
  2545. // If the caller requested to sync input windows, but there are no
  2546. // changes to input windows, notify immediately.
  2547. setInputWindowsFinished();
  2548. }
  2549. mInputWindowCommands.clear();
  2550. }
  2551. #define MAX_CONTEXT 6
  2552. void SurfaceFlinger::updateInputWindowInfo() {
  2553. std::vector<std::vector<InputWindowInfo>> inputHandles(MAX_CONTEXT);
  2554. int i = 0;
  2555. mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
  2556. if (layer->hasInput()) {
  2557. // When calculating the screen bounds we ignore the transparent region since it may
  2558. // result in an unwanted offset.
  2559. if(layer->getSystemName() ==String8("")){
  2560. inputHandles[0].push_back(layer->fillInputInfo());
  2561. }else{
  2562. sscanf(layer->systemName(), "cell%d",&i);
  2563. if(i > 0 && i < MAX_CONTEXT){
  2564. inputHandles[i].push_back(layer->fillInputInfo());
  2565. }
  2566. }
  2567. }
  2568. });
  2569. for(i = 0; i < MAX_CONTEXT; i++)
  2570. {
  2571. if( i == 0){
  2572. mInputFlinger->setInputWindows(inputHandles[0],
  2573. mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
  2574. : nullptr);
  2575. }else{
  2576. const sp<IServiceManager> sm = OtherServiceManager(i);
  2577. if (sm != nullptr) {
  2578. sp<IInputFlinger> mInputFlinger1 = interface_cast<IInputFlinger>(sm->getService( String16("inputflinger")));
  2579. if (mInputFlinger1 != nullptr) {
  2580. mInputFlinger1->setInputWindows(inputHandles[i],
  2581. mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
  2582. : nullptr);
  2583. }
  2584. }
  2585. }
  2586. }
  2587. }
  2588. void SurfaceFlinger::commitInputWindowCommands() {
  2589. mInputWindowCommands = mPendingInputWindowCommands;
  2590. mPendingInputWindowCommands.clear();
  2591. }
  2592. void SurfaceFlinger::updateCursorAsync()
  2593. {
  2594. for (const auto& [token, display] : mDisplays) {
  2595. if (!display->getId()) {
  2596. continue;
  2597. }
  2598. for (auto& layer : display->getVisibleLayersSortedByZ()) {
  2599. layer->updateCursorPosition(display);
  2600. }
  2601. }
  2602. }
  2603. void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
  2604. if (layer->hasReadyFrame()) {
  2605. bool ignored = false;
  2606. layer->latchBuffer(ignored, systemTime());
  2607. }
  2608. layer->releasePendingBuffer(systemTime());
  2609. }
  2610. void SurfaceFlinger::commitTransaction()
  2611. {
  2612. if (!mLayersPendingRemoval.isEmpty()) {
  2613. // Notify removed layers now that they can't be drawn from
  2614. for (const auto& l : mLayersPendingRemoval) {
  2615. recordBufferingStats(l->getName().string(),
  2616. l->getOccupancyHistory(true));
  2617. // Ensure any buffers set to display on any children are released.
  2618. if (l->isRemovedFromCurrentState()) {
  2619. latchAndReleaseBuffer(l);
  2620. }
  2621. // If the layer has been removed and has no parent, then it will not be reachable
  2622. // when traversing layers on screen. Add the layer to the offscreenLayers set to
  2623. // ensure we can copy its current to drawing state.
  2624. if (!l->getParent()) {
  2625. mOffscreenLayers.emplace(l.get());
  2626. }
  2627. }
  2628. mLayersPendingRemoval.clear();
  2629. }
  2630. // If this transaction is part of a window animation then the next frame
  2631. // we composite should be considered an animation as well.
  2632. mAnimCompositionPending = mAnimTransactionPending;
  2633. withTracingLock([&]() {
  2634. mDrawingState = mCurrentState;
  2635. // clear the "changed" flags in current state
  2636. mCurrentState.colorMatrixChanged = false;
  2637. mDrawingState.traverseInZOrder([&](Layer* layer) {
  2638. layer->commitChildList();
  2639. // If the layer can be reached when traversing mDrawingState, then the layer is no
  2640. // longer offscreen. Remove the layer from the offscreenLayer set.
  2641. if (mOffscreenLayers.count(layer)) {
  2642. mOffscreenLayers.erase(layer);
  2643. }
  2644. });
  2645. commitOffscreenLayers();
  2646. });
  2647. mTransactionPending = false;
  2648. mAnimTransactionPending = false;
  2649. mTransactionCV.broadcast();
  2650. }
  2651. void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
  2652. if (mTracingEnabledChanged) {
  2653. mTracingEnabled = mTracing.isEnabled();
  2654. mTracingEnabledChanged = false;
  2655. }
  2656. // Synchronize with Tracing thread
  2657. std::unique_lock<std::mutex> lock;
  2658. if (mTracingEnabled) {
  2659. lock = std::unique_lock<std::mutex>(mDrawingStateLock);
  2660. }
  2661. lockedOperation();
  2662. // Synchronize with Tracing thread
  2663. if (mTracingEnabled) {
  2664. lock.unlock();
  2665. }
  2666. }
  2667. void SurfaceFlinger::commitOffscreenLayers() {
  2668. for (Layer* offscreenLayer : mOffscreenLayers) {
  2669. offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
  2670. uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
  2671. if (!trFlags) return;
  2672. layer->doTransaction(0);
  2673. layer->commitChildList();
  2674. });
  2675. }
  2676. }
  2677. void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
  2678. Region& outDirtyRegion, Region& outOpaqueRegion) {
  2679. ATRACE_CALL();
  2680. ALOGV("computeVisibleRegions");
  2681. auto display = displayDevice->getCompositionDisplay();
  2682. Region aboveOpaqueLayers;
  2683. Region aboveCoveredLayers;
  2684. Region dirty;
  2685. outDirtyRegion.clear();
  2686. mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
  2687. // start with the whole surface at its current location
  2688. const Layer::State& s(layer->getDrawingState());
  2689. // only consider the layers on the given layer stack
  2690. if (!display->belongsInOutput(layer->getLayerStack(), displayDevice->getActiveSystemName(), layer->getSystemName(), layer->getPrimaryDisplayOnly())) {
  2691. return;
  2692. }
  2693. /*
  2694. * opaqueRegion: area of a surface that is fully opaque.
  2695. */
  2696. Region opaqueRegion;
  2697. /*
  2698. * visibleRegion: area of a surface that is visible on screen
  2699. * and not fully transparent. This is essentially the layer's
  2700. * footprint minus the opaque regions above it.
  2701. * Areas covered by a translucent surface are considered visible.
  2702. */
  2703. Region visibleRegion;
  2704. /*
  2705. * coveredRegion: area of a surface that is covered by all
  2706. * visible regions above it (which includes the translucent areas).
  2707. */
  2708. Region coveredRegion;
  2709. /*
  2710. * transparentRegion: area of a surface that is hinted to be completely
  2711. * transparent. This is only used to tell when the layer has no visible
  2712. * non-transparent regions and can be removed from the layer list. It
  2713. * does not affect the visibleRegion of this layer or any layers
  2714. * beneath it. The hint may not be correct if apps don't respect the
  2715. * SurfaceView restrictions (which, sadly, some don't).
  2716. */
  2717. Region transparentRegion;
  2718. // handle hidden surfaces by setting the visible region to empty
  2719. if (CC_LIKELY(layer->isVisible())) {
  2720. const bool translucent = !layer->isOpaque(s);
  2721. Rect bounds(layer->getScreenBounds());
  2722. visibleRegion.set(bounds);
  2723. ui::Transform tr = layer->getTransform();
  2724. if (!visibleRegion.isEmpty()) {
  2725. // Remove the transparent area from the visible region
  2726. if (translucent) {
  2727. if (tr.preserveRects()) {
  2728. // transform the transparent region
  2729. transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
  2730. } else {
  2731. // transformation too complex, can't do the
  2732. // transparent region optimization.
  2733. transparentRegion.clear();
  2734. }
  2735. }
  2736. // compute the opaque region
  2737. const int32_t layerOrientation = tr.getOrientation();
  2738. if (layer->getAlpha() == 1.0f && !translucent &&
  2739. layer->getRoundedCornerState().radius == 0.0f &&
  2740. ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
  2741. // the opaque region is the layer's footprint
  2742. opaqueRegion = visibleRegion;
  2743. }
  2744. }
  2745. }
  2746. if (visibleRegion.isEmpty()) {
  2747. layer->clearVisibilityRegions();
  2748. return;
  2749. }
  2750. // Clip the covered region to the visible region
  2751. coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
  2752. // Update aboveCoveredLayers for next (lower) layer
  2753. aboveCoveredLayers.orSelf(visibleRegion);
  2754. // subtract the opaque region covered by the layers above us
  2755. visibleRegion.subtractSelf(aboveOpaqueLayers);
  2756. // compute this layer's dirty region
  2757. if (layer->contentDirty) {
  2758. // we need to invalidate the whole region
  2759. dirty = visibleRegion;
  2760. // as well, as the old visible region
  2761. dirty.orSelf(layer->visibleRegion);
  2762. layer->contentDirty = false;
  2763. } else {
  2764. /* compute the exposed region:
  2765. * the exposed region consists of two components:
  2766. * 1) what's VISIBLE now and was COVERED before
  2767. * 2) what's EXPOSED now less what was EXPOSED before
  2768. *
  2769. * note that (1) is conservative, we start with the whole
  2770. * visible region but only keep what used to be covered by
  2771. * something -- which mean it may have been exposed.
  2772. *
  2773. * (2) handles areas that were not covered by anything but got
  2774. * exposed because of a resize.
  2775. */
  2776. const Region newExposed = visibleRegion - coveredRegion;
  2777. const Region oldVisibleRegion = layer->visibleRegion;
  2778. const Region oldCoveredRegion = layer->coveredRegion;
  2779. const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
  2780. dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
  2781. }
  2782. dirty.subtractSelf(aboveOpaqueLayers);
  2783. // accumulate to the screen dirty region
  2784. outDirtyRegion.orSelf(dirty);
  2785. // Update aboveOpaqueLayers for next (lower) layer
  2786. aboveOpaqueLayers.orSelf(opaqueRegion);
  2787. // Store the visible region in screen space
  2788. layer->setVisibleRegion(visibleRegion);
  2789. layer->setCoveredRegion(coveredRegion);
  2790. layer->setVisibleNonTransparentRegion(
  2791. visibleRegion.subtract(transparentRegion));
  2792. });
  2793. outOpaqueRegion = aboveOpaqueLayers;
  2794. }
  2795. void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
  2796. for (const auto& [token, displayDevice] : mDisplays) {
  2797. auto display = displayDevice->getCompositionDisplay();
  2798. if (display->belongsInOutput(layer->getLayerStack(), displayDevice->getActiveSystemName(), layer->getSystemName(), layer->getPrimaryDisplayOnly())) {
  2799. display->editState().dirtyRegion.orSelf(dirty);
  2800. }
  2801. }
  2802. }
  2803. bool SurfaceFlinger::handlePageFlip()
  2804. {
  2805. ATRACE_CALL();
  2806. ALOGV("handlePageFlip");
  2807. nsecs_t latchTime = systemTime();
  2808. bool visibleRegions = false;
  2809. bool frameQueued = false;
  2810. bool newDataLatched = false;
  2811. // Store the set of layers that need updates. This set must not change as
  2812. // buffers are being latched, as this could result in a deadlock.
  2813. // Example: Two producers share the same command stream and:
  2814. // 1.) Layer 0 is latched
  2815. // 2.) Layer 0 gets a new frame
  2816. // 2.) Layer 1 gets a new frame
  2817. // 3.) Layer 1 is latched.
  2818. // Display is now waiting on Layer 1's frame, which is behind layer 0's
  2819. // second frame. But layer 0's second frame could be waiting on display.
  2820. mDrawingState.traverseInZOrder([&](Layer* layer) {
  2821. if (layer->hasReadyFrame()) {
  2822. frameQueued = true;
  2823. const nsecs_t expectedPresentTime = getExpectedPresentTime();
  2824. if (layer->shouldPresentNow(expectedPresentTime)) {
  2825. mLayersWithQueuedFrames.push_back(layer);
  2826. } else {
  2827. ATRACE_NAME("!layer->shouldPresentNow()");
  2828. layer->useEmptyDamage();
  2829. }
  2830. } else {
  2831. layer->useEmptyDamage();
  2832. }
  2833. });
  2834. if (!mLayersWithQueuedFrames.empty()) {
  2835. // mStateLock is needed for latchBuffer as LayerRejecter::reject()
  2836. // writes to Layer current state. See also b/119481871
  2837. Mutex::Autolock lock(mStateLock);
  2838. for (auto& layer : mLayersWithQueuedFrames) {
  2839. if (layer->latchBuffer(visibleRegions, latchTime)) {
  2840. mLayersPendingRefresh.push_back(layer);
  2841. }
  2842. layer->useSurfaceDamage();
  2843. if (layer->isBufferLatched()) {
  2844. newDataLatched = true;
  2845. }
  2846. }
  2847. }
  2848. mVisibleRegionsDirty |= visibleRegions;
  2849. // If we will need to wake up at some time in the future to deal with a
  2850. // queued frame that shouldn't be displayed during this vsync period, wake
  2851. // up during the next vsync period to check again.
  2852. if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
  2853. signalLayerUpdate();
  2854. }
  2855. // enter boot animation on first buffer latch
  2856. if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
  2857. ALOGI("Enter boot animation");
  2858. mBootStage = BootStage::BOOTANIMATION;
  2859. }
  2860. // Only continue with the refresh if there is actually new work to do
  2861. return !mLayersWithQueuedFrames.empty() && newDataLatched;
  2862. }
  2863. void SurfaceFlinger::invalidateHwcGeometry()
  2864. {
  2865. mGeometryInvalid = true;
  2866. }
  2867. void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
  2868. const Region& inDirtyRegion) {
  2869. auto display = displayDevice->getCompositionDisplay();
  2870. // We only need to actually compose the display if:
  2871. // 1) It is being handled by hardware composer, which may need this to
  2872. // keep its virtual display state machine in sync, or
  2873. // 2) There is work to be done (the dirty region isn't empty)
  2874. if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
  2875. ALOGV("Skipping display composition");
  2876. return;
  2877. }
  2878. ALOGV("doDisplayComposition");
  2879. base::unique_fd readyFence;
  2880. if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
  2881. // swap buffers (presentation)
  2882. display->getRenderSurface()->queueBuffer(std::move(readyFence));
  2883. }
  2884. bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
  2885. const Region& debugRegion, base::unique_fd* readyFence) {
  2886. ATRACE_CALL();
  2887. ALOGV("doComposeSurfaces");
  2888. auto display = displayDevice->getCompositionDisplay();
  2889. const auto& displayState = display->getState();
  2890. const auto displayId = display->getId();
  2891. auto& renderEngine = getRenderEngine();
  2892. const bool supportProtectedContent = renderEngine.supportsProtectedContent();
  2893. const Region bounds(displayState.bounds);
  2894. const DisplayRenderArea renderArea(displayDevice);
  2895. const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
  2896. ATRACE_INT("hasClientComposition", hasClientComposition);
  2897. bool applyColorMatrix = false;
  2898. renderengine::DisplaySettings clientCompositionDisplay;
  2899. std::vector<renderengine::LayerSettings> clientCompositionLayers;
  2900. sp<GraphicBuffer> buf;
  2901. base::unique_fd fd;
  2902. if (hasClientComposition) {
  2903. ALOGV("hasClientComposition");
  2904. if (displayDevice->isPrimary() && supportProtectedContent) {
  2905. bool needsProtected = false;
  2906. for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
  2907. // If the layer is a protected layer, mark protected context is needed.
  2908. if (layer->isProtected()) {
  2909. needsProtected = true;
  2910. break;
  2911. }
  2912. }
  2913. if (needsProtected != renderEngine.isProtected()) {
  2914. renderEngine.useProtectedContext(needsProtected);
  2915. }
  2916. if (needsProtected != display->getRenderSurface()->isProtected() &&
  2917. needsProtected == renderEngine.isProtected()) {
  2918. display->getRenderSurface()->setProtected(needsProtected);
  2919. }
  2920. }
  2921. buf = display->getRenderSurface()->dequeueBuffer(&fd);
  2922. if (buf == nullptr) {
  2923. ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
  2924. "client composition for this frame",
  2925. displayDevice->getDisplayName().c_str());
  2926. return false;
  2927. }
  2928. clientCompositionDisplay.physicalDisplay = displayState.scissor;
  2929. clientCompositionDisplay.clip = displayState.scissor;
  2930. const ui::Transform& displayTransform = displayState.transform;
  2931. clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
  2932. clientCompositionDisplay.orientation = displayState.orientation;
  2933. const auto* profile = display->getDisplayColorProfile();
  2934. Dataspace outputDataspace = Dataspace::UNKNOWN;
  2935. if (profile->hasWideColorGamut()) {
  2936. outputDataspace = displayState.dataspace;
  2937. }
  2938. clientCompositionDisplay.outputDataspace = outputDataspace;
  2939. clientCompositionDisplay.maxLuminance =
  2940. profile->getHdrCapabilities().getDesiredMaxLuminance();
  2941. const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
  2942. const bool skipClientColorTransform =
  2943. getHwComposer()
  2944. .hasDisplayCapability(displayId,
  2945. HWC2::DisplayCapability::SkipClientColorTransform);
  2946. // Compute the global color transform matrix.
  2947. applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
  2948. if (applyColorMatrix) {
  2949. clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
  2950. }
  2951. }
  2952. /*
  2953. * and then, render the layers targeted at the framebuffer
  2954. */
  2955. ALOGV("Rendering client layers");
  2956. bool firstLayer = true;
  2957. Region clearRegion = Region::INVALID_REGION;
  2958. for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
  2959. const Region viewportRegion(displayState.viewport);
  2960. const Region clip(viewportRegion.intersect(layer->visibleRegion));
  2961. ALOGV("Layer: %s", layer->getName().string());
  2962. ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
  2963. if (!clip.isEmpty()) {
  2964. switch (layer->getCompositionType(displayDevice)) {
  2965. case Hwc2::IComposerClient::Composition::CURSOR:
  2966. case Hwc2::IComposerClient::Composition::DEVICE:
  2967. case Hwc2::IComposerClient::Composition::SIDEBAND:
  2968. case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
  2969. LOG_ALWAYS_FATAL_IF(!displayId);
  2970. const Layer::State& state(layer->getDrawingState());
  2971. if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
  2972. layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
  2973. layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
  2974. // never clear the very first layer since we're
  2975. // guaranteed the FB is already cleared
  2976. renderengine::LayerSettings layerSettings;
  2977. Region dummyRegion;
  2978. bool prepared =
  2979. layer->prepareClientLayer(renderArea, clip, dummyRegion,
  2980. supportProtectedContent, layerSettings);
  2981. if (prepared) {
  2982. layerSettings.source.buffer.buffer = nullptr;
  2983. layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
  2984. layerSettings.alpha = half(0.0);
  2985. layerSettings.disableBlending = true;
  2986. clientCompositionLayers.push_back(layerSettings);
  2987. }
  2988. }
  2989. break;
  2990. }
  2991. case Hwc2::IComposerClient::Composition::CLIENT: {
  2992. renderengine::LayerSettings layerSettings;
  2993. bool prepared =
  2994. layer->prepareClientLayer(renderArea, clip, clearRegion,
  2995. supportProtectedContent, layerSettings);
  2996. if (prepared) {
  2997. clientCompositionLayers.push_back(layerSettings);
  2998. }
  2999. break;
  3000. }
  3001. default:
  3002. break;
  3003. }
  3004. } else {
  3005. ALOGV(" Skipping for empty clip");
  3006. }
  3007. firstLayer = false;
  3008. }
  3009. // Perform some cleanup steps if we used client composition.
  3010. if (hasClientComposition) {
  3011. clientCompositionDisplay.clearRegion = clearRegion;
  3012. // We boost GPU frequency here because there will be color spaces conversion
  3013. // and it's expensive. We boost the GPU frequency so that GPU composition can
  3014. // finish in time. We must reset GPU frequency afterwards, because high frequency
  3015. // consumes extra battery.
  3016. const bool expensiveRenderingExpected =
  3017. clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
  3018. if (expensiveRenderingExpected && displayId) {
  3019. mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
  3020. }
  3021. if (!debugRegion.isEmpty()) {
  3022. Region::const_iterator it = debugRegion.begin();
  3023. Region::const_iterator end = debugRegion.end();
  3024. while (it != end) {
  3025. const Rect& rect = *it++;
  3026. renderengine::LayerSettings layerSettings;
  3027. layerSettings.source.buffer.buffer = nullptr;
  3028. layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
  3029. layerSettings.geometry.boundaries = rect.toFloatRect();
  3030. layerSettings.alpha = half(1.0);
  3031. clientCompositionLayers.push_back(layerSettings);
  3032. }
  3033. }
  3034. renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
  3035. buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
  3036. readyFence);
  3037. } else if (displayId) {
  3038. mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
  3039. }
  3040. return true;
  3041. }
  3042. void SurfaceFlinger::drawWormhole(const Region& region) const {
  3043. auto& engine(getRenderEngine());
  3044. engine.fillRegionWithColor(region, 0, 0, 0, 0);
  3045. }
  3046. status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
  3047. const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
  3048. const sp<IBinder>& parentHandle,
  3049. const sp<Layer>& parentLayer, bool addToCurrentState) {
  3050. // add this layer to the current state list
  3051. {
  3052. Mutex::Autolock _l(mStateLock);
  3053. sp<Layer> parent;
  3054. if (parentHandle != nullptr) {
  3055. parent = fromHandle(parentHandle);
  3056. if (parent == nullptr) {
  3057. return NAME_NOT_FOUND;
  3058. }
  3059. } else {
  3060. parent = parentLayer;
  3061. }
  3062. if (mNumLayers >= MAX_LAYERS) {
  3063. ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
  3064. MAX_LAYERS);
  3065. return NO_MEMORY;
  3066. }
  3067. mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
  3068. if (parent == nullptr && addToCurrentState) {
  3069. mCurrentState.layersSortedByZ.add(lbc);
  3070. } else if (parent == nullptr) {
  3071. lbc->onRemovedFromCurrentState();
  3072. } else if (parent->isRemovedFromCurrentState()) {
  3073. parent->addChild(lbc);
  3074. lbc->onRemovedFromCurrentState();
  3075. } else {
  3076. parent->addChild(lbc);
  3077. }
  3078. if (gbc != nullptr) {
  3079. mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
  3080. LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
  3081. mMaxGraphicBufferProducerListSize,
  3082. "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
  3083. mGraphicBufferProducerList.size(),
  3084. mMaxGraphicBufferProducerListSize, mNumLayers);
  3085. }
  3086. mLayersAdded = true;
  3087. }
  3088. // attach this layer to the client
  3089. client->attachLayer(handle, lbc);
  3090. return NO_ERROR;
  3091. }
  3092. uint32_t SurfaceFlinger::peekTransactionFlags() {
  3093. return mTransactionFlags;
  3094. }
  3095. uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
  3096. return mTransactionFlags.fetch_and(~flags) & flags;
  3097. }
  3098. uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
  3099. return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
  3100. }
  3101. uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
  3102. Scheduler::TransactionStart transactionStart) {
  3103. uint32_t old = mTransactionFlags.fetch_or(flags);
  3104. mVsyncModulator.setTransactionStart(transactionStart);
  3105. if ((old & flags)==0) { // wake the server up
  3106. signalTransaction();
  3107. }
  3108. return old;
  3109. }
  3110. bool SurfaceFlinger::flushTransactionQueues() {
  3111. // to prevent onHandleDestroyed from being called while the lock is held,
  3112. // we must keep a copy of the transactions (specifically the composer
  3113. // states) around outside the scope of the lock
  3114. std::vector<const TransactionState> transactions;
  3115. bool flushedATransaction = false;
  3116. {
  3117. Mutex::Autolock _l(mStateLock);
  3118. auto it = mTransactionQueues.begin();
  3119. while (it != mTransactionQueues.end()) {
  3120. auto& [applyToken, transactionQueue] = *it;
  3121. while (!transactionQueue.empty()) {
  3122. const auto& transaction = transactionQueue.front();
  3123. if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
  3124. transaction.states)) {
  3125. setTransactionFlags(eTransactionFlushNeeded);
  3126. break;
  3127. }
  3128. transactions.push_back(transaction);
  3129. applyTransactionState(transaction.states, transaction.displays, transaction.flags,
  3130. mPendingInputWindowCommands, transaction.desiredPresentTime,
  3131. transaction.buffer, transaction.callback,
  3132. transaction.postTime, transaction.privileged,
  3133. /*isMainThread*/ true);
  3134. transactionQueue.pop();
  3135. flushedATransaction = true;
  3136. }
  3137. if (transactionQueue.empty()) {
  3138. it = mTransactionQueues.erase(it);
  3139. mTransactionCV.broadcast();
  3140. } else {
  3141. it = std::next(it, 1);
  3142. }
  3143. }
  3144. }
  3145. return flushedATransaction;
  3146. }
  3147. bool SurfaceFlinger::transactionFlushNeeded() {
  3148. return !mTransactionQueues.empty();
  3149. }
  3150. bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
  3151. for (const ComposerState& state : states) {
  3152. // Here we need to check that the interface we're given is indeed
  3153. // one of our own. A malicious client could give us a nullptr
  3154. // IInterface, or one of its own or even one of our own but a
  3155. // different type. All these situations would cause us to crash.
  3156. if (state.client == nullptr) {
  3157. return true;
  3158. }
  3159. sp<IBinder> binder = IInterface::asBinder(state.client);
  3160. if (binder == nullptr) {
  3161. return true;
  3162. }
  3163. if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
  3164. return true;
  3165. }
  3166. }
  3167. return false;
  3168. }
  3169. bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
  3170. const Vector<ComposerState>& states) {
  3171. nsecs_t expectedPresentTime = getExpectedPresentTime();
  3172. // Do not present if the desiredPresentTime has not passed unless it is more than one second
  3173. // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
  3174. if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
  3175. desiredPresentTime < expectedPresentTime + s2ns(1)) {
  3176. return false;
  3177. }
  3178. for (const ComposerState& state : states) {
  3179. const layer_state_t& s = state.state;
  3180. if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
  3181. continue;
  3182. }
  3183. if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
  3184. return false;
  3185. }
  3186. }
  3187. return true;
  3188. }
  3189. void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
  3190. const Vector<DisplayState>& displays, uint32_t flags,
  3191. const sp<IBinder>& applyToken,
  3192. const InputWindowCommands& inputWindowCommands,
  3193. int64_t desiredPresentTime,
  3194. const client_cache_t& uncacheBuffer,
  3195. const std::vector<ListenerCallbacks>& listenerCallbacks) {
  3196. ATRACE_CALL();
  3197. const int64_t postTime = systemTime();
  3198. bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
  3199. Mutex::Autolock _l(mStateLock);
  3200. if (containsAnyInvalidClientState(states)) {
  3201. return;
  3202. }
  3203. // If its TransactionQueue already has a pending TransactionState or if it is pending
  3204. auto itr = mTransactionQueues.find(applyToken);
  3205. // if this is an animation frame, wait until prior animation frame has
  3206. // been applied by SF
  3207. if (flags & eAnimation) {
  3208. while (itr != mTransactionQueues.end()) {
  3209. status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
  3210. if (CC_UNLIKELY(err != NO_ERROR)) {
  3211. ALOGW_IF(err == TIMED_OUT,
  3212. "setTransactionState timed out "
  3213. "waiting for animation frame to apply");
  3214. break;
  3215. }
  3216. itr = mTransactionQueues.find(applyToken);
  3217. }
  3218. }
  3219. if (itr != mTransactionQueues.end() ||
  3220. !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
  3221. mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
  3222. uncacheBuffer, listenerCallbacks, postTime,
  3223. privileged);
  3224. setTransactionFlags(eTransactionFlushNeeded);
  3225. return;
  3226. }
  3227. applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
  3228. uncacheBuffer, listenerCallbacks, postTime, privileged);
  3229. }
  3230. void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
  3231. const Vector<DisplayState>& displays, uint32_t flags,
  3232. const InputWindowCommands& inputWindowCommands,
  3233. const int64_t desiredPresentTime,
  3234. const client_cache_t& uncacheBuffer,
  3235. const std::vector<ListenerCallbacks>& listenerCallbacks,
  3236. const int64_t postTime, bool privileged,
  3237. bool isMainThread) {
  3238. uint32_t transactionFlags = 0;
  3239. if (flags & eAnimation) {
  3240. // For window updates that are part of an animation we must wait for
  3241. // previous animation "frames" to be handled.
  3242. while (!isMainThread && mAnimTransactionPending) {
  3243. status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
  3244. if (CC_UNLIKELY(err != NO_ERROR)) {
  3245. // just in case something goes wrong in SF, return to the
  3246. // caller after a few seconds.
  3247. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
  3248. "waiting for previous animation frame");
  3249. mAnimTransactionPending = false;
  3250. break;
  3251. }
  3252. }
  3253. }
  3254. for (const DisplayState& display : displays) {
  3255. transactionFlags |= setDisplayStateLocked(display);
  3256. }
  3257. // In case the client has sent a Transaction that should receive callbacks but without any
  3258. // SurfaceControls that should be included in the callback, send the listener and callbackIds
  3259. // to the callback thread so it can send an empty callback
  3260. if (!listenerCallbacks.empty()) {
  3261. mTransactionCompletedThread.run();
  3262. }
  3263. for (const auto& [listener, callbackIds] : listenerCallbacks) {
  3264. mTransactionCompletedThread.addCallback(listener, callbackIds);
  3265. }
  3266. uint32_t clientStateFlags = 0;
  3267. for (const ComposerState& state : states) {
  3268. clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
  3269. postTime, privileged);
  3270. }
  3271. // If the state doesn't require a traversal and there are callbacks, send them now
  3272. if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
  3273. mTransactionCompletedThread.sendCallbacks();
  3274. }
  3275. transactionFlags |= clientStateFlags;
  3276. transactionFlags |= addInputWindowCommands(inputWindowCommands);
  3277. if (uncacheBuffer.isValid()) {
  3278. ClientCache::getInstance().erase(uncacheBuffer);
  3279. getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
  3280. }
  3281. // If a synchronous transaction is explicitly requested without any changes, force a transaction
  3282. // anyway. This can be used as a flush mechanism for previous async transactions.
  3283. // Empty animation transaction can be used to simulate back-pressure, so also force a
  3284. // transaction for empty animation transactions.
  3285. if (transactionFlags == 0 &&
  3286. ((flags & eSynchronous) || (flags & eAnimation))) {
  3287. transactionFlags = eTransactionNeeded;
  3288. }
  3289. // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
  3290. // so we don't have to wake up again next frame to preform an uneeded traversal.
  3291. if (isMainThread && (transactionFlags & eTraversalNeeded)) {
  3292. transactionFlags = transactionFlags & (~eTraversalNeeded);
  3293. mTraversalNeededMainThread = true;
  3294. }
  3295. if (transactionFlags) {
  3296. if (mInterceptor->isEnabled()) {
  3297. mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
  3298. }
  3299. // this triggers the transaction
  3300. const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
  3301. : Scheduler::TransactionStart::NORMAL;
  3302. setTransactionFlags(transactionFlags, start);
  3303. // if this is a synchronous transaction, wait for it to take effect
  3304. // before returning.
  3305. if (flags & eSynchronous) {
  3306. mTransactionPending = true;
  3307. }
  3308. if (flags & eAnimation) {
  3309. mAnimTransactionPending = true;
  3310. }
  3311. if (mPendingInputWindowCommands.syncInputWindows) {
  3312. mPendingSyncInputWindows = true;
  3313. }
  3314. // applyTransactionState can be called by either the main SF thread or by
  3315. // another process through setTransactionState. While a given process may wish
  3316. // to wait on synchronous transactions, the main SF thread should never
  3317. // be blocked. Therefore, we only wait if isMainThread is false.
  3318. while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
  3319. status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
  3320. if (CC_UNLIKELY(err != NO_ERROR)) {
  3321. // just in case something goes wrong in SF, return to the
  3322. // called after a few seconds.
  3323. ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
  3324. mTransactionPending = false;
  3325. mPendingSyncInputWindows = false;
  3326. break;
  3327. }
  3328. }
  3329. }
  3330. }
  3331. uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
  3332. const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
  3333. if (index < 0) return 0;
  3334. uint32_t flags = 0;
  3335. DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
  3336. const uint32_t what = s.what;
  3337. if (what & DisplayState::eSurfaceChanged) {
  3338. if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
  3339. state.surface = s.surface;
  3340. flags |= eDisplayTransactionNeeded;
  3341. }
  3342. }
  3343. if (what & DisplayState::eLayerStackChanged) {
  3344. if (state.layerStack != s.layerStack) {
  3345. state.layerStack = s.layerStack;
  3346. flags |= eDisplayTransactionNeeded;
  3347. }
  3348. }
  3349. if (what & DisplayState::eDisplayProjectionChanged) {
  3350. if (state.orientation != s.orientation) {
  3351. state.orientation = s.orientation;
  3352. flags |= eDisplayTransactionNeeded;
  3353. }
  3354. if (state.frame != s.frame) {
  3355. state.frame = s.frame;
  3356. flags |= eDisplayTransactionNeeded;
  3357. }
  3358. if (state.viewport != s.viewport) {
  3359. state.viewport = s.viewport;
  3360. flags |= eDisplayTransactionNeeded;
  3361. }
  3362. }
  3363. if (what & DisplayState::eDisplaySizeChanged) {
  3364. if (state.width != s.width) {
  3365. state.width = s.width;
  3366. flags |= eDisplayTransactionNeeded;
  3367. }
  3368. if (state.height != s.height) {
  3369. state.height = s.height;
  3370. flags |= eDisplayTransactionNeeded;
  3371. }
  3372. }
  3373. return flags;
  3374. }
  3375. bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
  3376. IPCThreadState* ipc = IPCThreadState::self();
  3377. const int pid = ipc->getCallingPid();
  3378. const int uid = ipc->getCallingUid();
  3379. if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
  3380. !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
  3381. return false;
  3382. }
  3383. return true;
  3384. }
  3385. uint32_t SurfaceFlinger::setClientStateLocked(
  3386. const ComposerState& composerState, int64_t desiredPresentTime,
  3387. const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
  3388. bool privileged) {
  3389. const layer_state_t& s = composerState.state;
  3390. sp<Client> client(static_cast<Client*>(composerState.client.get()));
  3391. sp<Layer> layer(client->getLayerUser(s.surface));
  3392. if (layer == nullptr) {
  3393. return 0;
  3394. }
  3395. uint32_t flags = 0;
  3396. const uint64_t what = s.what;
  3397. bool geometryAppliesWithResize =
  3398. what & layer_state_t::eGeometryAppliesWithResize;
  3399. // If we are deferring transaction, make sure to push the pending state, as otherwise the
  3400. // pending state will also be deferred.
  3401. if (what & layer_state_t::eDeferTransaction_legacy) {
  3402. layer->pushPendingState();
  3403. }
  3404. if (what & layer_state_t::ePositionChanged) {
  3405. if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
  3406. flags |= eTraversalNeeded;
  3407. }
  3408. }
  3409. if (what & layer_state_t::eLayerChanged) {
  3410. // NOTE: index needs to be calculated before we update the state
  3411. const auto& p = layer->getParent();
  3412. if (p == nullptr) {
  3413. ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
  3414. if (layer->setLayer(s.z) && idx >= 0) {
  3415. mCurrentState.layersSortedByZ.removeAt(idx);
  3416. mCurrentState.layersSortedByZ.add(layer);
  3417. // we need traversal (state changed)
  3418. // AND transaction (list changed)
  3419. flags |= eTransactionNeeded|eTraversalNeeded;
  3420. }
  3421. } else {
  3422. if (p->setChildLayer(layer, s.z)) {
  3423. flags |= eTransactionNeeded|eTraversalNeeded;
  3424. }
  3425. }
  3426. }
  3427. if (what & layer_state_t::eRelativeLayerChanged) {
  3428. // NOTE: index needs to be calculated before we update the state
  3429. const auto& p = layer->getParent();
  3430. if (p == nullptr) {
  3431. ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
  3432. if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
  3433. mCurrentState.layersSortedByZ.removeAt(idx);
  3434. mCurrentState.layersSortedByZ.add(layer);
  3435. // we need traversal (state changed)
  3436. // AND transaction (list changed)
  3437. flags |= eTransactionNeeded|eTraversalNeeded;
  3438. }
  3439. } else {
  3440. if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
  3441. flags |= eTransactionNeeded|eTraversalNeeded;
  3442. }
  3443. }
  3444. }
  3445. if (what & layer_state_t::eSizeChanged) {
  3446. if (layer->setSize(s.w, s.h)) {
  3447. flags |= eTraversalNeeded;
  3448. }
  3449. }
  3450. if (what & layer_state_t::eAlphaChanged) {
  3451. if (layer->setAlpha(s.alpha))
  3452. flags |= eTraversalNeeded;
  3453. }
  3454. if (what & layer_state_t::eColorChanged) {
  3455. if (layer->setColor(s.color))
  3456. flags |= eTraversalNeeded;
  3457. }
  3458. if (what & layer_state_t::eColorTransformChanged) {
  3459. if (layer->setColorTransform(s.colorTransform)) {
  3460. flags |= eTraversalNeeded;
  3461. }
  3462. }
  3463. if (what & layer_state_t::eBackgroundColorChanged) {
  3464. if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
  3465. flags |= eTraversalNeeded;
  3466. }
  3467. }
  3468. if (what & layer_state_t::eMatrixChanged) {
  3469. // TODO: b/109894387
  3470. //
  3471. // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
  3472. // rotation. To see the problem observe that if we have a square parent, and a child
  3473. // of the same size, then we rotate the child 45 degrees around it's center, the child
  3474. // must now be cropped to a non rectangular 8 sided region.
  3475. //
  3476. // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
  3477. // private API, and the WindowManager only uses rotation in one case, which is on a top
  3478. // level layer in which cropping is not an issue.
  3479. //
  3480. // However given that abuse of rotation matrices could lead to surfaces extending outside
  3481. // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
  3482. // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
  3483. // transformations.
  3484. if (layer->setMatrix(s.matrix, privileged))
  3485. flags |= eTraversalNeeded;
  3486. }
  3487. if (what & layer_state_t::eTransparentRegionChanged) {
  3488. if (layer->setTransparentRegionHint(s.transparentRegion))
  3489. flags |= eTraversalNeeded;
  3490. }
  3491. if (what & layer_state_t::eFlagsChanged) {
  3492. if (layer->setFlags(s.flags, s.mask))
  3493. flags |= eTraversalNeeded;
  3494. }
  3495. if (what & layer_state_t::eCropChanged_legacy) {
  3496. if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
  3497. flags |= eTraversalNeeded;
  3498. }
  3499. if (what & layer_state_t::eCornerRadiusChanged) {
  3500. if (layer->setCornerRadius(s.cornerRadius))
  3501. flags |= eTraversalNeeded;
  3502. }
  3503. if (what & layer_state_t::eLayerStackChanged) {
  3504. ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
  3505. // We only allow setting layer stacks for top level layers,
  3506. // everything else inherits layer stack from its parent.
  3507. if (layer->hasParent()) {
  3508. ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
  3509. layer->getName().string());
  3510. } else if (idx < 0) {
  3511. ALOGE("Attempt to set layer stack on layer without parent (%s) that "
  3512. "that also does not appear in the top level layer list. Something"
  3513. " has gone wrong.", layer->getName().string());
  3514. } else if (layer->setLayerStack(s.layerStack)) {
  3515. mCurrentState.layersSortedByZ.removeAt(idx);
  3516. mCurrentState.layersSortedByZ.add(layer);
  3517. // we need traversal (state changed)
  3518. // AND transaction (list changed)
  3519. flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
  3520. }
  3521. }
  3522. if (what & layer_state_t::eDeferTransaction_legacy) {
  3523. if (s.barrierHandle_legacy != nullptr) {
  3524. layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
  3525. } else if (s.barrierGbp_legacy != nullptr) {
  3526. const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
  3527. if (authenticateSurfaceTextureLocked(gbp)) {
  3528. const auto& otherLayer =
  3529. (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
  3530. layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
  3531. } else {
  3532. ALOGE("Attempt to defer transaction to to an"
  3533. " unrecognized GraphicBufferProducer");
  3534. }
  3535. }
  3536. // We don't trigger a traversal here because if no other state is
  3537. // changed, we don't want this to cause any more work
  3538. }
  3539. if (what & layer_state_t::eReparent) {
  3540. bool hadParent = layer->hasParent();
  3541. if (layer->reparent(s.parentHandleForChild)) {
  3542. if (!hadParent) {
  3543. mCurrentState.layersSortedByZ.remove(layer);
  3544. }
  3545. flags |= eTransactionNeeded|eTraversalNeeded;
  3546. }
  3547. }
  3548. if (what & layer_state_t::eReparentChildren) {
  3549. if (layer->reparentChildren(s.reparentHandle)) {
  3550. flags |= eTransactionNeeded|eTraversalNeeded;
  3551. }
  3552. }
  3553. if (what & layer_state_t::eDetachChildren) {
  3554. layer->detachChildren();
  3555. }
  3556. if (what & layer_state_t::eOverrideScalingModeChanged) {
  3557. layer->setOverrideScalingMode(s.overrideScalingMode);
  3558. // We don't trigger a traversal here because if no other state is
  3559. // changed, we don't want this to cause any more work
  3560. }
  3561. if (what & layer_state_t::eTransformChanged) {
  3562. if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
  3563. }
  3564. if (what & layer_state_t::eTransformToDisplayInverseChanged) {
  3565. if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
  3566. flags |= eTraversalNeeded;
  3567. }
  3568. if (what & layer_state_t::eCropChanged) {
  3569. if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
  3570. }
  3571. if (what & layer_state_t::eFrameChanged) {
  3572. if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
  3573. }
  3574. if (what & layer_state_t::eAcquireFenceChanged) {
  3575. if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
  3576. }
  3577. if (what & layer_state_t::eDataspaceChanged) {
  3578. if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
  3579. }
  3580. if (what & layer_state_t::eHdrMetadataChanged) {
  3581. if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
  3582. }
  3583. if (what & layer_state_t::eSurfaceDamageRegionChanged) {
  3584. if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
  3585. }
  3586. if (what & layer_state_t::eApiChanged) {
  3587. if (layer->setApi(s.api)) flags |= eTraversalNeeded;
  3588. }
  3589. if (what & layer_state_t::eSidebandStreamChanged) {
  3590. if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
  3591. }
  3592. if (what & layer_state_t::eInputInfoChanged) {
  3593. if (privileged) {
  3594. layer->setInputInfo(s.inputInfo);
  3595. flags |= eTraversalNeeded;
  3596. } else {
  3597. ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
  3598. }
  3599. }
  3600. if (what & layer_state_t::eMetadataChanged) {
  3601. if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
  3602. }
  3603. if (what & layer_state_t::eColorSpaceAgnosticChanged) {
  3604. if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
  3605. flags |= eTraversalNeeded;
  3606. }
  3607. }
  3608. std::vector<sp<CallbackHandle>> callbackHandles;
  3609. if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
  3610. for (const auto& [listener, callbackIds] : listenerCallbacks) {
  3611. callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
  3612. }
  3613. }
  3614. bool bufferChanged = what & layer_state_t::eBufferChanged;
  3615. bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
  3616. sp<GraphicBuffer> buffer;
  3617. if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
  3618. buffer = s.buffer;
  3619. bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
  3620. if (success) {
  3621. getRenderEngine().cacheExternalTextureBuffer(s.buffer);
  3622. success = ClientCache::getInstance()
  3623. .registerErasedRecipient(s.cachedBuffer,
  3624. wp<ClientCache::ErasedRecipient>(this));
  3625. if (!success) {
  3626. getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
  3627. }
  3628. }
  3629. } else if (cacheIdChanged) {
  3630. buffer = ClientCache::getInstance().get(s.cachedBuffer);
  3631. } else if (bufferChanged) {
  3632. buffer = s.buffer;
  3633. }
  3634. if (buffer) {
  3635. if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
  3636. flags |= eTraversalNeeded;
  3637. }
  3638. }
  3639. if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
  3640. // Do not put anything that updates layer state or modifies flags after
  3641. // setTransactionCompletedListener
  3642. return flags;
  3643. }
  3644. uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
  3645. uint32_t flags = 0;
  3646. if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
  3647. flags |= eTraversalNeeded;
  3648. }
  3649. if (inputWindowCommands.syncInputWindows) {
  3650. flags |= eTraversalNeeded;
  3651. }
  3652. mPendingInputWindowCommands.merge(inputWindowCommands);
  3653. return flags;
  3654. }
  3655. status_t SurfaceFlinger::createLayer(const String8& name, const String8& systemname, const sp<Client>& client, uint32_t w,
  3656. uint32_t h, PixelFormat format, uint32_t flags,
  3657. LayerMetadata metadata, sp<IBinder>* handle,
  3658. sp<IGraphicBufferProducer>* gbp,
  3659. const sp<IBinder>& parentHandle,
  3660. const sp<Layer>& parentLayer) {
  3661. if (int32_t(w|h) < 0) {
  3662. ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
  3663. int(w), int(h));
  3664. return BAD_VALUE;
  3665. }
  3666. ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
  3667. "Expected only one of parentLayer or parentHandle to be non-null. "
  3668. "Programmer error?");
  3669. status_t result = NO_ERROR;
  3670. sp<Layer> layer;
  3671. String8 uniqueName = getUniqueLayerName(name);
  3672. bool primaryDisplayOnly = false;
  3673. // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
  3674. // TODO b/64227542
  3675. if (metadata.has(METADATA_WINDOW_TYPE)) {
  3676. int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
  3677. if (windowType == 441731) {
  3678. metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
  3679. primaryDisplayOnly = true;
  3680. }
  3681. }
  3682. switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
  3683. case ISurfaceComposerClient::eFXSurfaceBufferQueue:
  3684. result = createBufferQueueLayer(client, uniqueName, systemname, w, h, flags, std::move(metadata),
  3685. format, handle, gbp, &layer);
  3686. break;
  3687. case ISurfaceComposerClient::eFXSurfaceBufferState:
  3688. result = createBufferStateLayer(client, uniqueName, systemname, w, h, flags, std::move(metadata),
  3689. handle, &layer);
  3690. break;
  3691. case ISurfaceComposerClient::eFXSurfaceColor:
  3692. // check if buffer size is set for color layer.
  3693. if (w > 0 || h > 0) {
  3694. ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
  3695. int(w), int(h));
  3696. return BAD_VALUE;
  3697. }
  3698. result = createColorLayer(client, uniqueName, systemname, w, h, flags, std::move(metadata), handle,
  3699. &layer);
  3700. break;
  3701. case ISurfaceComposerClient::eFXSurfaceContainer:
  3702. // check if buffer size is set for container layer.
  3703. if (w > 0 || h > 0) {
  3704. ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
  3705. int(w), int(h));
  3706. return BAD_VALUE;
  3707. }
  3708. result = createContainerLayer(client, uniqueName, systemname, w, h, flags, std::move(metadata),
  3709. handle, &layer);
  3710. break;
  3711. default:
  3712. result = BAD_VALUE;
  3713. break;
  3714. }
  3715. if (result != NO_ERROR) {
  3716. return result;
  3717. }
  3718. if (primaryDisplayOnly) {
  3719. layer->setPrimaryDisplayOnly();
  3720. }
  3721. bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
  3722. result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
  3723. addToCurrentState);
  3724. if (result != NO_ERROR) {
  3725. return result;
  3726. }
  3727. mInterceptor->saveSurfaceCreation(layer);
  3728. setTransactionFlags(eTransactionNeeded);
  3729. return result;
  3730. }
  3731. String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
  3732. {
  3733. bool matchFound = true;
  3734. uint32_t dupeCounter = 0;
  3735. // Tack on our counter whether there is a hit or not, so everyone gets a tag
  3736. String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
  3737. // Grab the state lock since we're accessing mCurrentState
  3738. Mutex::Autolock lock(mStateLock);
  3739. // Loop over layers until we're sure there is no matching name
  3740. while (matchFound) {
  3741. matchFound = false;
  3742. mCurrentState.traverseInZOrder([&](Layer* layer) {
  3743. if (layer->getName() == uniqueName) {
  3744. matchFound = true;
  3745. uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
  3746. }
  3747. });
  3748. }
  3749. ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
  3750. uniqueName.c_str());
  3751. return uniqueName;
  3752. }
  3753. status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name, const String8& systemname,
  3754. uint32_t w, uint32_t h, uint32_t flags,
  3755. LayerMetadata metadata, PixelFormat& format,
  3756. sp<IBinder>* handle,
  3757. sp<IGraphicBufferProducer>* gbp,
  3758. sp<Layer>* outLayer) {
  3759. // initialize the surfaces
  3760. switch (format) {
  3761. case PIXEL_FORMAT_TRANSPARENT:
  3762. case PIXEL_FORMAT_TRANSLUCENT:
  3763. format = PIXEL_FORMAT_RGBA_8888;
  3764. break;
  3765. case PIXEL_FORMAT_OPAQUE:
  3766. format = PIXEL_FORMAT_RGBX_8888;
  3767. break;
  3768. }
  3769. sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
  3770. LayerCreationArgs(this, client, name, systemname, w, h, flags, std::move(metadata)));
  3771. status_t err = layer->setDefaultBufferProperties(w, h, format);
  3772. if (err == NO_ERROR) {
  3773. *handle = layer->getHandle();
  3774. *gbp = layer->getProducer();
  3775. *outLayer = layer;
  3776. }
  3777. ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
  3778. return err;
  3779. }
  3780. status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name, const String8& systemname,
  3781. uint32_t w, uint32_t h, uint32_t flags,
  3782. LayerMetadata metadata, sp<IBinder>* handle,
  3783. sp<Layer>* outLayer) {
  3784. sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
  3785. LayerCreationArgs(this, client, name, systemname, w, h, flags, std::move(metadata)));
  3786. *handle = layer->getHandle();
  3787. *outLayer = layer;
  3788. return NO_ERROR;
  3789. }
  3790. status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, const String8& systemname, uint32_t w,
  3791. uint32_t h, uint32_t flags, LayerMetadata metadata,
  3792. sp<IBinder>* handle, sp<Layer>* outLayer) {
  3793. *outLayer = getFactory().createColorLayer(
  3794. LayerCreationArgs(this, client, name, systemname, w, h, flags, std::move(metadata)));
  3795. *handle = (*outLayer)->getHandle();
  3796. return NO_ERROR;
  3797. }
  3798. status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name, const String8& systemname,
  3799. uint32_t w, uint32_t h, uint32_t flags,
  3800. LayerMetadata metadata, sp<IBinder>* handle,
  3801. sp<Layer>* outLayer) {
  3802. *outLayer = getFactory().createContainerLayer(
  3803. LayerCreationArgs(this, client, name, systemname, w, h, flags, std::move(metadata)));
  3804. *handle = (*outLayer)->getHandle();
  3805. return NO_ERROR;
  3806. }
  3807. void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
  3808. mLayersPendingRemoval.add(layer);
  3809. mLayersRemoved = true;
  3810. setTransactionFlags(eTransactionNeeded);
  3811. }
  3812. void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
  3813. {
  3814. Mutex::Autolock lock(mStateLock);
  3815. // If a layer has a parent, we allow it to out-live it's handle
  3816. // with the idea that the parent holds a reference and will eventually
  3817. // be cleaned up. However no one cleans up the top-level so we do so
  3818. // here.
  3819. if (layer->getParent() == nullptr) {
  3820. mCurrentState.layersSortedByZ.remove(layer);
  3821. }
  3822. markLayerPendingRemovalLocked(layer);
  3823. auto it = mLayersByLocalBinderToken.begin();
  3824. while (it != mLayersByLocalBinderToken.end()) {
  3825. if (it->second == layer) {
  3826. it = mLayersByLocalBinderToken.erase(it);
  3827. } else {
  3828. it++;
  3829. }
  3830. }
  3831. layer.clear();
  3832. }
  3833. // ---------------------------------------------------------------------------
  3834. void SurfaceFlinger::onInitializeDisplays() {
  3835. const auto display = getDefaultDisplayDeviceLocked();
  3836. if (!display) return;
  3837. const sp<IBinder> token = display->getDisplayToken().promote();
  3838. LOG_ALWAYS_FATAL_IF(token == nullptr);
  3839. // reset screen orientation and use primary layer stack
  3840. Vector<ComposerState> state;
  3841. Vector<DisplayState> displays;
  3842. DisplayState d;
  3843. d.what = DisplayState::eDisplayProjectionChanged |
  3844. DisplayState::eLayerStackChanged;
  3845. d.token = token;
  3846. d.layerStack = 0;
  3847. d.orientation = DisplayState::eOrientationDefault;
  3848. d.frame.makeInvalid();
  3849. d.viewport.makeInvalid();
  3850. d.width = 0;
  3851. d.height = 0;
  3852. displays.add(d);
  3853. setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
  3854. setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
  3855. const nsecs_t vsyncPeriod = getVsyncPeriod();
  3856. mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
  3857. // Use phase of 0 since phase is not known.
  3858. // Use latency of 0, which will snap to the ideal latency.
  3859. DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
  3860. setCompositorTimingSnapped(stats, 0);
  3861. }
  3862. void SurfaceFlinger::initializeDisplays() {
  3863. // Async since we may be called from the main thread.
  3864. postMessageAsync(
  3865. new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
  3866. }
  3867. void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
  3868. if (mHWCVsyncState != enabled) {
  3869. getHwComposer().setVsyncEnabled(displayId, enabled);
  3870. mHWCVsyncState = enabled;
  3871. }
  3872. }
  3873. void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
  3874. if (display->isVirtual()) {
  3875. ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
  3876. return;
  3877. }
  3878. const auto displayId = display->getId();
  3879. LOG_ALWAYS_FATAL_IF(!displayId);
  3880. ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
  3881. int currentMode = display->getPowerMode();
  3882. if (mode == currentMode) {
  3883. return;
  3884. }
  3885. display->setPowerMode(mode);
  3886. if (mInterceptor->isEnabled()) {
  3887. mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
  3888. }
  3889. if (currentMode == HWC_POWER_MODE_OFF) {
  3890. // Turn on the display
  3891. getHwComposer().setPowerMode(*displayId, mode);
  3892. if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
  3893. setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
  3894. mScheduler->onScreenAcquired(mAppConnectionHandle);
  3895. mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
  3896. }
  3897. mVisibleRegionsDirty = true;
  3898. mHasPoweredOff = true;
  3899. repaintEverything();
  3900. struct sched_param param = {0};
  3901. param.sched_priority = 1;
  3902. if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
  3903. ALOGW("Couldn't set SCHED_FIFO on display on");
  3904. }
  3905. } else if (mode == HWC_POWER_MODE_OFF) {
  3906. // Turn off the display
  3907. struct sched_param param = {0};
  3908. if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
  3909. ALOGW("Couldn't set SCHED_OTHER on display off");
  3910. }
  3911. if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
  3912. mScheduler->disableHardwareVsync(true);
  3913. mScheduler->onScreenReleased(mAppConnectionHandle);
  3914. }
  3915. // Make sure HWVsync is disabled before turning off the display
  3916. setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
  3917. getHwComposer().setPowerMode(*displayId, mode);
  3918. mVisibleRegionsDirty = true;
  3919. // from this point on, SF will stop drawing on this display
  3920. } else if (mode == HWC_POWER_MODE_DOZE ||
  3921. mode == HWC_POWER_MODE_NORMAL) {
  3922. // Update display while dozing
  3923. getHwComposer().setPowerMode(*displayId, mode);
  3924. if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
  3925. mScheduler->onScreenAcquired(mAppConnectionHandle);
  3926. mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
  3927. }
  3928. } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
  3929. // Leave display going to doze
  3930. if (display->isPrimary()) {
  3931. mScheduler->disableHardwareVsync(true);
  3932. mScheduler->onScreenReleased(mAppConnectionHandle);
  3933. }
  3934. getHwComposer().setPowerMode(*displayId, mode);
  3935. } else {
  3936. ALOGE("Attempting to set unknown power mode: %d\n", mode);
  3937. getHwComposer().setPowerMode(*displayId, mode);
  3938. }
  3939. if (display->isPrimary()) {
  3940. mTimeStats->setPowerMode(mode);
  3941. mRefreshRateStats.setPowerMode(mode);
  3942. mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
  3943. }
  3944. ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
  3945. }
  3946. void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
  3947. postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
  3948. const auto display = getDisplayDevice(displayToken);
  3949. if (!display) {
  3950. ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
  3951. displayToken.get());
  3952. } else if (display->isVirtual()) {
  3953. ALOGW("Attempt to set power mode %d for virtual display", mode);
  3954. } else {
  3955. setPowerModeInternal(display, mode);
  3956. }
  3957. }));
  3958. }
  3959. // ---------------------------------------------------------------------------
  3960. status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
  3961. bool asProto) NO_THREAD_SAFETY_ANALYSIS {
  3962. std::string result;
  3963. IPCThreadState* ipc = IPCThreadState::self();
  3964. const int pid = ipc->getCallingPid();
  3965. const int uid = ipc->getCallingUid();
  3966. if ((uid != AID_SHELL) &&
  3967. !PermissionCache::checkPermission(sDump, pid, uid)) {
  3968. StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
  3969. pid, uid);
  3970. } else {
  3971. // Try to get the main lock, but give up after one second
  3972. // (this would indicate SF is stuck, but we want to be able to
  3973. // print something in dumpsys).
  3974. status_t err = mStateLock.timedLock(s2ns(1));
  3975. bool locked = (err == NO_ERROR);
  3976. if (!locked) {
  3977. StringAppendF(&result,
  3978. "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
  3979. "(no locks held)\n",
  3980. strerror(-err), err);
  3981. }
  3982. using namespace std::string_literals;
  3983. static const std::unordered_map<std::string, Dumper> dumpers = {
  3984. {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
  3985. {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
  3986. {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
  3987. {"--dispsync"s, dumper([this](std::string& s) {
  3988. mScheduler->dumpPrimaryDispSync(s);
  3989. })},
  3990. {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
  3991. {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
  3992. {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
  3993. {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
  3994. {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
  3995. {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
  3996. {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
  3997. {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
  3998. {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
  3999. {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
  4000. };
  4001. const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
  4002. if (const auto it = dumpers.find(flag); it != dumpers.end()) {
  4003. (it->second)(args, asProto, result);
  4004. } else {
  4005. if (asProto) {
  4006. LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
  4007. result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
  4008. } else {
  4009. dumpAllLocked(args, result);
  4010. }
  4011. }
  4012. if (locked) {
  4013. mStateLock.unlock();
  4014. }
  4015. }
  4016. write(fd, result.c_str(), result.size());
  4017. return NO_ERROR;
  4018. }
  4019. status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
  4020. if (asProto && mTracing.isEnabled()) {
  4021. mTracing.writeToFileAsync();
  4022. }
  4023. return doDump(fd, DumpArgs(), asProto);
  4024. }
  4025. void SurfaceFlinger::listLayersLocked(std::string& result) const {
  4026. mCurrentState.traverseInZOrder(
  4027. [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
  4028. }
  4029. void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
  4030. StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
  4031. if (args.size() > 1) {
  4032. const auto name = String8(args[1]);
  4033. mCurrentState.traverseInZOrder([&](Layer* layer) {
  4034. if (name == layer->getName()) {
  4035. layer->dumpFrameStats(result);
  4036. }
  4037. });
  4038. } else {
  4039. mAnimFrameTracker.dumpStats(result);
  4040. }
  4041. }
  4042. void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
  4043. mCurrentState.traverseInZOrder([&](Layer* layer) {
  4044. if (args.size() < 2 || String8(args[1]) == layer->getName()) {
  4045. layer->clearFrameStats();
  4046. }
  4047. });
  4048. mAnimFrameTracker.clearStats();
  4049. }
  4050. void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
  4051. mTimeStats->parseArgs(asProto, args, result);
  4052. }
  4053. // This should only be called from the main thread. Otherwise it would need
  4054. // the lock and should use mCurrentState rather than mDrawingState.
  4055. void SurfaceFlinger::logFrameStats() {
  4056. mDrawingState.traverseInZOrder([&](Layer* layer) {
  4057. layer->logFrameStats();
  4058. });
  4059. mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
  4060. }
  4061. void SurfaceFlinger::appendSfConfigString(std::string& result) const {
  4062. result.append(" [sf");
  4063. if (isLayerTripleBufferingDisabled())
  4064. result.append(" DISABLE_TRIPLE_BUFFERING");
  4065. StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
  4066. StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
  4067. StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
  4068. StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
  4069. StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
  4070. maxFrameBufferAcquiredBuffers);
  4071. result.append("]");
  4072. }
  4073. void SurfaceFlinger::dumpVSync(std::string& result) const {
  4074. mPhaseOffsets->dump(result);
  4075. StringAppendF(&result,
  4076. " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
  4077. dispSyncPresentTimeOffset, getVsyncPeriod());
  4078. StringAppendF(&result, "Scheduler enabled.");
  4079. StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
  4080. mUseSmart90ForVideo ? "on" : "off");
  4081. StringAppendF(&result, "Allowed Display Configs: ");
  4082. for (int32_t configId : mAllowedDisplayConfigs) {
  4083. for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
  4084. if (refresh.second && refresh.second->configId == configId) {
  4085. StringAppendF(&result, "%dHz, ", refresh.second->fps);
  4086. }
  4087. }
  4088. }
  4089. StringAppendF(&result, "(config override by backdoor: %s)\n\n",
  4090. mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
  4091. mScheduler->dump(mAppConnectionHandle, result);
  4092. }
  4093. void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
  4094. result.append("Static screen stats:\n");
  4095. for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
  4096. float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
  4097. float percent = 100.0f *
  4098. static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
  4099. StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
  4100. }
  4101. float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
  4102. float percent = 100.0f *
  4103. static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
  4104. StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
  4105. bucketTimeSec, percent);
  4106. }
  4107. void SurfaceFlinger::recordBufferingStats(const char* layerName,
  4108. std::vector<OccupancyTracker::Segment>&& history) {
  4109. Mutex::Autolock lock(getBE().mBufferingStatsMutex);
  4110. auto& stats = getBE().mBufferingStats[layerName];
  4111. for (const auto& segment : history) {
  4112. if (!segment.usedThirdBuffer) {
  4113. stats.twoBufferTime += segment.totalTime;
  4114. }
  4115. if (segment.occupancyAverage < 1.0f) {
  4116. stats.doubleBufferedTime += segment.totalTime;
  4117. } else if (segment.occupancyAverage < 2.0f) {
  4118. stats.tripleBufferedTime += segment.totalTime;
  4119. }
  4120. ++stats.numSegments;
  4121. stats.totalTime += segment.totalTime;
  4122. }
  4123. }
  4124. void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
  4125. result.append("Layer frame timestamps:\n");
  4126. const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
  4127. const size_t count = currentLayers.size();
  4128. for (size_t i=0 ; i<count ; i++) {
  4129. currentLayers[i]->dumpFrameEvents(result);
  4130. }
  4131. }
  4132. void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
  4133. result.append("Buffering stats:\n");
  4134. result.append(" [Layer name] <Active time> <Two buffer> "
  4135. "<Double buffered> <Triple buffered>\n");
  4136. Mutex::Autolock lock(getBE().mBufferingStatsMutex);
  4137. typedef std::tuple<std::string, float, float, float> BufferTuple;
  4138. std::map<float, BufferTuple, std::greater<float>> sorted;
  4139. for (const auto& statsPair : getBE().mBufferingStats) {
  4140. const char* name = statsPair.first.c_str();
  4141. const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
  4142. if (stats.numSegments == 0) {
  4143. continue;
  4144. }
  4145. float activeTime = ns2ms(stats.totalTime) / 1000.0f;
  4146. float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
  4147. stats.totalTime;
  4148. float doubleBufferRatio = static_cast<float>(
  4149. stats.doubleBufferedTime) / stats.totalTime;
  4150. float tripleBufferRatio = static_cast<float>(
  4151. stats.tripleBufferedTime) / stats.totalTime;
  4152. sorted.insert({activeTime, {name, twoBufferRatio,
  4153. doubleBufferRatio, tripleBufferRatio}});
  4154. }
  4155. for (const auto& sortedPair : sorted) {
  4156. float activeTime = sortedPair.first;
  4157. const BufferTuple& values = sortedPair.second;
  4158. StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
  4159. activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
  4160. }
  4161. result.append("\n");
  4162. }
  4163. void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
  4164. for (const auto& [token, display] : mDisplays) {
  4165. const auto displayId = display->getId();
  4166. if (!displayId) {
  4167. continue;
  4168. }
  4169. const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
  4170. if (!hwcDisplayId) {
  4171. continue;
  4172. }
  4173. StringAppendF(&result,
  4174. "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
  4175. *hwcDisplayId);
  4176. uint8_t port;
  4177. DisplayIdentificationData data;
  4178. if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
  4179. result.append("no identification data\n");
  4180. continue;
  4181. }
  4182. if (!isEdid(data)) {
  4183. result.append("unknown identification data: ");
  4184. for (uint8_t byte : data) {
  4185. StringAppendF(&result, "%x ", byte);
  4186. }
  4187. result.append("\n");
  4188. continue;
  4189. }
  4190. const auto edid = parseEdid(data);
  4191. if (!edid) {
  4192. result.append("invalid EDID: ");
  4193. for (uint8_t byte : data) {
  4194. StringAppendF(&result, "%x ", byte);
  4195. }
  4196. result.append("\n");
  4197. continue;
  4198. }
  4199. StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
  4200. result.append(edid->displayName.data(), edid->displayName.length());
  4201. result.append("\"\n");
  4202. }
  4203. }
  4204. void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
  4205. StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
  4206. StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
  4207. StringAppendF(&result, "DisplayColorSetting: %s\n",
  4208. decodeDisplayColorSetting(mDisplayColorSetting).c_str());
  4209. // TODO: print out if wide-color mode is active or not
  4210. for (const auto& [token, display] : mDisplays) {
  4211. const auto displayId = display->getId();
  4212. if (!displayId) {
  4213. continue;
  4214. }
  4215. StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
  4216. std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
  4217. for (auto&& mode : modes) {
  4218. StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
  4219. }
  4220. ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
  4221. StringAppendF(&result, " Current color mode: %s (%d)\n",
  4222. decodeColorMode(currentMode).c_str(), currentMode);
  4223. }
  4224. result.append("\n");
  4225. }
  4226. LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
  4227. uint32_t traceFlags) const {
  4228. LayersProto layersProto;
  4229. const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
  4230. const State& state = useDrawing ? mDrawingState : mCurrentState;
  4231. state.traverseInZOrder([&](Layer* layer) {
  4232. LayerProto* layerProto = layersProto.add_layers();
  4233. layer->writeToProto(layerProto, stateSet, traceFlags);
  4234. });
  4235. return layersProto;
  4236. }
  4237. LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
  4238. const sp<DisplayDevice>& displayDevice) const {
  4239. LayersProto layersProto;
  4240. SizeProto* resolution = layersProto.mutable_resolution();
  4241. resolution->set_w(displayDevice->getWidth());
  4242. resolution->set_h(displayDevice->getHeight());
  4243. auto display = displayDevice->getCompositionDisplay();
  4244. const auto& displayState = display->getState();
  4245. layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
  4246. layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
  4247. layersProto.set_global_transform(displayState.orientation);
  4248. const auto displayId = displayDevice->getId();
  4249. LOG_ALWAYS_FATAL_IF(!displayId);
  4250. mDrawingState.traverseInZOrder([&](Layer* layer) {
  4251. if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
  4252. LayerProto* layerProto = layersProto.add_layers();
  4253. layer->writeToProto(layerProto, displayDevice);
  4254. }
  4255. });
  4256. return layersProto;
  4257. }
  4258. void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
  4259. const bool colorize = !args.empty() && args[0] == String16("--color");
  4260. Colorizer colorizer(colorize);
  4261. // figure out if we're stuck somewhere
  4262. const nsecs_t now = systemTime();
  4263. const nsecs_t inTransaction(mDebugInTransaction);
  4264. nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
  4265. /*
  4266. * Dump library configuration.
  4267. */
  4268. colorizer.bold(result);
  4269. result.append("Build configuration:");
  4270. colorizer.reset(result);
  4271. appendSfConfigString(result);
  4272. appendUiConfigString(result);
  4273. appendGuiConfigString(result);
  4274. result.append("\n");
  4275. result.append("\nDisplay identification data:\n");
  4276. dumpDisplayIdentificationData(result);
  4277. result.append("\nWide-Color information:\n");
  4278. dumpWideColorInfo(result);
  4279. colorizer.bold(result);
  4280. result.append("Sync configuration: ");
  4281. colorizer.reset(result);
  4282. result.append(SyncFeatures::getInstance().toString());
  4283. result.append("\n\n");
  4284. colorizer.bold(result);
  4285. result.append("VSYNC configuration:\n");
  4286. colorizer.reset(result);
  4287. dumpVSync(result);
  4288. result.append("\n");
  4289. dumpStaticScreenStats(result);
  4290. result.append("\n");
  4291. StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
  4292. StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
  4293. StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
  4294. dumpBufferingStats(result);
  4295. /*
  4296. * Dump the visible layer list
  4297. */
  4298. colorizer.bold(result);
  4299. StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
  4300. StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
  4301. mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
  4302. colorizer.reset(result);
  4303. {
  4304. LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
  4305. auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
  4306. result.append(LayerProtoParser::layerTreeToString(layerTree));
  4307. result.append("\n");
  4308. }
  4309. {
  4310. StringAppendF(&result, "Composition layers\n");
  4311. mDrawingState.traverseInZOrder([&](Layer* layer) {
  4312. auto compositionLayer = layer->getCompositionLayer();
  4313. if (compositionLayer) compositionLayer->dump(result);
  4314. });
  4315. }
  4316. /*
  4317. * Dump Display state
  4318. */
  4319. colorizer.bold(result);
  4320. StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
  4321. colorizer.reset(result);
  4322. for (const auto& [token, display] : mDisplays) {
  4323. display->dump(result);
  4324. }
  4325. result.append("\n");
  4326. /*
  4327. * Dump SurfaceFlinger global state
  4328. */
  4329. colorizer.bold(result);
  4330. result.append("SurfaceFlinger global state:\n");
  4331. colorizer.reset(result);
  4332. getRenderEngine().dump(result);
  4333. DebugEGLImageTracker::getInstance()->dump(result);
  4334. if (const auto display = getDefaultDisplayDeviceLocked()) {
  4335. display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
  4336. "undefinedRegion");
  4337. StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
  4338. display->isPoweredOn());
  4339. }
  4340. StringAppendF(&result,
  4341. " transaction-flags : %08x\n"
  4342. " gpu_to_cpu_unsupported : %d\n",
  4343. mTransactionFlags.load(), !mGpuToCpuSupported);
  4344. if (const auto displayId = getInternalDisplayIdLocked();
  4345. displayId && getHwComposer().isConnected(*displayId)) {
  4346. const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
  4347. StringAppendF(&result,
  4348. " refresh-rate : %f fps\n"
  4349. " x-dpi : %f\n"
  4350. " y-dpi : %f\n",
  4351. 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
  4352. activeConfig->getDpiY());
  4353. }
  4354. StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
  4355. /*
  4356. * Tracing state
  4357. */
  4358. mTracing.dump(result);
  4359. result.append("\n");
  4360. /*
  4361. * HWC layer minidump
  4362. */
  4363. for (const auto& [token, display] : mDisplays) {
  4364. const auto displayId = display->getId();
  4365. if (!displayId) {
  4366. continue;
  4367. }
  4368. StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
  4369. Layer::miniDumpHeader(result);
  4370. const sp<DisplayDevice> displayDevice = display;
  4371. mCurrentState.traverseInZOrder(
  4372. [&](Layer* layer) { layer->miniDump(result, displayDevice); });
  4373. result.append("\n");
  4374. }
  4375. /*
  4376. * Dump HWComposer state
  4377. */
  4378. colorizer.bold(result);
  4379. result.append("h/w composer state:\n");
  4380. colorizer.reset(result);
  4381. bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
  4382. StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
  4383. getHwComposer().dump(result);
  4384. /*
  4385. * Dump gralloc state
  4386. */
  4387. const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
  4388. alloc.dump(result);
  4389. /*
  4390. * Dump VrFlinger state if in use.
  4391. */
  4392. if (mVrFlingerRequestsDisplay && mVrFlinger) {
  4393. result.append("VrFlinger state:\n");
  4394. result.append(mVrFlinger->Dump());
  4395. result.append("\n");
  4396. }
  4397. /**
  4398. * Scheduler dump state.
  4399. */
  4400. result.append("\nScheduler state:\n");
  4401. result.append(mScheduler->doDump() + "\n");
  4402. StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
  4403. result.append(mRefreshRateStats.doDump() + "\n");
  4404. result.append(mTimeStats->miniDump());
  4405. result.append("\n");
  4406. }
  4407. const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
  4408. // Note: mStateLock is held here
  4409. for (const auto& [token, display] : mDisplays) {
  4410. if (display->getId() == displayId) {
  4411. return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
  4412. }
  4413. }
  4414. ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
  4415. static const Vector<sp<Layer>> empty;
  4416. return empty;
  4417. }
  4418. void SurfaceFlinger::updateColorMatrixLocked() {
  4419. mat4 colorMatrix;
  4420. if (mGlobalSaturationFactor != 1.0f) {
  4421. // Rec.709 luma coefficients
  4422. float3 luminance{0.213f, 0.715f, 0.072f};
  4423. luminance *= 1.0f - mGlobalSaturationFactor;
  4424. mat4 saturationMatrix = mat4(
  4425. vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
  4426. vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
  4427. vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
  4428. vec4{0.0f, 0.0f, 0.0f, 1.0f}
  4429. );
  4430. colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
  4431. } else {
  4432. colorMatrix = mClientColorMatrix * mDaltonizer();
  4433. }
  4434. if (mCurrentState.colorMatrix != colorMatrix) {
  4435. mCurrentState.colorMatrix = colorMatrix;
  4436. mCurrentState.colorMatrixChanged = true;
  4437. setTransactionFlags(eTransactionNeeded);
  4438. }
  4439. }
  4440. status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
  4441. #pragma clang diagnostic push
  4442. #pragma clang diagnostic error "-Wswitch-enum"
  4443. switch (static_cast<ISurfaceComposerTag>(code)) {
  4444. // These methods should at minimum make sure that the client requested
  4445. // access to SF.
  4446. case BOOT_FINISHED:
  4447. case CLEAR_ANIMATION_FRAME_STATS:
  4448. case CREATE_DISPLAY:
  4449. case DESTROY_DISPLAY:
  4450. case ENABLE_VSYNC_INJECTIONS:
  4451. case GET_ANIMATION_FRAME_STATS:
  4452. case GET_HDR_CAPABILITIES:
  4453. case SET_ACTIVE_CONFIG:
  4454. case SET_ALLOWED_DISPLAY_CONFIGS:
  4455. case GET_ALLOWED_DISPLAY_CONFIGS:
  4456. case SET_ACTIVE_COLOR_MODE:
  4457. case INJECT_VSYNC:
  4458. case SET_POWER_MODE:
  4459. case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
  4460. case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
  4461. case GET_DISPLAYED_CONTENT_SAMPLE:
  4462. case NOTIFY_POWER_HINT: {
  4463. if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
  4464. IPCThreadState* ipc = IPCThreadState::self();
  4465. ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
  4466. ipc->getCallingPid(), ipc->getCallingUid());
  4467. return PERMISSION_DENIED;
  4468. }
  4469. return OK;
  4470. }
  4471. case GET_LAYER_DEBUG_INFO: {
  4472. IPCThreadState* ipc = IPCThreadState::self();
  4473. const int pid = ipc->getCallingPid();
  4474. const int uid = ipc->getCallingUid();
  4475. if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
  4476. ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
  4477. return PERMISSION_DENIED;
  4478. }
  4479. return OK;
  4480. }
  4481. // Used by apps to hook Choreographer to SurfaceFlinger.
  4482. case CREATE_DISPLAY_EVENT_CONNECTION:
  4483. // The following calls are currently used by clients that do not
  4484. // request necessary permissions. However, they do not expose any secret
  4485. // information, so it is OK to pass them.
  4486. case AUTHENTICATE_SURFACE:
  4487. case GET_ACTIVE_COLOR_MODE:
  4488. case GET_ACTIVE_CONFIG:
  4489. case GET_PHYSICAL_DISPLAY_IDS:
  4490. case GET_PHYSICAL_DISPLAY_TOKEN:
  4491. case GET_DISPLAY_COLOR_MODES:
  4492. case GET_DISPLAY_NATIVE_PRIMARIES:
  4493. case GET_DISPLAY_CONFIGS:
  4494. case GET_DISPLAY_STATS:
  4495. case GET_SUPPORTED_FRAME_TIMESTAMPS:
  4496. // Calling setTransactionState is safe, because you need to have been
  4497. // granted a reference to Client* and Handle* to do anything with it.
  4498. case SET_TRANSACTION_STATE:
  4499. case CREATE_CONNECTION:
  4500. case GET_COLOR_MANAGEMENT:
  4501. case GET_COMPOSITION_PREFERENCE:
  4502. case GET_PROTECTED_CONTENT_SUPPORT:
  4503. case IS_WIDE_COLOR_DISPLAY:
  4504. case GET_DISPLAY_BRIGHTNESS_SUPPORT:
  4505. case ENTERSELF:
  4506. case EXITSELF:
  4507. case SET_DISPLAY_BRIGHTNESS: {
  4508. return OK;
  4509. }
  4510. case CAPTURE_LAYERS:
  4511. case CAPTURE_SCREEN:
  4512. case ADD_REGION_SAMPLING_LISTENER:
  4513. case REMOVE_REGION_SAMPLING_LISTENER: {
  4514. // codes that require permission check
  4515. IPCThreadState* ipc = IPCThreadState::self();
  4516. const int pid = ipc->getCallingPid();
  4517. const int uid = ipc->getCallingUid();
  4518. if ((uid != AID_GRAPHICS) &&
  4519. !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
  4520. ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
  4521. return PERMISSION_DENIED;
  4522. }
  4523. return OK;
  4524. }
  4525. // The following codes are deprecated and should never be allowed to access SF.
  4526. case CONNECT_DISPLAY_UNUSED:
  4527. case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
  4528. ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
  4529. return PERMISSION_DENIED;
  4530. }
  4531. case CAPTURE_SCREEN_BY_ID: {
  4532. IPCThreadState* ipc = IPCThreadState::self();
  4533. const int uid = ipc->getCallingUid();
  4534. if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
  4535. return OK;
  4536. }
  4537. return PERMISSION_DENIED;
  4538. }
  4539. }
  4540. // These codes are used for the IBinder protocol to either interrogate the recipient
  4541. // side of the transaction for its canonical interface descriptor or to dump its state.
  4542. // We let them pass by default.
  4543. if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
  4544. code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
  4545. code == IBinder::SYSPROPS_TRANSACTION) {
  4546. return OK;
  4547. }
  4548. // Numbers from 1000 to 1034 are currently used for backdoors. The code
  4549. // in onTransact verifies that the user is root, and has access to use SF.
  4550. if (code >= 1000 && code <= 1035) {
  4551. ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
  4552. return OK;
  4553. }
  4554. ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
  4555. return PERMISSION_DENIED;
  4556. #pragma clang diagnostic pop
  4557. }
  4558. status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
  4559. uint32_t flags) {
  4560. status_t credentialCheck = CheckTransactCodeCredentials(code);
  4561. if (credentialCheck != OK) {
  4562. return credentialCheck;
  4563. }
  4564. status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
  4565. if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
  4566. CHECK_INTERFACE(ISurfaceComposer, data, reply);
  4567. IPCThreadState* ipc = IPCThreadState::self();
  4568. const int uid = ipc->getCallingUid();
  4569. if (CC_UNLIKELY(uid != AID_SYSTEM
  4570. && !PermissionCache::checkCallingPermission(sHardwareTest))) {
  4571. const int pid = ipc->getCallingPid();
  4572. ALOGE("Permission Denial: "
  4573. "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
  4574. return PERMISSION_DENIED;
  4575. }
  4576. int n;
  4577. switch (code) {
  4578. case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
  4579. case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
  4580. return NO_ERROR;
  4581. case 1002: // SHOW_UPDATES
  4582. n = data.readInt32();
  4583. mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
  4584. invalidateHwcGeometry();
  4585. repaintEverything();
  4586. return NO_ERROR;
  4587. case 1004:{ // repaint everything
  4588. repaintEverything();
  4589. return NO_ERROR;
  4590. }
  4591. case 1005:{ // force transaction
  4592. Mutex::Autolock _l(mStateLock);
  4593. setTransactionFlags(
  4594. eTransactionNeeded|
  4595. eDisplayTransactionNeeded|
  4596. eTraversalNeeded);
  4597. return NO_ERROR;
  4598. }
  4599. case 1006:{ // send empty update
  4600. signalRefresh();
  4601. return NO_ERROR;
  4602. }
  4603. case 1008: // toggle use of hw composer
  4604. n = data.readInt32();
  4605. mDebugDisableHWC = n != 0;
  4606. invalidateHwcGeometry();
  4607. repaintEverything();
  4608. return NO_ERROR;
  4609. case 1009: // toggle use of transform hint
  4610. n = data.readInt32();
  4611. mDebugDisableTransformHint = n != 0;
  4612. invalidateHwcGeometry();
  4613. repaintEverything();
  4614. return NO_ERROR;
  4615. case 1010: // interrogate.
  4616. reply->writeInt32(0);
  4617. reply->writeInt32(0);
  4618. reply->writeInt32(mDebugRegion);
  4619. reply->writeInt32(0);
  4620. reply->writeInt32(mDebugDisableHWC);
  4621. return NO_ERROR;
  4622. case 1013: {
  4623. const auto display = getDefaultDisplayDevice();
  4624. if (!display) {
  4625. return NAME_NOT_FOUND;
  4626. }
  4627. reply->writeInt32(display->getPageFlipCount());
  4628. return NO_ERROR;
  4629. }
  4630. case 1014: {
  4631. Mutex::Autolock _l(mStateLock);
  4632. // daltonize
  4633. n = data.readInt32();
  4634. switch (n % 10) {
  4635. case 1:
  4636. mDaltonizer.setType(ColorBlindnessType::Protanomaly);
  4637. break;
  4638. case 2:
  4639. mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
  4640. break;
  4641. case 3:
  4642. mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
  4643. break;
  4644. default:
  4645. mDaltonizer.setType(ColorBlindnessType::None);
  4646. break;
  4647. }
  4648. if (n >= 10) {
  4649. mDaltonizer.setMode(ColorBlindnessMode::Correction);
  4650. } else {
  4651. mDaltonizer.setMode(ColorBlindnessMode::Simulation);
  4652. }
  4653. updateColorMatrixLocked();
  4654. return NO_ERROR;
  4655. }
  4656. case 1015: {
  4657. Mutex::Autolock _l(mStateLock);
  4658. // apply a color matrix
  4659. n = data.readInt32();
  4660. if (n) {
  4661. // color matrix is sent as a column-major mat4 matrix
  4662. for (size_t i = 0 ; i < 4; i++) {
  4663. for (size_t j = 0; j < 4; j++) {
  4664. mClientColorMatrix[i][j] = data.readFloat();
  4665. }
  4666. }
  4667. } else {
  4668. mClientColorMatrix = mat4();
  4669. }
  4670. // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
  4671. // the division by w in the fragment shader
  4672. float4 lastRow(transpose(mClientColorMatrix)[3]);
  4673. if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
  4674. ALOGE("The color transform's last row must be (0, 0, 0, 1)");
  4675. }
  4676. updateColorMatrixLocked();
  4677. return NO_ERROR;
  4678. }
  4679. // This is an experimental interface
  4680. // Needs to be shifted to proper binder interface when we productize
  4681. case 1016: {
  4682. n = data.readInt32();
  4683. // TODO(b/113612090): Evaluate if this can be removed.
  4684. mScheduler->setRefreshSkipCount(n);
  4685. return NO_ERROR;
  4686. }
  4687. case 1017: {
  4688. n = data.readInt32();
  4689. mForceFullDamage = n != 0;
  4690. return NO_ERROR;
  4691. }
  4692. case 1018: { // Modify Choreographer's phase offset
  4693. n = data.readInt32();
  4694. mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
  4695. return NO_ERROR;
  4696. }
  4697. case 1019: { // Modify SurfaceFlinger's phase offset
  4698. n = data.readInt32();
  4699. mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
  4700. return NO_ERROR;
  4701. }
  4702. case 1020: { // Layer updates interceptor
  4703. n = data.readInt32();
  4704. if (n) {
  4705. ALOGV("Interceptor enabled");
  4706. mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
  4707. }
  4708. else{
  4709. ALOGV("Interceptor disabled");
  4710. mInterceptor->disable();
  4711. }
  4712. return NO_ERROR;
  4713. }
  4714. case 1021: { // Disable HWC virtual displays
  4715. n = data.readInt32();
  4716. mUseHwcVirtualDisplays = !n;
  4717. return NO_ERROR;
  4718. }
  4719. case 1022: { // Set saturation boost
  4720. Mutex::Autolock _l(mStateLock);
  4721. mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
  4722. updateColorMatrixLocked();
  4723. return NO_ERROR;
  4724. }
  4725. case 1023: { // Set native mode
  4726. int32_t colorMode;
  4727. mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
  4728. if (data.readInt32(&colorMode) == NO_ERROR) {
  4729. mForceColorMode = static_cast<ColorMode>(colorMode);
  4730. }
  4731. invalidateHwcGeometry();
  4732. repaintEverything();
  4733. return NO_ERROR;
  4734. }
  4735. // Deprecate, use 1030 to check whether the device is color managed.
  4736. case 1024: {
  4737. return NAME_NOT_FOUND;
  4738. }
  4739. case 1025: { // Set layer tracing
  4740. n = data.readInt32();
  4741. if (n) {
  4742. ALOGD("LayerTracing enabled");
  4743. Mutex::Autolock lock(mStateLock);
  4744. mTracingEnabledChanged = true;
  4745. mTracing.enable();
  4746. reply->writeInt32(NO_ERROR);
  4747. } else {
  4748. ALOGD("LayerTracing disabled");
  4749. bool writeFile = false;
  4750. {
  4751. Mutex::Autolock lock(mStateLock);
  4752. mTracingEnabledChanged = true;
  4753. writeFile = mTracing.disable();
  4754. }
  4755. if (writeFile) {
  4756. reply->writeInt32(mTracing.writeToFile());
  4757. } else {
  4758. reply->writeInt32(NO_ERROR);
  4759. }
  4760. }
  4761. return NO_ERROR;
  4762. }
  4763. case 1026: { // Get layer tracing status
  4764. reply->writeBool(mTracing.isEnabled());
  4765. return NO_ERROR;
  4766. }
  4767. // Is a DisplayColorSetting supported?
  4768. case 1027: {
  4769. const auto display = getDefaultDisplayDevice();
  4770. if (!display) {
  4771. return NAME_NOT_FOUND;
  4772. }
  4773. DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
  4774. switch (setting) {
  4775. case DisplayColorSetting::MANAGED:
  4776. reply->writeBool(useColorManagement);
  4777. break;
  4778. case DisplayColorSetting::UNMANAGED:
  4779. reply->writeBool(true);
  4780. break;
  4781. case DisplayColorSetting::ENHANCED:
  4782. reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
  4783. break;
  4784. default: // vendor display color setting
  4785. reply->writeBool(
  4786. display->hasRenderIntent(static_cast<RenderIntent>(setting)));
  4787. break;
  4788. }
  4789. return NO_ERROR;
  4790. }
  4791. // Is VrFlinger active?
  4792. case 1028: {
  4793. Mutex::Autolock _l(mStateLock);
  4794. reply->writeBool(getHwComposer().isUsingVrComposer());
  4795. return NO_ERROR;
  4796. }
  4797. // Set buffer size for SF tracing (value in KB)
  4798. case 1029: {
  4799. n = data.readInt32();
  4800. if (n <= 0 || n > MAX_TRACING_MEMORY) {
  4801. ALOGW("Invalid buffer size: %d KB", n);
  4802. reply->writeInt32(BAD_VALUE);
  4803. return BAD_VALUE;
  4804. }
  4805. ALOGD("Updating trace buffer to %d KB", n);
  4806. mTracing.setBufferSize(n * 1024);
  4807. reply->writeInt32(NO_ERROR);
  4808. return NO_ERROR;
  4809. }
  4810. // Is device color managed?
  4811. case 1030: {
  4812. reply->writeBool(useColorManagement);
  4813. return NO_ERROR;
  4814. }
  4815. // Override default composition data space
  4816. // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
  4817. // && adb shell stop zygote && adb shell start zygote
  4818. // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
  4819. // adb shell stop zygote && adb shell start zygote
  4820. case 1031: {
  4821. Mutex::Autolock _l(mStateLock);
  4822. n = data.readInt32();
  4823. if (n) {
  4824. n = data.readInt32();
  4825. if (n) {
  4826. Dataspace dataspace = static_cast<Dataspace>(n);
  4827. if (!validateCompositionDataspace(dataspace)) {
  4828. return BAD_VALUE;
  4829. }
  4830. mDefaultCompositionDataspace = dataspace;
  4831. }
  4832. n = data.readInt32();
  4833. if (n) {
  4834. Dataspace dataspace = static_cast<Dataspace>(n);
  4835. if (!validateCompositionDataspace(dataspace)) {
  4836. return BAD_VALUE;
  4837. }
  4838. mWideColorGamutCompositionDataspace = dataspace;
  4839. }
  4840. } else {
  4841. // restore composition data space.
  4842. mDefaultCompositionDataspace = defaultCompositionDataspace;
  4843. mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
  4844. }
  4845. return NO_ERROR;
  4846. }
  4847. // Set trace flags
  4848. case 1033: {
  4849. n = data.readUint32();
  4850. ALOGD("Updating trace flags to 0x%x", n);
  4851. mTracing.setTraceFlags(n);
  4852. reply->writeInt32(NO_ERROR);
  4853. return NO_ERROR;
  4854. }
  4855. case 1034: {
  4856. // TODO(b/129297325): expose this via developer menu option
  4857. n = data.readInt32();
  4858. if (n && !mRefreshRateOverlay) {
  4859. RefreshRateType type;
  4860. {
  4861. std::lock_guard<std::mutex> lock(mActiveConfigLock);
  4862. type = mDesiredActiveConfig.type;
  4863. }
  4864. mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
  4865. mRefreshRateOverlay->changeRefreshRate(type);
  4866. } else if (!n) {
  4867. mRefreshRateOverlay.reset();
  4868. }
  4869. return NO_ERROR;
  4870. }
  4871. case 1035: {
  4872. n = data.readInt32();
  4873. mDebugDisplayConfigSetByBackdoor = false;
  4874. if (n >= 0) {
  4875. const auto displayToken = getInternalDisplayToken();
  4876. status_t result = setAllowedDisplayConfigs(displayToken, {n});
  4877. if (result != NO_ERROR) {
  4878. return result;
  4879. }
  4880. mDebugDisplayConfigSetByBackdoor = true;
  4881. }
  4882. return NO_ERROR;
  4883. }
  4884. }
  4885. }
  4886. return err;
  4887. }
  4888. void SurfaceFlinger::repaintEverything() {
  4889. mRepaintEverything = true;
  4890. signalTransaction();
  4891. }
  4892. void SurfaceFlinger::repaintEverythingForHWC() {
  4893. mRepaintEverything = true;
  4894. mEventQueue->invalidate();
  4895. }
  4896. // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
  4897. class WindowDisconnector {
  4898. public:
  4899. WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
  4900. ~WindowDisconnector() {
  4901. native_window_api_disconnect(mWindow, mApi);
  4902. }
  4903. private:
  4904. ANativeWindow* mWindow;
  4905. const int mApi;
  4906. };
  4907. status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
  4908. sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
  4909. const Dataspace reqDataspace,
  4910. const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
  4911. uint32_t reqWidth, uint32_t reqHeight,
  4912. bool useIdentityTransform,
  4913. ISurfaceComposer::Rotation rotation,
  4914. bool captureSecureLayers) {
  4915. ATRACE_CALL();
  4916. if (!displayToken) return BAD_VALUE;
  4917. auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
  4918. sp<DisplayDevice> display;
  4919. {
  4920. Mutex::Autolock _l(mStateLock);
  4921. display = getDisplayDeviceLocked(displayToken);
  4922. if (!display) return BAD_VALUE;
  4923. // set the requested width/height to the logical display viewport size
  4924. // by default
  4925. if (reqWidth == 0 || reqHeight == 0) {
  4926. reqWidth = uint32_t(display->getViewport().width());
  4927. reqHeight = uint32_t(display->getViewport().height());
  4928. }
  4929. }
  4930. DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
  4931. renderAreaRotation, captureSecureLayers);
  4932. auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
  4933. std::placeholders::_1);
  4934. return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
  4935. useIdentityTransform, outCapturedSecureLayers);
  4936. }
  4937. static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
  4938. switch (colorMode) {
  4939. case ColorMode::DISPLAY_P3:
  4940. case ColorMode::BT2100_PQ:
  4941. case ColorMode::BT2100_HLG:
  4942. case ColorMode::DISPLAY_BT2020:
  4943. return Dataspace::DISPLAY_P3;
  4944. default:
  4945. return Dataspace::V0_SRGB;
  4946. }
  4947. }
  4948. const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
  4949. const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
  4950. if (displayToken) {
  4951. return getDisplayDeviceLocked(displayToken);
  4952. }
  4953. // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
  4954. // may not have a displayId.
  4955. for (const auto& [token, display] : mDisplays) {
  4956. if (display->getLayerStack() == displayOrLayerStack) {
  4957. return display;
  4958. }
  4959. }
  4960. return nullptr;
  4961. }
  4962. status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
  4963. sp<GraphicBuffer>* outBuffer) {
  4964. sp<DisplayDevice> display;
  4965. uint32_t width;
  4966. uint32_t height;
  4967. ui::Transform::orientation_flags captureOrientation;
  4968. {
  4969. Mutex::Autolock _l(mStateLock);
  4970. display = getDisplayByIdOrLayerStack(displayOrLayerStack);
  4971. if (!display) {
  4972. return BAD_VALUE;
  4973. }
  4974. width = uint32_t(display->getViewport().width());
  4975. height = uint32_t(display->getViewport().height());
  4976. captureOrientation = fromSurfaceComposerRotation(
  4977. static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
  4978. if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
  4979. captureOrientation = ui::Transform::orientation_flags::ROT_270;
  4980. } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
  4981. captureOrientation = ui::Transform::orientation_flags::ROT_90;
  4982. }
  4983. *outDataspace =
  4984. pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
  4985. }
  4986. DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
  4987. false /* captureSecureLayers */);
  4988. auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
  4989. std::placeholders::_1);
  4990. bool ignored = false;
  4991. return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
  4992. false /* useIdentityTransform */,
  4993. ignored /* outCapturedSecureLayers */);
  4994. }
  4995. status_t SurfaceFlinger::captureLayers(
  4996. const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
  4997. const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
  4998. const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
  4999. float frameScale, bool childrenOnly) {
  5000. ATRACE_CALL();
  5001. class LayerRenderArea : public RenderArea {
  5002. public:
  5003. LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
  5004. int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
  5005. bool childrenOnly)
  5006. : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
  5007. mLayer(layer),
  5008. mCrop(crop),
  5009. mNeedsFiltering(false),
  5010. mFlinger(flinger),
  5011. mChildrenOnly(childrenOnly) {}
  5012. const ui::Transform& getTransform() const override { return mTransform; }
  5013. Rect getBounds() const override {
  5014. const Layer::State& layerState(mLayer->getDrawingState());
  5015. return mLayer->getBufferSize(layerState);
  5016. }
  5017. int getHeight() const override {
  5018. return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
  5019. }
  5020. int getWidth() const override {
  5021. return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
  5022. }
  5023. bool isSecure() const override { return false; }
  5024. bool needsFiltering() const override { return mNeedsFiltering; }
  5025. const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
  5026. Rect getSourceCrop() const override {
  5027. if (mCrop.isEmpty()) {
  5028. return getBounds();
  5029. } else {
  5030. return mCrop;
  5031. }
  5032. }
  5033. class ReparentForDrawing {
  5034. public:
  5035. const sp<Layer>& oldParent;
  5036. const sp<Layer>& newParent;
  5037. ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
  5038. const Rect& drawingBounds)
  5039. : oldParent(oldParent), newParent(newParent) {
  5040. // Compute and cache the bounds for the new parent layer.
  5041. newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
  5042. oldParent->setChildrenDrawingParent(newParent);
  5043. }
  5044. ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
  5045. };
  5046. void render(std::function<void()> drawLayers) override {
  5047. const Rect sourceCrop = getSourceCrop();
  5048. // no need to check rotation because there is none
  5049. mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
  5050. sourceCrop.height() != getReqHeight();
  5051. if (!mChildrenOnly) {
  5052. mTransform = mLayer->getTransform().inverse();
  5053. drawLayers();
  5054. } else {
  5055. Rect bounds = getBounds();
  5056. screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
  5057. LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"), String8(""),
  5058. bounds.getWidth(), bounds.getHeight(), 0,
  5059. LayerMetadata()));
  5060. ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
  5061. drawLayers();
  5062. }
  5063. }
  5064. private:
  5065. const sp<Layer> mLayer;
  5066. const Rect mCrop;
  5067. // In the "childrenOnly" case we reparent the children to a screenshot
  5068. // layer which has no properties set and which does not draw.
  5069. sp<ContainerLayer> screenshotParentLayer;
  5070. ui::Transform mTransform;
  5071. bool mNeedsFiltering;
  5072. SurfaceFlinger* mFlinger;
  5073. const bool mChildrenOnly;
  5074. };
  5075. int reqWidth = 0;
  5076. int reqHeight = 0;
  5077. sp<Layer> parent;
  5078. Rect crop(sourceCrop);
  5079. std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
  5080. {
  5081. Mutex::Autolock _l(mStateLock);
  5082. parent = fromHandle(layerHandleBinder);
  5083. if (parent == nullptr || parent->isRemovedFromCurrentState()) {
  5084. ALOGE("captureLayers called with an invalid or removed parent");
  5085. return NAME_NOT_FOUND;
  5086. }
  5087. const int uid = IPCThreadState::self()->getCallingUid();
  5088. const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
  5089. if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
  5090. ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
  5091. return PERMISSION_DENIED;
  5092. }
  5093. if (sourceCrop.width() <= 0) {
  5094. crop.left = 0;
  5095. crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
  5096. }
  5097. if (sourceCrop.height() <= 0) {
  5098. crop.top = 0;
  5099. crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
  5100. }
  5101. reqWidth = crop.width() * frameScale;
  5102. reqHeight = crop.height() * frameScale;
  5103. for (const auto& handle : excludeHandles) {
  5104. sp<Layer> excludeLayer = fromHandle(handle);
  5105. if (excludeLayer != nullptr) {
  5106. excludeLayers.emplace(excludeLayer);
  5107. } else {
  5108. ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
  5109. return NAME_NOT_FOUND;
  5110. }
  5111. }
  5112. } // mStateLock
  5113. // really small crop or frameScale
  5114. if (reqWidth <= 0) {
  5115. reqWidth = 1;
  5116. }
  5117. if (reqHeight <= 0) {
  5118. reqHeight = 1;
  5119. }
  5120. LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
  5121. auto traverseLayers = [parent, childrenOnly,
  5122. &excludeLayers](const LayerVector::Visitor& visitor) {
  5123. parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
  5124. if (!layer->isVisible()) {
  5125. return;
  5126. } else if (childrenOnly && layer == parent.get()) {
  5127. return;
  5128. }
  5129. sp<Layer> p = layer;
  5130. while (p != nullptr) {
  5131. if (excludeLayers.count(p) != 0) {
  5132. return;
  5133. }
  5134. p = p->getParent();
  5135. }
  5136. visitor(layer);
  5137. });
  5138. };
  5139. bool outCapturedSecureLayers = false;
  5140. return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
  5141. outCapturedSecureLayers);
  5142. }
  5143. status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
  5144. TraverseLayersFunction traverseLayers,
  5145. sp<GraphicBuffer>* outBuffer,
  5146. const ui::PixelFormat reqPixelFormat,
  5147. bool useIdentityTransform,
  5148. bool& outCapturedSecureLayers) {
  5149. ATRACE_CALL();
  5150. // TODO(b/116112787) Make buffer usage a parameter.
  5151. const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
  5152. GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
  5153. *outBuffer =
  5154. getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
  5155. static_cast<android_pixel_format>(reqPixelFormat), 1,
  5156. usage, "screenshot");
  5157. return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
  5158. outCapturedSecureLayers);
  5159. }
  5160. status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
  5161. TraverseLayersFunction traverseLayers,
  5162. const sp<GraphicBuffer>& buffer,
  5163. bool useIdentityTransform,
  5164. bool& outCapturedSecureLayers) {
  5165. // This mutex protects syncFd and captureResult for communication of the return values from the
  5166. // main thread back to this Binder thread
  5167. std::mutex captureMutex;
  5168. std::condition_variable captureCondition;
  5169. std::unique_lock<std::mutex> captureLock(captureMutex);
  5170. int syncFd = -1;
  5171. std::optional<status_t> captureResult;
  5172. const int uid = IPCThreadState::self()->getCallingUid();
  5173. const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
  5174. sp<LambdaMessage> message = new LambdaMessage([&] {
  5175. // If there is a refresh pending, bug out early and tell the binder thread to try again
  5176. // after the refresh.
  5177. if (mRefreshPending) {
  5178. ATRACE_NAME("Skipping screenshot for now");
  5179. std::unique_lock<std::mutex> captureLock(captureMutex);
  5180. captureResult = std::make_optional<status_t>(EAGAIN);
  5181. captureCondition.notify_one();
  5182. return;
  5183. }
  5184. status_t result = NO_ERROR;
  5185. int fd = -1;
  5186. {
  5187. Mutex::Autolock _l(mStateLock);
  5188. renderArea.render([&] {
  5189. result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
  5190. useIdentityTransform, forSystem, &fd,
  5191. outCapturedSecureLayers);
  5192. });
  5193. }
  5194. {
  5195. std::unique_lock<std::mutex> captureLock(captureMutex);
  5196. syncFd = fd;
  5197. captureResult = std::make_optional<status_t>(result);
  5198. captureCondition.notify_one();
  5199. }
  5200. });
  5201. status_t result = postMessageAsync(message);
  5202. if (result == NO_ERROR) {
  5203. captureCondition.wait(captureLock, [&] { return captureResult; });
  5204. while (*captureResult == EAGAIN) {
  5205. captureResult.reset();
  5206. result = postMessageAsync(message);
  5207. if (result != NO_ERROR) {
  5208. return result;
  5209. }
  5210. captureCondition.wait(captureLock, [&] { return captureResult; });
  5211. }
  5212. result = *captureResult;
  5213. }
  5214. if (result == NO_ERROR) {
  5215. sync_wait(syncFd, -1);
  5216. close(syncFd);
  5217. }
  5218. return result;
  5219. }
  5220. void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
  5221. TraverseLayersFunction traverseLayers,
  5222. ANativeWindowBuffer* buffer, bool useIdentityTransform,
  5223. int* outSyncFd) {
  5224. ATRACE_CALL();
  5225. const auto reqWidth = renderArea.getReqWidth();
  5226. const auto reqHeight = renderArea.getReqHeight();
  5227. const auto rotation = renderArea.getRotationFlags();
  5228. const auto transform = renderArea.getTransform();
  5229. const auto sourceCrop = renderArea.getSourceCrop();
  5230. renderengine::DisplaySettings clientCompositionDisplay;
  5231. std::vector<renderengine::LayerSettings> clientCompositionLayers;
  5232. // assume that bounds are never offset, and that they are the same as the
  5233. // buffer bounds.
  5234. clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
  5235. clientCompositionDisplay.clip = sourceCrop;
  5236. clientCompositionDisplay.globalTransform = transform.asMatrix4();
  5237. // Now take into account the rotation flag. We append a transform that
  5238. // rotates the layer stack about the origin, then translate by buffer
  5239. // boundaries to be in the right quadrant.
  5240. mat4 rotMatrix;
  5241. int displacementX = 0;
  5242. int displacementY = 0;
  5243. float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
  5244. switch (rotation) {
  5245. case ui::Transform::ROT_90:
  5246. rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
  5247. displacementX = renderArea.getBounds().getHeight();
  5248. break;
  5249. case ui::Transform::ROT_180:
  5250. rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
  5251. displacementY = renderArea.getBounds().getWidth();
  5252. displacementX = renderArea.getBounds().getHeight();
  5253. break;
  5254. case ui::Transform::ROT_270:
  5255. rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
  5256. displacementY = renderArea.getBounds().getWidth();
  5257. break;
  5258. default:
  5259. break;
  5260. }
  5261. // We need to transform the clipping window into the right spot.
  5262. // First, rotate the clipping rectangle by the rotation hint to get the
  5263. // right orientation
  5264. const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
  5265. const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
  5266. const vec4 rotClipTL = rotMatrix * clipTL;
  5267. const vec4 rotClipBR = rotMatrix * clipBR;
  5268. const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
  5269. const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
  5270. const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
  5271. const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
  5272. // Now reposition the clipping rectangle with the displacement vector
  5273. // computed above.
  5274. const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
  5275. clientCompositionDisplay.clip =
  5276. Rect(newClipLeft + displacementX, newClipTop + displacementY,
  5277. newClipRight + displacementX, newClipBottom + displacementY);
  5278. mat4 clipTransform = displacementMat * rotMatrix;
  5279. clientCompositionDisplay.globalTransform =
  5280. clipTransform * clientCompositionDisplay.globalTransform;
  5281. clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
  5282. clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
  5283. const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
  5284. renderengine::LayerSettings fillLayer;
  5285. fillLayer.source.buffer.buffer = nullptr;
  5286. fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
  5287. fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
  5288. fillLayer.alpha = half(alpha);
  5289. clientCompositionLayers.push_back(fillLayer);
  5290. Region clearRegion = Region::INVALID_REGION;
  5291. traverseLayers([&](Layer* layer) {
  5292. renderengine::LayerSettings layerSettings;
  5293. bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
  5294. false, layerSettings);
  5295. if (prepared) {
  5296. clientCompositionLayers.push_back(layerSettings);
  5297. }
  5298. });
  5299. clientCompositionDisplay.clearRegion = clearRegion;
  5300. // Use an empty fence for the buffer fence, since we just created the buffer so
  5301. // there is no need for synchronization with the GPU.
  5302. base::unique_fd bufferFence;
  5303. base::unique_fd drawFence;
  5304. getRenderEngine().useProtectedContext(false);
  5305. getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
  5306. /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
  5307. *outSyncFd = drawFence.release();
  5308. }
  5309. status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
  5310. TraverseLayersFunction traverseLayers,
  5311. ANativeWindowBuffer* buffer,
  5312. bool useIdentityTransform, bool forSystem,
  5313. int* outSyncFd, bool& outCapturedSecureLayers) {
  5314. ATRACE_CALL();
  5315. traverseLayers([&](Layer* layer) {
  5316. outCapturedSecureLayers =
  5317. outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
  5318. });
  5319. // We allow the system server to take screenshots of secure layers for
  5320. // use in situations like the Screen-rotation animation and place
  5321. // the impetus on WindowManager to not persist them.
  5322. if (outCapturedSecureLayers && !forSystem) {
  5323. ALOGW("FB is protected: PERMISSION_DENIED");
  5324. return PERMISSION_DENIED;
  5325. }
  5326. renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
  5327. return NO_ERROR;
  5328. }
  5329. void SurfaceFlinger::setInputWindowsFinished() {
  5330. Mutex::Autolock _l(mStateLock);
  5331. mPendingSyncInputWindows = false;
  5332. mTransactionCV.broadcast();
  5333. }
  5334. // ---------------------------------------------------------------------------
  5335. void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
  5336. layersSortedByZ.traverseInZOrder(stateSet, visitor);
  5337. }
  5338. void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
  5339. layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
  5340. }
  5341. void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
  5342. const LayerVector::Visitor& visitor) {
  5343. // We loop through the first level of layers without traversing,
  5344. // as we need to determine which layers belong to the requested display.
  5345. for (const auto& layer : mDrawingState.layersSortedByZ) {
  5346. if (!layer->belongsToDisplay(display->getLayerStack(), display->getActiveSystemName(), false)) {
  5347. continue;
  5348. }
  5349. // relative layers are traversed in Layer::traverseInZOrder
  5350. layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
  5351. if (!layer->belongsToDisplay(display->getLayerStack(), display->getActiveSystemName(), false)) {
  5352. return;
  5353. }
  5354. if (!layer->isVisible()) {
  5355. return;
  5356. }
  5357. visitor(layer);
  5358. });
  5359. }
  5360. }
  5361. void SurfaceFlinger::setPreferredDisplayConfig() {
  5362. const auto& type = mScheduler->getPreferredRefreshRateType();
  5363. const auto& config = mRefreshRateConfigs.getRefreshRate(type);
  5364. if (config && isDisplayConfigAllowed(config->configId)) {
  5365. ALOGV("switching to Scheduler preferred config %d", config->configId);
  5366. setDesiredActiveConfig({type, config->configId, Scheduler::ConfigEvent::Changed});
  5367. } else {
  5368. // Set the highest allowed config by iterating backwards on available refresh rates
  5369. const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
  5370. for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
  5371. if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
  5372. ALOGV("switching to allowed config %d", iter->second->configId);
  5373. setDesiredActiveConfig({iter->first, iter->second->configId,
  5374. Scheduler::ConfigEvent::Changed});
  5375. }
  5376. }
  5377. }
  5378. }
  5379. void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
  5380. const std::vector<int32_t>& allowedConfigs) {
  5381. if (!display->isPrimary()) {
  5382. return;
  5383. }
  5384. const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
  5385. allowedConfigs.end());
  5386. if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
  5387. return;
  5388. }
  5389. ALOGV("Updating allowed configs");
  5390. mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
  5391. // TODO(b/140204874): This hack triggers a notification that something has changed, so
  5392. // that listeners that care about a change in allowed configs can get the notification.
  5393. // Giving current ActiveConfig so that most other listeners would just drop the event
  5394. mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
  5395. display->getActiveConfig());
  5396. setPreferredDisplayConfig();
  5397. }
  5398. status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
  5399. const std::vector<int32_t>& allowedConfigs) {
  5400. ATRACE_CALL();
  5401. if (!displayToken || allowedConfigs.empty()) {
  5402. return BAD_VALUE;
  5403. }
  5404. if (mDebugDisplayConfigSetByBackdoor) {
  5405. // ignore this request as config is overridden by backdoor
  5406. return NO_ERROR;
  5407. }
  5408. postMessageSync(new LambdaMessage([&]() {
  5409. const auto display = getDisplayDeviceLocked(displayToken);
  5410. if (!display) {
  5411. ALOGE("Attempt to set allowed display configs for invalid display token %p",
  5412. displayToken.get());
  5413. } else if (display->isVirtual()) {
  5414. ALOGW("Attempt to set allowed display configs for virtual display");
  5415. } else {
  5416. Mutex::Autolock lock(mStateLock);
  5417. setAllowedDisplayConfigsInternal(display, allowedConfigs);
  5418. }
  5419. }));
  5420. return NO_ERROR;
  5421. }
  5422. status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
  5423. std::vector<int32_t>* outAllowedConfigs) {
  5424. ATRACE_CALL();
  5425. if (!displayToken || !outAllowedConfigs) {
  5426. return BAD_VALUE;
  5427. }
  5428. Mutex::Autolock lock(mStateLock);
  5429. const auto display = getDisplayDeviceLocked(displayToken);
  5430. if (!display) {
  5431. return NAME_NOT_FOUND;
  5432. }
  5433. if (display->isPrimary()) {
  5434. outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
  5435. }
  5436. return NO_ERROR;
  5437. }
  5438. void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
  5439. mFlinger->setInputWindowsFinished();
  5440. }
  5441. sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
  5442. BBinder *b = handle->localBinder();
  5443. if (b == nullptr) {
  5444. return nullptr;
  5445. }
  5446. auto it = mLayersByLocalBinderToken.find(b);
  5447. if (it != mLayersByLocalBinderToken.end()) {
  5448. return it->second.promote();
  5449. }
  5450. return nullptr;
  5451. }
  5452. void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
  5453. getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
  5454. }
  5455. status_t SurfaceFlinger::enterSelf(){
  5456. invalidateHwcGeometry();
  5457. repaintEverything();
  5458. return NO_ERROR;
  5459. }
  5460. status_t SurfaceFlinger::exitSelf(){
  5461. //invalidateHwcGeometry();
  5462. //repaintEverything();
  5463. return NO_ERROR;
  5464. }
  5465. } // namespace android
  5466. #if defined(__gl_h_)
  5467. #error "don't include gl/gl.h in this file"
  5468. #endif
  5469. #if defined(__gl2_h_)
  5470. #error "don't include gl2/gl2.h in this file"
  5471. #endif