Layer.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  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 ATRACE_TAG ATRACE_TAG_GRAPHICS
  17. #include <stdlib.h>
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include <math.h>
  21. #include <cutils/compiler.h>
  22. #include <cutils/native_handle.h>
  23. #include <cutils/properties.h>
  24. #include <utils/Errors.h>
  25. #include <utils/Log.h>
  26. #include <utils/NativeHandle.h>
  27. #include <utils/StopWatch.h>
  28. #include <utils/Trace.h>
  29. #include <ui/GraphicBuffer.h>
  30. #include <ui/PixelFormat.h>
  31. #include <gui/BufferItem.h>
  32. #include <gui/Surface.h>
  33. #include "clz.h"
  34. #include "Colorizer.h"
  35. #include "DisplayDevice.h"
  36. #include "Layer.h"
  37. #include "MonitoredProducer.h"
  38. #include "SurfaceFlinger.h"
  39. #include "DisplayHardware/HWComposer.h"
  40. #include "RenderEngine/RenderEngine.h"
  41. #define DEBUG_RESIZE 0
  42. namespace android {
  43. // ---------------------------------------------------------------------------
  44. int32_t Layer::sSequence = 1;
  45. Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
  46. const String8& name, uint32_t w, uint32_t h, uint32_t flags)
  47. : contentDirty(false),
  48. sequence(uint32_t(android_atomic_inc(&sSequence))),
  49. mFlinger(flinger),
  50. mTextureName(-1U),
  51. mPremultipliedAlpha(true),
  52. mName("unnamed"),
  53. mFormat(PIXEL_FORMAT_NONE),
  54. mTransactionFlags(0),
  55. mQueuedFrames(0),
  56. mSidebandStreamChanged(false),
  57. mCurrentTransform(0),
  58. mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
  59. mCurrentOpacity(true),
  60. mRefreshPending(false),
  61. mFrameLatencyNeeded(false),
  62. mFiltering(false),
  63. mNeedsFiltering(false),
  64. mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
  65. mProtectedByApp(false),
  66. mHasSurface(false),
  67. mClientRef(client),
  68. mPotentialCursor(false),
  69. mQueueItemLock(),
  70. mQueueItemCondition(),
  71. mQueueItems(),
  72. mLastFrameNumberReceived(0),
  73. mUpdateTexImageFailed(false),
  74. mTransformHint(0)
  75. {
  76. mCurrentCrop.makeInvalid();
  77. mFlinger->getRenderEngine().genTextures(1, &mTextureName);
  78. mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
  79. uint32_t layerFlags = 0;
  80. if (flags & ISurfaceComposerClient::eHidden)
  81. layerFlags |= layer_state_t::eLayerHidden;
  82. if (flags & ISurfaceComposerClient::eOpaque)
  83. layerFlags |= layer_state_t::eLayerOpaque;
  84. if (flags & ISurfaceComposerClient::eSecure)
  85. layerFlags |= layer_state_t::eLayerSecure;
  86. if (flags & ISurfaceComposerClient::eNonPremultiplied)
  87. mPremultipliedAlpha = false;
  88. mName = name;
  89. mCurrentState.active.x = 0;
  90. mCurrentState.active.y = 0;
  91. mCurrentState.active.w = w;
  92. mCurrentState.active.h = h;
  93. mCurrentState.active.crop.makeInvalid();
  94. mCurrentState.active.isPositionPending = false;
  95. mCurrentState.z = 0;
  96. mCurrentState.alpha = 0xFF;
  97. mCurrentState.blur = 0xFF;
  98. mCurrentState.layerStack = 0;
  99. mCurrentState.flags = layerFlags;
  100. mCurrentState.sequence = 0;
  101. mCurrentState.transform.set(0, 0);
  102. mCurrentState.requested = mCurrentState.active;
  103. // drawing state & current state are identical
  104. mDrawingState = mCurrentState;
  105. nsecs_t displayPeriod =
  106. flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
  107. mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
  108. }
  109. void Layer::onFirstRef() {
  110. // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
  111. sp<IGraphicBufferProducer> producer;
  112. sp<IGraphicBufferConsumer> consumer;
  113. BufferQueue::createBufferQueue(&producer, &consumer);
  114. mProducer = new MonitoredProducer(producer, mFlinger);
  115. mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
  116. mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
  117. mSurfaceFlingerConsumer->setContentsChangedListener(this);
  118. mSurfaceFlingerConsumer->setName(mName);
  119. #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
  120. #warning "disabling triple buffering"
  121. mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
  122. #else
  123. mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
  124. #endif
  125. const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
  126. updateTransformHint(hw);
  127. }
  128. Layer::~Layer() {
  129. sp<Client> c(mClientRef.promote());
  130. if (c != 0) {
  131. c->detachLayer(this);
  132. }
  133. mFlinger->deleteTextureAsync(mTextureName);
  134. mFrameTracker.logAndResetStats(mName);
  135. }
  136. // ---------------------------------------------------------------------------
  137. // callbacks
  138. // ---------------------------------------------------------------------------
  139. void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
  140. HWComposer::HWCLayerInterface* layer) {
  141. if (layer) {
  142. layer->onDisplayed();
  143. mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
  144. }
  145. }
  146. void Layer::onFrameAvailable(const BufferItem& item) {
  147. // Add this buffer from our internal queue tracker
  148. { // Autolock scope
  149. Mutex::Autolock lock(mQueueItemLock);
  150. // Reset the frame number tracker when we receive the first buffer after
  151. // a frame number reset
  152. if (item.mFrameNumber == 1) {
  153. mLastFrameNumberReceived = 0;
  154. }
  155. // Ensure that callbacks are handled in order
  156. while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
  157. status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
  158. ms2ns(500));
  159. if (result != NO_ERROR) {
  160. ALOGE("[%s] Timed out waiting on callback", mName.string());
  161. }
  162. }
  163. mQueueItems.push_back(item);
  164. android_atomic_inc(&mQueuedFrames);
  165. // Wake up any pending callbacks
  166. mLastFrameNumberReceived = item.mFrameNumber;
  167. mQueueItemCondition.broadcast();
  168. }
  169. mFlinger->signalLayerUpdate();
  170. }
  171. void Layer::onFrameReplaced(const BufferItem& item) {
  172. Mutex::Autolock lock(mQueueItemLock);
  173. // Ensure that callbacks are handled in order
  174. while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
  175. status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
  176. ms2ns(500));
  177. if (result != NO_ERROR) {
  178. ALOGE("[%s] Timed out waiting on callback", mName.string());
  179. }
  180. }
  181. if (mQueueItems.empty()) {
  182. ALOGE("Can't replace a frame on an empty queue");
  183. return;
  184. }
  185. mQueueItems.editItemAt(0) = item;
  186. // Wake up any pending callbacks
  187. mLastFrameNumberReceived = item.mFrameNumber;
  188. mQueueItemCondition.broadcast();
  189. }
  190. void Layer::onSidebandStreamChanged() {
  191. if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
  192. // mSidebandStreamChanged was false
  193. mFlinger->signalLayerUpdate();
  194. }
  195. }
  196. // called with SurfaceFlinger::mStateLock from the drawing thread after
  197. // the layer has been remove from the current state list (and just before
  198. // it's removed from the drawing state list)
  199. void Layer::onRemoved() {
  200. mSurfaceFlingerConsumer->abandon();
  201. }
  202. // ---------------------------------------------------------------------------
  203. // set-up
  204. // ---------------------------------------------------------------------------
  205. const String8& Layer::getName() const {
  206. return mName;
  207. }
  208. status_t Layer::setBuffers( uint32_t w, uint32_t h,
  209. PixelFormat format, uint32_t flags)
  210. {
  211. uint32_t const maxSurfaceDims = min(
  212. mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
  213. // never allow a surface larger than what our underlying GL implementation
  214. // can handle.
  215. if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
  216. ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
  217. return BAD_VALUE;
  218. }
  219. mFormat = format;
  220. mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
  221. mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
  222. mCurrentOpacity = getOpacityForFormat(format);
  223. mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
  224. mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
  225. mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
  226. return NO_ERROR;
  227. }
  228. sp<IBinder> Layer::getHandle() {
  229. Mutex::Autolock _l(mLock);
  230. LOG_ALWAYS_FATAL_IF(mHasSurface,
  231. "Layer::getHandle() has already been called");
  232. mHasSurface = true;
  233. /*
  234. * The layer handle is just a BBinder object passed to the client
  235. * (remote process) -- we don't keep any reference on our side such that
  236. * the dtor is called when the remote side let go of its reference.
  237. *
  238. * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
  239. * this layer when the handle is destroyed.
  240. */
  241. class Handle : public BBinder, public LayerCleaner {
  242. wp<const Layer> mOwner;
  243. public:
  244. Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
  245. : LayerCleaner(flinger, layer), mOwner(layer) {
  246. }
  247. };
  248. return new Handle(mFlinger, this);
  249. }
  250. sp<IGraphicBufferProducer> Layer::getProducer() const {
  251. return mProducer;
  252. }
  253. // ---------------------------------------------------------------------------
  254. // h/w composer set-up
  255. // ---------------------------------------------------------------------------
  256. Rect Layer::getContentCrop() const {
  257. // this is the crop rectangle that applies to the buffer
  258. // itself (as opposed to the window)
  259. Rect crop;
  260. if (!mCurrentCrop.isEmpty()) {
  261. // if the buffer crop is defined, we use that
  262. crop = mCurrentCrop;
  263. } else if (mActiveBuffer != NULL) {
  264. // otherwise we use the whole buffer
  265. crop = mActiveBuffer->getBounds();
  266. } else {
  267. // if we don't have a buffer yet, we use an empty/invalid crop
  268. crop.makeInvalid();
  269. }
  270. return crop;
  271. }
  272. Rect Layer::reduce(const Rect& win, const Region& exclude) const{
  273. if (CC_LIKELY(exclude.isEmpty())) {
  274. return win;
  275. }
  276. Rect tmp;
  277. win.intersect(exclude.getBounds(), &tmp);
  278. if (exclude.isRect() && !tmp.isEmpty()) {
  279. return win.reduce(exclude.getBounds());
  280. }
  281. return Region(win).subtract(exclude).getBounds();
  282. }
  283. Rect Layer::computeBounds() const {
  284. const Layer::State& s(getDrawingState());
  285. return computeBounds(s.activeTransparentRegion);
  286. }
  287. Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
  288. const Layer::State& s(getDrawingState());
  289. Rect win(s.active.w, s.active.h);
  290. if (!s.active.crop.isEmpty()) {
  291. win.intersect(s.active.crop, &win);
  292. }
  293. // subtract the transparent region and snap to the bounds
  294. return reduce(win, activeTransparentRegion);
  295. }
  296. FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
  297. // the content crop is the area of the content that gets scaled to the
  298. // layer's size.
  299. FloatRect crop(getContentCrop());
  300. // the active.crop is the area of the window that gets cropped, but not
  301. // scaled in any ways.
  302. const State& s(getDrawingState());
  303. // apply the projection's clipping to the window crop in
  304. // layerstack space, and convert-back to layer space.
  305. // if there are no window scaling involved, this operation will map to full
  306. // pixels in the buffer.
  307. // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
  308. // a viewport clipping and a window transform. we should use floating point to fix this.
  309. Rect activeCrop(s.active.w, s.active.h);
  310. if (!s.active.crop.isEmpty()) {
  311. activeCrop = s.active.crop;
  312. }
  313. activeCrop = s.transform.transform(activeCrop);
  314. activeCrop.intersect(hw->getViewport(), &activeCrop);
  315. activeCrop = s.transform.inverse().transform(activeCrop);
  316. // This needs to be here as transform.transform(Rect) computes the
  317. // transformed rect and then takes the bounding box of the result before
  318. // returning. This means
  319. // transform.inverse().transform(transform.transform(Rect)) != Rect
  320. // in which case we need to make sure the final rect is clipped to the
  321. // display bounds.
  322. activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop);
  323. // subtract the transparent region and snap to the bounds
  324. activeCrop = reduce(activeCrop, s.activeTransparentRegion);
  325. if (!activeCrop.isEmpty()) {
  326. // Transform the window crop to match the buffer coordinate system,
  327. // which means using the inverse of the current transform set on the
  328. // SurfaceFlingerConsumer.
  329. uint32_t invTransform = mCurrentTransform;
  330. if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
  331. /*
  332. * the code below applies the display's inverse transform to the buffer
  333. */
  334. uint32_t invTransformOrient = hw->getOrientationTransform();
  335. // calculate the inverse transform
  336. if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
  337. invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  338. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  339. // If the transform has been rotated the axis of flip has been swapped
  340. // so we need to swap which flip operations we are performing
  341. bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
  342. bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
  343. if (is_h_flipped != is_v_flipped) {
  344. invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  345. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  346. }
  347. }
  348. // and apply to the current transform
  349. invTransform = (Transform(invTransform) * Transform(invTransformOrient)).getOrientation();
  350. }
  351. int winWidth = s.active.w;
  352. int winHeight = s.active.h;
  353. if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
  354. // If the activeCrop has been rotate the ends are rotated but not
  355. // the space itself so when transforming ends back we can't rely on
  356. // a modification of the axes of rotation. To account for this we
  357. // need to reorient the inverse rotation in terms of the current
  358. // axes of rotation.
  359. bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
  360. bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
  361. if (is_h_flipped == is_v_flipped) {
  362. invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  363. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  364. }
  365. winWidth = s.active.h;
  366. winHeight = s.active.w;
  367. }
  368. const Rect winCrop = activeCrop.transform(
  369. invTransform, s.active.w, s.active.h);
  370. // below, crop is intersected with winCrop expressed in crop's coordinate space
  371. float xScale = crop.getWidth() / float(winWidth);
  372. float yScale = crop.getHeight() / float(winHeight);
  373. float insetL = winCrop.left * xScale;
  374. float insetT = winCrop.top * yScale;
  375. float insetR = (winWidth - winCrop.right ) * xScale;
  376. float insetB = (winHeight - winCrop.bottom) * yScale;
  377. crop.left += insetL;
  378. crop.top += insetT;
  379. crop.right -= insetR;
  380. crop.bottom -= insetB;
  381. }
  382. return crop;
  383. }
  384. void Layer::setGeometry(
  385. const sp<const DisplayDevice>& hw,
  386. HWComposer::HWCLayerInterface& layer)
  387. {
  388. layer.setDefaultState();
  389. // enable this layer
  390. layer.setSkip(false);
  391. if (isSecure() && !hw->isSecure()) {
  392. layer.setSkip(true);
  393. }
  394. // this gives us only the "orientation" component of the transform
  395. const State& s(getDrawingState());
  396. #if defined(QTI_BSP) && !defined(QCOM_BSP_LEGACY)
  397. if (!isOpaque(s)) {
  398. #else
  399. if (!isOpaque(s) || s.alpha != 0xFF) {
  400. #endif
  401. layer.setBlending(mPremultipliedAlpha ?
  402. HWC_BLENDING_PREMULT :
  403. HWC_BLENDING_COVERAGE);
  404. }
  405. // apply the layer's transform, followed by the display's global transform
  406. // here we're guaranteed that the layer's transform preserves rects
  407. Region activeTransparentRegion(s.activeTransparentRegion);
  408. if (!s.active.crop.isEmpty()) {
  409. Rect activeCrop(s.active.crop);
  410. activeCrop = s.transform.transform(activeCrop);
  411. activeCrop.intersect(hw->getViewport(), &activeCrop);
  412. activeCrop = s.transform.inverse().transform(activeCrop);
  413. // This needs to be here as transform.transform(Rect) computes the
  414. // transformed rect and then takes the bounding box of the result before
  415. // returning. This means
  416. // transform.inverse().transform(transform.transform(Rect)) != Rect
  417. // in which case we need to make sure the final rect is clipped to the
  418. // display bounds.
  419. activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop);
  420. // mark regions outside the crop as transparent
  421. activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
  422. activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
  423. s.active.w, s.active.h));
  424. activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
  425. activeCrop.left, activeCrop.bottom));
  426. activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
  427. s.active.w, activeCrop.bottom));
  428. }
  429. Rect frame(s.transform.transform(computeBounds(activeTransparentRegion)));
  430. frame.intersect(hw->getViewport(), &frame);
  431. const Transform& tr(hw->getTransform());
  432. layer.setFrame(tr.transform(frame));
  433. setPosition(hw, layer, s);
  434. layer.setCrop(computeCrop(hw));
  435. layer.setPlaneAlpha(s.alpha);
  436. /*
  437. * Transformations are applied in this order:
  438. * 1) buffer orientation/flip/mirror
  439. * 2) state transformation (window manager)
  440. * 3) layer orientation (screen orientation)
  441. * (NOTE: the matrices are multiplied in reverse order)
  442. */
  443. const Transform bufferOrientation(mCurrentTransform);
  444. Transform transform(tr * s.transform * bufferOrientation);
  445. if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
  446. /*
  447. * the code below applies the display's inverse transform to the buffer
  448. */
  449. uint32_t invTransform = hw->getOrientationTransform();
  450. uint32_t t_orientation = transform.getOrientation();
  451. // calculate the inverse transform
  452. if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
  453. invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  454. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  455. // If the transform has been rotated the axis of flip has been swapped
  456. // so we need to swap which flip operations we are performing
  457. bool is_h_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
  458. bool is_v_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
  459. if (is_h_flipped != is_v_flipped) {
  460. t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  461. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  462. }
  463. }
  464. // and apply to the current transform
  465. transform = Transform(t_orientation) * Transform(invTransform);
  466. }
  467. // this gives us only the "orientation" component of the transform
  468. const uint32_t orientation = transform.getOrientation();
  469. if (orientation & Transform::ROT_INVALID) {
  470. // we can only handle simple transformation
  471. layer.setSkip(true);
  472. } else {
  473. layer.setTransform(orientation);
  474. }
  475. }
  476. void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
  477. HWComposer::HWCLayerInterface& layer) {
  478. // we have to set the visible region on every frame because
  479. // we currently free it during onLayerDisplayed(), which is called
  480. // after HWComposer::commit() -- every frame.
  481. // Apply this display's projection's viewport to the visible region
  482. // before giving it to the HWC HAL.
  483. const Transform& tr = hw->getTransform();
  484. Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
  485. layer.setVisibleRegionScreen(visible);
  486. layer.setSurfaceDamage(surfaceDamageRegion);
  487. if (mSidebandStream.get()) {
  488. layer.setSidebandStream(mSidebandStream);
  489. } else {
  490. // NOTE: buffer can be NULL if the client never drew into this
  491. // layer yet, or if we ran out of memory
  492. layer.setBuffer(mActiveBuffer);
  493. }
  494. }
  495. void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
  496. HWComposer::HWCLayerInterface& layer) {
  497. int fenceFd = -1;
  498. // TODO: there is a possible optimization here: we only need to set the
  499. // acquire fence the first time a new buffer is acquired on EACH display.
  500. if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
  501. sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
  502. if (fence->isValid()) {
  503. fenceFd = fence->dup();
  504. if (fenceFd == -1) {
  505. ALOGW("failed to dup layer fence, skipping sync: %d", errno);
  506. }
  507. }
  508. }
  509. setAcquiredFenceIfBlit(fenceFd, layer);
  510. layer.setAcquireFenceFd(fenceFd);
  511. }
  512. Rect Layer::getPosition(
  513. const sp<const DisplayDevice>& hw)
  514. {
  515. // this gives us only the "orientation" component of the transform
  516. const State& s(getCurrentState());
  517. // apply the layer's transform, followed by the display's global transform
  518. // here we're guaranteed that the layer's transform preserves rects
  519. Rect win(s.active.w, s.active.h);
  520. if (!s.active.crop.isEmpty()) {
  521. win.intersect(s.active.crop, &win);
  522. }
  523. // subtract the transparent region and snap to the bounds
  524. Rect bounds = reduce(win, s.activeTransparentRegion);
  525. Rect frame(s.transform.transform(bounds));
  526. frame.intersect(hw->getViewport(), &frame);
  527. const Transform& tr(hw->getTransform());
  528. return Rect(tr.transform(frame));
  529. }
  530. // ---------------------------------------------------------------------------
  531. // drawing...
  532. // ---------------------------------------------------------------------------
  533. void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) {
  534. onDraw(hw, clip, false);
  535. }
  536. void Layer::draw(const sp<const DisplayDevice>& hw,
  537. bool useIdentityTransform) {
  538. onDraw(hw, Region(hw->bounds()), useIdentityTransform);
  539. }
  540. void Layer::draw(const sp<const DisplayDevice>& hw) {
  541. onDraw(hw, Region(hw->bounds()), false);
  542. }
  543. void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
  544. bool useIdentityTransform)
  545. {
  546. ATRACE_CALL();
  547. if (CC_UNLIKELY(mActiveBuffer == 0)) {
  548. // the texture has not been created yet, this Layer has
  549. // in fact never been drawn into. This happens frequently with
  550. // SurfaceView because the WindowManager can't know when the client
  551. // has drawn the first time.
  552. // If there is nothing under us, we paint the screen in black, otherwise
  553. // we just skip this update.
  554. // figure out if there is something below us
  555. Region under;
  556. const SurfaceFlinger::LayerVector& drawingLayers(
  557. mFlinger->mDrawingState.layersSortedByZ);
  558. const size_t count = drawingLayers.size();
  559. for (size_t i=0 ; i<count ; ++i) {
  560. const sp<Layer>& layer(drawingLayers[i]);
  561. if (layer.get() == static_cast<Layer const*>(this))
  562. break;
  563. under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
  564. }
  565. // if not everything below us is covered, we plug the holes!
  566. Region holes(clip.subtract(under));
  567. if (!holes.isEmpty()) {
  568. clearWithOpenGL(hw, holes, 0, 0, 0, 1);
  569. }
  570. return;
  571. }
  572. // Bind the current buffer to the GL texture, and wait for it to be
  573. // ready for us to draw into.
  574. status_t err = mSurfaceFlingerConsumer->bindTextureImage();
  575. if (err != NO_ERROR) {
  576. ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
  577. // Go ahead and draw the buffer anyway; no matter what we do the screen
  578. // is probably going to have something visibly wrong.
  579. }
  580. bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
  581. RenderEngine& engine(mFlinger->getRenderEngine());
  582. if (!blackOutLayer ||
  583. ((hw->getDisplayType() == HWC_DISPLAY_PRIMARY) && canAllowGPUForProtected())) {
  584. // TODO: we could be more subtle with isFixedSize()
  585. const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
  586. // Query the texture matrix given our current filtering mode.
  587. float textureMatrix[16];
  588. mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
  589. mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
  590. if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
  591. /*
  592. * the code below applies the display's inverse transform to the texture transform
  593. */
  594. // create a 4x4 transform matrix from the display transform flags
  595. const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
  596. const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
  597. const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
  598. mat4 tr;
  599. uint32_t transform = hw->getOrientationTransform();
  600. if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
  601. tr = tr * rot90;
  602. if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
  603. tr = tr * flipH;
  604. if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
  605. tr = tr * flipV;
  606. // calculate the inverse
  607. tr = inverse(tr);
  608. // and finally apply it to the original texture matrix
  609. const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
  610. memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
  611. }
  612. // Set things up for texturing.
  613. mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
  614. mTexture.setFiltering(useFiltering);
  615. mTexture.setMatrix(textureMatrix);
  616. engine.setupLayerTexturing(mTexture);
  617. } else {
  618. engine.setupLayerBlackedOut();
  619. }
  620. drawWithOpenGL(hw, clip, useIdentityTransform);
  621. engine.disableTexturing();
  622. }
  623. void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
  624. const Region& /* clip */, float red, float green, float blue,
  625. float alpha) const
  626. {
  627. RenderEngine& engine(mFlinger->getRenderEngine());
  628. computeGeometry(hw, mMesh, false);
  629. engine.setupFillWithColor(red, green, blue, alpha);
  630. engine.drawMesh(mMesh);
  631. }
  632. void Layer::clearWithOpenGL(
  633. const sp<const DisplayDevice>& hw, const Region& clip) const {
  634. clearWithOpenGL(hw, clip, 0,0,0,0);
  635. }
  636. void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
  637. const Region& /* clip */, bool useIdentityTransform) const {
  638. const State& s(getDrawingState());
  639. computeGeometry(hw, mMesh, useIdentityTransform);
  640. /*
  641. * NOTE: the way we compute the texture coordinates here produces
  642. * different results than when we take the HWC path -- in the later case
  643. * the "source crop" is rounded to texel boundaries.
  644. * This can produce significantly different results when the texture
  645. * is scaled by a large amount.
  646. *
  647. * The GL code below is more logical (imho), and the difference with
  648. * HWC is due to a limitation of the HWC API to integers -- a question
  649. * is suspend is whether we should ignore this problem or revert to
  650. * GL composition when a buffer scaling is applied (maybe with some
  651. * minimal value)? Or, we could make GL behave like HWC -- but this feel
  652. * like more of a hack.
  653. */
  654. Rect win(s.active.w, s.active.h);
  655. if(!s.active.crop.isEmpty()) {
  656. win = s.active.crop;
  657. }
  658. #ifdef QTI_BSP
  659. win = s.transform.transform(win);
  660. win.intersect(hw->getViewport(), &win);
  661. win = s.transform.inverse().transform(win);
  662. win.intersect(Rect(s.active.w, s.active.h), &win);
  663. win = reduce(win, s.activeTransparentRegion);
  664. #else
  665. win = reduce(win, s.activeTransparentRegion);
  666. #endif
  667. float left = float(win.left) / float(s.active.w);
  668. float top = float(win.top) / float(s.active.h);
  669. float right = float(win.right) / float(s.active.w);
  670. float bottom = float(win.bottom) / float(s.active.h);
  671. // TODO: we probably want to generate the texture coords with the mesh
  672. // here we assume that we only have 4 vertices
  673. Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
  674. texCoords[0] = vec2(left, 1.0f - top);
  675. texCoords[1] = vec2(left, 1.0f - bottom);
  676. texCoords[2] = vec2(right, 1.0f - bottom);
  677. texCoords[3] = vec2(right, 1.0f - top);
  678. RenderEngine& engine(mFlinger->getRenderEngine());
  679. engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
  680. engine.drawMesh(mMesh);
  681. engine.disableBlending();
  682. }
  683. uint32_t Layer::getProducerStickyTransform() const {
  684. int producerStickyTransform = 0;
  685. int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
  686. if (ret != OK) {
  687. ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
  688. strerror(-ret), ret);
  689. return 0;
  690. }
  691. return static_cast<uint32_t>(producerStickyTransform);
  692. }
  693. void Layer::setFiltering(bool filtering) {
  694. mFiltering = filtering;
  695. }
  696. bool Layer::getFiltering() const {
  697. return mFiltering;
  698. }
  699. // As documented in libhardware header, formats in the range
  700. // 0x100 - 0x1FF are specific to the HAL implementation, and
  701. // are known to have no alpha channel
  702. // TODO: move definition for device-specific range into
  703. // hardware.h, instead of using hard-coded values here.
  704. #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
  705. bool Layer::getOpacityForFormat(uint32_t format) {
  706. if (HARDWARE_IS_DEVICE_FORMAT(format)) {
  707. return true;
  708. }
  709. switch (format) {
  710. case HAL_PIXEL_FORMAT_RGBA_8888:
  711. case HAL_PIXEL_FORMAT_BGRA_8888:
  712. return false;
  713. }
  714. // in all other case, we have no blending (also for unknown formats)
  715. return true;
  716. }
  717. // ----------------------------------------------------------------------------
  718. // local state
  719. // ----------------------------------------------------------------------------
  720. void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
  721. bool useIdentityTransform) const
  722. {
  723. const Layer::State& s(getDrawingState());
  724. Transform tr(useIdentityTransform ?
  725. hw->getTransform() : hw->getTransform() * s.transform);
  726. const uint32_t hw_h = hw->getHeight();
  727. Rect win(s.active.w, s.active.h);
  728. if (!s.active.crop.isEmpty()) {
  729. win.intersect(s.active.crop, &win);
  730. }
  731. #ifdef QTI_BSP
  732. win = s.transform.transform(win);
  733. win.intersect(hw->getViewport(), &win);
  734. win = s.transform.inverse().transform(win);
  735. win.intersect(Rect(s.active.w, s.active.h), &win);
  736. win = reduce(win, s.activeTransparentRegion);
  737. const Transform bufferOrientation(mCurrentTransform);
  738. Transform transform(tr * s.transform * bufferOrientation);
  739. if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
  740. uint32_t invTransform = hw->getOrientationTransform();
  741. uint32_t t_orientation = transform.getOrientation();
  742. if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
  743. invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  744. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  745. bool is_h_flipped = (t_orientation &
  746. NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
  747. bool is_v_flipped = (t_orientation &
  748. NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
  749. if (is_h_flipped != is_v_flipped) {
  750. t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
  751. NATIVE_WINDOW_TRANSFORM_FLIP_H;
  752. }
  753. transform = Transform(t_orientation) * Transform(invTransform);
  754. }
  755. }
  756. const uint32_t orientation = transform.getOrientation();
  757. if (!(mTransformHint | mCurrentTransform | orientation)) {
  758. tr = hw->getTransform();
  759. if (!useIdentityTransform) {
  760. win = s.transform.transform(win);
  761. win.intersect(hw->getViewport(), &win);
  762. }
  763. }
  764. #else
  765. win = reduce(win, s.activeTransparentRegion);
  766. #endif
  767. Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
  768. position[0] = tr.transform(win.left, win.top);
  769. position[1] = tr.transform(win.left, win.bottom);
  770. position[2] = tr.transform(win.right, win.bottom);
  771. position[3] = tr.transform(win.right, win.top);
  772. for (size_t i=0 ; i<4 ; i++) {
  773. position[i].y = hw_h - position[i].y;
  774. }
  775. }
  776. bool Layer::isOpaque(const Layer::State& s) const
  777. {
  778. // if we don't have a buffer yet, we're translucent regardless of the
  779. // layer's opaque flag.
  780. if (mActiveBuffer == 0) {
  781. return false;
  782. }
  783. // if the layer has the opaque flag, then we're always opaque,
  784. // otherwise we use the current buffer's format.
  785. return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
  786. }
  787. bool Layer::isSecure() const
  788. {
  789. const Layer::State& s(mDrawingState);
  790. return (s.flags & layer_state_t::eLayerSecure);
  791. }
  792. bool Layer::isProtected() const
  793. {
  794. const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
  795. return (activeBuffer != 0) &&
  796. (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
  797. }
  798. bool Layer::isFixedSize() const {
  799. return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
  800. }
  801. bool Layer::isCropped() const {
  802. return !mCurrentCrop.isEmpty();
  803. }
  804. bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
  805. return mNeedsFiltering || hw->needsFiltering();
  806. }
  807. void Layer::setVisibleRegion(const Region& visibleRegion) {
  808. // always called from main thread
  809. this->visibleRegion = visibleRegion;
  810. }
  811. void Layer::setCoveredRegion(const Region& coveredRegion) {
  812. // always called from main thread
  813. this->coveredRegion = coveredRegion;
  814. }
  815. void Layer::setVisibleNonTransparentRegion(const Region&
  816. setVisibleNonTransparentRegion) {
  817. // always called from main thread
  818. this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
  819. }
  820. // ----------------------------------------------------------------------------
  821. // transaction
  822. // ----------------------------------------------------------------------------
  823. uint32_t Layer::doTransaction(uint32_t flags) {
  824. ATRACE_CALL();
  825. const Layer::State& s(getDrawingState());
  826. const Layer::State& c(getCurrentState());
  827. const bool sizeChanged = (c.requested.w != s.requested.w) ||
  828. (c.requested.h != s.requested.h);
  829. if (sizeChanged) {
  830. // the size changed, we need to ask our client to request a new buffer
  831. ALOGD_IF(DEBUG_RESIZE,
  832. "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
  833. " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
  834. " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n"
  835. " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
  836. " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
  837. this, getName().string(), mCurrentTransform, mCurrentScalingMode,
  838. c.active.w, c.active.h,
  839. c.active.crop.left,
  840. c.active.crop.top,
  841. c.active.crop.right,
  842. c.active.crop.bottom,
  843. c.active.crop.getWidth(),
  844. c.active.crop.getHeight(),
  845. c.requested.w, c.requested.h,
  846. c.requested.crop.left,
  847. c.requested.crop.top,
  848. c.requested.crop.right,
  849. c.requested.crop.bottom,
  850. c.requested.crop.getWidth(),
  851. c.requested.crop.getHeight(),
  852. s.active.w, s.active.h,
  853. s.active.crop.left,
  854. s.active.crop.top,
  855. s.active.crop.right,
  856. s.active.crop.bottom,
  857. s.active.crop.getWidth(),
  858. s.active.crop.getHeight(),
  859. s.requested.w, s.requested.h,
  860. s.requested.crop.left,
  861. s.requested.crop.top,
  862. s.requested.crop.right,
  863. s.requested.crop.bottom,
  864. s.requested.crop.getWidth(),
  865. s.requested.crop.getHeight());
  866. // record the new size, form this point on, when the client request
  867. // a buffer, it'll get the new size.
  868. mSurfaceFlingerConsumer->setDefaultBufferSize(
  869. c.requested.w, c.requested.h);
  870. }
  871. if (!isFixedSize()) {
  872. const bool resizePending = (c.requested.w != c.active.w) ||
  873. (c.requested.h != c.active.h);
  874. if (resizePending && mSidebandStream == NULL) {
  875. // don't let Layer::doTransaction update the drawing state
  876. // if we have a pending resize, unless we are in fixed-size mode.
  877. // the drawing state will be updated only once we receive a buffer
  878. // with the correct size.
  879. //
  880. // in particular, we want to make sure the clip (which is part
  881. // of the geometry state) is latched together with the size but is
  882. // latched immediately when no resizing is involved.
  883. //
  884. // If a sideband stream is attached, however, we want to skip this
  885. // optimization so that transactions aren't missed when a buffer
  886. // never arrives
  887. flags |= eDontUpdateGeometryState;
  888. }
  889. }
  890. // always set active to requested, unless we're asked not to
  891. // this is used by Layer, which special cases resizes.
  892. if (flags & eDontUpdateGeometryState) {
  893. } else {
  894. Layer::State& editCurrentState(getCurrentState());
  895. // If a position change was requested, and we have the correct
  896. // buffer size, no need to delay, update state now.
  897. if (editCurrentState.requested.isPositionPending) {
  898. float requestedX = editCurrentState.requested.x;
  899. float requestedY = editCurrentState.requested.y;
  900. if (requestedX != editCurrentState.active.x ||
  901. requestedY != editCurrentState.active.y) {
  902. editCurrentState.requested.isPositionPending = false;
  903. editCurrentState.transform.set(requestedX, requestedY);
  904. }
  905. }
  906. editCurrentState.active = c.requested;
  907. }
  908. if (s.active != c.active) {
  909. // invalidate and recompute the visible regions if needed
  910. flags |= Layer::eVisibleRegion;
  911. }
  912. if (c.sequence != s.sequence) {
  913. // invalidate and recompute the visible regions if needed
  914. flags |= eVisibleRegion;
  915. this->contentDirty = true;
  916. // we may use linear filtering, if the matrix scales us
  917. const uint8_t type = c.transform.getType();
  918. mNeedsFiltering = (!c.transform.preserveRects() ||
  919. (type >= Transform::SCALE));
  920. }
  921. // Commit the transaction
  922. commitTransaction();
  923. return flags;
  924. }
  925. void Layer::commitTransaction() {
  926. mDrawingState = mCurrentState;
  927. }
  928. uint32_t Layer::getTransactionFlags(uint32_t flags) {
  929. return android_atomic_and(~flags, &mTransactionFlags) & flags;
  930. }
  931. uint32_t Layer::setTransactionFlags(uint32_t flags) {
  932. return android_atomic_or(flags, &mTransactionFlags);
  933. }
  934. bool Layer::setPosition(float x, float y) {
  935. if ((mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y
  936. && !mCurrentState.requested.isPositionPending) ||
  937. (mCurrentState.requested.isPositionPending && mCurrentState.requested.x == x
  938. && mCurrentState.requested.y == y))
  939. return false;
  940. mCurrentState.sequence++;
  941. mCurrentState.requested.x = x;
  942. mCurrentState.requested.y = y;
  943. mCurrentState.requested.isPositionPending = true;
  944. setTransactionFlags(eTransactionNeeded);
  945. return true;
  946. }
  947. bool Layer::setLayer(uint32_t z) {
  948. if (mCurrentState.z == z)
  949. return false;
  950. mCurrentState.sequence++;
  951. mCurrentState.z = z;
  952. setTransactionFlags(eTransactionNeeded);
  953. return true;
  954. }
  955. bool Layer::setBlur(uint8_t blur) {
  956. if (mCurrentState.blur == blur)
  957. return false;
  958. mCurrentState.sequence++;
  959. mCurrentState.blur = blur;
  960. setTransactionFlags(eTransactionNeeded);
  961. return true;
  962. }
  963. bool Layer::setSize(uint32_t w, uint32_t h) {
  964. if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
  965. return false;
  966. mCurrentState.requested.w = w;
  967. mCurrentState.requested.h = h;
  968. setTransactionFlags(eTransactionNeeded);
  969. return true;
  970. }
  971. bool Layer::setAlpha(uint8_t alpha) {
  972. if (mCurrentState.alpha == alpha)
  973. return false;
  974. mCurrentState.sequence++;
  975. mCurrentState.alpha = alpha;
  976. setTransactionFlags(eTransactionNeeded);
  977. return true;
  978. }
  979. bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
  980. mCurrentState.sequence++;
  981. mCurrentState.transform.set(
  982. matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
  983. setTransactionFlags(eTransactionNeeded);
  984. return true;
  985. }
  986. bool Layer::setTransparentRegionHint(const Region& transparent) {
  987. mCurrentState.requestedTransparentRegion = transparent;
  988. setTransactionFlags(eTransactionNeeded);
  989. return true;
  990. }
  991. bool Layer::setFlags(uint8_t flags, uint8_t mask) {
  992. const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
  993. if (mCurrentState.flags == newFlags)
  994. return false;
  995. mCurrentState.sequence++;
  996. mCurrentState.flags = newFlags;
  997. setTransactionFlags(eTransactionNeeded);
  998. return true;
  999. }
  1000. bool Layer::setCrop(const Rect& crop) {
  1001. if (mCurrentState.requested.crop == crop)
  1002. return false;
  1003. mCurrentState.sequence++;
  1004. mCurrentState.requested.crop = crop;
  1005. setTransactionFlags(eTransactionNeeded);
  1006. return true;
  1007. }
  1008. bool Layer::setLayerStack(uint32_t layerStack) {
  1009. if (mCurrentState.layerStack == layerStack)
  1010. return false;
  1011. mCurrentState.sequence++;
  1012. mCurrentState.layerStack = layerStack;
  1013. setTransactionFlags(eTransactionNeeded);
  1014. return true;
  1015. }
  1016. void Layer::useSurfaceDamage() {
  1017. if (mFlinger->mForceFullDamage) {
  1018. surfaceDamageRegion = Region::INVALID_REGION;
  1019. } else {
  1020. surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
  1021. }
  1022. }
  1023. void Layer::useEmptyDamage() {
  1024. surfaceDamageRegion.clear();
  1025. }
  1026. // ----------------------------------------------------------------------------
  1027. // pageflip handling...
  1028. // ----------------------------------------------------------------------------
  1029. bool Layer::shouldPresentNow(const DispSync& dispSync) const {
  1030. if (mSidebandStreamChanged) {
  1031. return true;
  1032. }
  1033. Mutex::Autolock lock(mQueueItemLock);
  1034. if (mQueueItems.empty()) {
  1035. return false;
  1036. }
  1037. auto timestamp = mQueueItems[0].mTimestamp;
  1038. nsecs_t expectedPresent =
  1039. mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
  1040. // Ignore timestamps more than a second in the future
  1041. bool isPlausible = timestamp < (expectedPresent + s2ns(1));
  1042. ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
  1043. "relative to expectedPresent %" PRId64, mName.string(), timestamp,
  1044. expectedPresent);
  1045. bool isDue = timestamp < expectedPresent;
  1046. return isDue || !isPlausible;
  1047. }
  1048. bool Layer::onPreComposition() {
  1049. mRefreshPending = false;
  1050. return mQueuedFrames > 0 || mSidebandStreamChanged;
  1051. }
  1052. void Layer::onPostComposition() {
  1053. if (mFrameLatencyNeeded) {
  1054. nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
  1055. mFrameTracker.setDesiredPresentTime(desiredPresentTime);
  1056. sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
  1057. if (frameReadyFence->isValid()) {
  1058. mFrameTracker.setFrameReadyFence(frameReadyFence);
  1059. } else {
  1060. // There was no fence for this frame, so assume that it was ready
  1061. // to be presented at the desired present time.
  1062. mFrameTracker.setFrameReadyTime(desiredPresentTime);
  1063. }
  1064. const HWComposer& hwc = mFlinger->getHwComposer();
  1065. sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
  1066. if (presentFence->isValid()) {
  1067. mFrameTracker.setActualPresentFence(presentFence);
  1068. } else {
  1069. // The HWC doesn't support present fences, so use the refresh
  1070. // timestamp instead.
  1071. nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
  1072. mFrameTracker.setActualPresentTime(presentTime);
  1073. }
  1074. mFrameTracker.advanceFrame();
  1075. mFrameLatencyNeeded = false;
  1076. }
  1077. }
  1078. bool Layer::isVisible() const {
  1079. const Layer::State& s(mDrawingState);
  1080. return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
  1081. && (mActiveBuffer != NULL || mSidebandStream != NULL);
  1082. }
  1083. Region Layer::latchBuffer(bool& recomputeVisibleRegions)
  1084. {
  1085. ATRACE_CALL();
  1086. if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
  1087. // mSidebandStreamChanged was true
  1088. mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
  1089. if (mSidebandStream != NULL) {
  1090. setTransactionFlags(eTransactionNeeded);
  1091. mFlinger->setTransactionFlags(eTraversalNeeded);
  1092. }
  1093. recomputeVisibleRegions = true;
  1094. const State& s(getDrawingState());
  1095. return s.transform.transform(Region(Rect(s.active.w, s.active.h)));
  1096. }
  1097. Region outDirtyRegion;
  1098. if (mQueuedFrames > 0) {
  1099. // if we've already called updateTexImage() without going through
  1100. // a composition step, we have to skip this layer at this point
  1101. // because we cannot call updateTeximage() without a corresponding
  1102. // compositionComplete() call.
  1103. // we'll trigger an update in onPreComposition().
  1104. if (mRefreshPending) {
  1105. return outDirtyRegion;
  1106. }
  1107. // Capture the old state of the layer for comparisons later
  1108. const State& s(getDrawingState());
  1109. const bool oldOpacity = isOpaque(s);
  1110. sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
  1111. struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
  1112. Layer::State& front;
  1113. Layer::State& current;
  1114. bool& recomputeVisibleRegions;
  1115. bool stickyTransformSet;
  1116. Reject(Layer::State& front, Layer::State& current,
  1117. bool& recomputeVisibleRegions, bool stickySet)
  1118. : front(front), current(current),
  1119. recomputeVisibleRegions(recomputeVisibleRegions),
  1120. stickyTransformSet(stickySet) {
  1121. }
  1122. virtual bool reject(const sp<GraphicBuffer>& buf,
  1123. const BufferItem& item) {
  1124. if (buf == NULL) {
  1125. return false;
  1126. }
  1127. uint32_t bufWidth = buf->getWidth();
  1128. uint32_t bufHeight = buf->getHeight();
  1129. // check that we received a buffer of the right size
  1130. // (Take the buffer's orientation into account)
  1131. if (item.mTransform & Transform::ROT_90) {
  1132. swap(bufWidth, bufHeight);
  1133. }
  1134. bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
  1135. if (front.active != front.requested) {
  1136. if (isFixedSize ||
  1137. (bufWidth == front.requested.w &&
  1138. bufHeight == front.requested.h))
  1139. {
  1140. // If a position change was requested along with a resize.
  1141. // Now that we have the correct buffer size, update the position as well.
  1142. if (current.requested.isPositionPending) {
  1143. float requestedX = current.requested.x;
  1144. float requestedY = current.requested.y;
  1145. if (requestedX != current.active.x || requestedY != current.active.y) {
  1146. front.transform.set(requestedX, requestedY);
  1147. current.transform.set(requestedX, requestedY);
  1148. current.requested.isPositionPending = false;
  1149. }
  1150. }
  1151. // Here we pretend the transaction happened by updating the
  1152. // current and drawing states. Drawing state is only accessed
  1153. // in this thread, no need to have it locked
  1154. front.active = front.requested;
  1155. // We also need to update the current state so that
  1156. // we don't end-up overwriting the drawing state with
  1157. // this stale current state during the next transaction
  1158. //
  1159. // NOTE: We don't need to hold the transaction lock here
  1160. // because State::active is only accessed from this thread.
  1161. current.active = front.active;
  1162. // recompute visible region
  1163. recomputeVisibleRegions = true;
  1164. }
  1165. ALOGD_IF(DEBUG_RESIZE,
  1166. "latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
  1167. " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
  1168. " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
  1169. bufWidth, bufHeight, item.mTransform, item.mScalingMode,
  1170. front.active.w, front.active.h,
  1171. front.active.crop.left,
  1172. front.active.crop.top,
  1173. front.active.crop.right,
  1174. front.active.crop.bottom,
  1175. front.active.crop.getWidth(),
  1176. front.active.crop.getHeight(),
  1177. front.requested.w, front.requested.h,
  1178. front.requested.crop.left,
  1179. front.requested.crop.top,
  1180. front.requested.crop.right,
  1181. front.requested.crop.bottom,
  1182. front.requested.crop.getWidth(),
  1183. front.requested.crop.getHeight());
  1184. }
  1185. if (!isFixedSize && !stickyTransformSet) {
  1186. if (front.active.w != bufWidth ||
  1187. front.active.h != bufHeight) {
  1188. // reject this buffer
  1189. ALOGE("rejecting buffer: bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
  1190. bufWidth, bufHeight, front.active.w, front.active.h);
  1191. return true;
  1192. }
  1193. }
  1194. // if the transparent region has changed (this test is
  1195. // conservative, but that's fine, worst case we're doing
  1196. // a bit of extra work), we latch the new one and we
  1197. // trigger a visible-region recompute.
  1198. if (!front.activeTransparentRegion.isTriviallyEqual(
  1199. front.requestedTransparentRegion)) {
  1200. front.activeTransparentRegion = front.requestedTransparentRegion;
  1201. // We also need to update the current state so that
  1202. // we don't end-up overwriting the drawing state with
  1203. // this stale current state during the next transaction
  1204. //
  1205. // NOTE: We don't need to hold the transaction lock here
  1206. // because State::active is only accessed from this thread.
  1207. current.activeTransparentRegion = front.activeTransparentRegion;
  1208. // recompute visible region
  1209. recomputeVisibleRegions = true;
  1210. }
  1211. return false;
  1212. }
  1213. };
  1214. Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
  1215. getProducerStickyTransform() != 0);
  1216. uint64_t maxFrameNumber = 0;
  1217. {
  1218. Mutex::Autolock lock(mQueueItemLock);
  1219. maxFrameNumber = mLastFrameNumberReceived;
  1220. }
  1221. status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
  1222. mFlinger->mPrimaryDispSync, maxFrameNumber);
  1223. if (updateResult == BufferQueue::PRESENT_LATER) {
  1224. // Producer doesn't want buffer to be displayed yet. Signal a
  1225. // layer update so we check again at the next opportunity.
  1226. mFlinger->signalLayerUpdate();
  1227. return outDirtyRegion;
  1228. } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
  1229. // If the buffer has been rejected, remove it from the shadow queue
  1230. // and return early
  1231. Mutex::Autolock lock(mQueueItemLock);
  1232. mQueueItems.removeAt(0);
  1233. android_atomic_dec(&mQueuedFrames);
  1234. return outDirtyRegion;
  1235. } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
  1236. // This can occur if something goes wrong when trying to create the
  1237. // EGLImage for this buffer. If this happens, the buffer has already
  1238. // been released, so we need to clean up the queue and bug out
  1239. // early.
  1240. {
  1241. Mutex::Autolock lock(mQueueItemLock);
  1242. mQueueItems.clear();
  1243. android_atomic_and(0, &mQueuedFrames);
  1244. }
  1245. // Once we have hit this state, the shadow queue may no longer
  1246. // correctly reflect the incoming BufferQueue's contents, so even if
  1247. // updateTexImage starts working, the only safe course of action is
  1248. // to continue to ignore updates.
  1249. mUpdateTexImageFailed = true;
  1250. return outDirtyRegion;
  1251. }
  1252. { // Autolock scope
  1253. auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
  1254. Mutex::Autolock lock(mQueueItemLock);
  1255. // Remove any stale buffers that have been dropped during
  1256. // updateTexImage
  1257. while ((mQueuedFrames > 0) && (mQueueItems[0].mFrameNumber != currentFrameNumber)) {
  1258. mQueueItems.removeAt(0);
  1259. android_atomic_dec(&mQueuedFrames);
  1260. }
  1261. if (mQueuedFrames == 0) {
  1262. ALOGE("[%s] mQueuedFrames is zero !!", mName.string());
  1263. return outDirtyRegion;
  1264. }
  1265. mQueueItems.removeAt(0);
  1266. }
  1267. // Decrement the queued-frames count. Signal another event if we
  1268. // have more frames pending.
  1269. if (android_atomic_dec(&mQueuedFrames) > 1) {
  1270. mFlinger->signalLayerUpdate();
  1271. }
  1272. if (updateResult != NO_ERROR) {
  1273. // something happened!
  1274. recomputeVisibleRegions = true;
  1275. return outDirtyRegion;
  1276. }
  1277. // update the active buffer
  1278. mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
  1279. if (mActiveBuffer == NULL) {
  1280. // this can only happen if the very first buffer was rejected.
  1281. return outDirtyRegion;
  1282. }
  1283. mRefreshPending = true;
  1284. mFrameLatencyNeeded = true;
  1285. if (oldActiveBuffer == NULL) {
  1286. // the first time we receive a buffer, we need to trigger a
  1287. // geometry invalidation.
  1288. recomputeVisibleRegions = true;
  1289. }
  1290. Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
  1291. const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
  1292. const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
  1293. if ((crop != mCurrentCrop) ||
  1294. (transform != mCurrentTransform) ||
  1295. (scalingMode != mCurrentScalingMode))
  1296. {
  1297. mCurrentCrop = crop;
  1298. mCurrentTransform = transform;
  1299. mCurrentScalingMode = scalingMode;
  1300. recomputeVisibleRegions = true;
  1301. }
  1302. if (oldActiveBuffer != NULL) {
  1303. uint32_t bufWidth = mActiveBuffer->getWidth();
  1304. uint32_t bufHeight = mActiveBuffer->getHeight();
  1305. if (bufWidth != uint32_t(oldActiveBuffer->width) ||
  1306. bufHeight != uint32_t(oldActiveBuffer->height)) {
  1307. recomputeVisibleRegions = true;
  1308. }
  1309. }
  1310. mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
  1311. if (oldOpacity != isOpaque(s)) {
  1312. recomputeVisibleRegions = true;
  1313. }
  1314. // FIXME: postedRegion should be dirty & bounds
  1315. Region dirtyRegion(Rect(s.active.w, s.active.h));
  1316. // transform the dirty region to window-manager space
  1317. outDirtyRegion = (s.transform.transform(dirtyRegion));
  1318. }
  1319. return outDirtyRegion;
  1320. }
  1321. uint32_t Layer::getEffectiveUsage(uint32_t usage) const
  1322. {
  1323. // TODO: should we do something special if mSecure is set?
  1324. if (mProtectedByApp) {
  1325. // need a hardware-protected path to external video sink
  1326. usage |= GraphicBuffer::USAGE_PROTECTED;
  1327. }
  1328. if (mPotentialCursor) {
  1329. usage |= GraphicBuffer::USAGE_CURSOR;
  1330. }
  1331. usage |= GraphicBuffer::USAGE_HW_COMPOSER;
  1332. return usage;
  1333. }
  1334. void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) {
  1335. uint32_t orientation = 0;
  1336. if (!mFlinger->mDebugDisableTransformHint) {
  1337. // The transform hint is used to improve performance, but we can
  1338. // only have a single transform hint, it cannot
  1339. // apply to all displays.
  1340. const Transform& planeTransform(hw->getTransform());
  1341. orientation = planeTransform.getOrientation();
  1342. if (orientation & Transform::ROT_INVALID) {
  1343. orientation = 0;
  1344. }
  1345. }
  1346. mSurfaceFlingerConsumer->setTransformHint(orientation);
  1347. mTransformHint = orientation;
  1348. }
  1349. // ----------------------------------------------------------------------------
  1350. // debugging
  1351. // ----------------------------------------------------------------------------
  1352. void Layer::dump(String8& result, Colorizer& colorizer) const
  1353. {
  1354. const Layer::State& s(getDrawingState());
  1355. colorizer.colorize(result, Colorizer::GREEN);
  1356. result.appendFormat(
  1357. "+ %s %p (%s)\n",
  1358. getTypeId(), this, getName().string());
  1359. colorizer.reset(result);
  1360. s.activeTransparentRegion.dump(result, "transparentRegion");
  1361. visibleRegion.dump(result, "visibleRegion");
  1362. surfaceDamageRegion.dump(result, "surfaceDamageRegion");
  1363. sp<Client> client(mClientRef.promote());
  1364. result.appendFormat( " "
  1365. "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), "
  1366. "isOpaque=%1d, invalidate=%1d, "
  1367. "alpha=0x%02x, blur=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
  1368. " client=%p\n",
  1369. s.layerStack, s.z, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h,
  1370. s.active.crop.left, s.active.crop.top,
  1371. s.active.crop.right, s.active.crop.bottom,
  1372. isOpaque(s), contentDirty,
  1373. s.alpha, s.blur, s.flags,
  1374. s.transform[0][0], s.transform[0][1],
  1375. s.transform[1][0], s.transform[1][1],
  1376. client.get());
  1377. sp<const GraphicBuffer> buf0(mActiveBuffer);
  1378. uint32_t w0=0, h0=0, s0=0, f0=0;
  1379. if (buf0 != 0) {
  1380. w0 = buf0->getWidth();
  1381. h0 = buf0->getHeight();
  1382. s0 = buf0->getStride();
  1383. f0 = buf0->format;
  1384. }
  1385. result.appendFormat(
  1386. " "
  1387. "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
  1388. " queued-frames=%d, mRefreshPending=%d\n",
  1389. mFormat, w0, h0, s0,f0,
  1390. mQueuedFrames, mRefreshPending);
  1391. if (mSurfaceFlingerConsumer != 0) {
  1392. mSurfaceFlingerConsumer->dump(result, " ");
  1393. }
  1394. }
  1395. void Layer::dumpFrameStats(String8& result) const {
  1396. mFrameTracker.dumpStats(result);
  1397. }
  1398. void Layer::clearFrameStats() {
  1399. mFrameTracker.clearStats();
  1400. }
  1401. void Layer::logFrameStats() {
  1402. mFrameTracker.logAndResetStats(mName);
  1403. }
  1404. void Layer::getFrameStats(FrameStats* outStats) const {
  1405. mFrameTracker.getStats(outStats);
  1406. }
  1407. // ---------------------------------------------------------------------------
  1408. Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
  1409. const sp<Layer>& layer)
  1410. : mFlinger(flinger), mLayer(layer) {
  1411. }
  1412. Layer::LayerCleaner::~LayerCleaner() {
  1413. // destroy client resources
  1414. mFlinger->onLayerDestroyed(mLayer);
  1415. }
  1416. // ---------------------------------------------------------------------------
  1417. }; // namespace android
  1418. #if defined(__gl_h_)
  1419. #error "don't include gl/gl.h in this file"
  1420. #endif
  1421. #if defined(__gl2_h_)
  1422. #error "don't include gl2/gl2.h in this file"
  1423. #endif